I have a main window with some widgets on it, each needs its own graphic. 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.
The problem is, if I just create a QPainter in any function, it won’t work:
QPainter::setPen: Painter not active
The QPainter methods can only be called inside a paintEvent(QPaintEvent *) function! This raises the following problems:
-
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.
-
The widgets redraw themselves after each paint event of the window, like moving it around, or moving other windows in front of it. 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.
For your second question, one of the approaches is to create a
QPixmapfor each of your widgets. When your widget’s appearance needs to be changed, you draw in that pixmap (usingQPainter‘s constructor that takes aQPaintDevice–QPixmapis aQPaintDevice).In your widget’s
paintEventfunction, you simply fill your widget with that “cache” pixmap. This way, you only do the (potentially expensive) painting when it’s actually necessary.