【问题标题】:How to anchor QGraphicsView to a special point on a scene?如何将 QGraphicsView 锚定到场景上的特殊点?
【发布时间】:2012-06-22 08:12:54
【问题描述】:

如何将 QGraphicsView 锚定到场景中的特殊点?

我想要一个 view 的中心锚定到 scene 点 (0,0)。

但正如文档中所说:

如果整个场景在 视图,(即,没有可见的 滚动条,)视图的对齐方式 将决定场景的位置 呈现在视图中。

如果我将 agnment 设置为 Qt::AlignCenter view 将锚定到 scene 中心。

可以吗?

我需要像 QGraphicsView::centerOn 这样的东西,它总是把点放在视图中心。

【问题讨论】:

    标签: qt qt4


    【解决方案1】:

    您可以通过定义(“强制”)它的 sceneRect 属性一个 QGraphicsView 在特定位置,而不是默认属性(即 QGraphicsScene 边界矩形)。

    http://qt-project.org/doc/qt-4.8/qgraphicsview.html#sceneRect-prop

    这是一个代码示例。 view 以点 (0,0) 为中心,与边界矩形场景或 centerOn 函数无关。

    #include <QGraphicsView>
    #include <QGraphicsScene>
    #include <QGraphicsRectItem>
    #include <QGraphicsEllipseItem>
    #include <QDebug>
    
    //...
    
    QGraphicsScene scene;
    QGraphicsView view(&scene);
    
    QRect viewRect(-100, -100, 200, 200);
    view.setSceneRect(viewRect);
    qDebug() << viewRect.center(); //QPointF(0,0)
    
    scene.addEllipse(-5,-5,10,10);
    qDebug() << scene.sceneRect(); //QRectF(-5,-5 10x10)
    scene.addRect(QRectF(0, 0, 200, 200));
    qDebug() << scene.sceneRect(); //QRectF(-5,-5 205x205)
    
    view.show();
    
    view.centerOn(QPointF(50, 50)); //nothing happens!
    

    这应该可以解决问题。

    【讨论】:

      【解决方案2】:

      您可以设置alignment property 来实现这一点。

      【讨论】:

      • 使用AlignmentCenter,整个场景将在视图中居中。但没有什么特别之处。
      • 说特殊点是指场景中QGraphicsItem的点?就我而言,视图无法管理场景内的对象。
      • 尝试使用 setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff ) 关闭滚动条,水平滚动条也是如此。如果仍有问题,请尝试确保场景始终大于视图区域。
      • “尝试确保场景始终大于视图区域”我认为这是不可能的,因为您始终可以缩小以使场景更小。
      猜你喜欢
      • 2021-08-24
      • 2023-03-12
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 2011-10-17
      • 2023-03-06
      相关资源
      最近更新 更多