我正在为我大学的一个项目学习 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;
}