使用模型数据
注意:这是 “带小部件的图表”示例库的一部分。

首先,我们创建一个 CustomTableModel 类的实例。CustomTableModel 类继承自QAbstractTableModel ,是专为本示例而创建的。该类的构造函数会将适合本图表示例的数据填充到模型的内部数据存储中。
auto *model = new ModelDataModel;现在,我们有一个包含数据的模型,希望将其同时显示在图表和QTableView 中。首先,我们创建QTableView ,并指定使用该模型作为数据源。为了让数据单元格填满表格视图,我们还更改了标题的调整大小模式。
// create table view and add model to it
auto tableView = new QTableView;
tableView->setModel(model);
tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);现在,我们需要一个 QChart 实例来在图表上显示相同的数据。同时,我们还启用了动画效果,这样可以更直观地观察修改模型数据对图表的影响。
下面的代码创建了一个新的线形系列并为其命名。下一行代码创建了 QVXYModelMapper 类的实例。 接下来的两行指定 X 坐标取自模型中索引为 0 的列(Qt::Vertical ),Y 坐标取自模型中索引为 1 的列。为了在系列和模型之间建立连接,我们将这两个对象都设置为 QVXYModelMapper。
最后,将该数据系列添加到图表中。
auto series = new QLineSeries;
series->setName("Line 1");
auto mapper = new QVXYModelMapper(this);
mapper->setXColumn(0);
mapper->setYColumn(1);
mapper->setSeries(series);
mapper->setModel(model);
chart->addSeries(series);为了在QTableView 中显示哪些数据对应于哪个系列,本示例使用了表格着色。当一个系列被添加到图表时,系统会根据当前选定的主题为其分配一种颜色。下面的代码从该系列中提取该颜色,并用它来创建一个带颜色的QTableView 。视图的着色功能不属于QChart的功能范围。
// for storing color hex from the series
QString seriesColorHex = "#000000";
// get the color of the series and use it for showing the mapped area
seriesColorHex = "#" + QString::number(series->pen().color().rgb(), 16).right(6).toUpper();
model->addMapping(seriesColorHex, QRect(0, 0, 2, model->rowCount()));对第二个系列也执行相同的操作。请注意,对于该系列,映射的是同一模型的不同列。
series = new QLineSeries;
series->setName("Line 2");
mapper = new QVXYModelMapper(this);
mapper->setXColumn(2);
mapper->setYColumn(3);
mapper->setSeries(series);
mapper->setModel(model);
chart->addSeries(series);
// get the color of the series and use it for showing the mapped area
seriesColorHex = "#" + QString::number(series->pen().color().rgb(), 16).right(6).toUpper();
model->addMapping(seriesColorHex, QRect(2, 0, 2, model->rowCount()));为避免手动设置QGraphicsScene ,我们使用QChartView类来自动完成此操作。QChart对象指针作为QChartView构造函数的参数传入。为了使图表外观更美观,我们启用了抗锯齿功能,并设置了chartView小部件的最小尺寸。
chart->createDefaultAxes();
chart->layout()->setContentsMargins(0, 0, 0, 0);
auto chartView = new QChartView(chart, this);
chartView->setRenderHint(QPainter::Antialiasing);最后,我们将这两个控件放置在布局中,并将该布局设为应用程序的布局。
// create main layout
auto mainLayout = new QGridLayout;
mainLayout->addWidget(tableView, 1, 0);
mainLayout->addWidget(chartView, 1, 1);
mainLayout->setColumnStretch(1, 1);
mainLayout->setColumnStretch(0, 0);
setLayout(mainLayout);应用程序已准备就绪。请尝试修改表格视图中的数据,并观察其对图表的影响。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.