pythonpyqt5qinputdialog

How to change the default text and the function of OK and Cancel button in QInputDialog


I use this line in my code to pop up the QInputDialog and take input from the user.

But I want to change the button on this pop-up dialogue

def add(self):
    text, ok = QInputDialog.getText(self, " ", "Enter Value")

    if text == "" or text.isdigit() == False:
        print("Enter valid input")
        self.alert()
    else:
        print("ok value")
        self.ui.label_result.setText(str(text))

Solution

  • Using the static method QInputDialog::getText() it is difficult to modify the text of the buttons, so instead of using an object of that class and using the methods setOkButtonText() and setCancelButtonText():

    def add(self):
        dialog = QInputDialog(self)
        dialog.setWindowTitle(" ")
        dialog.setLabelText("Enter Value")
        dialog.setOkButtonText("Foo")
        dialog.setCancelButtonText("Bar")
        if dialog.exec_() == QDialog.Accepted:
            text = dialog.textValue()
            if text == "" or not text.isdigit():
                print("Enter valid input")
                self.alert()
            else:
                print("ok value")
                self.ui.label_result.setText(str(text))
        else:
            print("canceled")
    

    enter image description here