向QGraphicsItem中添加控件
时间: 2023-09-19 07:05:01 浏览: 370
如果你想在Qt的图形界面中向QGraphicsItem中添加控件,可以使用QGraphicsProxyWidget类。它可以将QWidget转换为QGraphicsItem,从而将QWidget添加到QGraphicsScene中。
以下是一个简单的示例代码,演示如何向QGraphicsItem中添加QPushButton控件:
```cpp
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsProxyWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
// 创建一个QGraphicsItem
QGraphicsRectItem item(0, 0, 100, 100);
item.setBrush(Qt::red);
scene.addItem(&item);
// 创建一个QPushButton控件
QPushButton *button = new QPushButton("Click Me!");
// 创建一个QGraphicsProxyWidget,将QPushButton添加到其中
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(&item);
proxy->setWidget(button);
proxy->setPos(10, 10);
view.show();
return app.exec();
}
```
在这个示例中,我们首先创建了一个QGraphicsItem(QGraphicsRectItem),并将其添加到QGraphicsScene中。然后,我们创建了一个QPushButton控件,并使用QGraphicsProxyWidget将其添加到QGraphicsItem中。最后,我们将QGraphicsView显示出来,以便查看结果。
注意:当向QGraphicsItem中添加QWidget时,QWidget的父项应该设置为QGraphicsItem,而不是QGraphicsScene。在本例中,我们将QPushButton的父项设置为QGraphicsItem(QGraphicsRectItem)。
阅读全文
相关推荐
















