PySide6 QMainWindow Status Bar 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
# The QStatusBar class provides a horizontal bar
# suitable for presenting status information.
import sys
from PySide6.QtWidgets import (QApplication, QMainWindow,
QTextEdit, QLabel)
class QEditor(QMainWindow):
def __init__(self):
super().__init__()
self.text_edit = QTextEdit()
self.setCentralWidget(self.text_edit)
# 1 - Create widgets to display information
self.position_label = QLabel()
self.charcount_label = QLabel()
# 2 - Add the widget to QStatusBar
# You access the status bar using QMainWindow.statusBar()
self.statusBar().addWidget(self.position_label)
self.statusBar().addPermanentWidget(self.charcount_label)
self.text_edit.textChanged.connect(self.on_text_changed)
self.text_edit.copyAvailable.connect(self.on_copy_available)
# 3 - Display some stats in the widget associated
# with the status bar.
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.position_label.setText('Ln: {}, Col: {}'.format(x, y))
self.charcount_label.setText('Chars: {}'.format(size))
def on_copy_available(self):
self.statusBar().showMessage('Copy available!', 2000)
if __name__ == '__main__':
app = QApplication(sys.argv)
editor = QEditor()
editor.show()
sys.exit(app.exec())
The QStatusBar
class represents the main window status bar. It can display three kinds of information:
- Temporary, eg. short help messages,
- Normal, eg. row and column number
- Permanent, eg. the Caps Lock status
To use it in your application
-
Create the widgets to hold the desired status information. In the example we create two labels, one to display the cursor row and column and the other to display total character count.
-
Add the widgets to the status bar. You access the status bar using the
QMainWindow.statusBar()
method and add widgets to it with eitheraddWidget()
oraddPermanentWidget()
. The widgets added with the former method are placed on the left and the widgets added with the latter are placed on the right hand side of the status bar. -
Use the appropriate signals to display the status information. In the example we display three pieces of information: the total character count, which displayed permanently, the current cursor position (normal) and a message to notify the user when there is selected text available for copying (temporary). The temporary message, “Copy available!” is displayed for two seconds and hides the normal status widgets but does not hide the permanent status information.