当弹出如下QMenu的实例时,只有菜单可以接收mouseMoveEvent。
def contextMenuEvent(self, event):
'''
some code
'''
menu.exec_(event.globalPos())
但我希望其他小部件的行为就像菜单不在那里一样。这意味着如果光标在它上面,小部件可以接收mouseMoveEvent。
我知道我的目的可以实现,因为有些应用程序已经实现了。但我不知道Qt中的正确方法。
感谢您的帮助。
答案 0 :(得分:1)
一种方法应该是在接收全部的QMenu上安装QEventHandler 事件到达菜单之前。然后,您可以检查事件类型,并在鼠标事件直接发送到窗口小部件时将其发送。
您可能遇到鼠标坐标问题,但也有一些方法(如全局x和y)映射到正确的窗口小部件相对坐标。
简单示例(c ++但python或多或少相同):
void MyClass::init() {
m_menu->installEventFilter(this);
}
bool MyClass::eventFilter(QObject * obj, QEvent * event) {
// filter the events you are interested in ...
if (event->type() == QEvent::MouseButtonPress) {
// at this point you may need to alter the coordinates, not sure, just try
// send the event to your mouseEventHandling method
this->mousePressEvent(event);
} else {
// this will stop any further handling of this event (the menu itself will not receive it)
// change to false if the menu shall work as usual
return true;
}
// this will trigger regular event handling for all other events
return QObject::eventFilter(obj, event);
}
另见http://doc.qt.io/qt-5/qobject.html#installEventFilter
要自己处理所有事件并根据需要进行分发,请考虑使用透明小部件覆盖可以过滤其事件的所有事件。 (您可以将多个小部件放在同一个网格布局单元格中。)