次の基本ウィンドウがあります。その問題は、一度タブボタンを押すたびにイベントが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_())
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'は、タブのチェーンを管理する必要があるため、キーボードフォーカスを受け取ることができる各ウィジェットのイベントを取得します。 – ekhumoro