使用 CSV 数据制作图表
如何在Qt Graphs 中可视化CSV文件中的数据。

“基于 CSV 数据的图表”示例演示了如何将 CSV 文件中的数据以二维条形图的形式显示出来。 该应用程序使用第三方 CSV 解析器读取 CSV 文件。数据被插入到一个继承自 `QAbstractTableModel` 的自定义模型中。数据插入模型后,最左侧一列包含垂直标题数据,而顶部一行包含水平标题数据。
所选的第三方库不了解Qt 资源系统,因此无法从文件路径加载 CSV 文件。因此,必须先加载源文件的内容,然后再将其传递给该库。本示例中的 CSV 库接受以下三种形式的文件:文件路径、std::fstream 或std::stringstream 。 由于 CSV 文件位于 Qt 资源中,该库无法加载它,且QFile 不支持std::fstream ;因此唯一的选择是使用std::stringstream 。可通过QFile::readAll() 将整个文件读入字符串,然后将该字符串作为std::stringstream 打开。
在应用程序窗口中,一个表格视图展示了模型中的数据。用户可以在表格视图中选择一部分数据,该数据随后将显示在条形图中。
由于条形图系列不会修改类别轴标签,因此更新系列时不会更新轴标签。该问题通过 JavaScript 从模型的最左侧列中提取标签名称来处理。随后,将提取的标签名称设置为类别轴的 labels 属性。
function extractBarSetGategories(first, count) {
let categories = [];
const last = first + count;
for (let i = first; i < last; ++i)
categories.push(tv.model.headerData(i, Qt.Horizontal, Qt.DisplayRole) + " medals");
return categories;
}运行示例
您可以通过以下方式运行示例:
- Qt Creator
打开Welcome 模式,并从Examples 中选择该示例。有关更多信息,请参阅Qt Creator :教程:构建和运行。
- Qt Extension for Visual Studio Code
在Command Palette 中运行Qt: Open Qt examples 命令,并从列表中选择该示例。有关更多信息,请参阅Qt Extension for Visual Studio Code :教程:构建和运行。
另请参阅 QML 应用程序。
© 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.