所以我有以下的基本窗口,我的問題是,每當我按下標籤按鈕一次觸發事件兩次。打印「標籤」和「按鍵」兩次。我環顧四周,所有我發現這個問題是C++的答案,我試圖理解解決方案,但無法。PyQt5/Python - 多個按鍵事件只有一個按鍵被調用
from PyQt5 import QtCore, QtWidgets
class MyWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__(self)
# Install the event filter that will be used later to detect key presses
QtWidgets.qApp.installEventFilter(self)
self.button = QtGui.QPushButton('Test', self)
self.button.clicked.connect(self.handleButton)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.button)
def handleButton(self):
print("Button")
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress:
print("keypress")
if event.key() == QtCore.Qt.Key_Escape:
self.close()
if event.key() == QtCore.Qt.Key_Tab:
print("Tab")
pass
return super(ItemPrice, self).eventFilter(obj, event)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
沒有必要使用事件過濾器對於這一點,因爲Qt的已經提供[QShortcut](https://doc.qt.io /qt-5/qshortcut.html):'QtWidgets.QShortcut('Esc',self,self.close); QtWidgets.QShortcut('Tab',self,lambda:print('Tab'))'。 – ekhumoro
吞嚥事件也可能產生不必要的副作用 – PRMoureu
@PRMoureu。是。 Tab鍵是特殊的 - 'QApplication'爲每個可以接收鍵盤焦點的widget獲取一個事件,因爲它必須管理tab鍵。 – ekhumoro