python - 未调用 PyQt 窗口焦点事件

标签 python qt focus pyqt

我有一个 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/

相关文章:

python - Python 中的递归二分查找

javascript - Objective-C/Swift 正则表达式跨多行匹配

python - 关于 Python 中的 os.fork() 函数

c++ - 在 QGraphicsScene 的特定坐标中放置和图像

c++ - 输入 SpinBox 时点击默认的 QPushButton

c++ - Qt GraphicsView mouseMoveEvent 阴影 GraphicsItem mouseMoveEvent

WPF:控制自定义控件中的焦点

python - 使用 cat 时权限被拒绝 - 即使作为 root?

android - EditText 的 onFocusChange 中的 setSelection

jquery - 使用 jQuery 检查 <input type ="text"> 中的文本输入,为什么此代码不起作用?