QT在QGraphicsScene上方显示QWidget

时间:2014-11-29 11:33:16

标签: c++ qt c++11 qgraphicsscene

目前我有QGraphicsScene放在QGraphicsView内,并显示在屏幕上。我将所有元素添加到我设置为活动场景的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();
}

在这个场景之上,我想要一个包含多个布局元素的栏,比如几个QProgressBar

对于我到目前为止所发现的内容,可以轻松定位QWidget。我已经制作了一个我需要在场景上方显示的小部件:

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

但是如何让它显示在QGraphicsScene上方?

1 个答案:

答案 0 :(得分:1)

如果要在视图上方显示窗口小部件,可以使用类似于dummyWidget的布局,并在其中添加窗口小部件和视图:

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

如果要在场景中添加窗口小部件,可以使用QGraphicsScene::addWidget为窗口小部件创建新的QGraphicsProxyWidget,将其添加到场景中,并返回指向代理的指针:

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

您也可以将其添加到项目中:

item->setParentItem(anOtherItem);