QInputDialog

QInputDialog is a dialog that you use to enter simple values.

Input values can be numbers, strings, or items selected in the list. ( QInputDialog official document )

Five useful functions are provided according to the type of input value as follows.

  • getText()

  • getMultiLineText()

  • getInt()

  • getDouble()

  • getItem()

In this example we’ll use getText() method.


Example

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QInputDialog


class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.btn = QPushButton('Dialog', self)
        self.btn.move(30, 30)
        self.btn.clicked.connect(self.showDialog)

        self.le = QLineEdit(self)
        self.le.move(120, 35)

        self.setWindowTitle('Input dialog')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def showDialog(self):

        text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')

        if ok:
            self.le.setText(str(text))


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

We created a QPushButton and QLineEdit widget. If you press the button, the Input dialog appears and displays the entered text on the QLineEdit widget.


Description

text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')

This code shows you the Input dialog window.

The second parameter stands for the title of the dialog window, and the third parameter stands for the message that will be displayed inside the dialog window. The Input dialogue restores the entered text and the Boolean value.

If you press the ‘OK’ button after entering the text, theBoolean value becomes True; if you press the ‘Cancel’ button, the value becomes False.


if ok:
    self.le.setText(str(text))

Let the entered values appear in the QLineEdit widget through the setText() method.


Results

../_images/5_1_qinputdialog.png ../_images/5_1_qinputdialog_mac.png

Figure 6-1. Input dialog.


Prev/Next