In this article, you'll learn about Qt windows and the differences between QMainWindow, QWidget, and QDialog, along with their usage in PySide6.

Qt primarily uses these classes to create windows: PySide6.QtWidgets.QMainWindow, QWidget, and QDialog.

Differences

  • QMainWindow: Qt's main window management class. Certain widgets like the menu bar (QMenuBar) and status bar (QStatusBar) can only be displayed in QMainWindow.
  • QWidget: The base class for all user interface objects in Qt (like buttons, text boxes).
  • QDialog: Qt's base class for dialog windows, mainly used for short-term tasks (like settings windows) and brief user interactions. QDialog can be modal or non-modal - meaning it can prevent interaction with its parent window until closed. QDialog inherits from QWidget.

Creating Windows

Creating windows in PySide6 is very straightforward. Example code:

import sys
from PySide6 import QtWidgets

#import ui_xxxx # UI creation code, if available

class MyWindow(QtWidgets.QMainWindow): # Inherits QMainWindow
    def __init__(self):
        super().__init__()
        
        # Create widgets here

        # Create widgets using UI file if available
        #self.ui = ui_xxxx.Ui_MainWindow()
        #self.ui.setupUi(self)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    window = MyWindow() # Instantiate window
    window.show() # Display window
    sys.exit(app.exec())

The code defines a MyWindow class that inherits from QMainWindow. After instantiation, MyWindow can be displayed by calling the show() method.

Using QDialog

class MyDialog(QtWidgets.QDialog):
    def __init__(self):
        super().__init__()

        # Create widgets here
        pass

Using QWidget

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        
        # Create widgets here
        pass