0

我正在为我大学的一个项目学习 qt 库。我正在尝试创建一个只有 a 的简单窗口,graphicsView仅当光标位于graphicsView. 我首先尝试了mouseMoveEvent功能,但我无法让它工作。然后我尝试使用filter,即使使用它们也无法正常工作。我真的被这件事困住了,我在这里提供代码。问题是 mousePressEvent 只能在 graphicsView 之外正常工作,总是打印“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;
}
4

1 回答 1

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

主窗口.cpp

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

MainWindow::~MainWindow()
{
    delete ui;
}
于 2015-07-15T15:10:34.487 回答