如何通过QGraphicsProxy调整QGraphicScene中添加的QWidget的大小?

时间:2018-08-26 08:24:14

标签: c++ qt qgraphicsview qgraphicsscene qgraphicsrectitem

我已经通过QGraphicsProxyWidget将小部件添加到图形场景(QGraphicScene)。要移动并选择添加了QGraphicsRectItem句柄的小部件。 要调整窗口小部件的大小,请将QSizegrip添加到窗口小部件。但是当我调整小部件的大小超过QGraphicsRect项时,rect右和底边就落后了。如何解决这个问题? 当我调整窗口小部件图形的大小时,rect项目应调整大小,反之亦然。怎么做?欢迎其他任何想法。 这是代码

     auto *dial= new QDial();                                        // The widget
     auto *handle = new QGraphicsRectItem(QRect(0, 0, 120, 120));    // Created to move and select on scene
     auto *proxy = new QGraphicsProxyWidget(handle);                 // Adding the widget through the proxy

     dial->setGeometry(0, 0, 100, 100);
     dial->move(10, 10);

     proxy->setWidget(dial);

     QSizeGrip * sizeGrip = new QSizeGrip(dial);
     QHBoxLayout *layout = new QHBoxLayout(dial);
     layout->setContentsMargins(0, 0, 0, 0);
     layout->addWidget(sizeGrip, 0, Qt::AlignRight | Qt::AlignBottom);

     handle->setPen(QPen(Qt::transparent));
     handle->setBrush(Qt::gray);
     handle->setFlags(QGraphicsItem::ItemIsMovable | 
     QGraphicsItem::ItemIsSelectable);

     Scene->addItem(handle); // adding to scene 

这是输出::
   调整大小之前
Before Resize 调整大小后 After Resize

1 个答案:

答案 0 :(得分:2)

原因

用作句柄的 QGraphicsRectItem 无法识别 QDial 的大小变化,因此它不会通过调整大小来响应。

限制

QWidget 及其子类无法提供类似sizeChanged信号的信号。

解决方案

考虑原因和给定的限制,我的解决方法是:

  1. Dial 的子索引中,例如 Dial ,添加新信号void sizeChanged();
  2. 重新实现拨号resizeEvent

在dial.cpp

void Dial::resizeEvent(QResizeEvent *event)
{
    QDial::resizeEvent(event);

    sizeChanged();
}
  1. auto *dial= new QDial();更改为auto *dial= new Dial();
  2. Scene->addItem(handle); // adding to scene之后添加以下代码:

您的示例代码所在的地方

connect(dial, &Dial::sizeChanged, [dial, handle](){
        handle->setRect(dial->geometry().adjusted(-10, -10, 10, 10));
    });

注意:也可以使用eventFilter代替子类 QDial 来解决此问题。但是,从您的其他question那里我知道您已经将 QDial 子类化,这就是为什么我发现所建议的解决方案更适合您的原因。

结果

这是提议的解决方案的结果:

before resize

after resize