PyQt input dialog (QInputDialog) example
Dialog windows, commonly referred to as dialogs, are essential components of contemporary GUI applications.
These dialog boxes serve as an interaction medium between the user and the software.
In the realm of computer applications, a dialog box operates as an isolated window, primarily designed for tasks such as data entry, data modification, and tweaking application configurations.
Book: Create Desktop Apps with Python PyQt5
Understanding the QInputDialog
The QInputDialog offers a streamlined and user-friendly interface for users to input specific values.
The data submitted can be in the form of a text string, a numerical figure, or an option from a predefined list.
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_())
The above example showcases a GUI setup containing a button and a single-line text editor.
Pressing the button initiates the input dialog, prompting users to enter text.
Subsequent to hitting the ‘OK’ button, the user-inputted text will appear in the main window’s text editing section.
Dissecting the Code
The following segment initiates the display of the Input dialog box.
text, ok = QInputDialog.getText(self, 'input dialog', 'Is this ok?')
Here, the first string represents the dialog’s title, while the second string stands as the message the dialog conveys.
The resulting output of this dialog box encompasses the text entered by the user along with a Boolean value, with a ‘true’ value signifying the pressing of the ‘OK’ button.
if ok:
self.le.setText(str(text))
This segment dictates that the dialog’s acquired text is set as the value in the main application’s text editing area.