Paint / Draw on top of attached widgets in QDodckWidget

I have a class in Qt that inherits QDockWidget. And this class contains another widget. Is it possible to define a function in my inherited QDockWidget class that draws material on top of the contained widget? Like a picture that does not depend on the widget it contains, but should be associated with an inherited class.

thank

+5
source share
2 answers

Of course it is possible. This is actually quite simple. You need to place a child widget that sits on top of everything else in yours QDockWidget. To do this, it must be the last child widget that you add to your dock widget. This widget does not have to draw its own background, and it can then draw all the children of the dock widget. The widget size should track the size of the parent widget.

The following is a self-sufficient compiled example.

Screenshots of the example

// https://github.com/KubaO/stackoverflown/tree/master/questions/overlay-line-11034838
#include <QtGui>
#if QT_VERSION > QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif

class Line : public QWidget {
    void paintEvent(QPaintEvent *) override {
        QPainter p{this};
        p.setRenderHint(QPainter::Antialiasing);
        p.drawLine(rect().topLeft(), rect().bottomRight());
    }
public:
    using QWidget::QWidget;
};

class Window : public QWidget {
    QHBoxLayout layout{this};
    QLabel left{"Left", this};
    QLabel right{"Right", this};
    Line line{this};

    void resizeEvent(QResizeEvent *) override {
        line.setGeometry(rect());
    }
public:
    Window(QWidget * parent = nullptr) : QWidget{parent} {
        left.setFrameStyle(QFrame::Box | QFrame::Raised);
        layout.addWidget(&left);
        right.setFrameStyle(QFrame::Box | QFrame::Raised);
        layout.addWidget(&right);
    }
};

int main(int argc, char *argv[])
{
    QApplication app{argc, argv};
    Window w;
    w.show();
    return app.exec();
}
+8
source

AFAIK: No.

Widgets are drawn in order of depth, so no matter what your class drawings QDockWidgetare drawn by the contained widgets when they are updated (immediately after that, no doubt, because the color updates apply to child widgets).

0

All Articles