PySide6 QMainWindow Central Widget Example

QMainWindow central widget

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#  QMainWindow has its own layout to which you can add 
# QToolBars, QDockWidgets, a QMenuBar, and a QStatusBar. 
# The layout has a center area that can be occupied 
# by any kind of widget. In this case we use QTextEdit

import sys

from PySide6.QtWidgets import (QApplication, QMainWindow,
    QTextEdit)


# 1 - Create a class that inherits QMainWindow
class Editor(QMainWindow):
    
    def __init__(self):

        super().__init__()
        
        # 2 - Create a widget
        
        text_edit = QTextEdit()        
        
        # 3 - Set the widget as QMainWindow central widget
        
        self.setCentralWidget(text_edit)


if __name__ == '__main__':

    app = QApplication(sys.argv)

    editor = Editor()
    editor.show()

    sys.exit(app.exec())

The QMainWindow class provides support for the following UI elements out of the box: - Toolbars - Dock widgets - Menu bars - A status bar and is a good starting point for making complex user interfaces. To use it in your application

  1. Create a class that inherits QMainWindow. In the example the child class name is Editor as the example will be used to make a rudimantary text editor.

  2. In the Editor __init__ method create to be used as its central widget, QTextEdit in the example.

  3. Set the created QTextEdit object as the editor’s central widget using QMainWindow.setCentralWidget()

Now, if you run the example you’ll see a Qt window filled with the text widget.