如何将 QGraphicsView 锚定到场景中的特殊点?
我想要一个 view 的中心锚定到 scene 点 (0,0)。
但正如文档中所说:
If the whole scene is visible in the view, (i.e., there are no visible scroll bars,) the view's alignment will decide where the scene will be rendered in the view.
如果我将 agnment 设置为 Qt::AlignCenter view 将锚定到 scene 中心。
可以吗?
我需要像 QGraphicsView::centerOn 这样的东西,它总是把点放在 View 中心。
最佳答案
您可以通过定义(“强制”)它的 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!
这应该可以解决问题。
关于qt - 如何将 QGraphicsView 锚定到场景上的特殊点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4022907/