PyQt Prevent QInputDialog from closing on ESC/Enter cross click

2.2k views Asked by At

I created QInputDialog and configured event filter in it, but I don't know how to prevent it from closing on ESC or ENTER button click in eventFilter(self, widget, event) method.

 self.inDialog = QInputDialog(self)
 #some config...
 self.inDialog.setLabelText('')
 self.nameAction.setText('&Nazwa pola głównego ✔')
 self.inDialog.show()

My event filter concept:

def eventFilter(self, widget, event):
    if isinstance(event, QtGui.QKeyEvent):
        if event.key() == 16777220:
            return False
    # here I want to call super somehow?
    return

It is worth mentioning that I am doing all this operations in QMainWindow class from which I am calling this QInputdialog. I would prefer not to subclass QDialog and write everything manually.

1

There are 1 answers

2
eyllanesc On BEST ANSWER

If you want to avoid that the event happens to the QInputDialog you must return True in the filter, on the other hand it is better to use the Qt::Key to make a more readable code.

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_())

Update: + Disable close button:

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)