如何在Qt中禁用向小部件而不是其子级的鼠标事件传递? [英] How to disable the delivery of mouse events to the widget but not its children in Qt?

查看:372
本文介绍了如何在Qt中禁用向小部件而不是其子级的鼠标事件传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的两天里,我一直在寻找一种将鼠标事件传递给小部件后面的小部件的方法,该小部件用作其子级的容器/父级.我知道有一种方法可以使小部件对鼠标事件透明,例如:

For the last two days, I've been searching for a way to pass mouse events to the widgets behind a widget used as a container/parent for it's children. I know there is a way to make a widget transparent for mouse events like this:

QWidget w;
w.setAttribute( Qt::WA_TransparentForMouseEvents );

但这也会禁用向其子级传递鼠标事件!我希望前端小部件的孩子以及前端小部件后面的小部件能够接收鼠标事件.

But this also disables the delivery of mouse events to its children! I want the children of the front widget and the widgets behind the front widget to receive the mouse events.

Qt :: WA_TransparentForMouseEvents:启用后,此属性禁用向小部件及其子部件传递鼠标事件. 鼠标事件会传递到其他小部件,就像该小部件及其 子代层次结构中不存在子代;鼠标点击和 其他事件有效地通过"了它们.该属性是 默认情况下处于禁用状态.

Qt::WA_TransparentForMouseEvents: When enabled, this attribute disables the delivery of mouse events to the widget and its children. Mouse events are delivered to other widgets as if the widget and its children were not present in the widget hierarchy; mouse clicks and other events effectively "pass through" them. This attribute is disabled by default.

如果您有关于如何使小部件对鼠标事件透明的任何想法,但不是小孩子,请与我们分享!

If you have any idea about how to make a widget transparent for mouse events but not it's children then please share!

推荐答案

最后我找到了一个解决方案:)

At last I found a solution :)

QWidget :: setMask(const QRegion& region)

https://doc.qt.io/qt-5 /qwidget.html#setMask-1

http://qt-project.org/doc/qt -4.8/qwidget.html#setMask

我在这里找到了解决方案: http://www.qtcentre .org/archive/index.php/t-3033.html

I found the solution here: http://www.qtcentre.org/archive/index.php/t-3033.html

QRegion reg(frameGeometry());
reg -= QRegion(geometry());
reg += childrenRegion();
setMask(reg);

现在,前小部件和后小部件后面的小部件的子级会根据需要响应鼠标事件!

Now children of the front widget and the widgets behind the front widget respond to the mouse events as required!

请记住,每当调整前小部件的大小以重新计算蒙版的几何图形时,您都需要再次调用这些行!

Remember, you would need to call these lines again whenever the front widget is re-sized to recalculate the geometry for the mask!

void someWidget::resizeEvent(QResizeEvent *e){
  QWidget::resizeEvent(e);
  QRegion reg(frameGeometry());
  reg-=QRegion(geometry()); 
  reg+=childrenRegion();
  setMask(reg);
}

这篇关于如何在Qt中禁用向小部件而不是其子级的鼠标事件传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆