QGraphicsView ensureVisible()和centerOn()

时间:2010-05-25 13:11:47

标签: c++ qt qt4 qgraphicsview

我将在QGraphicsView上进行平移/缩放。
QGraphicsView的文档,并查看了一些实用函数,例如ensureVisible()centerOn()
我想我明白文件说的是什么,但我无法写出一个有效的例子 能否请您写一下示例代码来了解这个问题。

1 个答案:

答案 0 :(得分:3)

将视图平移一定量(例如在视图的mouseMoveEvent()中),假设MyViewQGraphicsView的子类(以下所有代码都是从Python移植的,I没试过它):

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(),直到边界矩形自然“稳定”自己。