jdepypere
jdepypere

Reputation: 3553

QT Display a QWidget above QGraphicsScene

Currently I have a QGraphicsScene that is put inside a QGraphicsView and is shown on the display. I add all my elements to my scene that I set as the active scene.

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsView w;
    GameScene *gameScene = new GameScene(); // GameScene extends QGraphicsScene, adds tons of elements to the scene
    w.setScene(gameScene);
    w.show();
    return a.exec();
}

Above this scene I want a bar that contains several layout elements, like several QProgressBar.

For what I have found so far, QWidget's can be positioned easily. I've made already a widget of what I need to be displayed above the scene:

QWidget *dummyWidget = new QWidget();
QFormLayout *formLayout = new QFormLayout;
QProgressBar *bar1 = new QProgressBar();
QProgressBar *bar2 = new QProgressBar();
bar1->setValue(20);
bar2->setValue(100);
formLayout->addRow("&Health:", bar1);
formLayout->addRow("&Energy:", bar2);
dummyWidget->setLayout(formLayout);
dummyWidget->show();

Health- and energy bars

But how do I get this to be displayed above my QGraphicsScene?

Upvotes: 2

Views: 1539

Answers (1)

Nejat
Nejat

Reputation: 32695

If you want to display your widget above the view you can have a layout similar to the one for dummyWidget and add the widget and view in it :

    QGraphicsView w;

    QWidget *widget = new QWidget();
    QFormLayout *formLayout2 = new QFormLayout(widget);

    QWidget *dummyWidget = new QWidget();
    QFormLayout *formLayout = new QFormLayout;
    QProgressBar *bar1 = new QProgressBar();
    QProgressBar *bar2 = new QProgressBar();
    bar1->setValue(20);
    bar2->setValue(100);
    formLayout->addRow("&Health:", bar1);
    formLayout->addRow("&Energy:", bar2);
    dummyWidget->setLayout(formLayout);

    formLayout2->addRow("", dynamic_cast<QWidget*>(dummyWidget));
    formLayout2->addRow("", dynamic_cast<QWidget*>(&w));

    widget->show();

If you want to add the widget in the scene, you can use QGraphicsScene::addWidget which creates a new QGraphicsProxyWidget for widget, adds it to the scene, and returns a pointer to the proxy :

QGraphicsProxyWidget * item = gameScene->addWidget(dummyWidget);
item->setPos(100,100);
item->setZValue(1);

You can also add it to an item :

item->setParentItem(anOtherItem);

Upvotes: 1

Related Questions