假设MyView 是QGraphicsView 的子类,将视图平移一定量(例如在您的视图的mouseMoveEvent() 中)(以下所有代码都是从Python 移植的,我没有测试它) :
void MyView::moveBy(QPoint &delta)
{
QScrollBar *horiz_scroll = horizontalScrollBar();
QScrollBar *vert_scroll = verticalScrollBar();
horiz_scroll->setValue(horiz_scroll.value() - delta.x());
vert_scroll->setValue(vert_scroll.value() - delta.y());
}
通过缩放和平移来适应场景坐标中指定的矩形:
void MyView::fit(QRectF &rect)
{
setSceneRect(rect);
fitInView(rect, Qt::KeepAspectRatio);
}
请注意,如果您的场景包含不可变形的项目(设置了QGraphicsItem::ItemIgnoresTransformations 标志),您将不得不采取额外的步骤来计算它们的正确边界框:
/**
* Compute the bounding box of an item in scene space, handling non
* transformable items.
*/
QRectF sceneBbox(QGraphicsItem *item, QGraphicsItemView *view=NULL)
{
QRectF bbox = item->boundingRect();
QTransform vp_trans, item_to_vp_trans;
if (!(item->flags() & QGraphicsItem::ItemIgnoresTransformations)) {
// Normal item, simply map its bounding box to scene space
bbox = item->mapRectToScene(bbox);
} else {
// Item with the ItemIgnoresTransformations flag, need to compute its
// bounding box with deviceTransform()
if (view) {
vp_trans = view->viewportTransform();
} else {
vp_trans = QTransform();
}
item_to_vp_trans = item->deviceTransform(vp_trans);
// Map bbox to viewport space
bbox = item_to_vp_trans.mapRect(bbox);
// Map bbox back to scene space
bbox = vp_trans.inverted().mapRect(bbox);
}
return bbox;
}
在这种情况下,您的对象的边界矩形取决于视图的缩放级别,这意味着有时MyView::fit() 不会完全适合您的对象(例如,当从大幅缩小的视图中选择对象时)。一个快速而肮脏的解决方案是反复调用MyView::fit(),直到边界矩形自然“稳定”自身。