gpt4 book ai didi

c++ - 是否可以在自定义 QGraphicsWidget 中嵌入 QWidget?

转载 作者:行者123 更新时间:2023-11-28 04:34:10 25 4
gpt4 key购买 nike

我想在我的 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);
}

最佳答案

解决方案

为了嵌入一个小部件,例如QPushButton,在您的 QGraphicsWidget 子类中使用 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"));,就是essentially the same作为:

QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget();

proxy->setWidget(new QPushButton("Test Test"));
m_scene->addItem(proxy);

您将QPushButton(通过代理)直接添加到场景

如果您想让QPushButton成为您的自定义QGraphicsWidget部分,请设置QGraphicsProxyWidget的父级> 到自定义 QGraphicsWidget 的实例。

注意:无需调用QGraphicsScene::addItem,因为(由于父/子关系)代理将与您的自定义 QGraphicsWidget


结果

使用您的paint 方法,结果类似于:

enter image description here

关于c++ - 是否可以在自定义 QGraphicsWidget 中嵌入 QWidget?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51993096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com