2017-08-01 26 views
2

次の基本ウィンドウがあります。その問題は、一度タブボタンを押すたびにイベントが2回トリガーされます。 "tab"と "keypress"を2回印刷します。私は周りを見回し、この問題について私が知ったのはC++の答えでした。私は解決策を理解しようとしましたが、それもできませんでした。PyQt5/Python - 複数のキー押下イベントが1回のキー押下だけで呼び出されます

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'は、タブのチェーンを管理する必要があるため、キーボードフォーカスを受け取ることができる各ウィジェットのイベントを取得します。 – ekhumoro

答えて

3

eventFilter()方法は、イベントが(フィルタ部)関連であるかどうかを返すように、ブール結果、又は0/1を必要とします。 Falseを返すと、イベントはブロックされず、ターゲットにヒットします。これにより、アプリケーションはイベントを通常の方法で処理できます。

あなたの例では、(これは関連するイベントです)1またはTrueを "傍受して"それを処理しないようにする必要があります。あなたがやったように、他の例では、スーパーメソッドを呼び出すことができます。

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

関連する問題