c++ - 是否可以在自定义 QGraphicsWidget 中嵌入 QWidget?
问题描述
我想在我的 QGraphicswidget 中嵌入一个 QWidget,例如按钮或进度条,但我只看到了将 QWidget 添加到 QGraphicsScene 的示例,即
m_scene->addWidget(new QPushButton("Test Test"));
在我的自定义图形小部件中,我正在绘制函数中绘制文本和其他自定义形状。我认为您需要在此处添加 QWidget,但我可能错了。有谁知道如何做到这一点?
这是我重载的绘画功能:
void TestWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem
*option, QWidget *widget /*= 0*/)
{
Q_UNUSED(widget);
Q_UNUSED(option);
QRectF frame(QPointF(0,0), geometry().size());
QGradientStops stops;
//Draw border
painter->drawRoundedRect(boundingRect(), 5.0, 5.0);
//Name of the test
painter->drawText(40, 20, m_name);
//Status of test
QFont font = painter->font() ;
font.setPointSize(14);
painter->setFont(font);
painter->drawText(600, 20, m_status);
//Arrow button
QPolygonF poly;
poly << QPointF(5, 10) << QPointF(25, 10) << QPointF(15, 20 )<<
QPointF(5,10);
painter->setBrush(Qt::black);
painter->drawPolygon(poly, Qt::OddEvenFill);
}
解决方案
解决方案
为了在您的QGraphicsWidget子类中嵌入一个小部件,例如QPushButton ,请使用QGraphicsProxyWidget,如下所示:
#include "TestWidget.h"
#include <QGraphicsProxyWidget>
#include <QPushButton>
TestWidget::TestWidget(QGraphicsItem *parent) :
QGraphicsWidget(parent)
{
...
auto *proxy = new QGraphicsProxyWidget(this);
proxy->setWidget(new QPushButton(tr("CLick me")));
proxy->moveBy(20, 40);
...
}
背景
如果你使用m_scene->addWidget(new QPushButton("Test Test"));
,这本质上是相同的:
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget();
proxy->setWidget(new QPushButton("Test Test"));
m_scene->addItem(proxy);
您将QPushButton(通过代理)直接添加到场景中。
如果您想让QPushButton成为您的自定义QGraphicsWidget的一部分,请将QGraphicsProxyWidget的父级设置为自定义QGraphicsWidget的实例。
注意:不需要调用QGraphicsScene::addItem ,因为(由于父/子关系)代理将与您的自定义QGraphicsWidget一起添加到场景中。
结果
使用您的paint
方法,结果与此类似:
推荐阅读
- c# - 如何在 XPath .net 应用程序中按索引选择元素
- python - 将存储为 Azure Blob 的 CSV 直接加载到 Pandas 数据帧中,而无需先保存到磁盘
- angular - 如何使用带条件的 mat 表扩展行
- c# - 标签未显示随机模拟的输出
- spring-boot - 如何使用默认类从 JSON 登录尝试中读取用户凭据?
- android - Android Bluedroid BLE:某些手机没有收到来自 GATT 服务器的通知?
- azure - 将变量传递到 YAML 文件
- django - 将 AWS Elastic 搜索与 VPC 端点 django haystack 一起使用
- python-3.x - 在没有中间浮点数组的情况下将整数 numpy 数组与浮点标量相乘
- dynamics-crm - XrmToolBox 插件注册。从插件代码编辑插件步骤配置