So, for example, if I had another function that was responsible for drawing a diagonal line across the widget, I could do something along the lines of
No. You cannot do any drawing to the screen in Qt outside of the paintEvent() (or a function called while inside paintEvent()) of the QWidget in which you want to do the drawing (unless you have a custom QPaintEngine, which you will likely never have).
QPainter(viewport());
To copy to clipboard, switch view to plain text mode
There is no such QPainter constructor that simply takes a rect as an argument. QPainter always renders its output to a QPaintDevice instance you give it as a constructor argument, and the only place you can construct a QPainter to render to the screen is inside of the QWidget's paintEvent().
You are never dependent on drawForeground() or drawBackground() if all you are drawing to the screen are QGraphicsItems added to a QGraphicsScene. These two functions exist only to provide you a "hook" into QGraphicView's paintEvent() processing so that you can draw things before the QGraphicsScene is rendered (drawBackground()) or after the scene is rendered (drawForeground()). The widget is a sandwich - background bread on the bottom, scene meat in the middle, and foreground bread on the top. If you just have meat, then you can omit the bread.
Everything (background, scene, forground) is redrawn with every paintEvent(). The QPaintEvent::rect() and QPaintEvent::region() methods give you the part of the widget that needs to be repainted so you don't have to repaint the entire thing if your painting is complex. In most cases, most widgets repaint everything all the time because their painting needs are simple.
a.drawLine(0,0,viewport()->rect().x(),viewport()->rect().y());
a.drawLine(0,0,viewport()->rect().x(),viewport()->rect().y());
To copy to clipboard, switch view to plain text mode
Even if you could do this, this code would not give you a diagonal line, it would give you a dot in the top left corner. (0, 0) is top left, and x() and y() return the left (0) and top (0) coordinates, respectively.
Bookmarks