Nisha Miller
Nisha Miller

Reputation: 33

Painting inside QLabel recursively calls paintEvent

I'm using a QLabel to draw graphics in a Qt 5 app. Instead of subclassing QLabel, I'm installing an event filter. The event filter does get called and painting inside the QLabel does work. The problem is that the event filter gets called recursively and my cpu hits 100% usage.

What am I doing wrong here?

Here is my code:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->label->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject *obj, QEvent *ev)
{
    if ((obj == ui->label) && (ev->type() == QEvent::Paint))
    {
        QPixmap pix(50, 50);
        pix.fill(Qt::blue);
        ui->label->setPixmap(pix);
    }
    return false;
}

Thanks for your help Nisha Miller

Upvotes: 2

Views: 482

Answers (1)

jonspaceharper
jonspaceharper

Reputation: 4367

setPixmap() calls update() which queues another paint event, leading to an infinite loop.

Paint events are sent frequently and should be as inexpensive an operation as possible. Consider setting the pixmap ahead of time in response to a signal or event or re-implement QLabel and its paintEvent().

Upvotes: 2

Related Questions