Question

I'm learning about QPainter, and I've created a simple widget where each time the user clicks on the widget, a new circle appears at that point.

enter image description here

But Qt doesn't allow painting outside paintEvent, so each time I want to draw a new circle, I need to invalidate the widget area and redraw all the previous circles, too. That doesn't seem very efficient - what if there are hundreds or even thousands of elements.

It would be best if the previous circles weren't erased, and I just drew the new one on top of the widget. But on Qt I can't draw without first invalidating (and thus erasing) the previous content.

What is the recommended way of handling this situation in Qt?

Était-ce utile?

La solution

The recommended way to handle that situation is to use a QGraphicsScene and QGraphicsView, and then populate the scene with QGraphicsItems. According to the docs, that is exactly what the framework is designed for.

In short, you would override QGraphicsScene::mousePressEvent(), and in the new method you would create a new QGraphicsEllipseItem.

Autres conseils

There is no need to invalidate the entire widget. update() and repaint() can take coordinates that you want to repaint thus only re-drawing the part that changed.

void  update ( int x, int y, int w, int h ) 
void  update ( const QRect & rect ) 
void  update ( const QRegion & rgn ) 

void  repaint ( int x, int y, int w, int h ) 
void  repaint ( const QRect & rect ) 
void  repaint ( const QRegion & rgn ) 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top