没有调用PyQt窗口焦点事件

时间:2011-09-11 09:41:04

标签: python qt focus pyqt

我有一个PyQt4程序,我试图在窗口获得焦点时收到通知,遵循QUndoGroup文档中的建议:

程序员有责任通过调用QUndoStack :: setActive()来指定哪个堆栈处于活动状态,通常是在关联的文档窗口获得焦点时。

但我有一个奇怪的问题,其中只有一个窗口实际上获得了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()

1 个答案:

答案 0 :(得分:6)

我实际上不太确定为什么它不起作用,可能是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() 

希望这有帮助,尊重