通过安装事件筛选器,可以查看窗口是否已被激活/停用(QtCore.QEvent.WindowActivate、QtCore.QEvent.WindowDeactivate)。
class SomeWidget(QtWidgets.QWidget, object):
# ...
def __init__(self):
# ...
self.installEventFilter(self)
# ...
def eventFilter(self, object, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
print('Window was deactivated.')
if event.type() == QtCore.QEvent.WindowActivate:
print('Window was activated.')是否有可能找到A)将焦点传递到哪个其他窗口(同一应用程序),以及( B)整个应用程序是否已被禁用(即:没有一个窗口是活动的)?
我希望解决方案是“最小侵入性”,在这个意义上,我不需要在我的所有候选窗口安装事件过滤器。是否有可能从当前小部件中监视其他窗口?
我对这些信息很感兴趣,因为我想为我的应用程序捕获一些使用指标。
发布于 2019-05-10 23:08:26
如果要监视窗口的状态,可以使用QApplication的通知方法:
from PyQt5 import QtCore, QtWidgets
class Application(QtWidgets.QApplication):
def notify(self, obj, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
print("{} was deactivated:".format(obj))
if event.type() == QtCore.QEvent.WindowActivate:
print("{} was activated.".format(obj))
return super().notify(obj, event)
if __name__ == "__main__":
import sys
app = Application(sys.argv)
windows = []
for _ in range(3):
w = QtWidgets.QWidget()
w.show()
windows.append(w)
sys.exit(app.exec_())使用前面的方法,我实现了一个用函数QApplication::activeWindow()发送激活窗口的信号:
from PyQt5 import QtCore, QtWidgets
class Application(QtWidgets.QApplication):
activateChanged = QtCore.pyqtSignal(QtWidgets.QWidget)
def __init__(self, l):
super().__init__(l)
self._window_activate = None
def notify(self, obj, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
QtCore.QTimer.singleShot(0, self.on_timeout)
if event.type() == QtCore.QEvent.WindowActivate:
QtCore.QTimer.singleShot(0, self.on_timeout)
return super().notify(obj, event)
def on_timeout(self):
if self._window_activate != QtWidgets.QApplication.activeWindow():
self._window_activate = QtWidgets.QApplication.activeWindow()
self.activateChanged.emit(self._window_activate)
if __name__ == "__main__":
import sys
app = Application(sys.argv)
app.activateChanged.connect(print)
windows = []
for _ in range(5):
w = QtWidgets.QWidget()
w.show()
windows.append(w)
sys.exit(app.exec_())https://stackoverflow.com/questions/56085553
复制相似问题