Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

qt - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...