PyQt窗口焦点事件未被调用

4 投票
1 回答
10337 浏览
提问于 2025-04-17 02:01

我有一个使用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 个回答

9

我其实也不太确定为什么它不工作,可能是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() 

希望这能帮到你,祝好!

撰写回答