【问题标题】:Handle arrow key events by setting the focus policy通过设置焦点策略来处理箭头键事件
【发布时间】:2016-10-01 14:39:00
【问题描述】:

我想在我的应用程序中处理箭头键的按键事件。我已经读过这样做必须禁用焦点。我遵循这个方法:PyQt not recognizing arrow keys。事实上,当在MyApp.__init__ 中调用self.setChildrenFocusPolicy(QtCore.Qt.NoFocus)(在链接线程和我下面的源代码中定义)时,按下箭头键会引发一个键事件。但是,我不想在应用程序的整个运行时保持禁用焦点,而只是在单击按钮时。于是我把self.setChildrenFocusPolicy(QtCore.Qt.NoFocus)移到了按钮点击功能:

def __init__(self):
    self.pushButton.clicked.connect(self.pushButtonClicked)

def pushButtonClicked(self):
    self.setChildrenFocusPolicy(QtCore.Qt.NoFocus)

确实,点击按钮会禁用焦点(例如,行编辑不能再使用文本光标)。但是,按箭头键仍然不会引发按键事件。

整个应用程序(您需要一个带有按钮的 mainwindow.ui):

import sys
from PyQt4 import QtCore, QtGui, uic

qtCreatorFile = "d:/test/mainwindow.ui"

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyApp(QtGui.QMainWindow, Ui_MainWindow):

    def setChildrenFocusPolicy(self, policy):
        def recursiveSetChildFocusPolicy (parentQWidget):
            for childQWidget in parentQWidget.findChildren(QtGui.QWidget):
                childQWidget.setFocusPolicy(policy)
                recursiveSetChildFocusPolicy(childQWidget)
        recursiveSetChildFocusPolicy(self)

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.pushButtonClicked)

    def pushButtonClicked(self):
        self.setChildrenFocusPolicy(QtCore.Qt.NoFocus)

    def keyPressEvent(self, event):
        print "a"

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

【问题讨论】:

    标签: pyqt pyqt4 keyevent qkeyevent


    【解决方案1】:

    无需禁用焦点。您可以通过在应用程序上安装事件过滤器来访问所有关键事件:

    class MyApp(QtGui.QMainWindow, Ui_MainWindow):
        def __init__(self):
            ...
            QtGui.qApp.installEventFilter(self)
    
        def eventFilter(self, source, event):
            if event.type() == QtCore.QEvent.KeyPress:
                print(event.key())
            return super(MyApp, self).eventFilter(source, event)
    

    但请注意,这确实得到了一切,因此您最终可能会得到比您讨价还价的更多...

    【讨论】:

    • 这行得通。您知道为什么其他线程中提到的方法仅在 __init__ 函数中有效,而在以后无效?
    • @MichaelWestwort。不是真的,而且我没有动力去研究该答案中的所有代码以了解它正在尝试做什么;-) 你为什么需要知道?
    • 谢谢你拯救了我的夜晚 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2012-09-26
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    相关资源
    最近更新 更多