在 QGraphicsView 上锁定视图

Locking view on QGraphicsView

我正在创建原理图编辑器,简而言之,用户可以在其中绘制线条和矩形。为此,我使用带有重新实现的事件处理程序的子类 QGraphicsView。 现在,绘制线条时,视图会发生变化,以便将所有绘制线条的中心点放在应用程序的中间 window(我猜?)。这在绘图程序中非常烦人,我该如何解决?

MWE:

#include <QApplication>
#include <QMainWindow>
#include <QGraphicsView>
#include <QMouseEvent>

class view : public QGraphicsView
{
public:
    view(QGraphicsScene* scene, QWidget* parent = 0) : QGraphicsView::QGraphicsView(scene, parent) { }

    void mousePressEvent(QMouseEvent* event)
    {
        static QPointF p;
        static bool active = false;
        if(!active)
        {
            p = mapToScene(event->pos());
            active = true;
        }
        else
        {
            QPointF p2 = mapToScene(event->pos());
            active = false;
            draw_line(p, p2);
        }
    }

    void draw_line(QPointF p1, QPointF p2)
    {
        QPen pen;
        pen.setWidth(2);
        this->scene()->addLine(p1.x(), p1.y(), p2.x(), p2.y(), pen);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QMainWindow w;
    QGraphicsScene* scene = new QGraphicsScene;
    view* mview = new view(scene);
    w.setCentralWidget(mview);
    w.show();

    return a.exec();
}

问题是因为你没有将sceneRect设置为QGraphicsScene,根据docs:

sceneRect : QRectF

This property holds the scene rectangle; the bounding rectangle of the scene

The scene rectangle defines the extent of the scene. It is primarily used by QGraphicsView to determine the view's default scrollable area, and by QGraphicsScene to manage item indexing.

If unset, or if set to a null QRectF, sceneRect() will return the largest bounding rect of all items on the scene since the scene was created (i.e., a rectangle that grows when items are added to or moved in the scene, but never shrinks).

所以每次你添加一个新行,如果它比以前的大QGraphicsScene尝试适应那个大小给人一种移动中心的感觉。

例如你的情况:

view(QGraphicsScene* scene, QWidget* parent = 0) : 
QGraphicsView::QGraphicsView(scene, parent) 
{
    scene->setSceneRect(QRectF(rect()));
    //scene->setSceneRect(0, 0, 640, 480)
}