mousPressEvent off position when drawing on scene



  • I'm trying to draw points on a scene but the points are drawn off position.

    
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    #include <QGraphicsView>
    #include <QGraphicsScene>
    #include <QGraphicsEllipseItem>
    #include <QMouseEvent>
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
        void mousePressEvent(QMouseEvent *e);
    
    private:
        Ui::MainWindow *ui;
        QGraphicsScene *scene;
    };
    
    #endif // MAINWINDOW_H
    
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QGraphicsScene>
    #include <QPointF>
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        scene = new QGraphicsScene();
    
        ui->graphicsView->setScene(scene);
    }
    
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::mousePressEvent(QMouseEvent *e)
    {
    
        double rad = 2;
        QPointF pt = ui->graphicsView->mapToScene(e->pos());
        scene->addEllipse(pt.x()-rad, pt.y()-rad, rad*2.0, rad*2.0, QPen(), QBrush(Qt::SolidPattern));
    }
    

    Any thoughts?
    Thanks in advance!


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You are mapping to the scene a point that is valid in your MainWindow not in your QGraphicsView



  • Thank you for your reply!
    This was simple and useful. Problem solved!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.