Paint/Draw on top of docked widgets in QDodckWidget

I have a class in Qt that inherits QDockWidget. And that class contains another widget. Is there any possibility to define a function in my QDockWidget inherited class that draws stuff on top of the contained widget? Like the painting to be independent of the contained widget but to be linked to the inherited class.

Thank you


Sure it's possible. It is fairly simple to do, in fact. You need to place a child widget that sits on top of everything else in your QDockWidget. To do it so, it must be the last child widget you add to your dockwidget. That widget must not to draw its background, and it can then draw over any children of the dockwidget. The widget's size must track the size of the parent widget.

Below is a self-contained example.

Screenshot 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 {
protected:
   void paintEvent(QPaintEvent *) override {
        QPainter p(this);
        p.setRenderHint(QPainter::Antialiasing);
        p.drawLine(rect().topLeft(), rect().bottomRight());
    }
public:
    explicit Line(QWidget *parent = nullptr) : QWidget(parent) {
       setAttribute(Qt::WA_TransparentForMouseEvents);
    }
};

class Window : public QWidget {
    QHBoxLayout layout{this};
    QPushButton left{"Left"};
    QLabel right{"Right"};
    Line line{this};
protected:
    void resizeEvent(QResizeEvent *) override {
        line.resize(size());
    }
public:
    explicit Window(QWidget *parent = nullptr) : QWidget(parent) {
        layout.addWidget(&left);
        right.setFrameStyle(QFrame::Box | QFrame::Raised);
        layout.addWidget(&right);
        line.raise();
    }
};

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