Chapter 5 - Add a chart view

A table is nice to present data, but a chart is even better. For this, you need the QtCharts module that provides many types of plots and options to graphically represent data.

The placeholder for a plot is a QChartView, and inside that Widget you can place a QChart. As a first step, try including only this without any data to plot.

Make the following highlighted changes to main_widget.py from the previous chapter to add a QChartView:

 1from __future__ import annotations
 2
 3from PySide6.QtCore import QDateTime, Qt
 4from PySide6.QtGui import QPainter
 5from PySide6.QtWidgets import (QWidget, QHeaderView, QHBoxLayout, QTableView,
 6                               QSizePolicy)
 7from PySide6.QtCharts import QChart, QChartView, QLineSeries, QDateTimeAxis, QValueAxis
 8
 9from table_model import CustomTableModel
10
11
12class Widget(QWidget):
13    def __init__(self, data):
14        QWidget.__init__(self)
15
16        # Getting the Model
17        self.model = CustomTableModel(data)
18
19        # Creating a QTableView
20        self.table_view = QTableView()
21        self.table_view.setModel(self.model)
22
23        # QTableView Headers
24        self.horizontal_header = self.table_view.horizontalHeader()
25        self.vertical_header = self.table_view.verticalHeader()
26        self.horizontal_header.setSectionResizeMode(QHeaderView.ResizeToContents)
27        self.vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
28        self.horizontal_header.setStretchLastSection(True)
29
30        # Creating QChart
31        self.chart = QChart()
32        self.chart.setAnimationOptions(QChart.AllAnimations)
33
34        # Creating QChartView
35        self.chart_view = QChartView(self.chart)
36        self.chart_view.setRenderHint(QPainter.Antialiasing)
37
38        # QWidget Layout
39        self.main_layout = QHBoxLayout()
40        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
41
42        ## Left layout
43        size.setHorizontalStretch(1)
44        self.table_view.setSizePolicy(size)
45        self.main_layout.addWidget(self.table_view)
46
47        ## Right Layout
48        size.setHorizontalStretch(4)
49        self.chart_view.setSizePolicy(size)
50        self.main_layout.addWidget(self.chart_view)
51
52        # Set the layout to the QWidget
53        self.setLayout(self.main_layout)