是否可以将QWidget嵌入自定义QGraphicsWidget内?

时间:2018-08-23 19:33:56

标签: 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);   
}

1 个答案:

答案 0 :(得分:1)

解决方案

为了嵌入小部件,例如 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