问题描述
最近我在做一个gui应用程序&我想把QTableView的数据保存在.csv或.txt文件中。 I使用指南,这使我想如果反向也是可能的;即如果QTableView可以从.csv或.txt文件填充。再次,我更喜欢保留一个基于模型的设计,如QTableView,而不是基于项目的QTableWidget。
任何代码片段或教程文档将是非常有用的。请考虑一个 test.csv
文件(它可以由任何文本生成)。编辑者):
后面的文本流是(如果通过编程生成的):
1 ,2,3,\ n4,5,6,\ n7,8,9,\\\
10,11,12,\\\
13,14,15,
如果在Microsoft Office Excel中打开,它可能如下所示:
要将此 .csv
文件读入您的 QTableView
的模型:
QStandardItemModel * model = new QStandardItemModel;
QFile文件(test.csv);
if(file.open(QIODevice :: ReadOnly)){
int lineindex = 0; // file line counter
QTextStream in(& file); //读到文本流
while(!in.atEnd()){
//从文本流中读取一行(用\\\
分隔)
QString fileLine = in.readLine();
//使用,作为分隔符将读取的行解析为单独的片段(标记)
QStringList lineToken = fileLine.split(,,QString :: SkipEmptyParts);
//根据模型加载解析的数据
for(int j = 0; j< lineToken.size(); j ++){
QString value = lineToken.at j)。
QStandardItem * item = new QStandardItem(value);
model-> setItem(lineindex,j,item);
}
lineindex ++;
}
file.close();
}
(你可以操纵代码来满足表格格式) / strong>
[结果]
Recently I was working on a gui application & I wanted to save the data of QTableView in a .csv or .txt file. I Used the guidance received during this question which made me think if the reverse is also possible; i.e. if the QTableView can be populated from a .csv or .txt file. Once again I would prefer staying with a model based design such as QTableView instead of item based QTableWidget.
Any code-snippet or tutorial-documentation would be really helpful.
Consider a test.csv
file (it could be generated by any text editor):
And the textstream behind is (if generated by programming):
1,2,3,\n4,5,6,\n7,8,9,\n10,11,12,\n13,14,15,
If opened in Microsoft Office Excel, it might looked like:
To read this .csv
file to the model of your QTableView
:
QStandardItemModel *model = new QStandardItemModel;
QFile file("test.csv");
if (file.open(QIODevice::ReadOnly)) {
int lineindex = 0; // file line counter
QTextStream in(&file); // read to text stream
while (!in.atEnd()) {
// read one line from textstream(separated by "\n")
QString fileLine = in.readLine();
// parse the read line into separate pieces(tokens) with "," as the delimiter
QStringList lineToken = fileLine.split(",", QString::SkipEmptyParts);
// load parsed data to model accordingly
for (int j = 0; j < lineToken.size(); j++) {
QString value = lineToken.at(j);
QStandardItem *item = new QStandardItem(value);
model->setItem(lineindex, j, item);
}
lineindex++;
}
file.close();
}
(You could manipulate the code to meet you table format)
[Result]
这篇关于上传.csv或.txt文件以填充QTableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!