2016-10-01 62 views
1

我想处理我的应用程序中箭头键的键事件。我已经读过,因为这样做必须禁用焦点。我遵循这种方法: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_()) 

回答

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) 

但是请注意,这确实让一切,所以你可能有更多的最终会让您应接不暇......

+0

This Works。你有什么想法为什么在另一个线程中提到的方法只能在'__init__'函数中使用,但不会在以后使用? –

+0

@MichaelWestwort。并非如此,为了理解它正在尝试做什么,我并不乐意在该答案的所有代码中使用;-)为什么你需要知道? – ekhumoro

相关问题