简体   繁体   English

如何仅在特定事件之后使用 QPainter 进行绘画?

[英]How to paint with QPainter only after a specific event?

I have a main window with some widgets on it, each needs its own graphic.我有一个主 window 上面有一些小部件,每个小部件都需要自己的图形。 I would like to use QPainter to draw shapes, lines, etc. on them, but only after a specific event, like the press of a button.我想使用 QPainter 在它们上绘制形状、线条等,但只能在特定事件之后,比如按下按钮。

The problem is, if I just create a QPainter in any function, it won't work:问题是,如果我只是在任何 function 中创建 QPainter,它将无法正常工作:

QPainter::setPen: Painter not active

The QPainter methods can only be called inside a paintEvent(QPaintEvent *) function: This raises the following problems: QPainter 方法只能在paintEvent(QPaintEvent *) function 内部调用:这会引发以下问题:

  1. I have to derive my custom classes for all the widgets I would like to paint on, so I can't use the Designer to place my widgets.我必须为我想要绘制的所有小部件派生我的自定义类,所以我不能使用设计器来放置我的小部件。 This can get frustrating with a large number of widgets.使用大量小部件可能会令人沮丧。

  2. The widgets redraw themselves after each paint event of the window, like moving it around, or moving other windows in front of it.小部件在 window 的每个绘制事件之后重新绘制自己,例如移动它,或移动它前面的其他 windows。 I do a lot of drawing in those widgets, so they will visibly blink in these cases.我在这些小部件中做了很多绘图,所以在这些情况下它们会明显闪烁。

Is there a better and simpler way to solve this?有没有更好更简单的方法来解决这个问题? I started to think about just displaying images, and re-manufacturing those images only when the specific buttons are pressed.我开始考虑只显示图像,并仅在按下特定按钮时重新制造这些图像。 I doubt that it's the most elegant solution...我怀疑这是最优雅的解决方案......

You can use custom widgets in the designer: Creating Custom Widgets for Qt Designer .您可以在设计器中使用自定义小部件:为 Qt 设计器创建自定义小部件

Qt Designer's plugin-based architecture allows user-defined and third party custom widgets to be edited just like you do with standard Qt widgets. Qt Designer 基于插件的体系结构允许编辑用户定义和第三方自定义小部件,就像使用标准 Qt 小部件一样。

For your second question, one of the approaches is to create a QPixmap for each of your widgets.对于第二个问题,其中一种方法是为每个小部件创建一个QPixmap When your widget's appearance needs to be changed, you draw in that pixmap (using QPainter 's constructor that takes a QPaintDevice - QPixmap is a QPaintDevice ).当您的小部件的外观需要更改时,您可以绘制该像素图(使用QPainter的构造函数,该构造函数采用QPaintDevice - QPixmapQPaintDevice )。

In your widget's paintEvent function, you simply fill your widget with that "cache" pixmap.在您的小部件的paintEvent function 中,您只需使用该“缓存”像素图填充您的小部件。 This way, you only do the (potentially expensive) painting when it's actually necessary.这样,您只在实际需要时才进行(可能很昂贵)的绘画。

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

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