Qt中TreeModel中读取文件内容进行显示注意事项
根据案例,为实现在读取txt文件中的内容显示在treeView界面内实现下图(树模型)效果,本次主要讲解我遇到的困难:
以下代码实现文件的打开、读取,为更好的展示效果,我运用file.pos()函数定位指针位置,file.seek()函数跳转指针位置。
void Widget::setTreeView(){
QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
cout<<"file.pos start:"<<file.pos()<<endl;
cout<<"file.readAll():"<<file.readAll().toStdString()<<endl;
cout<<"file.pos end:"<<file.pos()<<endl;
file.seek(0);
cout<<"file.pos start1:"<<file.pos()<<endl;
cout<<"file.readAll()1:"<<file.readAll().toStdString()<<endl;
cout<<"file.pos end1:"<<file.pos()<<endl;
file.seek(0);
static QString TreeModelData(file.readAll()); //静态变量存储,否则函数调用结束后会失效,不显示;也可定义成员变量进行实现;《《《《《非常重要》》》》》
treemodel= new TreeModel(TreeModelData,ui->treeView);
file.close();
ui->treeView->setModel(treemodel);
}
readAll()函数只能读取一次,读取后 相当于指针发生偏移,不会自动归位,如果下次继续读取,结果将为空;需要注意的是内容并没有删除,只是指针发生偏移而已。
seek()函数会将指针重新定位,这样就可以继续实现读取内容。
最重要的是内存的处理,尤为重要。
file.pos start:0
file.readAll():。。。。。。。。
file.pos end:2017
file.pos start1:0
file.readAll()1:。。。。。。。。
file.pos end1:2017
以上为实现的结果