Search code examples
c++qtqgraphicsviewqlayout

Qt - Making a panel that overlaps a QGraphicsView


I am trying to make a panel that shows some data, that gets added when I press a button. I will explain it trough these images:

this would be the initial state of the app, a window with a QGraphicsViewThis would be the initial state of the app

if I click "Help" it should display a window above it that never goes out of focusenter image description here

I looked into using QDockWidget, but that just creates a panel next to it, that that's not what I Want. If anyone knows how to do this, I would be very grateful, thanks.


Solution

  • You can set children widgets in your QGraphicsView and consider it like a regular QWidget:

        QApplication app(argc, argv);
        QGraphicsScene* scene = new QGraphicsScene(0, 0, 1000, 1000);
        QGraphicsView* view = new QGraphicsView(scene);
        view->show();
    
        QPushButton* button = new QPushButton("Show label");
        QLabel* label = new QLabel("Foobar");
        QVBoxLayout* layout = new QVBoxLayout(view);
        layout->setAlignment(Qt::AlignRight | Qt::AlignTop);
        layout->addWidget(button);
        layout->addWidget(label);
        label->hide();
        QObject::connect(button, &QPushButton::clicked, label, &QLabel::show);
        return app.exec();
    

    The label will be visible in the QGraphicsView when you click on the button.

    You can also embed a widget in your scene with QGraphicsProxyWidget class:

        QApplication app(argc, argv);
        QGraphicsScene* scene = new QGraphicsScene(0, 0, 1000, 1000);
        scene->addItem(new QGraphicsRectItem(500, 500, 50, 50));
        QGraphicsView* view = new QGraphicsView(scene);
        view->show();
    
        QWidget* w = new QWidget();
        QGraphicsProxyWidget* proxy = new QGraphicsProxyWidget();
    
    
        QPushButton* button = new QPushButton("Show label");
        QLabel* label = new QLabel("Foobar");
        QVBoxLayout* layout = new QVBoxLayout(w);
        layout->addWidget(button);
        layout->addWidget(label);
        layout->setAlignment(Qt::AlignRight | Qt::AlignTop);
        label->hide();
        QObject::connect(button, &QPushButton::clicked, label, &QLabel::show);
    
        proxy->setWidget(w);
        scene->addItem(proxy);
        return app.exec();