我有一个 PyQt4 程序,我试图在窗口获得焦点时收到通知,遵循 QUndoGroup 文档中的建议:
It is the programmer's responsibility to specify which stack is active by calling QUndoStack::setActive(), usually when the associated document window receives focus.
但我有一个奇怪的问题,只有一个窗口实际上获得了 focusIn 和 focusOut 事件,而其他窗口要么在创建时只接收到一个事件,要么根本没有接收到它们。这是一个示例程序:
#!/usr/bin/env python
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.label = QLabel('Window')
self.setCentralWidget(self.label)
self.setFocusPolicy(Qt.StrongFocus)
def focusInEvent(self, event):
self.label.setText('Got focus')
def focusOutEvent(self, event):
self.label.setText('Lost focus')
def main():
app = QApplication(sys.argv)
win1 = MyWindow()
win2 = MyWindow()
win1.show()
win2.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
最佳答案
我实际上不太确定为什么它不起作用,可能是 qt 如何处理窗口之间的焦点转换的问题。无论如何,下面是您可能如何解决这个问题,我已经稍微更改了您的代码
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__()
self.label = QLabel('Window')
self.setCentralWidget(self.label)
self.setFocusPolicy(Qt.StrongFocus)
def focusInEvent(self, event):
self.label.setText('Got focus')
def focusOutEvent(self, event):
self.label.setText('Lost focus')
def changedFocusSlot(old, now):
if (now==None and QApplication.activeWindow()!=None):
print "set focus to the active window"
QApplication.activeWindow().setFocus()
def main():
app = QApplication(sys.argv)
QObject.connect(app, SIGNAL("focusChanged(QWidget *, QWidget *)"), changedFocusSlot)
win1 = MyWindow()
win2 = MyWindow()
win1.show()
win2.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
希望这对你有帮助,问候
关于python - 未调用 PyQt 窗口焦点事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7377397/