如何捕获 PyQt5 QMainWindow 失去焦点
How to capture PyQt5 QMainWindow losing focus
我想要实现的目标:如果用户在 QMainWindow 之外单击,window 应该隐藏。
我是如何尝试解决这个问题的:找到一种方法来确定 QMainWindow 是否失去焦点,如果是,则使用后续函数隐藏 window。
不幸的是,我无法完全掌握如何实现这一目标。
可以使用标志 Qt::Popup 来完成,但是我无法向我的 QMainWindow 包含的小部件提供任何键盘输入。
void QApplication::focusChanged(QWidget *old, QWidget *now)
This signal is emitted when the widget that has keyboard focus changed from old to now, i.e., because the user pressed the tab-key, clicked into a widget or changed the active window. Both old and now can be the null-pointer.
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_())
我想要实现的目标:如果用户在 QMainWindow 之外单击,window 应该隐藏。
我是如何尝试解决这个问题的:找到一种方法来确定 QMainWindow 是否失去焦点,如果是,则使用后续函数隐藏 window。
不幸的是,我无法完全掌握如何实现这一目标。
可以使用标志 Qt::Popup 来完成,但是我无法向我的 QMainWindow 包含的小部件提供任何键盘输入。
void QApplication::focusChanged(QWidget *old, QWidget *now)
This signal is emitted when the widget that has keyboard focus changed from old to now, i.e., because the user pressed the tab-key, clicked into a widget or changed the active window. Both old and now can be the null-pointer.
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_())