【发布时间】: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