我需要在小部件内移动鼠标:
eventFilter 是不可能的,因为它将安装在 QApplication 上。小部件位于类型层次结构的最底层。将此小部件传递到创建 QApplication 对象的主函数会弄乱代码。
因此我实施了
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent * event);
void mouseMoveEvent(QMouseEvent *event);
Run Code Online (Sandbox Code Playgroud)
在小部件中。
没有任何事件被调用。即使在中央小部件和我实际需要事件的小部件上将 mousetracking 设置为 true 后,也不会调用这些函数:
centralWidget->setMouseTracking(true);
Run Code Online (Sandbox Code Playgroud)
如何在 Qt 中为 QWidget 的自定义子类获取鼠标事件?
更新:这是 .h 文件:
class Plot : public QWidget
{
Q_OBJECT
//...
protected:
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent * event);
void mouseMoveEvent(QMouseEvent *event);
Run Code Online (Sandbox Code Playgroud)
更新:
我尝试了 eventFilter 方法。
在.h文件中:
protected:
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent * event);
void mouseMoveEvent(QMouseEvent *event);
bool eventFilter(QObject* object, QEvent* event);
Run Code Online (Sandbox Code Playgroud)
在.cpp中:
void Plot::mousePressEvent(QMouseEvent *event){
//...
}
void Plot::mouseMoveEvent(QMouseEvent *event){
}
void Plot::mouseReleaseEvent(QMouseEvent *event){
}
bool Plot::eventFilter(QObject* object, QEvent* event)
{
if(event->type() == QEvent::MouseButtonPress)
{
QMouseEvent* mev=static_cast<QMouseEvent*>(event);
qDebug()<<mev->x();
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后在我的 qWidget 的构造函数中:
this->installEventFilter(this);
Run Code Online (Sandbox Code Playgroud)
代码编译并运行良好。事件过滤器中if语句处的断点停止程序,调用eventFilter方法。但 if 语句永远不会被评估为 true。即使是简单的buttonPress 事件也没有注册。
事件的覆盖方法仍然没有被调用。
bool someClass::eventFilter(QObject* object, QEvent* event)
{
if(event->type() == QEvent::MouseMove)
{
mouseMoveFunction(static_cast<QMouseEvent*>(event))
}
// Repeat for other mouse events
// returning true blocks event returning false doesnt so if you want to block all mouse events except what your handling then return true inside each of your ifs
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后将事件过滤器安装在您希望应用过滤器的位置上,假设您在 ui 类中,您将这样做(在构造函数中)
this->installEventFilter(this)
Run Code Online (Sandbox Code Playgroud)
编辑:OP正在使用QCustomPlot,根据以前的经验,我知道这会消耗所有事件并且不会将它们传递回去,因此您必须连接到它发出的鼠标单击(或任何您想要的事件)信号以及其中的点或事件