QPainter saves previous drawings

This is my first time using Qt and I need to do the equivalent of MSPaint with Qt. I have problems drawing my lines. Currently, I can draw a line by clicking somewhere on the screen and letting go to another place, however, when I draw the second line, the previous line is erased. How can you save previously painted objects when drawing another object?

void Canvas::paintEvent(QPaintEvent *pe){ QWidget::paintEvent(pe); QPainter p(this); p.drawPicture(0,0,pic); } void Canvas::mousePressEvent(QMouseEvent *mp){ start = mp->pos(); } void Canvas::mouseReleaseEvent(QMouseEvent *mr){ end = mr->pos(); addline(); } void Canvas::addline()Q_DECL_OVERRIDE{ QPainter p(&pic); p.drawLine(start,end); p.end(); this->update(); } 

Canvas is a class that receives a QWidget, it has two QPoint attributes, starting and ending.

Body class:

 class Canvas : public QWidget{ Q_OBJECT private: QPoint start; QPoint end; QPicture pic; public: Canvas(){paint = false;setAttribute(Qt::WA_StaticContents);} void addline(); protected: void paintEvent(QPaintEvent *); void mousePressEvent( QMouseEvent * ); //void mouseMoveEvent( QMouseEvent * ); void mouseReleaseEvent( QMouseEvent * ); }; 
+6
source share
1 answer

QPicture writes QPainter commands. Also from his documentation you can read this:

Please note that the list of painter commands reset each time the QPainter :: begin () function is called.

And the QPainter constructor with the drawing device calls begin() . Therefore, every time old recorded commands are deleted.

It may seem tempting to use it, as it says a few good things, for example, that it is independent of resolution, but that’s not how drawing applications work. Switch to QPixmap and your drawings will be saved.

Also, do not forget to initialize pixmap, because by default it will be empty and you cannot draw it.

 Canvas() : pic(width,height) {...} 

In addition, if you want to introduce the concept of brushes, as in art brushes, rather than QBrush , you can look at this approach for drawing a line .

EDIT: Please note that you should be able to prevent QPicture from losing content by not calling begin() on it more than once. If you create an artist intended only for drawing on it in the class area, and the call starts in the designer, different operations of writing the drawing should be saved. But as they increase in number, it will take longer to draw a QPicture for your widget. You can get around this using both QPicture and QPixmap , and draw them both, use an image to record actions and a pixmap to avoid continuously redrawing the image, even if you do double the work is still more efficient while you still retain the ability to use the image to re-rasterize at a different resolution or to save the drawing history. But I doubt that QPicture succeed when your drawing application starts forming the actual drawing application, for example, when you start using pixpap stencils, etc.

+4
source

All Articles