我想在QGraphicswidget中嵌入QWidget,例如按钮或进度条,但是我只看到了将QWidget添加到QGraphicsScene的示例,即

m_scene->addWidget(new QPushButton("Test Test"));


在我的自定义图形小部件中,我正在绘画功能中绘制文本和其他自定义形状。我认为您需要在此处添加QWidget,但我可能错了。有谁知道如何做到这一点?

这是我重载的paint函数:

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方法的结果类似于以下内容:

c&#43;&#43; - 是否可以将QWidget嵌入自定义QGraphicsWidget中?-LMLPHP

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

10-15 07:00