第五章 - 添加图表视图#

表格适用于展示数据,但图表更佳。为此,您需要 QtCharts 模块,该模块提供了多种绘图类型和选项来图形化地表示数据。

绘图占位符为 QChartView,在 Widget 内部您可以放置 QChart。作为第一步,尝试只包含此部分而没有要绘制的任何数据。

修改上章中的 main_widget.py,如下标出的更改以添加 QChartView

 1
 2from PySide6.QtCore import QDateTime, Qt
 3from PySide6.QtGui import QPainter
 4from PySide6.QtWidgets import (QWidget, QHeaderView, QHBoxLayout, QTableView,
 5                               QSizePolicy)
 6from PySide6.QtCharts import QChart, QChartView, QLineSeries, QDateTimeAxis, QValueAxis
 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 = QChart()
31        self.chart.setAnimationOptions(QChart.AllAnimations)
32
33        # Creating QChartView
34        self.chart_view = 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)