如果你想避免事件发生在QInputDialog
你必须True
在过滤器中返回,另一方面最好使用Qt::Key
来制作更易读的代码。
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
button = QtWidgets.QPushButton("Press me")
button.clicked.connect(self.opendialog)
self.setCentralWidget(button)
self.inDialog = QtWidgets.QInputDialog()
self.inDialog.setLabelText('')
self.inDialog.installEventFilter(self)
@QtCore.pyqtSlot()
def opendialog(self):
if self.inDialog.exec_() == QtWidgets.QDialog.Accepted:
print("Acepted")
print(self.inDialog.textValue())
def eventFilter(self, obj, event):
if obj is self.inDialog and event.type() == QtCore.QEvent.KeyPress:
if event.key() in (QtCore.Qt.Key_Return,
QtCore.Qt.Key_Escape,
QtCore.Qt.Key_Enter,):
return True
return super(MainWindow, self).eventFilter(obj, event)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
更新: +禁用关闭按钮:
def eventFilter(self, obj, event):
if obj is self.inDialog:
if event.type() == QtCore.QEvent.KeyPress:
if event.key() in (QtCore.Qt.Key_Return,
QtCore.Qt.Key_Escape,
QtCore.Qt.Key_Enter,):
return True
if event.type() == QtCore.QEvent.Close:
event.ignore()
return True
return super(MainWindow, self).eventFilter(obj, event)