A
A
Alexey Akulovich2012-10-13 13:48:52
Qt
Alexey Akulovich, 2012-10-13 13:48:52

Is it possible to override paintEvent in Qt without creating a child?

There is a need to draw on the component, but I don’t want to fence for the sake of this descendant of QWidget, which overrides the only method.
Is there some trick with the ears, by analogy with SetWindowLong(hWnd, GWL_WNDPROC, &myWndProc) + CallWindowProc() from Win32API.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mik_os, 2012-10-13
@AterCattus

You can: doc.qt.digia.com/4.7-snapshot/eventsandfilters.html#event-filters , if you return true from eventFilter then the widget's paintEvent will not be called.

S
silvansky, 2012-10-15
@silvansky

It is much more cunning to act if you first need to draw what the widget itself wants, and on top - your own.
For example, let's say we have a QLabel and we want to cross out the text diagonally in red. Then you need to make such a feint with your ears in the eventFilter:

bool MyClass::eventFilter(QObject *obj, QEvent *evt)
{
    if (evt->type() == QEvent::Paint)
    {
        obj->removeEventFilter(this);
        QApplication::sendEvent(obj, evt);
        obj->installEventFilter(this)
        // наша отрисовка поверх уже нарисованного
        return true;
    }
}

That is, we remove the filter, draw the “native”, turn the filter back on, draw what we need.

A
Alexey Akulovich, 2012-10-13
@AterCattus

Actually, the filter can be set for an existing widget, then you do not have to create a separate filter class:

...
  this->paint_area->installEventFilter(this);
...
bool MainWindow::eventFilter(QObject *target, QEvent *event) {
    if (target == this->paint_area) {
        if (event->type() == QEvent::Paint) {
            this->paintSmth((QPaintEvent*)event);
            return true;
        }
    }

    return false;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question