How to Use QInputDialog in PyQt6

While working on a project for one of my clients, on a desktop application for a small business in Chicago that needed various user inputs for their inventory management system. The challenge was creating easy input interfaces that are simple for their non-technical staff to use.

That’s when I realized how valuable the QInputDialog class in PyQt6 could be. This simple yet efficient widget makes collecting user input simple and consistent.

In this article, I will show you how to use QInputDialog in PyQt6 with practical examples that you can implement in your projects.

Uses of QInputDialog in PyQt6

QInputDialog in Python PyQt6 is a convenience dialog that provides a simple way to get single values from users. It offers several input methods:

  • Text input
  • Integer input
  • Double (decimal) input
  • Item selection from a list
  • Multi-line text input

The best part about QInputDialog is that it handles all the dialog creation details for you, so you can focus on what matters – your application’s core functionality.

Method 1: Use Static Methods for Quick Dialogs

The simplest way to use QInputDialog in PyQt6 is through its static methods, which create and show the dialog in a single function call.

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QInputDialog, QLabel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QInputDialog Example")
        self.setGeometry(100, 100, 400, 300)

        # Create central widget and layout
        central_widget = QWidget()
        layout = QVBoxLayout(central_widget)

        # Create buttons for different dialog types
        self.text_btn = QPushButton("Get Text")
        self.int_btn = QPushButton("Get Integer")
        self.double_btn = QPushButton("Get Decimal")
        self.item_btn = QPushButton("Select Item")
        self.result_label = QLabel("Result will appear here")

        # Connect buttons to functions
        self.text_btn.clicked.connect(self.get_text)
        self.int_btn.clicked.connect(self.get_integer)
        self.double_btn.clicked.connect(self.get_double)
        self.item_btn.clicked.connect(self.get_item)

        # Add widgets to layout
        layout.addWidget(self.text_btn)
        layout.addWidget(self.int_btn)
        layout.addWidget(self.double_btn)
        layout.addWidget(self.item_btn)
        layout.addWidget(self.result_label)

        self.setCentralWidget(central_widget)

    def get_text(self):
        text, ok = QInputDialog.getText(
            self, 
            "Customer Information", 
            "Enter customer name:"
        )
        if ok and text:
            self.result_label.setText(f"Customer name: {text}")

    def get_integer(self):
        number, ok = QInputDialog.getInt(
            self, 
            "Inventory Count", 
            "Enter quantity in stock:",
            min=0, max=1000, step=1
        )
        if ok:
            self.result_label.setText(f"Quantity in stock: {number}")

    def get_double(self):
        amount, ok = QInputDialog.getDouble(
            self, 
            "Product Pricing", 
            "Enter product price ($):",
            min=0.99, max=999.99, decimals=2
        )
        if ok:
            self.result_label.setText(f"Product price: ${amount:.2f}")

    def get_item(self):
        states = ["California", "Texas", "New York", "Florida", "Illinois"]
        state, ok = QInputDialog.getItem(
            self, 
            "Shipping Location", 
            "Select customer state:",
            states, current=0, editable=False
        )
        if ok and state:
            self.result_label.setText(f"Shipping to: {state}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot below.

QInputDialog in PyQt6

In this example, I’ve created four different types of input dialogs that you might use in a business application. Each button opens a different type of QInputDialog, and the result is displayed in a label.

Read Create Dynamic Tables with QTableWidget in PyQt6

Method 2: Customize QInputDialog Appearance

Sometimes you need more control over the appearance of your dialog. You can create an instance of QInputDialog in PyQt6 and customize it before showing it:

def get_multiline_text(self):
    dialog = QInputDialog(self)
    dialog.setWindowTitle("Product Description")
    dialog.setLabelText("Enter detailed product description:")
    dialog.setTextValue("This premium product...")
    dialog.setOption(QInputDialog.InputDialogOption.UsePlainTextEditForTextInput, True)

    # Set position relative to parent window
    dialog.move(self.geometry().center() - dialog.rect().center())

    # Set minimum width
    dialog.resize(400, 200)

    if dialog.exec():
        description = dialog.textValue()
        self.result_label.setText(f"Description saved ({len(description)} chars)")

I executed the above example code and added the screenshot below.

Use QInputDialog in PyQt6

This method allows you to:

  • Set the dialog’s position
  • Resize the dialog
  • Use a multiline text input
  • Customize other properties not available through static methods

Method 3: Integrate QInputDialog with Form Validation

When collecting data from users, validation is crucial. Here’s how you can validate input from QInputDialog:

def get_validated_email(self):
    import re

    while True:
        email, ok = QInputDialog.getText(
            self, 
            "User Account", 
            "Enter valid email address:"
        )

        if not ok:
            return  # User canceled

        # Validate email format using regex
        if re.match(r"[^@]+@[^@]+\.[^@]+", email):
            self.result_label.setText(f"Email validated: {email}")
            return email
        else:
            # Show error and try again
            from PyQt6.QtWidgets import QMessageBox
            QMessageBox.warning(
                self, 
                "Invalid Input", 
                "Please enter a valid email address."
            )

I executed the above example code and added the screenshot below.

How to Use QInputDialog in PyQt6

This function uses a loop to repeatedly prompt for an email until a valid one is entered or the user cancels. It’s a pattern I’ve found useful in many business applications.

Method 4: Create a Multi-Step Input Process

For complex input scenarios, you can chain multiple QInputDialog calls together:

def add_new_product(self):
    # Step 1: Get product name
    name, ok1 = QInputDialog.getText(
        self, "New Product", "Enter product name:"
    )
    if not ok1 or not name:
        return

    # Step 2: Get product category
    categories = ["Electronics", "Clothing", "Home Goods", "Office Supplies"]
    category, ok2 = QInputDialog.getItem(
        self, "Product Category", "Select category:", 
        categories, editable=False
    )
    if not ok2:
        return

    # Step 3: Get product price
    price, ok3 = QInputDialog.getDouble(
        self, "Product Price", "Enter retail price ($):",
        value=19.99, min=0.01, max=9999.99, decimals=2
    )
    if not ok3:
        return

    # All inputs received, process the new product
    self.result_label.setText(
        f"Added: {name} (Category: {category}, Price: ${price:.2f})"
    )

This approach creates a wizard-like interface where each step depends on the previous one. It’s perfect for processes like adding complex inventory items or creating user accounts.

Check out Use QVBoxLayout in PyQt6 for Vertical Layouts

Method 5: Use QInputDialog with Modern Styling

PyQt6 allows you to style your dialogs with CSS-like stylesheets. Here’s how to create a more modern-looking QInputDialog:

def get_styled_input(self):
    dialog = QInputDialog(self)
    dialog.setWindowTitle("Feedback Form")
    dialog.setLabelText("How would you rate your experience?")

    # Apply custom stylesheet
    dialog.setStyleSheet("""
        QInputDialog {
            background-color: #f5f5f5;
        }
        QLabel {
            font-size: 14px;
            color: #333;
            padding: 5px;
        }
        QLineEdit {
            border: 2px solid #3498db;
            border-radius: 5px;
            padding: 5px;
            font-size: 13px;
        }
        QPushButton {
            background-color: #3498db;
            color: white;
            border-radius: 5px;
            padding: 6px 12px;
        }
        QPushButton:hover {
            background-color: #2980b9;
        }
    """)

    if dialog.exec():
        feedback = dialog.textValue()
        self.result_label.setText(f"Feedback received: {feedback}")

By applying a stylesheet, you can make your dialogs match your application’s branding or improve usability with better visual hierarchy.

Read Use QHBoxLayout in PyQt6 for Horizontal Layouts

Method 6: Position QInputDialog at Mouse Cursor

For a more intuitive user experience, you might want to show the dialog at the mouse cursor position:

def show_dialog_at_cursor(self):
    from PyQt6.QtGui import QCursor

    dialog = QInputDialog(self)
    dialog.setWindowTitle("Quick Note")
    dialog.setLabelText("Add a quick note:")

    # Get global cursor position
    cursor_pos = QCursor.pos()

    # Position dialog at cursor
    dialog.move(cursor_pos)

    if dialog.exec():
        note = dialog.textValue()
        self.result_label.setText(f"Note added: {note}")

This approach is especially useful for context menu-triggered dialogs or any situation where you want the input to appear right where the user is currently focused.

Check out Create a QLineEdit Widget in PyQt6

Practical Example: A Customer Information Form

Let’s combine what we’ve learned into a practical example, a customer information form for a retail application:

import sys
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QPushButton, QVBoxLayout,
    QWidget, QInputDialog, QMessageBox
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Customer Info Form")
        self.setGeometry(100, 100, 400, 300)

        # Create button
        self.button = QPushButton("Collect Customer Info")
        self.button.clicked.connect(self.collect_customer_info)

        # Set layout
        layout = QVBoxLayout()
        layout.addWidget(self.button)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

    def collect_customer_info(self): 
        # Get name
        name, ok1 = QInputDialog.getText(
            self, "Customer Registration", "Enter full name:"
        )
        if not ok1 or not name:
            return

        # Get phone
        phone, ok2 = QInputDialog.getText(
            self, "Customer Registration", "Enter phone number:"
        )
        if not ok2 or not phone:
            return

        # Get state
        states = ["California", "Texas", "New York", "Florida", "Illinois", 
                  "Pennsylvania", "Ohio", "Michigan", "Georgia", "North Carolina"]
        state, ok3 = QInputDialog.getItem(
            self, "Customer Registration", "Select state:",
            states, editable=False
        )
        if not ok3 or not state:
            return

        # Get age range
        age_ranges = ["18-24", "25-34", "35-44", "45-54", "55-64", "65+"]
        age_range, ok4 = QInputDialog.getItem(
            self, "Customer Registration", "Select age range:",
            age_ranges, editable=False
        )
        if not ok4 or not age_range:
            return

        # Show summary
        QMessageBox.information(
            self,
            "Customer Info Collected",
            f"Name: {name}\nPhone: {phone}\nState: {state}\nAge Range: {age_range}"
        )

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

This example demonstrates how to gather complete customer information using various input dialogs in PyQt6. It’s a simple and effective way to collect structured data interactively in desktop applications.

In this QInputDialog in PyQt6 tutorial, I explained six important methods to demonstrate the uses of QInputDialog in PyQt6, they are: using static methods, QInputDialog with modern styling, customizing QInputDialog appearance, creating a multi-step input process, integrating QInputDialog with form validation, and positioning QInputDialog at the mouse cursor.

PyQt6-related tutorial:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.