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

标签 c++ qt qt5 qgraphicsscene qgraphicswidget

我想在我的 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/

相关文章:

c++ - 在 QAbstractItemModel 中包装 QStringListModel 呈现一个空白列表

c++ - QDoubleSpinBox 在值和显示之间进行缩放

c++ - 简化简单的 C++ 代码——类似于 Pythons any

c++ - Valgrind 在程序出现段错误之前就以 "pure virtual method called"中止

c++ - 使 QString 数据字节无效

c++ - Qt5 WebKit 未检测到 NPAPI 插件

c++ - Qt 设计师和创造者

c++ - GDI+:如何用红色像素替换黑色像素?

c++ - 模板 vector

c++ - 使用 Qt 和 QNetworkRequest 恢复失败的 HTTP 下载