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.

1class Widget(QWidget):
2    def __init__(self):
3        QWidget.__init__(self)
4
5        # Example data
6        self._data = {"Water": 24.5, "Electricity": 55.1, "Rent": 850.0,
7                      "Supermarket": 230.4, "Internet": 29.99, "Bars": 21.85,
8                      "Public transportation": 60.0, "Coffee": 22.45, "Restaurants": 120}

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
5    window = MainWindow(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.

 1    def __init__(self):
 2        QWidget.__init__(self)
 3        self.items = 0
 4
 5        # Example data
 6        self._data = {"Water": 24.5, "Electricity": 55.1, "Rent": 850.0,
 7                      "Supermarket": 230.4, "Internet": 29.99, "Bars": 21.85,
 8                      "Public transportation": 60.0, "Coffee": 22.45, "Restaurants": 120}
 9
10        # Left
11        self.table = QTableWidget()
12        self.table.setColumnCount(2)
13        self.table.setHorizontalHeaderLabels(["Description", "Price"])
14        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
15
16        # QWidget Layout
17        self.layout = QHBoxLayout()
18
19        #self.table_view.setSizePolicy(size)
20        self.layout.addWidget(self.table)
21
22        # Set the layout to the QWidget
23        self.setLayout(self.layout)
24
25        # Fill example data
26        self.fill_table()

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    def fill_table(self, data=None):
2        data = self._data if not data else data
3        for desc, price in data.items():
4            self.table.insertRow(self.items)
5            self.table.setItem(self.items, 0, QTableWidgetItem(desc))
6            self.table.setItem(self.items, 1, QTableWidgetItem(str(price)))
7            self.items += 1

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        # Right
 2        self.description = QLineEdit()
 3        self.price = QLineEdit()
 4        self.add = QPushButton("Add")
 5        self.clear = QPushButton("Clear")
 6        self.quit = QPushButton("Quit")
 7
 8        self.right = QVBoxLayout()
 9        self.right.setMargin(10)
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 PySide2.QtCore import Slot
2from PySide2.QtWidgets import (QAction, QApplication, QHeaderView, QHBoxLayout, QLabel, QLineEdit,
3                               QMainWindow, QPushButton, QTableWidget, QTableWidgetItem,
4                               QVBoxLayout, QWidget)
5
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 PySide2 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 = QtCharts.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.setMargin(10)
 3        self.right.addWidget(QLabel("Description"))
 4        self.right.addWidget(self.description)
 5        self.right.addWidget(QLabel("Price"))
 6        self.right.addWidget(self.price)
 7        self.right.addWidget(self.add)
 8        self.right.addWidget(self.plot)
 9        self.right.addWidget(self.chart_view)
10        self.right.addWidget(self.clear)
11        self.right.addWidget(self.quit)

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        # Signals and Slots
2        self.add.clicked.connect(self.add_element)
3        self.quit.clicked.connect(self.quit_application)
4        self.plot.clicked.connect(self.plot_data)
5        self.clear.clicked.connect(self.clear_table)
6        self.description.textChanged[str].connect(self.check_disable)
7        self.price.textChanged[str].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    @Slot()
 2    def plot_data(self):
 3        # Get table information
 4        series = QtCharts.QPieSeries()
 5        for i in range(self.table.rowCount()):
 6            text = self.table.item(i, 0).text()
 7            number = float(self.table.item(i, 1).text())
 8            series.append(text, number)
 9
10        chart = QtCharts.QChart()
11        chart.addSeries(series)
12        chart.legend().setAlignment(Qt.AlignLeft)
13        self.chart_view.setChart(chart)

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 PySide2.QtCore import Qt, Slot
 43from PySide2.QtGui import QPainter
 44from PySide2.QtWidgets import (QAction, QApplication, QHeaderView, QHBoxLayout, QLabel, QLineEdit,
 45                               QMainWindow, QPushButton, QTableWidget, QTableWidgetItem,
 46                               QVBoxLayout, QWidget)
 47from PySide2.QtCharts import QtCharts
 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 = QtCharts.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.setMargin(10)
 83        self.right.addWidget(QLabel("Description"))
 84        self.right.addWidget(self.description)
 85        self.right.addWidget(QLabel("Price"))
 86        self.right.addWidget(self.price)
 87        self.right.addWidget(self.add)
 88        self.right.addWidget(self.plot)
 89        self.right.addWidget(self.chart_view)
 90        self.right.addWidget(self.clear)
 91        self.right.addWidget(self.quit)
 92
 93        # QWidget Layout
 94        self.layout = QHBoxLayout()
 95
 96        #self.table_view.setSizePolicy(size)
 97        self.layout.addWidget(self.table)
 98        self.layout.addLayout(self.right)
 99
100        # Set the layout to the QWidget
101        self.setLayout(self.layout)
102
103        # Signals and Slots
104        self.add.clicked.connect(self.add_element)
105        self.quit.clicked.connect(self.quit_application)
106        self.plot.clicked.connect(self.plot_data)
107        self.clear.clicked.connect(self.clear_table)
108        self.description.textChanged[str].connect(self.check_disable)
109        self.price.textChanged[str].connect(self.check_disable)
110
111        # Fill example data
112        self.fill_table()
113
114    @Slot()
115    def add_element(self):
116        des = self.description.text()
117        price = self.price.text()
118
119        self.table.insertRow(self.items)
120        description_item = QTableWidgetItem(des)
121        price_item = QTableWidgetItem("{:.2f}".format(float(price)))
122        price_item.setTextAlignment(Qt.AlignRight)
123
124        self.table.setItem(self.items, 0, description_item)
125        self.table.setItem(self.items, 1, price_item)
126
127        self.description.setText("")
128        self.price.setText("")
129
130        self.items += 1
131
132    @Slot()
133    def check_disable(self, s):
134        if not self.description.text() or not self.price.text():
135            self.add.setEnabled(False)
136        else:
137            self.add.setEnabled(True)
138
139    @Slot()
140    def plot_data(self):
141        # Get table information
142        series = QtCharts.QPieSeries()
143        for i in range(self.table.rowCount()):
144            text = self.table.item(i, 0).text()
145            number = float(self.table.item(i, 1).text())
146            series.append(text, number)
147
148        chart = QtCharts.QChart()
149        chart.addSeries(series)
150        chart.legend().setAlignment(Qt.AlignLeft)
151        self.chart_view.setChart(chart)
152
153    @Slot()
154    def quit_application(self):
155        QApplication.quit()
156
157    def fill_table(self, data=None):
158        data = self._data if not data else data
159        for desc, price in data.items():
160            description_item = QTableWidgetItem(desc)
161            price_item = QTableWidgetItem("{:.2f}".format(price))
162            price_item.setTextAlignment(Qt.AlignRight)
163            self.table.insertRow(self.items)
164            self.table.setItem(self.items, 0, description_item)
165            self.table.setItem(self.items, 1, price_item)
166            self.items += 1
167
168    @Slot()
169    def clear_table(self):
170        self.table.setRowCount(0)
171        self.items = 0
172
173
174class MainWindow(QMainWindow):
175    def __init__(self, widget):
176        QMainWindow.__init__(self)
177        self.setWindowTitle("Tutorial")
178
179        # Menu
180        self.menu = self.menuBar()
181        self.file_menu = self.menu.addMenu("File")
182
183        # Exit QAction
184        exit_action = QAction("Exit", self)
185        exit_action.setShortcut("Ctrl+Q")
186        exit_action.triggered.connect(self.exit_app)
187
188        self.file_menu.addAction(exit_action)
189        self.setCentralWidget(widget)
190
191    @Slot()
192    def exit_app(self, checked):
193        QApplication.quit()
194
195
196if __name__ == "__main__":
197    # Qt Application
198    app = QApplication(sys.argv)
199    # QWidget
200    widget = Widget()
201    # QMainWindow using QWidget as central widget
202    window = MainWindow(widget)
203    window.resize(800, 600)
204    window.show()
205
206    # Execute application
207    sys.exit(app.exec_())