Qt paintEvent violations
I am trying to draw a simple board on my widget.
When I try to automate this, my paintEvent crashes. I think this is caused by an inner loop, right? How do I draw it in a different 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);
}
source to share
Your for loop is wrong and is causing the program to crash (I'm sure 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 assignment of an increment. This way it will get the job done and finished correctly.
On the side of the note, I would suggest using drawPixmap()
instead setPixmap()
. But setPixmap()
will not lead to infinite recursion, and for example the following code works correctly.
//...
this->setPixmap(QPixmap("G:/2/qt.jpg"));
QLabel::paintEvent(event);
Why? With this approach, infinite recursion is never performed (see here ):
If you call repaint () on a function that itself can be called from paintEvent (), you can end up with infinite recursion. The update () function never calls recursion.
Really setPixmap()
calls update()
, not repaint()
. To prove that see the source code:
void QLabel::setPixmap(const QPixmap &pixmap)
{
Q_D(QLabel);
//...
d->updateLabel();//what it does?
}
void QLabelPrivate::updateLabel()
{
Q_Q(QLabel);
//...
q->updateGeometry();
q->update(q->contentsRect());//not repaint
}
As I said, this is not a bug, but I think it will be better if you do whatever you need to do with QPainter
.
source to share