I'm making an application where I draw an image on a QGraphicsScene and then draw items over the scene in viewport coordinates (as I always want the items to appear in the same place, regardless of transformations of the scene).

In order to accomplish this I created the following subclass of QImageView:

Qt Code:
  1. class ImageView : public QGraphicsView
  2. {
  3. public:
  4. ImageView(QWidget* parent = nullptr)
  5. :QGraphicsView(parent)
  6. {
  7. }
  8.  
  9. protected:
  10. void paintEvent(QPaintEvent* event)
  11. {
  12. QGraphicsView::paintEvent(event);
  13. QPainter painter(viewport());
  14. painter.setPen(QPen(Qt::green));
  15. painter.drawRect(0, 0, 100, 100);
  16. }
  17. };
To copy to clipboard, switch view to plain text mode 

When using the standard viewport, this code works perfectly. However, when I set a QOpenQLWidget as viewport (using "myView->setViewport(new QOpenGLWidget());"), it will no longer paint
the image in the scene, only the green rectangle from the paintEvent. If I comment out the last 3 lines of the paintEvent, the image is drawn normally.

Through a bit of experimentation I learned that creating a QPainter with the QOpenGLWidget, will clear the widget.

As an alternative option I tried creating a class derived from QOpenGLWidget, overriding the paintGL() method (so that it paints the green rectangle) and then setting it as the viewport in a standard QGraphicsView. This didn't work either as the paintGL method is never called when the widget is used as a viewport.

So my questions are simple: Why doesn't the above code work with QOpenGLWidgets and how can I make it work?

To sum it up I need to do the following things:
  • Draw an image on a QGraphicsScene (or anywhere elsewhere I can zoom and translate at will).
  • Draw items over the image at a fixed place (so that they are always visible and not affected by zoom or translation).
  • It is important to note that the things I draw may not be known at compile time (in the actual application I draw a QPicture, which can contain anything).


The code example above is the smallest class I could create where I could recreate the problem, if you need more information please let me know.