I am trying to do a painting program with QT 4.5, so I am using the QGraphicsView for the canvas, and QGraphicsScene to store the items drawn. For some reasons, I just couldn’t get a QPainter context in my own derived QGraphicsView
class DrawingCanvas : public QGraphicsView
{
DrawingCanvas::DrawingCanvas(QWidget * parent);
...
};
DrawingCanvas::DrawingCanvas(QWidget * parent = 0) : QGraphicsView(parent)
{
....
}
void DrawingCanvas::paintEvent(QPaintEvent& paintEventInfo)
{
// Result in painter not active
QPainter(this);
...
}
However, if I change the DrawingCanvas to be a child of QWidget, it works. Seeing that QGraphicsView is derived from QAbstractScrollArea, then QFrame, then QWidget, I would expecting that the code would work.
So I guess the questions are:
1) Why is that I can’t use paintEvent in a QGraphicsView to get a active QPainter?
2) Is there possible I could get one?
Thanks in advance!
If anyone still is wondering if this somehow is possible, the answer is yes.
Short version
Long version
QGraphicsScene does no painting on itself but instead paints on the viewport widget you give it or by default a QWidget.
By painting on the viewport instead you can achieve overlayed painting that will be aligned to the view and not the scene. Alternatively you could use QGlWidget and its paintOverlayGl().
Also remember to set viewportUpdateMode(QGraphicsView::FullViewportUpdate) or you will get rendering artifacts. There might be a smarter way to avoid artifacts than to update the entire view every time but until I encounter performance problems I will let it rest.