0

我是 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(); 
}

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

4

1 回答 1

0

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

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

并添加以下条件eventfilter

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

问题解决了。

于 2018-03-07T00:23:45.077 回答