1
votes

I'm creating a schematics edit where, simply put, the user can draw lines and rectangles. For this i am using a subclassed QGraphicsView with reimplemented event handlers. Now, when drawing lines, the view shifts in order to put the centerpoint of all drawn lines together in the middle of the application window (i guess?). For this is very annoying in a drawing program, how can i fix this?

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();
}
1

1 Answers

2
votes

The problem is caused because you have not set sceneRect to QGraphicsScene, according to the 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).

So every time you add a new line if it is larger than the previous QGraphicsScene try to adapt to that size giving the feeling that is moving the center.

For example in your case:

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