Qt paintEvent crashes

1.6k views Asked by At

Im trying to draw simple board on my widget.

When I'm trying to automatize this, my paintEvent crashes. I think it is caused by for loop inside, am I right? How to paint it in other way?

void Widget::paintEvent(QPaintEvent *event)
{
QPixmap myPix( QSize(20,20) );
QPainter painter(this);
for(int i = 0; i < 100; i+5){
    painter.drawLine(QPointF(i,0),QPointF(i,max));
}
this->setPixmap(myPix);
}
1

There are 1 answers

5
Jablonski On BEST ANSWER

Your for loop is incorrect and causes the program crash (I'm sure that's not your fault here). It should be written like this:

for(int i = 0; i < 100; i+=5){
    p.drawLine(QPointF(i,0),QPointF(i,max));
}

i.e. with an assignment of the increment. This way it will do the job and finish properly.

On a side note, I would suggest to use drawPixmap() instead of setPixmap(). But setPixmap() will not cause infinite recursion and for example next code works properly.

//...
this->setPixmap(QPixmap("G:/2/qt.jpg"));
QLabel::paintEvent(event);

Why? With this approach infinite recursion is never produced (see here):

If you call repaint() in a function which may itself be called from paintEvent(), you may get infinite recursion. The update() function never causes recursion.

Indeed setPixmap() calls update(), not repaint(). To prove that see source code:

setPixmap source:

void QLabel::setPixmap(const QPixmap &pixmap)
{
    Q_D(QLabel);
    //...
    d->updateLabel();//what it does?
}

updateLabel source:

void QLabelPrivate::updateLabel()
{
    Q_Q(QLabel);
    //...
    q->updateGeometry();
    q->update(q->contentsRect());//not repaint

}

As I said it is not a mistake but I think that it will be better if you will do all what you need with QPainter.