Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Call for Presentations - Qt World Summit

    Solved mousPressEvent off position when drawing on scene

    General and Desktop
    2
    3
    426
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Richter9.7
      Richter9.7 last edited by

      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!

      1 Reply Last reply Reply Quote 0
      • SGaist
        SGaist Lifetime Qt Champion last edited by

        Hi and welcome to devnet,

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

        Interested in AI ? www.idiap.ch
        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

        1 Reply Last reply Reply Quote 1
        • Richter9.7
          Richter9.7 last edited by

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

          1 Reply Last reply Reply Quote 0
          • First post
            Last post