我正在为大学的一个项目学习qt库。我试图创建一个简单的窗口,其中只有一个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;
}
我推荐以下方法:
创建你自己的类继承自QGraphicsView
<标题> mygraphicview.h h1> mygraphicview.cpp h1> mainwindow.cpp h1> /html>标题>