Adrian Maire Adrian Maire - 1 year ago 58
C++ Question

How to highlight a specific `QWidget`

For a searching/linking behavior, the idea is to highlight the specific

QWidget
resulting from the search.

In my first prototype, it just create on top of the given
QWidget
a decoration for the highlight. However, when the widget is resized, the highlight does not adapt/align.

DecorationWidget decoration;
...
QWidget* result = search(searchStr);
if (result)
{
decoration.setParent(result);
decoration.setGeometry(QRect(QPoint(0,0),result->size()));
decoration.raise();
decoration.show();

}
else
{
decoration.hide();
}


How could I detect the
QWidget
resizing?


I obviously though about connecting, but the
QWidget
does not emit on resize. It is also not allowed to
extends
the widget because the search could point to any arbitrary
QWidget
.

Changing the style of the
QWidget
itself (actually changing anything of the QWidget) is not allowed, as it might have a specific style or
PaintEvent
implementation.

Answer Source

It can be easily done with event filter.

In DecorationWidget override the eventFilter method (derived from QObject) and capture resize event there.

For example:

bool DecorationWidget::eventFilter(QObject* watched, QEvent* event)
{
    if(event->type() == QEvent::Resize)
    {
        QResizeEvent *resizeEvent = static_cast<QResizeEvent *>(event);
        resize(resizeEvent->size());
    }
    return false;
}

Than on the result widget install the instance of DecorationWidget as event filter:

result->installEventFilter(myDecorationWidget);

Remember to remove the event filter when you switch to another widget.

prevoiusResult->removeEventFiter(myDecorationWidget);

Documentation about event filters

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download