为什么我不能放大QSizeGrip添加到QGraphicScene的小部件?

时间:2018-08-28 14:56:03

标签: c++ qt qgraphicsview qgraphicsscene qgraphicsrectitem

我已经通过QGraphicsProxyWidget向图形场景 QGraphicScene 中添加了一个小部件。为了移动它,我将 QGraphicsRectitem 设置为其父级。使用sizegrip调整窗口小部件的大小。

第一次创建对象时,可以将其放大到某个尺寸。第二次我可以将其放大到小于第一次。第三次少于第二次,依此类推。

在我看来,它的行为是随机的。为什么会这样?

代码如下:

void GraphicsView::dropEvent(QDropEvent *event)// subclass of QGraphicsView
{

  if(event->mimeData()->text() == "Dial")
  {
   auto *dial= new Dial;      // The widget
   auto *handle = new QGraphicsRectItem(QRect(event->pos().x(),event->pos().y(), 120, 120));    // Created to move and select on scene
   auto *proxy = new QGraphicsProxyWidget(handle); // Adding the widget through the proxy
   dial->setGeometry(event->pos().x()+10,event->pos().y()+10, 100, 100);
   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 

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

code

我不能将小部件放大得更多,如图所示。

1 个答案:

答案 0 :(得分:1)

您的拨号不能调整大小超出GraphicView的右侧(水平)和底部(垂直)边缘。如果场景足够大,例如2000x2000(setSceneRect(2000, 2000);),将显示滚动条。如果您手动移动滚动条,则将能够进一步放大小部件。

您还可以通过更改lambda函数来尝试自动滚动条移动:

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

    int dx = handle->rect().bottomRight().x() > viewport()->rect().bottomRight().x();
    int dy = handle->rect().bottomRight().y() > viewport()->rect().bottomRight().y();

    if (dx > 0) {
        horizontalScrollBar()->setValue(horizontalScrollBar()->value() + dx);
    }

    if (dy > 0) {
        verticalScrollBar()->setValue(verticalScrollBar()->value() + dy);
    }
});

请注意,尽管此代码有效,但非常麻烦。但是,它可以让您了解如何开始。