c++ 如何识别QGraphicsView鼠标移动事件?

iqxoj9l9  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(206)

我是qt和c++的新手。我有一个qgraphicsview来绘制信号。我会用鼠标点击和矩形绘图缩放特定区域。所以我需要鼠标按下的位置和拖动的位置。为此,我这样做:
在头文件中:

#include <QtWidgets/QMainWindow>
#include <QGraphicsScene>
#include <QMouseEvent>
#include <QGraphicsSceneMouseEvent>
#include "ui_QtGuiApplication.h"

class QtGuiApplication : public QMainWindow
{
Q_OBJECT

public:
QtGuiApplication(QWidget *parent = Q_NULLPTR);

protected:
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
bool eventFilter(QObject *obj, QEvent *ev);

private:
Ui::QtGuiApplicationClass ui;
QPoint Zoom_point1_;
QPoint Zoom_point2_;
QGraphicsScene* scene = new QGraphicsScene();

};

在源文件中:

QtGuiApplication::QtGuiApplication(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    ui.graphicsView->installEventFilter(this);
    ui.graphicsView->setMouseTracking(true);
}

bool QtGuiApplication::eventFilter(QObject * obj, QEvent * ev)
{
    if (obj == ui.graphicsView)
        if (ev->type() == QEvent::MouseMove)
        {
            QMouseEvent *mEvent = (QMouseEvent*)ev;
            Zoom_point2_ = mEvent->pos();
        }
    return false;
}
void QtGuiApplication::mouseMoveEvent(QMouseEvent * ev)
{
    Zoom_point2_ = ev->globalPos();
    //do some thing …
}

void QtGuiApplication::mousePressEvent(QMouseEvent * ev)
{
    Zoom_point1_ = ev->globalPos(); 
}

当我在graphicsview中按下并移动鼠标时,我可以识别单击的位置,但mouseMoveEvent(QMouseEvent * ev)永远不会被调用。而且eventFilter中的obj == ui.graphicsView语句永远不会发生。我怎么了?我该怎么解决?

dwthyt8l

dwthyt8l1#

通过在QgraphicsView对象的视口上安装事件过滤器,例如

ui.graphicsView->viewport()->installEventFilter(this);

并在eventfilter上添加以下条件

if (ui.graphicsView->viewport())
        if (ev->type() == QEvent::MouseMove)
        {
            QMouseEvent *mEvent = (QMouseEvent*)ev;
            Zoom_point2_ = mEvent->pos();
        }

问题解决了。

相关问题