PyQt window focus events not called

只愿长相守 提交于 2020-01-02 07:08:21

问题


I have a PyQt4 program where I'm trying to get notified when a window gets focus, following the advice in the QUndoGroup docs:

It is the programmer's responsibility to specify which stack is active by calling QUndoStack::setActive(), usually when the associated document window receives focus.

But I have a weird problem where only one window actually gets the focusIn and focusOut events, while the others either receive only one at their creation, or else never receive them at all. Here is an example program:



    #!/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:


I'm actually not quite sure why it doesn't work, might be an issue in how qt handles focus transition between windows. Anyways, below is how you might fix this, I've changed your code a bit

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() 

hope this helps, regards



来源:https://stackoverflow.com/questions/7377397/pyqt-window-focus-events-not-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!