KelvinS
KelvinS

Reputation: 3071

How to avoid repaint on QFrame?

I have a QFrame that is used to paint some rectangles to represent some periods of the day, for example, the period when the user was sleeping.

To do so I overwrite the paintEvent(QPaintEvent *) function and I'm using a QPainter to paint the rectangles.

It is working fine, the problem is that the paintEvent(QPaintEvent *) function is automatically called multiple times by Qt to repaint the QFrame and it is consuming too much CPU. Actually, I just need to repaint a few times (by manually calling the repaint function).

There is some way that I can avoid the QFrame to automatically repaint itself?

Thanks in advance

I'm using Qt 5.3

Upvotes: 0

Views: 856

Answers (2)

KelvinS
KelvinS

Reputation: 3071

I finally found the problem. I was setting the style sheet inside the paintEvent function and I think it was being repainted because of that.

I was doing something like this:

MyFrameBar::MyFrameBar(QWidget *parent) : QFrame(parent)
{
    color = QColor(50, 50, 50, 200);
}

void MyFrameBar::paintEvent(QPaintEvent *)
{
    QString style = "border: 1px solid rgba(%1, %2, %3, %4);";
    style = style.arg(color.red()).arg(color.green()).arg(color.blue()).arg(color.alpha());
    setStyleSheet(style);
    ...
}

I just changed the place where I was setting the style sheet and everything is working fine.

The new code looks like this:

MyFrameBar::MyFrameBar(QWidget *parent) : QFrame(parent)
{
    setColor(QColor(50, 50, 50, 200));
}

void MyFrameBar::paintEvent(QPaintEvent *)
{
    ...
}

void MyFrameBar::setColor(const QColor &color)
{
    this->color = color;

    QString style = "border: 1px solid rgba(%1, %2, %3, %4);";
    style = style.arg(color.red()).arg(color.green()).arg(color.blue()).arg(color.alpha());
    setStyleSheet(style);
}

Upvotes: 0

Widgets are repainted whenever Qt needs to repaint them. You have no control over any of that, generally speaking. You can only add repaint requests when needed, not reduce them.

You should never need to call the repaint method. Instead, whenever the data used for painting changes, you should update() the widget. The update events are fused to improve performance. The calls to update() should be in the widget's setter methods, or should be connected to the dataChanged() and equivalent signals of the data model used to feed the widget.

Most likely you're doing something else wrong. You'd need to provide a self-contained example to demonstrate the problem.

Upvotes: 2

Related Questions