我用QGraphicsScene
制作了一个mouseClickEvent
,让用户在其中创建蓝色方块。但是,当项目放置在其边框上时,我希望场景增长,这样用户永远不会耗尽图形场景上的空间。
在这种情况下,使图形场景更大的最佳方法是什么?
我建议做类似以下的事情:
QGraphicsScene::itemsBoundingRect()
获取场景中所有项目的边界矩形。myRect.adjust(-20, -20, 20, 20)
这样的东西应该足够了。QGraphicsView::fitInView(myRect, Qt::KeepAspectRatio)
确保拍摄区域在视图的可见边界内。应该这样做。只要场景中发生了某些变化,就应该调用此代码。您可以使用QRectF :: intersects()函数来确定新的rect是否已放置在视图的边缘。
在这种情况下,使图形场景更大的最佳方法是什么?
GraphicsScene是一个无限坐标系。大多数客户将使用itemsBoundingRect()
来了解场景中项目实际使用了多少空间。如果您已清除场景,则可能需要再次调用QGraphicsScene::setSceneRect(QRectF())
以“将其缩小”。
希望有所帮助。
对不起,如果这有点晚了(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);