2017-08-01 168 views
2

所以我有以下的基本窗口,我的問題是,每當我按下標籤按鈕一次觸發事件兩次。打印「標籤」和「按鍵」兩次。我環顧四周,所有我發現這個問題是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_()) 
+3

沒有必要使用事件過濾器對於這一點,因爲Qt的已經提供[QShortcut](https://doc.qt.io /qt-5/qshortcut.html):'QtWidgets.QShortcut('Esc',self,self.close); QtWidgets.QShortcut('Tab',self,lambda:print('Tab'))'。 – ekhumoro

+1

吞嚥事件也可能產生不必要的副作用 – PRMoureu

+1

@PRMoureu。是。 Tab鍵是特殊的 - 'QApplication'爲每個可以接收鍵盤焦點的widget獲取一個事件,因爲它必須管理tab鍵。 – ekhumoro

回答

3

eventFilter()該方法需要一個布爾結果,或0/1,以返回如果事件是相關的或不(過濾器部)。當您返回False時,該事件不會被阻止,並且會擊中他的目標,這可讓應用程序以正常方式處理事件。

在你的榜樣,當預期的按鍵(這是一個相關的事件),你需要返回1True爲「攔截」,並禁止該程序來處理它,因爲你提供自己的過程。在其他情況下,你可以調用超級方法像你這樣:

def eventFilter(self, obj, event): 
    if event.type() == QtCore.QEvent.KeyPress: 
     print("keypress") 

     if event.key() == QtCore.Qt.Key_Escape: 
      self.close() 
      return 1 
     if event.key() == QtCore.Qt.Key_Tab: 
      print("Tab") 
      return 1 

    return super().eventFilter(obj, event) 
+0

它現在可以工作,我補充說。謝謝! – Gorlan

+0

@Gorian感謝您的反饋!關注ekhumoro的評論,在你的情況下,它可能更合適,也更容易實施 – PRMoureu