我将在QGraphicsView上进行平移/缩放。
所以我阅读了QGraphicsView的文档并看到了一些实用功能,例如ensureVisible()和centerOn()。
我想我理解文档所说的内容,但我无法编写一个有效的示例。
你能否写/建议我一个示例代码来理解这个问题。
问问题
3836 次
1 回答
3
将视图平移一定量(例如在您的视图中mouseMoveEvent()
),假设MyView
是QGraphicsView
(以下所有代码都是从 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()
,直到边界矩形自然“稳定”自身。
于 2010-05-25T23:17:24.900 回答