PySide6 QMainWindow Menus Example

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# The QMenu class provides a menu widget for use 
# in menu bars, context menus, and other popup menus. 

# The QAction class provides an abstraction for user commands
# Same action objects can be added to 
# menus, toolbars and keyboard shortcuts.

import sys

from PySide6.QtGui import QAction
from PySide6.QtWidgets import (QApplication, QMainWindow,
    QTextEdit, QLabel, QMessageBox)


class QEditor(QMainWindow):
    
    def __init__(self):

        super().__init__()

        self.text_edit = QTextEdit()        
        self.setCentralWidget(self.text_edit)

        self.label = QLabel()
        self.statusBar().addWidget(self.label)
        
        self.text_edit.textChanged.connect(self.on_text_changed)
        
        # You can access the main window QMenuBar
        # using QMainWindow.menuBar()
        
        menu_bar = self.menuBar()
        
        # 1 - Create a QMenu instance using QMenuBar.addMenu() 
        #     Use the ampersand to make keyboard shortcuts work.
        
        file_menu = menu_bar.addMenu('&File')
        
        # 2 - Create a QAction instance.
        #     Connect a slot to its triggered signal.
        #     I set QEditor as QAction's parent.
        
        exit_action = QAction(self)
        exit_action.setText('&Exit')
        exit_action.triggered.connect(QApplication.quit)
        
        # 3 - Add action to the menu.
        
        file_menu.addAction(exit_action)
        
        # Repeat the steps for each menu item ...
        
        help_menu = menu_bar.addMenu('&Help')
        
        about_action = QAction(self)
        about_action.setText('&About')
        about_action.triggered.connect(self.show_messagebox)
        
        help_menu.addAction(about_action)
    
    def on_text_changed(self):
        
        cursor = self.text_edit.textCursor()
        
        size = len(self.text_edit.toPlainText())
        x = str(cursor.blockNumber() + 1)
        y = str(cursor.columnNumber() + 1)
        
        self.label.setText('Chars: {}, Ln: {}, Col: {}'.format(size, x, y))
        
    def show_messagebox(self):
        
        messagebox = QMessageBox()
        messagebox.setText('PySide6 menu example')
        messagebox.exec()


if __name__ == '__main__':

    if not QApplication.instance():
        app = QApplication(sys.argv)
    else:
        app = QApplication.instance()

    editor = QEditor()
    editor.show()

    sys.exit(app.exec())