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_())
This Works。你有什麼想法爲什麼在另一個線程中提到的方法只能在'__init__'函數中使用,但不會在以後使用? –
@MichaelWestwort。並非如此,爲了理解它正在嘗試做什麼,我並不樂意在該答案的所有代碼中使用;-)爲什麼你需要知道? – ekhumoro