我正在开发一个Qt项目。必须在Qpainter区域上单击鼠标绘制一个点。点位置应该位于鼠标点击的同一个精确位置,但由于某种原因,该点被绘制在与预期位置成对角线的另一个位置。
代码:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
QGraphicsView * view = new QGraphicsView(this) ;
ui->setupUi(this);
QGridLayout * gridLayout = new QGridLayout(ui->centralWidget);
gridLayout->addWidget(view);
scene = new QGraphicsScene();
scene->setSceneRect(50, 50, 350, 350);
view->setScene(scene);
}
void MainWindow::mousePressEvent(QMouseEvent * e)
{
QGraphicsView * view = new QGraphicsView(this) ;
double rad = 1;
QPointF pt = view->mapToScene(e->pos());
scene->addEllipse(pt.x()-rad, pt.y()-rad, rad*2.0, rad*2.0,QPen(), QBrush(Qt::SolidPattern));
}
答案 0 :(得分:0)
您的代码不正确。每次点击都会创建沉重的视图,不应该这样做。如果您希望该用户能够与场景交互,则创建新的自定义场景并在场景中执行您需要的所有帽子。
#ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H
#include <QGraphicsScene>
#include <QPoint>
#include <QMouseEvent>
class GraphicsScene : public QGraphicsScene
{
Q_OBJECT
public:
explicit GraphicsScene(QObject *parent = 0);
~GraphicsScene();
signals:
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
public slots:
private:
};
#endif // GRAPHICSSCENE_H
CPP:
#include "graphicsscene.h"
#include <QDebug>
GraphicsScene::GraphicsScene(QObject *parent) :
QGraphicsScene(parent)
{
}
GraphicsScene::~GraphicsScene()
{
qDebug() << "deleted scene";
}
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
if (mouseEvent->button() == Qt::LeftButton)
{
double rad = 1;
QPointF pt = mouseEvent->scenePos();
this->addEllipse(pt.x()-rad, pt.y()-rad, rad*2.0, rad*2.0,QPen(),
QBrush(Qt::SolidPattern));
}
QGraphicsScene::mousePressEvent(mouseEvent);
}
用法,例如:
#include "graphicsscene.h"
//...
GraphicsScene *scene = new GraphicsScene(this);
someview->setScene(scene);