mousePressEvent无法使用简单的QGraphicsView

时间:2015-07-15 14:19:33

标签: c++ qt mouseevent qt5 mousepress

我正在为我大学的一个项目学习qt图书馆。 我正在尝试创建一个只有graphicsView的简单窗口,仅当光标位于graphicsView内时才捕获鼠标坐标。 我首先尝试使用mouseMoveEvent函数,但我无法使其正常工作。 然后我尝试使用filter,即使使用它们也无法正常工作。 我真的被这件事困住了,我在这里提供代码。 问题是mousePressEvent仅在图形视图外部工作正常,始终打印“1. X:... Y:...”。 我还为graphicsView创建了一个新类,如下所示:

//myGraphicsView.h
class MyGraphicsView : public QWidget
{
  Q_OBJECT
public:
  explicit MyGraphicsView(QWidget *parent = 0);

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

private:
  QGraphicsView *gv;
  QVBoxLayout *layout;
};

myGraphicView.cpp如下:

MyGraphicsView::MyGraphicsView(QWidget *parent) :
  QWidget(parent)
{
  gv = new QGraphicsView;
  layout = new QVBoxLayout;
  layout->addWidget(gv);
  setLayout(layout);

  gv->setMouseTracking(true);
  setMouseTracking(true);
}

void MyGraphicsView::mousePressEvent(QMouseEvent* event)
{
  qDebug() << "1. X: " << event->pos().x() << "; Y: " << event->pos().y() << endl;
}

bool MyGraphicsView::eventFilter(QObject *obj, QEvent *e)
{
  if (e->type() == QEvent::MouseButtonPress)
  {
    QMouseEvent *mouseEvent = (QMouseEvent *) e;
    qDebug() << "3. X: " << mouseEvent->x() << "; Y: " << mouseEvent->y() << endl;
    return true;
  }
  return false;
}

MainWindows.h如下:

    namespace Ui {
  class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();

protected:
  void mousePressEvent(QMouseEvent* ev);

private:
  Ui::MainWindow *ui;
  MyGraphicsView *v;
};

MainWindows.cpp如下:

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{
  ui->setupUi(this);

  v = new MyGraphicsView;
  setMouseTracking(true);
  setCentralWidget(v);

  setWindowTitle("Simple mouse tracker");
  resize(300, 300);
}

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

void MainWindow::mousePressEvent(QMouseEvent* ev)
{
  qDebug() << "2. X: " << ev->pos().x() << "; Y: " << ev->pos().y() << endl;
}

1 个答案:

答案 0 :(得分:0)

我建议采用以下方式:

从QGraphicsView创建自己的类

mygraphicview.h

#ifndef MYGRAPHICVIEW_H
#define MYGRAPHICVIEW_H

#include <QGraphicsView>

class MyGraphicView : public QGraphicsView
{
     public:
     MyGraphicView(QWidget *parent);

     protected:
     virtual void mouseMoveEvent(QMouseEvent *e);
};

#endif // MYGRAPHICVIEW_Hcode here

mygraphicview.cpp

#include "mygraphicview.h"
#include <QMouseEvent>
#include <QDebug>

MyGraphicView::MyGraphicView(QWidget *parent) : QGraphicsView(parent)
{
     setMouseTracking(true);
}

void MyGraphicView::mouseMoveEvent(QMouseEvent *e)
{
    qDebug() << e->pos().x() << e->pos().y();
}

mainwindow.cpp

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MyGraphicView *v = new MyGraphicView(this);
}

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