Summary: in this tutorial, you’ll learn how to use the PyQt QInputDialog
class to create an input dialog widget that receives input from the user.
Introduction to the PyQt QInputDialog class
The QInputDialog
class creates an input dialog widget that receives the inputs from users. The input value can be a string, an integer, a float, or an item from a list.
The QInputDialog
has five static methods for getting inputs:
getText()
– allows the user to enter a single string.getInt()
– allows the user to enter an integer.getDouble()
– allows the user to enter a floating point number.getMultiLineText()
– allows the user to enter multiline text.getItem()
– allows the user to select an item from a list.
These methods return a tuple of two elements. The first element stores the user input and the second element indicate whether the user selects the OK
or Cancel button.
The following program shows how to display an input dialog that receives a single string from a user:
import sys
from PyQt6.QtWidgets import QApplication, QInputDialog, QWidget, QVBoxLayout, QPushButton
class MainWindow(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('PyQt Input Dialog')
self.setGeometry(100, 100, 300, 100)
layout = QVBoxLayout()
self.setLayout(layout)
# file selection
btn = QPushButton('Set Window Title')
btn.clicked.connect(self.open_input_dialog)
layout.addWidget(btn)
self.show()
def open_input_dialog(self):
title, ok = QInputDialog.getText(self, 'Title Setting', 'Title:')
if ok and title:
self.setWindowTitle(title)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())
Code language: Python (python)
Output:
How it works.
First, create a button and connect its clicked signal to the open_input_dialog
method:
btn = QPushButton('Set Window Title')
btn.clicked.connect(self.open_input_dialog)
Code language: Python (python)
Second, define the open_input_dialog
method and call the getText()
method to get the title input by the user:
def open_input_dialog(self):
title, ok = QInputDialog.getText(self, 'Title Setting', 'Title:')
if ok and title:
self.setWindowTitle(title)
Code language: Python (python)
The getText()
method returns a tuple of two elements assigned to the title and ok variable
If you enter some text and click the OK button, the title
will store the input text and the ok
variable will be True.
However, if you enter some text but click the Cancel button, the title
variable will store the input text but the ok
variable is False
instead.
Summary
- Use
QInputDialog
to create an input dialog that receives input from the user.