QGraphicsSceneMouseEvent get position will not work [duplicate]

大憨熊 提交于 2019-12-13 20:22:23

问题


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!";
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/58268790/qgraphicsscenemouseevent-get-position-will-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!