如何通过 QGraphics Proxy 调整 QGraphicSscene 添加的 QWidget 的大小?

How to resize QWidget added in QGraphicScene through QGraphicsProxy?

我已经通过 QGraphicsProxyWidget 向图形场景 (QGraphicScene) 添加了一个小部件。移动和 select 小部件添加了 QGraphicsRectItem 句柄。 要调整小部件的大小,请将 QSizegrip 添加到小部件。但是当我调整小部件的大小超过 QGraphicsRect 项目右和底部边缘落后时。如何克服这个问题? 当我调整小部件图形矩形项目的大小时应该调整大小,反之亦然。如何做到这一点? 欢迎任何其他想法。 这是代码

     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 

这是输出::
调整大小前
调整大小后

原因

你用作句柄的QGraphicsRectItem,不知道QDial的大小变化,所以不响应通过调整自身大小。

限制

QWidget 及其子类不提供开箱即用的 sizeChanged 信号。

解决方案

考虑到原因和给定的限制,我的解决方案如下:

  1. QDial 的子类中,说 Dial,添加一个新信号 void sizeChanged();
  2. 像这样重新实现 DialresizeEvent

在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 instead of subclassing QDial. However, from your other 来解决我知道你已经继承了QDial,这就是为什么我找到更适合您的建议解决方案。

结果

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