Qt QGraphicsScene clicked event

718 views Asked by At

So I'm building this little project(I'm new to qt). I want to add a new ellipse in the place where I click. I just know it has something to do with the "click" event, but i don't know how to link these two things. Can someone help?

1

There are 1 answers

0
Jablonski On BEST ANSWER

Create custom scene and reimplement mousePressEvent. For example:

Header:

#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);

};

#endif // GRAPHICSSCENE_H

Cpp:

void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{

      if (mouseEvent->button() == Qt::LeftButton)
      {
          QPointF p = mouseEvent->scenePos();
          int l = 20;
          addEllipse(p.x()-l/2,p.y()-l/2,l,l,QPen(Qt::green));//you can use another approach to create ellipse
      }
      QGraphicsScene::mousePressEvent(mouseEvent);
}

What doest this line? addEllipse(p.x()-l/2,p.y()-l/2,l,l,QPen(Qt::green));

It draws ellipce but center of this ellipse will be in position where you clicked.