简体   繁体   English

QPainter保存状态

[英]QPainter Save State

I have a QWidget in which I use a QPainter object to draw some dots but when update() method is invoked, the QWidget's draw is cleared completely. 我有一个QWidget,其中我使用QPainter对象绘制一些点但是当调用update()方法时,QWidget的绘制被完全清除。 Is there any way to save the actual state and just add dots, or i have to save every dot and paint them in every paintEvent() call ? 有没有办法保存实际状态只是添加点,或者我必须保存每个点并在每个paintEvent()调用中绘制它们? Basically when I press an arrow, I must show a line on the QWidget (it's for a car rally). 基本上当我按箭头时,我必须在QWidget上显示一条线(这是为了汽车拉力赛)。

In addition to SingerOfTheFall 's answer, you could also draw all your incremental changes into an image and then only draw this image in each update invocation. 除了SingerOfTheFall的答案之外,您还可以将所有增量更改绘制到图像中,然后仅在每次更新调用中绘制此图像。

For working with images Qt has a bunch of classes, most important being QImage and QPixmap and since they are both derived from QPaintDevice , they can be directly drawn into with a QPainter . 对于处理图像,Qt有一堆类,最重要的是QImageQPixmap ,因为它们都是从QPaintDevice派生的,所以可以直接用QPainter绘制它们。 Whereas QImage is optimized for direct pixel access and file I/O, QPixmap is optimized for showing it on the screen. QImage针对直接像素访问和文件I / O进行了优化,而QPixmap则经过优化,可在屏幕上显示。 It doesn't say which one is better for drawing into, but I would start with QPixmap and see how it performs. 它没有说哪一个更适合绘图,但我会从QPixmap开始,看看它是如何表现的。

There is also another "image" class you can draw into, QPicture . QPicture还有另一个你可以画的“图像”类。 But this is not really an image storing the resulting rendering, but merely records the draw commands done with the QPainter to be easily played back later. 但这并不是存储生成的渲染的图像,而是仅记录使用QPainter完成的绘制命令,以便以后轻松播放。 Therefore I think it's performance shouldn't be much better than that of a "real" image. 因此,我认为它的表现不应该比“真实”图像好得多。 But it may be worth a try, especially if there is something more involved going on in the drawing and just storing the final image is not sufficient. 但它可能值得一试,特别是如果图中有更多内容,只是存储最终图像是不够的。

QPainter simply can not save the "state", because it's not his purpose. QPainter根本无法保存“状态”,因为这不是他的目的。 The only thing it does is drawing. 它唯一能做的就是画画。 After you tell it to draw a line from [x,y] to [x 1 ,y 1 ], it draws it, and "forgets" everything. 在你告诉它从[x,y]到[x 1 ,y 1 ]画一条线之后,它会画出它并“忘记”一切。 Each paintEvent() starts painting the widget from scratch. 每个paintEvent()从头开始绘制小部件。 So, to add the elements you will have to redraw the existing ones each time. 因此,要添加元素,您每次都必须重绘现有元素。

Actually I solve my problem using QPainterPath so I can group ellipses to draw 'dynamic' lines: 实际上我使用QPainterPath解决了我的问题所以我可以将椭圆分组以绘制“动态”线:

QPainterPath* p = new QPainterPath(this); //this should be a class attribute to save all points
p->addEllipse(myCustomPoint); //we should add the points dynamically

QPainter painter(this); // On QPainter::paintEvent;
painter.drawPath(p); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM