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:

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