Learn Python PyQt

PyQt input dialog (QInputDialog) example

Dialogue windows or dialogs are an integral part of most modern GUI applications.

A dialog box is defined as a window for communication between the user and the program.

A dialog box in a computer application is a separate window used to communicate information with the computer, usually for entering data, modifying data, changing application settings, etc.

Book: Create Desktop Apps with Python PyQt5

QInputDialog input dialog

QInputDialog provides a simple and convenient dialog to obtain individual values from the user.

The input value can be a string, a number, or an item from a list.

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

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.btn = QPushButton('Show Dialog', self)
        self.btn.move(20, 20)
        self.btn.clicked.connect(self.showDialog)

        self.le = QLineEdit(self)
        self.le.move(130, 22)

        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Input Dialog')        
        self.show()

    def showDialog(self):
        text, ok = QInputDialog.getText(self, 'input dialog', 'Is this ok?')
        if ok:
            self.le.setText(str(text))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

This example has a button and a single line text editing control.

Click the button to display the input dialog box for getting text values.

The text entered after clicking the OK button will be displayed in the line text editing control in the main window.

Code analysis

This line displays the Input dialog box.

text, ok = QInputDialog.getText(self, 'input dialog', 'Is this ok?')

The first string is the dialog title and the second is the message displayed in the dialog.

The dialog box returns the entered text and a Boolean value. If you click the OK button, the Boolean value is true.

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

The text we receive from this dialog is set to the value of the single line text edit box control.