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:

../../_images/expenses_tool.png

And now you can see the whole code:

  1#############################################################################
  2##
  3## Copyright (C) 2020 The Qt Company Ltd.
  4## Contact: http://www.qt.io/licensing/
  5##
  6## This file is part of the Qt for Python examples of the Qt Toolkit.
  7##
  8## $QT_BEGIN_LICENSE:BSD$
  9## You may use this file under the terms of the BSD license as follows:
 10##
 11## "Redistribution and use in source and binary forms, with or without
 12## modification, are permitted provided that the following conditions are
 13## met:
 14##   * Redistributions of source code must retain the above copyright
 15##     notice, this list of conditions and the following disclaimer.
 16##   * Redistributions in binary form must reproduce the above copyright
 17##     notice, this list of conditions and the following disclaimer in
 18##     the documentation and/or other materials provided with the
 19##     distribution.
 20##   * Neither the name of The Qt Company Ltd nor the names of its
 21##     contributors may be used to endorse or promote products derived
 22##     from this software without specific prior written permission.
 23##
 24##
 25## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 26## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 27## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 28## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 29## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 30## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 31## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 32## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 33## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 34## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 35## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 36##
 37## $QT_END_LICENSE$
 38##
 39#############################################################################
 40
 41import sys
 42from PySide6.QtCore import Qt, Slot
 43from PySide6.QtGui import QAction, QPainter
 44from PySide6.QtWidgets import (QApplication, QHeaderView, QHBoxLayout, QLabel, QLineEdit,
 45                               QMainWindow, QPushButton, QTableWidget, QTableWidgetItem,
 46                               QVBoxLayout, QWidget)
 47from PySide6.QtCharts import QChartView, QPieSeries, QChart
 48
 49
 50class Widget(QWidget):
 51    def __init__(self):
 52        QWidget.__init__(self)
 53        self.items = 0
 54
 55        # Example data
 56        self._data = {"Water": 24.5, "Electricity": 55.1, "Rent": 850.0,
 57                      "Supermarket": 230.4, "Internet": 29.99, "Bars": 21.85,
 58                      "Public transportation": 60.0, "Coffee": 22.45, "Restaurants": 120}
 59
 60        # Left
 61        self.table = QTableWidget()
 62        self.table.setColumnCount(2)
 63        self.table.setHorizontalHeaderLabels(["Description", "Price"])
 64        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
 65
 66        # Chart
 67        self.chart_view = QChartView()
 68        self.chart_view.setRenderHint(QPainter.Antialiasing)
 69
 70        # Right
 71        self.description = QLineEdit()
 72        self.price = QLineEdit()
 73        self.add = QPushButton("Add")
 74        self.clear = QPushButton("Clear")
 75        self.quit = QPushButton("Quit")
 76        self.plot = QPushButton("Plot")
 77
 78        # Disabling 'Add' button
 79        self.add.setEnabled(False)
 80
 81        self.right = QVBoxLayout()
 82        self.right.addWidget(QLabel("Description"))
 83        self.right.addWidget(self.description)
 84        self.right.addWidget(QLabel("Price"))
 85        self.right.addWidget(self.price)
 86        self.right.addWidget(self.add)
 87        self.right.addWidget(self.plot)
 88        self.right.addWidget(self.chart_view)
 89        self.right.addWidget(self.clear)
 90        self.right.addWidget(self.quit)
 91
 92        # QWidget Layout
 93        self.layout = QHBoxLayout()
 94
 95        #self.table_view.setSizePolicy(size)
 96        self.layout.addWidget(self.table)
 97        self.layout.addLayout(self.right)
 98
 99        # Set the layout to the QWidget
100        self.setLayout(self.layout)
101
102        # Signals and Slots
103        self.add.clicked.connect(self.add_element)
104        self.quit.clicked.connect(self.quit_application)
105        self.plot.clicked.connect(self.plot_data)
106        self.clear.clicked.connect(self.clear_table)
107        self.description.textChanged[str].connect(self.check_disable)
108        self.price.textChanged[str].connect(self.check_disable)
109
110        # Fill example data
111        self.fill_table()
112
113    @Slot()
114    def add_element(self):
115        des = self.description.text()
116        price = self.price.text()
117
118        try:
119            price_item = QTableWidgetItem(f"{float(price):.2f}")
120            price_item.setTextAlignment(Qt.AlignRight)
121
122            self.table.insertRow(self.items)
123            description_item = QTableWidgetItem(des)
124
125            self.table.setItem(self.items, 0, description_item)
126            self.table.setItem(self.items, 1, price_item)
127
128            self.description.setText("")
129            self.price.setText("")
130
131            self.items += 1
132        except ValueError:
133            print("Wrong price", price)
134
135
136    @Slot()
137    def check_disable(self, s):
138        if not self.description.text() or not self.price.text():
139            self.add.setEnabled(False)
140        else:
141            self.add.setEnabled(True)
142
143    @Slot()
144    def plot_data(self):
145        # Get table information
146        series = QPieSeries()
147        for i in range(self.table.rowCount()):
148            text = self.table.item(i, 0).text()
149            number = float(self.table.item(i, 1).text())
150            series.append(text, number)
151
152        chart = QChart()
153        chart.addSeries(series)
154        chart.legend().setAlignment(Qt.AlignLeft)
155        self.chart_view.setChart(chart)
156
157    @Slot()
158    def quit_application(self):
159        QApplication.quit()
160
161    def fill_table(self, data=None):
162        data = self._data if not data else data
163        for desc, price in data.items():
164            description_item = QTableWidgetItem(desc)
165            price_item = QTableWidgetItem(f"{price:.2f}")
166            price_item.setTextAlignment(Qt.AlignRight)
167            self.table.insertRow(self.items)
168            self.table.setItem(self.items, 0, description_item)
169            self.table.setItem(self.items, 1, price_item)
170            self.items += 1
171
172    @Slot()
173    def clear_table(self):
174        self.table.setRowCount(0)
175        self.items = 0
176
177
178class MainWindow(QMainWindow):
179    def __init__(self, widget):
180        QMainWindow.__init__(self)
181        self.setWindowTitle("Tutorial")
182
183        # Menu
184        self.menu = self.menuBar()
185        self.file_menu = self.menu.addMenu("File")
186
187        # Exit QAction
188        exit_action = QAction("Exit", self)
189        exit_action.setShortcut("Ctrl+Q")
190        exit_action.triggered.connect(self.exit_app)
191
192        self.file_menu.addAction(exit_action)
193        self.setCentralWidget(widget)
194
195    @Slot()
196    def exit_app(self, checked):
197        QApplication.quit()
198
199
200if __name__ == "__main__":
201    # Qt Application
202    app = QApplication(sys.argv)
203    # QWidget
204    widget = Widget()
205    # QMainWindow using QWidget as central widget
206    window = MainWindow(widget)
207    window.resize(800, 600)
208    window.show()
209
210    # Execute application
211    sys.exit(app.exec())