【问题标题】:Locking view on QGraphicsView在 QGraphicsView 上锁定视图
【发布时间】:2017-11-16 22:21:14
【问题描述】:

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

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

【问题讨论】:

    标签: c++ qt qt5 qgraphicsview qgraphicsscene


    【解决方案1】:

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

    sceneRect : QRectF

    此属性保存场景矩形;的边界矩形 场景

    场景矩形定义场景的范围。它主要是 QGraphicsView 用于确定视图的默认可滚动区域, 并通过 QGraphicsScene 来管理项目索引。

    如果未设置,或者设置为空 QRectF,sceneRect() 将返回 自场景创建以来,场景中所有项目的最大边界矩形 已创建(即,在添加或移动项目时增长的矩形 在场景中,但从不缩小)。

    因此,每次添加新行时,如果它比之前的 QGraphicsScene 大,请尝试适应该大小,给人一种移动中心的感觉。

    例如你的情况:

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

    【讨论】:

    • 有时候就是这么简单!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多