Expenses Tool Tutorial#
- In this tutorial you will learn the following concepts:
creating user interfaces programatically,
layouts and widgets,
overloading Qt classes,
connecting signal and slots,
interacting with QWidgets,
and building your own application.
- The requirements:
A simple window for the application (QMainWindow).
A table to keep track of the expenses (QTableWidget).
Two input fields to add expense information (QLineEdit).
Buttons to add information to the table, plot data, clear table, and exit the application (QPushButton).
A verification step to avoid invalid data entry.
A chart to visualize the expense data (QChart) that will be embedded in a chart view (QChartView).
Empty window#
The base structure for a QApplication is located inside the if __name__ == “__main__”: code block.
1 if __name__ == "__main__":
2 app = QApplication([])
3 # ...
4 sys.exit(app.exec())
Now, to start the development, create an empty window called MainWindow. You could do that by defining a class that inherits from QMainWindow.
1class MainWindow(QMainWindow):
2 def __init__(self):
3 QMainWindow.__init__(self)
4 self.setWindowTitle("Tutorial")
5
6if __name__ == "__main__":
7 # Qt Application
8 app = QApplication(sys.argv)
9
10 window = MainWindow()
11 window.resize(800, 600)
12 window.show()
13
14 # Execute application
15 sys.exit(app.exec())
Now that our class is defined, create an instance of it and call show().
1class MainWindow(QMainWindow):
2 def __init__(self):
3 QMainWindow.__init__(self)
4 self.setWindowTitle("Tutorial")
5
6if __name__ == "__main__":
7 # Qt Application
8 app = QApplication(sys.argv)
9
10 window = MainWindow()
11 window.resize(800, 600)
12 window.show()
13
14 # Execute application
15 sys.exit(app.exec())
First signal/slot connection#
The Exit option must be connected to a slot that triggers the application to exit. The main idea to achieve this, is the following:
element.signal_name.connect(slot_name)
All the interface’s elements could be connected through signals to certain slots, in the case of a QAction, the signal triggered can be used:
exit_action.triggered.connect(slot_name)
Note
Now a slot needs to be defined to exit the application, which can be done using QApplication.quit(). If we put all these concepts together you will end up with the following code:
1 # Exit QAction
2 exit_action = QAction("Exit", self)
3 exit_action.setShortcut("Ctrl+Q")
4 exit_action.triggered.connect(self.exit_app)
5
6 self.file_menu.addAction(exit_action)
7
8 @Slot()
9 def exit_app(self, checked):
10 QApplication.quit()
Notice that the decorator @Slot() is required for each slot you declare to properly register them. Slots are normal functions, but the main difference is that they will be invokable from Signals of QObjects when connected.
Empty widget and data#
The QMainWindow enables us to set a central widget that will be displayed when showing the window (read more). This central widget could be another class derived from QWidget.
Additionally, you will define example data to visualize later.
1
2class Widget(QWidget):
3 def __init__(self):
4 QWidget.__init__(self)
5
6 # Example data
7 self._data = {"Water": 24.5, "Electricity": 55.1, "Rent": 850.0,
8 "Supermarket": 230.4, "Internet": 29.99, "Bars": 21.85,
With the Widget class in place, modify MainWindow’s initialization code
1 # Qt Application
2 app = QApplication(sys.argv)
3 # QWidget
4 widget = Widget()
5 # QMainWindow using QWidget as central widget
Window layout#
Now that the main empty window is in place, you need to start adding widgets to achieve the main goal of creating an expenses application.
After declaring the example data, you can visualize it on a simple QTableWidget. To do so, you will add this procedure to the Widget constructor.
Warning
Only for the example purpose a QTableWidget will be used, but for more performance-critical applications the combination of a model and a QTableView is encouraged.
1class Widget(QWidget):
2 def __init__(self):
3 QWidget.__init__(self)
4 self.items = 0
5
6 # Example data
7 self._data = {"Water": 24.5, "Electricity": 55.1, "Rent": 850.0,
8 "Supermarket": 230.4, "Internet": 29.99, "Bars": 21.85,
9 "Public transportation": 60.0, "Coffee": 22.45, "Restaurants": 120}
10
11 # Left
12 self.table = QTableWidget()
13 self.table.setColumnCount(2)
14 self.table.setHorizontalHeaderLabels(["Description", "Price"])
15 self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
16
17 # QWidget Layout
18 self.layout = QHBoxLayout()
19
20 #self.table_view.setSizePolicy(size)
21 self.layout.addWidget(self.table)
22
23 # Set the layout to the QWidget
24 self.setLayout(self.layout)
25
26 # Fill example data
As you can see, the code also includes a QHBoxLayout that provides the container to place widgets horizontally.
Additionally, the QTableWidget allows for customizing it, like adding the labels for the two columns that will be used, and to stretch the content to use the whole Widget space.
The last line of code refers to filling the table*, and the code to perform that task is displayed below.
1
2 def fill_table(self, data=None):
3 data = self._data if not data else data
4 for desc, price in data.items():
5 self.table.insertRow(self.items)
6 self.table.setItem(self.items, 0, QTableWidgetItem(desc))
7 self.table.setItem(self.items, 1, QTableWidgetItem(str(price)))
Having this process on a separate method is a good practice to leave the constructor more readable, and to split the main functions of the class in independent processes.
Right side layout#
Because the data that is being used is just an example, you are required to include a mechanism to input items to the table, and extra buttons to clear the table’s content, and also quit the application.
To distribute these input lines and buttons, you will use a QVBoxLayout that allows you to place elements vertically inside a layout.
1
2 # Right
3 self.description = QLineEdit()
4 self.price = QLineEdit()
5 self.add = QPushButton("Add")
6 self.clear = QPushButton("Clear")
7 self.quit = QPushButton("Quit")
8
9 self.right = QVBoxLayout()
10 self.right.addWidget(QLabel("Description"))
11 self.right.addWidget(self.description)
12 self.right.addWidget(QLabel("Price"))
13 self.right.addWidget(self.price)
14 self.right.addWidget(self.add)
15 self.right.addStretch()
16 self.right.addWidget(self.clear)
17 self.right.addWidget(self.quit)
Leaving the table on the left side and these newly included widgets to the right side will be just a matter to add a layout to our main QHBoxLayout as you saw in the previous example:
1from PySide6.QtCore import Slot
2from PySide6.QtGui import QAction
3from PySide6.QtWidgets import (QApplication, QHeaderView, QHBoxLayout, QLabel, QLineEdit,
4 QMainWindow, QPushButton, QTableWidget, QTableWidgetItem,
5 QVBoxLayout, QWidget)
6
The next step will be connecting those new buttons to slots.
Adding elements#
Each QPushButton have a signal called clicked, that is emitted when you click on the button. This will be more than enough for this example, but you can see other signals in the official documentation.
1 self.add.clicked.connect(self.add_element)
2 self.quit.clicked.connect(self.quit_application)
3 self.clear.clicked.connect(self.clear_table)
4
As you can see on the previous lines, we are connecting each clicked signal to different slots. In this example slots are normal class methods in charge of perform a determined task associated with our buttons. It is really important to decorate each method declaration with a @Slot(), in that way PySide6 knows internally how to register them into Qt.
1 def add_element(self):
2 des = self.description.text()
3 price = self.price.text()
4
5 self.table.insertRow(self.items)
6 self.table.setItem(self.items, 0, QTableWidgetItem(des))
7 self.table.setItem(self.items, 1, QTableWidgetItem(price))
8
9 self.description.setText("")
10 self.price.setText("")
11
12 self.items += 1
13
14 @Slot()
15 def quit_application(self):
16 QApplication.quit()
17
18 def fill_table(self, data=None):
19 data = self._data if not data else data
20 for desc, price in data.items():
21 self.table.insertRow(self.items)
22 self.table.setItem(self.items, 0, QTableWidgetItem(desc))
23 self.table.setItem(self.items, 1, QTableWidgetItem(str(price)))
24 self.items += 1
25
26 @Slot()
27 def clear_table(self):
28 self.table.setRowCount(0)
29 self.items = 0
30
Since these slots are methods, we can access the class variables, like our QTableWidget to interact with it.
The mechanism to add elements into the table is described as the following:
get the description and price from the fields,
insert a new empty row to the table,
set the values for the empty row in each column,
clear the input text fields,
include the global count of table rows.
To exit the application you can use the quit() method of the unique QApplication instance, and to clear the content of the table you can just set the table row count, and the internal count to zero.
Verification step#
Adding information to the table needs to be a critical action that require a verification step to avoid adding invalid information, for example, empty information.
You can use a signal from QLineEdit called textChanged[str] which will be emitted every time something inside changes, i.e.: each key stroke. Notice that this time, there is a [str] section on the signal, this means that the signal will also emit the value of the text that was changed, which will be really useful to verify the current content of the QLineEdit.
You can connect two different object’s signal to the same slot, and this will be the case for your current application:
1 self.description.textChanged[str].connect(self.check_disable)
2 self.price.textChanged[str].connect(self.check_disable)
The content of the check_disable slot will be really simple:
1 @Slot()
2 def check_disable(self, s):
3 if not self.description.text() or not self.price.text():
4 self.add.setEnabled(False)
5 else:
6 self.add.setEnabled(True)
You have two options, write a verification based on the current value of the string you retrieve, or manually get the whole content of both QLineEdit. The second is preferred in this case, so you can verify if the two inputs are not empty to enable the button Add.
Note
Qt also provides a special class called QValidator that you can use to validate any input.
Empty chart view#
New items can be added to the table, and the visualization is so far OK, but you can accomplish more by representing the data graphically.
First you will include an empty QChartView placeholder into the right side of your application.
1 # Chart
2 self.chart_view = QChartView()
3 self.chart_view.setRenderHint(QPainter.Antialiasing)
Additionally the order of how you include widgets to the right QVBoxLayout will also change.
1 self.right = QVBoxLayout()
2 self.right.addWidget(QLabel("Description"))
3 self.right.addWidget(self.description)
4 self.right.addWidget(QLabel("Price"))
5 self.right.addWidget(self.price)
6 self.right.addWidget(self.add)
7 self.right.addWidget(self.plot)
8 self.right.addWidget(self.chart_view)
9 self.right.addWidget(self.clear)
10 self.right.addWidget(self.quit)
11
Notice that before we had a line with self.right.addStretch() to fill up the vertical space between the Add and the Clear buttons, but now, with the QChartView it will not be necessary.
Also, you need include a Plot button if you want to do it on-demand.
Full application#
For the final step, you will need to connect the Plot button to a slot that creates a chart and includes it into your QChartView.
1 self.add.clicked.connect(self.add_element)
2 self.quit.clicked.connect(self.quit_application)
3 self.plot.clicked.connect(self.plot_data)
4 self.clear.clicked.connect(self.clear_table)
5 self.description.textChanged[str].connect(self.check_disable)
6 self.price.textChanged[str].connect(self.check_disable)
7
That is nothing new, since you already did it for the other buttons, but now take a look at how to create a chart and include it into your QChartView.
1 def plot_data(self):
2 # Get table information
3 series = QPieSeries()
4 for i in range(self.table.rowCount()):
5 text = self.table.item(i, 0).text()
6 number = float(self.table.item(i, 1).text())
7 series.append(text, number)
8
9 chart = QChart()
10 chart.addSeries(series)
11 chart.legend().setAlignment(Qt.AlignLeft)
12 self.chart_view.setChart(chart)
13
The following steps show how to fill a QPieSeries:
create a QPieSeries,
iterate over the table row IDs,
get the items at the i position,
add those values to the series.
Once the series has been populated with our data, you create a new QChart, add the series on it, and optionally set an alignment for the legend.
The final line self.chart_view.setChart(chart) is in charge of bringing your newly created chart to the QChartView.
The application will look like this:

And now you can see the whole code:
1# Copyright (C) 2022 The Qt Company Ltd.
2# SPDX-License-Identifier: LicenseRef-Qt-Commercial
3
4import sys
5from PySide6.QtCore import Qt, Slot
6from PySide6.QtGui import QAction, QPainter
7from PySide6.QtWidgets import (QApplication, QHeaderView, QHBoxLayout, QLabel, QLineEdit,
8 QMainWindow, QPushButton, QTableWidget, QTableWidgetItem,
9 QVBoxLayout, QWidget)
10from PySide6.QtCharts import QChartView, QPieSeries, QChart
11
12
13class Widget(QWidget):
14 def __init__(self):
15 QWidget.__init__(self)
16 self.items = 0
17
18 # Example data
19 self._data = {"Water": 24.5, "Electricity": 55.1, "Rent": 850.0,
20 "Supermarket": 230.4, "Internet": 29.99, "Bars": 21.85,
21 "Public transportation": 60.0, "Coffee": 22.45, "Restaurants": 120}
22
23 # Left
24 self.table = QTableWidget()
25 self.table.setColumnCount(2)
26 self.table.setHorizontalHeaderLabels(["Description", "Price"])
27 self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
28
29 # Chart
30 self.chart_view = QChartView()
31 self.chart_view.setRenderHint(QPainter.Antialiasing)
32
33 # Right
34 self.description = QLineEdit()
35 self.price = QLineEdit()
36 self.add = QPushButton("Add")
37 self.clear = QPushButton("Clear")
38 self.quit = QPushButton("Quit")
39 self.plot = QPushButton("Plot")
40
41 # Disabling 'Add' button
42 self.add.setEnabled(False)
43
44 self.right = QVBoxLayout()
45 self.right.addWidget(QLabel("Description"))
46 self.right.addWidget(self.description)
47 self.right.addWidget(QLabel("Price"))
48 self.right.addWidget(self.price)
49 self.right.addWidget(self.add)
50 self.right.addWidget(self.plot)
51 self.right.addWidget(self.chart_view)
52 self.right.addWidget(self.clear)
53 self.right.addWidget(self.quit)
54
55 # QWidget Layout
56 self.layout = QHBoxLayout()
57
58 #self.table_view.setSizePolicy(size)
59 self.layout.addWidget(self.table)
60 self.layout.addLayout(self.right)
61
62 # Set the layout to the QWidget
63 self.setLayout(self.layout)
64
65 # Signals and Slots
66 self.add.clicked.connect(self.add_element)
67 self.quit.clicked.connect(self.quit_application)
68 self.plot.clicked.connect(self.plot_data)
69 self.clear.clicked.connect(self.clear_table)
70 self.description.textChanged[str].connect(self.check_disable)
71 self.price.textChanged[str].connect(self.check_disable)
72
73 # Fill example data
74 self.fill_table()
75
76 @Slot()
77 def add_element(self):
78 des = self.description.text()
79 price = self.price.text()
80
81 try:
82 price_item = QTableWidgetItem(f"{float(price):.2f}")
83 price_item.setTextAlignment(Qt.AlignRight)
84
85 self.table.insertRow(self.items)
86 description_item = QTableWidgetItem(des)
87
88 self.table.setItem(self.items, 0, description_item)
89 self.table.setItem(self.items, 1, price_item)
90
91 self.description.setText("")
92 self.price.setText("")
93
94 self.items += 1
95 except ValueError:
96 print("Wrong price", price)
97
98
99 @Slot()
100 def check_disable(self, s):
101 if not self.description.text() or not self.price.text():
102 self.add.setEnabled(False)
103 else:
104 self.add.setEnabled(True)
105
106 @Slot()
107 def plot_data(self):
108 # Get table information
109 series = QPieSeries()
110 for i in range(self.table.rowCount()):
111 text = self.table.item(i, 0).text()
112 number = float(self.table.item(i, 1).text())
113 series.append(text, number)
114
115 chart = QChart()
116 chart.addSeries(series)
117 chart.legend().setAlignment(Qt.AlignLeft)
118 self.chart_view.setChart(chart)
119
120 @Slot()
121 def quit_application(self):
122 QApplication.quit()
123
124 def fill_table(self, data=None):
125 data = self._data if not data else data
126 for desc, price in data.items():
127 description_item = QTableWidgetItem(desc)
128 price_item = QTableWidgetItem(f"{price:.2f}")
129 price_item.setTextAlignment(Qt.AlignRight)
130 self.table.insertRow(self.items)
131 self.table.setItem(self.items, 0, description_item)
132 self.table.setItem(self.items, 1, price_item)
133 self.items += 1
134
135 @Slot()
136 def clear_table(self):
137 self.table.setRowCount(0)
138 self.items = 0
139
140
141class MainWindow(QMainWindow):
142 def __init__(self, widget):
143 QMainWindow.__init__(self)
144 self.setWindowTitle("Tutorial")
145
146 # Menu
147 self.menu = self.menuBar()
148 self.file_menu = self.menu.addMenu("File")
149
150 # Exit QAction
151 exit_action = QAction("Exit", self)
152 exit_action.setShortcut("Ctrl+Q")
153 exit_action.triggered.connect(self.exit_app)
154
155 self.file_menu.addAction(exit_action)
156 self.setCentralWidget(widget)
157
158 @Slot()
159 def exit_app(self, checked):
160 QApplication.quit()
161
162
163if __name__ == "__main__":
164 # Qt Application
165 app = QApplication(sys.argv)
166 # QWidget
167 widget = Widget()
168 # QMainWindow using QWidget as central widget
169 window = MainWindow(widget)
170 window.resize(800, 600)
171 window.show()
172
173 # Execute application
174 sys.exit(app.exec())