【问题标题】:Update QGraphicsLineItem correctly正确更新 QGraphicsLineItem
【发布时间】:2020-04-29 20:19:44
【问题描述】:

我正在尝试使用 QGraphicsScene 中的 mouseEvent 函数绘制一条线,当我按下鼠标按钮并在场景上移动时,该线应该从左上角 [0,0] 开始从我按下鼠标按钮的地方开始,但是当我释放并再次执行该操作时,线条正常绘制,这种行为的原因是什么以及如何解决它?


这里是完整的代码:

Scene.h:

#ifndef SCENE_H
#define SCENE_H

#include <QGraphicsScene>
#include <QGraphicsLineItem>
#include <QGraphicsSceneMouseEvent>

class Scene : public QGraphicsScene
{

public:
    Scene();

private:
    QGraphicsLineItem* line;
    QPointF startPoint;

protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
};

#endif // SCENE_H

Scene.cpp:

#include "Scene.h"

Scene::Scene() : startPoint(0,0)
{
    line = new QGraphicsLineItem();
    this->addItem(line);
}

void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    startPoint = event->scenePos();
}

void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    qreal x = event->scenePos().x();
    qreal y = event->scenePos().y();
    line->setLine(startPoint.x(),startPoint.y(),x,y);
}

主要:

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include "Scene.h"

int main(int argc,char* argv[])
{
    QApplication app(argc,argv);
    Scene scene;
    QGraphicsView view(&scene);
    view.setMinimumSize(800,600);
    view.setAlignment(Qt::AlignLeft|Qt::AlignTop);
    view.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    view.show();
    return app.exec();
}

【问题讨论】:

    标签: c++ qt qgraphicsscene


    【解决方案1】:

    这个问题是因为QGraphicsScene对象没有用边界框初始化。在构造函数中使用

    Scene::Scene() : QGraphicsScene(0, 0, 400, 400), startPoint(0,0)
    

    (例如),它将按预期工作。

    如果您不这样做,在第一次单击时,场景坐标将重新定位,以便您的线的起始坐标(例如,(x0, y0))将是左上角的场景坐标。因此,如果您稍微移动鼠标,例如到(x0+1,y0),实际场景坐标变为(2*x0+1,2*y0)

    此外,最好在重载事件处理程序结束时调用父类的事件处理程序。

    最后,这可能会有所帮助: https://www.walletfox.com/course/qgraphicsitemruntimedrawing.php

    【讨论】:

    • ... 另请参阅QGraphicsScenesceneRect 属性。
    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 2012-12-05
    • 1970-01-01
    • 2021-11-03
    • 2018-01-20
    • 2020-04-09
    • 2013-04-02
    • 2017-03-09
    相关资源
    最近更新 更多