[英]How to capture PyQt5 QMainWindow losing focus
What I want to achieve: if a user clicks outside of the QMainWindow the window should hide.我想要实现的是:如果用户在 QMainWindow 之外单击,则窗口应该隐藏。
How I tried to to tackle this problem: find a way to determine if the QMainWindow lost focus, and if so, hide the window using a followup function.我是如何尝试解决这个问题的:找到一种方法来确定 QMainWindow 是否失去焦点,如果是,则使用后续函数隐藏窗口。
Unfortunately I can not totally grasp how to achieve this.不幸的是,我无法完全掌握如何实现这一目标。
It can be done using the flag Qt::Popup but than I am not able to give any keyboard input to the widget my QMainWindow contains.它可以使用标志 Qt::Popup 来完成,但我无法为 QMainWindow 包含的小部件提供任何键盘输入。
void QApplication::focusChanged(QWidget *old, QWidget *now) void QApplication::focusChanged(QWidget *old, QWidget *now)
This signal is emitted when the widget that has keyboard focus changed from old to now, ie, because the user pressed the tab-key, clicked into a widget or changed the active window.当具有键盘焦点的小部件从旧更改为现在时,即因为用户按下 tab 键、单击小部件或更改活动窗口,会发出此信号。 Both old and now can be the null-pointer. old 和 now 都可以是空指针。
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MyWin(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setFocus()
QtWidgets.qApp.focusChanged.connect(self.on_focusChanged)
@QtCore.pyqtSlot("QWidget*", "QWidget*")
def on_focusChanged(self, old, now):
if now == None:
print(f"\nwindow is the active window: {self.isActiveWindow()}")
# window lost focus
# do what you want
self.setWindowState(QtCore.Qt.WindowMinimized)
else: print(f"window is the active window: {self.isActiveWindow()}")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = MyWin()
MainWindow.show()
sys.exit(app.exec_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.