C++ 在 Qt 中显示窗口而不窃取焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/966688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:09:16  来源:igfitidea点击:

Show window in Qt without stealing focus

c++qtfocuswindow-managementactive-window

提问by dutchmega

I'm using the Qt library to show a slideshow on the second monitor when the user isn't using the second monitor. An example is the user playing a game in the first monitor and showing the slideshow in the second monitor.

当用户不使用第二台显示器时,我使用 Qt 库在第二台显示器上显示幻灯片。一个例子是用户在第一台显示器上玩游戏并在第二台显示器上显示幻灯片。

The problem is that when I open a new window in Qt, it automatically steals the focus from the previous application. Is there any way to prevent this from happening?

问题是当我在 Qt 中打开一个新窗口时,它会自动从以前的应用程序中窃取焦点。有什么办法可以防止这种情况发生吗?

回答by dutchmega

It took me a while to find it but I found it: setAttribute(Qt::WA_ShowWithoutActivating);

我花了一段时间才找到它,但我找到了: setAttribute(Qt::WA_ShowWithoutActivating);

This forces the window not to activate. Even with the Qt::WindowStaysOnTopHintflag

这会强制窗口不激活。即使有Qt::WindowStaysOnTopHint国旗

回答by Yash

If you want to make floating preview box/ any other widget just use below

如果您想制作浮动预览框/任何其他小部件,请在下面使用

thumbnail = new QLabel;
thumbnail->setAttribute(Qt::WA_ShowWithoutActivating);
thumbnail->setParent(0);
thumbnail->setWindowFlags(Qt::Tool | Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);

Qt::Tool is important flag to make it work. I mean not stealing focus.

Qt::Tool 是使其工作的重要标志。我的意思是不偷焦点。

回答by Troubadour

Widgets don't accept focus by default but presumably you haven't created a plain widget? Which subclass was it? QMainWindow or something else?

小部件默认不接受焦点,但大概您还没有创建普通小部件?是哪个子类?QMainWindow 还是别的什么?

It's possible the window subclasses default to accepting focus so try explicitly calling QWidget::setFocusPolicy with Qt::NoFocus before calling QWidget::show().

有可能窗口子类默认接受焦点,因此在调用 QWidget::show() 之前尝试使用 Qt::NoFocus 显式调用 QWidget::setFocusPolicy。

Also, make sure you're not calling QWidget::activateWindow() on the window or any of its widgets at any point.

另外,请确保您在任何时候都没有在窗口或其任何小部件上调用 QWidget::activateWindow() 。