View Full Version : Painting on QMdiArea

3rd October 2018, 22:27
From some messages I've read, I believe it's possible to paint directly onto a QMdiArea, but obviously I am not doing it right. This is not surprising since my C++ skills are very limited.
In Qt Creator I have added a QMdiArea called mdiArea_test inside a QWidget. I try to draw an ellipse and a rectangle + text within mdiArea_test with the following code, but it does not generate anything:

QBrush brush;
QPainter painter(mdiArea_test->viewport());
// do paint operations
QRect rect = QRect(0, 0, 20, 20);
painter.drawText(rect, Qt::AlignCenter, "Data");

I would be grateful if somebody could show me my mistake(s).


3rd October 2018, 23:17
If this code is anywhere except inside the paintEvent() for the class you have derived from QMdiArea, it will have no effect. The only time you can paint on a QWidget of any sort is when you are inside the QWidget::paintEvent().

3rd October 2018, 23:38
I was wondering about that. I am not using paintEvent(), mdiArea_test was added to my form from the menu in Qt Creator. This is a convenient way to define an area to paint within. I'm looking for the simplest way to add some simple 2D graphics - is there a way to paint to an intermediary that is somehow attached to mdiArea_test?
Thanks for your help.

4th October 2018, 17:03
is there a way to paint to an intermediary that is somehow attached to mdiArea_test?

Only if "mdiArea_test" or the intermediary is your own class, derived from QWidget, and you do the painting inside the paintEvent() for that class.

The only exception to this rule is if you are "painting" to a QBitmap, QPixmap, or QImage. This can be done anywhere, but in order to get it to appear on the screen is to paint the bitmap in a paintEvent() using QPainter::drawPixmap().

You can also construct a QPainterPath anywhere, but again, in order to show it on screen, it hase to be done in a paintEvent() using QPainter::drawPath().

For example, you could create a QPixmap, use QPainter to draw on it, and then set that pixmap on a QLabel. QLabel::setPixmap() Setting the pixmap causes the label to repaint itself, which it does in its own paintEvent(). So if you can use a QLabel as your "intermediary", then that is one way to accomplish painting outside of a paintEvent().

Basically, in all modern graphics systems there is no more "immediate mode" painting where you can draw onscreen any time you want. Everything that occurs is under the control of an "event loop", and it is a paint event inserted into the list of things to be processed by the loop that determines when the display changes.