当图形项目靠边框放置时,使QGraphicsScene更大

问题描述 投票:2回答:2

我用QGraphicsScene制作了一个mouseClickEvent,让用户在其中创建蓝色方块。但是,当项目放置在其边框上时,我希望场景增长,这样用户永远不会耗尽图形场景上的空间。

在这种情况下,使图形场景更大的最佳方法是什么?

c++ qt qgraphicsview
2个回答
4
投票

我建议做类似以下的事情:

  1. 使用QGraphicsScene::itemsBoundingRect()获取场景中所有项目的边界矩形。
  2. 在该矩形周围添加一些填充,以确保项目的边界不会到达视图的边缘。像myRect.adjust(-20, -20, 20, 20)这样的东西应该足够了。
  3. 使用QGraphicsView::fitInView(myRect, Qt::KeepAspectRatio)确保拍摄区域在视图的可见边界内。

应该这样做。只要场景中发生了某些变化,就应该调用此代码。您可以使用QRectF :: intersects()函数来确定新的rect是否已放置在视图的边缘。

在这种情况下,使图形场景更大的最佳方法是什么?

GraphicsScene是一个无限坐标系。大多数客户将使用itemsBoundingRect()来了解场景中项目实际使用了多少空间。如果您已清除场景,则可能需要再次调用QGraphicsScene::setSceneRect(QRectF())以“将其缩小”。

希望有所帮助。


1
投票

对不起,如果这有点晚了(6年)但我会提供一个答案,如果有人仍在努力与此或想要另一种方法。我在mouseReleaseEvent实现这个自定义类来自QGraphicsObject。请注意,我使用以下code.QGraphicsScene初始化我的scene->setSceneRect(0,0,1000,1000)(1000,1000)的大小。所以我的代码将在这里做。如果项目(项目可拖动)放置在边框上,则该边框将增加。所以这是我的代码:

void MyItem::mouseReleaseEvent(QgraphicsceneMouseEvent* event){
  QRectF tempRect = this->scene()->sceneRect();
  if(this->scenePos().y() < this->scene()->sceneRect().top()){
      tempRect.adjust(0,-200,0,0);
      if(this->scenePos().x() < this->scene()->sceneRect().left()){
          tempRect.adjust(-200,0,0,0);
      }
      else if(this->scenePos().x() + 200> this->scene()->sceneRect().right()){
        tempRect.adjust(0,0,200,0);
      }
  }
  else if(this->scenePos().y() + 200 > this->scene()->sceneRect().bottom()){
      tempRect.adjust(0,0,0,200);
      if(this->scenePos().x() < this->scene()->sceneRect().left()){
          tempRect.adjust(-200,0,0,0);
     }
     else if(this->scenePos().x() + 200> this->scene()->sceneRect().right()){
        tempRect.adjust(0,0,200,0);
     }
 }
 else if(this->scenePos().x() < this->scene()->sceneRect().left()){
      tempRect.adjust(-200,0,0,0);
      if(this->scenePos().y() < this->scene()->sceneRect().top()){
          tempRect.adjust(0,-200,0,0);
      }
      else if(this->scenePos().y() + 200 > this->scene()->sceneRect().bottom()){
          tempRect.adjust(0,0,0,200);
      }
  }
  else if(this->scenePos().x() + 200> this->scene()->sceneRect().right()){
      tempRect.adjust(0,0,200,0);
      if(this->scenePos().y() < this->scene()->sceneRect().top()){
          tempRect.adjust(0,-200,0,0);
      }
      else if(this->scenePos().y() + 200 > this->scene()->sceneRect().bottom()){
          tempRect.adjust(0,0,0,200);
      }
  }

  this->scene()->setSceneRect(tempRect);
© www.soinside.com 2019 - 2024. All rights reserved.