PyQt防止QInputDialog在ESC上关闭/输入交叉点击

时间:2018-12-09 15:59:32

标签: python pyqt pyqt5 qinputdialog

我创建了QInputDialog并在其中配置了事件过滤器,但是我不知道如何防止在eventFilter(self, widget, event)方法中单击ESC或ENTER按钮时关闭它。

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

我的事件过滤器概念:

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

值得一提的是,我正在QMainWindow类中执行所有这些操作,从中我将其称为QInputdialog。我宁愿不要继承QDialog并手动编写所有内容。

1 个答案:

答案 0 :(得分:1)

如果要避免事件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)