Types of Windows in PyQt6

As a PyQt developer with experience in creating desktop applications, I’ve worked extensively with various window types and configurations. It is important to know all the types of windows in PyQt6 to choose different types based on your requirements. Let us get into the topic of PyQt6 windows and explore how can we use them.

What is PyQt6?

Before we explore window types, let’s quickly review what PyQt6 is. PyQt6 is a set of Python bindings for Qt, a powerful cross-platform application framework written in C++. It enables Python developers to create desktop applications with rich graphical user interfaces across Windows, macOS, and Linux.

Read QComboBox Widget in PyQt6

Main Window vs. Dialog: Basics

In PyQt6, windows generally fall into two main categories:

  1. Main Windows – The primary windows of your application
  2. Dialogs – Secondary windows that communicate with users

Let’s examine each in detail:

Main Windows (QMainWindow)

The QMainWindow the class provides the standard application window framework. It includes:

  • Menu bar
  • Toolbars
  • Dock widgets
  • Status bar
  • Central widget

Here’s a basic example of creating a main window:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("My PyQt Application")
        self.setGeometry(100, 100, 800, 600)
        
        # Central widget
        label = QLabel("Welcome to my application!")
        self.setCentralWidget(label)
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

Refer screenshot below to see the output.

Windows in PyQt

Dialogs (QDialog)

Dialogs are secondary windows used for brief interactions with the user. They’re commonly used for tasks like:

  • Input forms
  • Confirmation messages
  • Settings configuration
  • File operations

Here’s how to create a basic dialog:

import sys
from PyQt6.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QPushButton

class CustomDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        
        self.setWindowTitle("Important Information")
        
        layout = QVBoxLayout()
        layout.addWidget(QLabel("This is critical information!"))
        
        button = QPushButton("OK")
        button.clicked.connect(self.accept)
        layout.addWidget(button)
        
        self.setLayout(layout)

# Ensure the script runs a PyQt6 application
if __name__ == "__main__":
    app = QApplication(sys.argv)  # Initialize the application
    dialog = CustomDialog()  # Create an instance of the dialog
    dialog.exec()  # Show the dialog modally (blocking)
    sys.exit(app.exec())  # Start the event loop

Refer screenshot below to see the output.

Types of Windows in PyQt

Check out Create a Random Number Generator with QLCDNumber in PyQt6

Modal vs. Non-Modal Windows

One key distinction in PyQt6 windows is whether they’re modal or non-modal:

Modal Windows

Modal windows block interaction with other windows in the application until they’re closed. They’re ideal for critical operations where the user must complete an action before continuing.

To make a dialog modal, use:

dialog = CustomDialog(self)
result = dialog.exec()  # This blocks until dialog is closed

Non-Modal Windows

Non-modal windows allow users to interact with other application windows while they’re open. They’re useful for toolboxes, property panels, and similar interfaces.

dialog = CustomDialog(self)
dialog.show()  # This returns immediately, allowing interaction with other windows

Read QCalendarWidget in PyQt6

Specialized Window Types in PyQt6

PyQt offers several specialized window types for different scenarios:

Message Boxes (QMessageBox)

Message boxes display informational messages, warnings, or questions. They’re perfect for alerts and confirmations.

from PyQt6.QtWidgets import QMessageBox

# Information message
QMessageBox.information(self, "Information", "Your file has been saved.")

# Warning message
QMessageBox.warning(self, "Warning", "Low disk space detected.")

# Question with buttons
reply = QMessageBox.question(self, "Confirmation", 
                           "Are you sure you want to delete this file?",
                           QMessageBox.StandardButton.Yes | 
                           QMessageBox.StandardButton.No)
if reply == QMessageBox.StandardButton.Yes:
    # Delete the file
    pass

File Dialogs (QFileDialog)

File dialogs allow users to navigate the file system to open or save files, essential for document-based applications.

from PyQt6.QtWidgets import QFileDialog

# Open file dialog
filename, _ = QFileDialog.getOpenFileName(
    self,
    "Open Data File",
    "",
    "Text Files (*.txt);;CSV Files (*.csv);;All Files (*)"
)

# Save file dialog
filename, _ = QFileDialog.getSaveFileName(
    self,
    "Save Report",
    "",
    "PDF Files (*.pdf);;Text Files (*.txt)"
)

Input Dialogs (QInputDialog)

Input dialogs provide a simple way to get specific input from users:

from PyQt6.QtWidgets import QInputDialog

# Get text input
text, ok = QInputDialog.getText(self, "User Information", "Enter your name:")
if ok and text:
    # Process the text
    pass

# Get numeric input
number, ok = QInputDialog.getInt(self, "Configuration", "Enter maximum connections:", 
                                min=1, max=100, step=1)
if ok:
    # Use the number
    pass

# Get item selection
items = ["Low", "Medium", "High", "Critical"]
item, ok = QInputDialog.getItem(self, "Priority", "Select task priority:", 
                               items, editable=False)
if ok and item:
    # Process the selected item
    pass

Check out QSpinBox Widget in PyQt6

Color Dialog (QColorDialog)

The color dialog allows users to select colors, perfect for design and customization features:

from PyQt6.QtWidgets import QColorDialog

color = QColorDialog.getColor()
if color.isValid():
    # Use the color
    print(f"Selected color: {color.name()}")

Font Dialog (QFontDialog)

Font dialogs enable users to choose fonts for text display:

from PyQt6.QtWidgets import QFontDialog

font, ok = QFontDialog.getFont()
if ok:
    # Apply the font to a widget
    self.textEdit.setFont(font)

Advanced Window Types and Techniques

Let us learn some important advanced window types and techniques in PyQt6.

MDI (Multiple Document Interface)

PyQt supports MDI applications where multiple document windows exist within a parent window—ideal for applications like text editors or design tools.

from PyQt6.QtWidgets import QMdiArea, QMdiSubWindow

class MDIWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.mdi = QMdiArea()
        self.setCentralWidget(self.mdi)
        
        # Add sub-windows
        for i in range(3):
            sub = QMdiSubWindow()
            sub.setWidget(QTextEdit())
            sub.setWindowTitle(f"Document {i+1}")
            self.mdi.addSubWindow(sub)
            sub.show()

Frameless Windows

For modern, sleek interfaces, you might want to create frameless windows:

def __init__(self):
    super().__init__()
    # Remove window frame
    self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
    
    # For movable frameless window, implement mousePressEvent, 
    # mouseMoveEvent, etc.

Tool Windows

Tool windows are specialized and often used for floating toolboxes:

tool_window = QWidget()
tool_window.setWindowTitle("Tools")
tool_window.setWindowFlags(Qt.WindowType.Tool)

Read QCheckBox Widget in PyQt6

Comparison of PyQt Window Types

Here’s a comparison table of different window types and their use cases:

Window TypeClassBest ForModal Support
Main WindowQMainWindowPrimary application windowN/A
DialogQDialogUser interaction, formsYes
Message BoxQMessageBoxAlerts, notificationsYes
File DialogQFileDialogFile operationsYes
Input DialogQInputDialogSimple data collectionYes
Color DialogQColorDialogColor selectionYes
Font DialogQFontDialogFont selectionYes
MDI WindowQMdiAreaDocument-based applicationsNo
Tool WindowQWidget with flagsToolboxes, palettesUsually No

Check out QRadioButton Widget in PyQt6

Best Practices for Window Management

Based on my experience developing for US clients from startups in Silicon Valley to enterprises in Chicago, here are some best practices:

1. Window Sizing and Positioning

  • Save and restore window positions between application launches
  • Use sensible defaults that work on common screen resolutions
  • Implement minimum size constraints to prevent unusable UI
# Save window geometry on close
def closeEvent(self, event):
    settings = QSettings("MyCompany", "MyApp")
    settings.setValue("geometry", self.saveGeometry())
    event.accept()
    
# Restore geometry on startup
def __init__(self):
    super().__init__()
    settings = QSettings("MyCompany", "MyApp")
    geometry = settings.value("geometry")
    if geometry:
        self.restoreGeometry(geometry)

2. Modal Dialog Usage

  • Use sparingly – Modal dialogs interrupt workflow
  • Keep them focused on a single task
  • Provide clear actions for dismissing

3. Accessibility Considerations

  • Ensure keyboard navigation works for all windows
  • Set tab order explicitly for form dialogs
  • Add tooltips for buttons and controls

Check out  Handle Button Click Events Using Signals and Slots in PyQt6

Window Styling and Customization

PyQt6 windows can be styled using Qt Style Sheets (QSS), similar to CSS:

# Apply style to specific window
self.setStyleSheet("""
    QMainWindow {
        background-color: #f0f0f0;
    }
    QDialog {
        background-color: #e0e0e0;
        border: 1px solid #c0c0c0;
        border-radius: 5px;
    }
    QPushButton {
        background-color: #0078d7;
        color: white;
        padding: 6px 12px;
        border-radius: 3px;
    }
""")

Conclusion

In this article, I explained the types of windows in PyQt6. I discussed the difference between the main window and the dialog window, specialized window types in PyQt6, and some important advanced window types and techniques. I also covered a comparison of PyQt6 window types and some best practices.

You may read:

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.