- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 309字
- 2021-08-27 18:31:08
Widgets inside Graphics View
In order to show a neat feature of Graphics View, take a look at the following code snippet, which adds a widget to the scene:
QSpinBox *box = new QSpinBox; QGraphicsProxyWidget *proxyItem = new QGraphicsProxyWidget; proxyItem->setWidget(box); scene()->addItem(proxyItem); proxyItem->setScale(2); proxyItem->setRotation(45);
First, we create a QSpinBox and a QGraphicsProxyWidget element, which act as containers for widgets and indirectly inherit QGraphicsItem. Then, we add the spin box to the proxy widget by calling addWidget(). When QGraphicsProxyWidget gets deleted, it calls delete on all assigned widgets, so we do not have to worry about that ourselves. The widget you add should be parentless and must not be shown elsewhere. After setting the widget to the proxy, you can treat the proxy widget like any other item. Next, we add it to the scene and apply a transformation for demonstration. As a result, we get this:
Be aware that, originally, Graphics View wasn't designed for holding widgets. So when you add a lot of widgets to the scene, you will quickly notice performance issues, but in most situations, it should be fast enough.
If you want to arrange some widgets in a layout, you can use QGraphicsAnchorLayout, QGraphicsGridLayout, or QGraphicsLinearLayout. Create all widgets, create a layout of your choice, add the widgets to that layout, and set the layout to a QGraphicsWidget element, which is the base class for all widgets and is, easily spoken, the QWidget equivalent for Graphics View by calling setLayout():
QGraphicsProxyWidget *edit = scene()->addWidget( new QLineEdit(tr("Some Text"))); QGraphicsProxyWidget *button = scene()->addWidget( new QPushButton(tr("Click me!"))); QGraphicsLinearLayout *layout = new QGraphicsLinearLayout; layout->addItem(edit); layout->addItem(button); QGraphicsWidget *graphicsWidget = new QGraphicsWidget; graphicsWidget->setLayout(layout); scene()->addItem(graphicsWidget);
The scene's addWidget() function is a convenience function and behaves similar to addRect, as shown in the following code snippet:
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0); proxy->setWidget(new QLineEdit(QObject::tr("Some Text"))); scene()->addItem(proxy);
The item with the layout will look like this: