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.

 1
 2class MainWindow(QMainWindow):
 3    def __init__(self):
 4        super().__init__()
 5        self.setWindowTitle("Tutorial")
 6
 7if __name__ == "__main__":
 8    # Qt Application
 9    app = QApplication(sys.argv)
10
11    window = MainWindow()
12    window.resize(800, 600)
13    window.show()
14
15    # Execute application

Now that our class is defined, create an instance of it and call show().

 1
 2class MainWindow(QMainWindow):
 3    def __init__(self):
 4        super().__init__()
 5        self.setWindowTitle("Tutorial")
 6
 7if __name__ == "__main__":
 8    # Qt Application
 9    app = QApplication(sys.argv)
10
11    window = MainWindow()
12    window.resize(800, 600)
13    window.show()
14
15    # Execute application

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        super().__init__()
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    app = QApplication(sys.argv)
2    # QWidget
3    widget = Widget()
4    # 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        super().__init__()
 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(self)
19        self.layout.addWidget(self.table)
20
21        # 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.

For input lines along with descriptive labels, you will use a QFormLayout. Then, you will nest the form layout into a QVBoxLayout along with the buttons.

 1
 2        # Right
 3        self.description = QLineEdit()
 4        self.description.setClearButtonEnabled(True)
 5        self.price = QLineEdit()
 6        self.price.setClearButtonEnabled(True)
 7
 8        self.add = QPushButton("Add")
 9        self.clear = QPushButton("Clear")
10
11        form_layout = QFormLayout()
12        form_layout.addRow("Description", self.description)
13        form_layout.addRow("Price", self.price)
14        self.right = QVBoxLayout()
15        self.right.addLayout(form_layout)
16        self.right.addWidget(self.add)
17        self.right.addStretch()

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:

1
2        # QWidget Layout
3        self.layout = QHBoxLayout(self)
4        self.layout.addWidget(self.table)

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
2        # Signals and Slots
3        self.add.clicked.connect(self.add_element)

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(), that way, PySide6 knows internally how to register them into Qt and they will be invokable from Signals of QObjects when connected.

 1
 2    @Slot()
 3    def add_element(self):
 4        des = self.description.text()
 5        price = self.price.text()
 6
 7        self.table.insertRow(self.items)
 8        self.table.setItem(self.items, 0, QTableWidgetItem(des))
 9        self.table.setItem(self.items, 1, QTableWidgetItem(price))
10
11        self.description.clear()
12        self.price.clear()
13
14        self.items += 1
15
16    def fill_table(self, data=None):
17        data = self._data if not data else data
18        for desc, price in data.items():
19            self.table.insertRow(self.items)
20            self.table.setItem(self.items, 0, QTableWidgetItem(desc))
21            self.table.setItem(self.items, 1, QTableWidgetItem(str(price)))
22            self.items += 1
23
24    @Slot()
25    def clear_table(self):
26        self.table.setRowCount(0)

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 which will be emitted every time something inside changes, i.e.: each key stroke.

You can connect two different object’s signal to the same slot, and this will be the case for your current application:

1        self.clear.clicked.connect(self.clear_table)
2        self.description.textChanged.connect(self.check_disable)

The content of the check_disable slot will be really simple:

1
2    @Slot()
3    def check_disable(self, s):
4        enabled = bool(self.description.text() and self.price.text())

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
2        # Chart
3        self.chart_view = QChartView()

Additionally the order of how you include widgets to the right QVBoxLayout will also change.

1
2        form_layout = QFormLayout()
3        form_layout.addRow("Description", self.description)
4        form_layout.addRow("Price", self.price)
5        self.right = QVBoxLayout()
6        self.right.addLayout(form_layout)
7        self.right.addWidget(self.add)
8        self.right.addWidget(self.plot)
9        self.right.addWidget(self.chart_view)

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
2        # Signals and Slots
3        self.add.clicked.connect(self.add_element)
4        self.plot.clicked.connect(self.plot_data)
5        self.clear.clicked.connect(self.clear_table)
6        self.description.textChanged.connect(self.check_disable)

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
 2    @Slot()
 3    def plot_data(self):
 4        # Get table information
 5        series = QPieSeries()
 6        for i in range(self.table.rowCount()):
 7            text = self.table.item(i, 0).text()
 8            number = float(self.table.item(i, 1).text())
 9            series.append(text, number)
10
11        chart = QChart()
12        chart.addSeries(series)
13        chart.legend().setAlignment(Qt.AlignLeft)

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:

../../_images/expenses_tool.png

And now you can see the whole code:

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