我在窗口子A和子B中有两个重叠的小部件.孩子A在B之上并且获得鼠标事件但有时点击应该通过并最终命中孩子B.
理想的解决方案是使用,event->ignore()但这会将事件传递给父窗口小部件,而不是兄弟.
"全部通过"解决方案setAttribute(Qt::WA_TransparentForMouseEvents);无效,因为子A需要捕获一些事件.
我怎么告诉Qt"我不想处理这个事件,表现得像我不在场"?
更简单的解决方案(如果适用)是WA_TransparentForMouseEvents根据您的点击条件进行设置。
例如,如果你想点击Child-A的某些区域,你可以使用它mouseMoveEvent()来检查是否WA_TransparentForMouseEvents需要设置或取消设置。然后点击事件自动通过。
如果您无法确定是否应在实际触发之前接受点击事件,您可以执行以下操作:
void ChildA::mousePressEvent(QMouseEvent* event) {
const bool accepted = ...; //insert custom logic here
if (accepted) {
... //handle event here
} else {
//not accepting event -> resend a copy of this event...
QMouseEvent* eventCopy = new QMouseEvent(*event);
QApplication::instance()->postEvent(eventCopy);
//...but this time, ignore it
setAttribute(Qt::WA_TransparentForMouseEvents, true);
QTimer::singleSlot(1, this, SLOT(resetClickTransparency()));
//don't propagate original event any further
event->accept();
}
}
void ChildA::resetClickTransparency() { //slot
setAttribute(Qt::WA_TransparentForMouseEvents, false);
}
Run Code Online (Sandbox Code Playgroud)
免责声明:所有这些都是在一年没有使用 Qt 后记下来的,所以请纠正我的名称或类型错误。
如果该事件必须被 Child-A 忽略,则发出一个信号并用其父级捕获该信号,然后父级发出一个新信号以由 Child-B 捕获
子级-A -> 父级 -> 子级-B
(信号)->(槽)(信号)->(槽)