Search code examples
qtqgraphicsviewqgraphicsscene

QGraphicsSceneMouseEvent get position will not work


I am trying to make an application with a QGraphicsView in it. I tried to get the position of a mouse when the mouse was pressed with QGraphicsSceneMouseEvent, but it doesn't seem to work. The entire function is never called when I press the mouse.

I would like to make an application that can load an image into the QGraphicsView and then when you press the mouse button, it should add a small circle.

This is my code:

dialog.cpp:

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    ui->graphicsView = new GraphicsView();
}

Dialog::~Dialog()
{
    delete ui;
}

graphicsview.h:

#ifndef GRAPHICSVIEW_H
#define GRAPHICSVIEW_H
#include <QGraphicsView>
#include <QMouseEvent>
#include <QDebug>

class GraphicsView : public QGraphicsView
{
public:
    GraphicsView();
protected:
    void mousePressEvent(QMouseEvent *event) override;

private:
    QGraphicsScene *scene;
};

#endif // GRAPHICSVIEW_H

graphicsview.cpp:

#include "graphicsview.h"

GraphicsView::GraphicsView()
{
    scene = new QGraphicsScene();
    this->setScene(scene);
}

void GraphicsView::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        qDebug() << "The left button was pressed!";
    }
}

Solution

  • You're almost there.

    Just change GraphicsView::GraphicsView() to:

    GraphicsView::GraphicsView(QWidget *parent=nullptr) : QGraphicsView(parent) {}
    

    and change ui->graphicsView = new GraphicsView(); to

    QVBoxLayout *verticalLayout = new QVBoxLayout(this);
    verticalLayout->addWidget(new GraphicsView(this));
    

    This will make the graphics view a parent of the dialog. Make sure that your dialog doesn't have anything in it when you add the code above. Alternatively, you can add a vertical layout to the dialog in your dialog.ui file and do

    ui->verticalLayout->addWidget(new GraphicsView(this));
    

    I believe that solves your problem. Respond if you still have any issues.

    Make sure you always have a parent parameter. Without it, you're not telling your program where it's supposed to add your widget.