QListWidget读取本地文件夹中文件并显示名字,双击读取xml数据
生活随笔
收集整理的這篇文章主要介紹了
QListWidget读取本地文件夹中文件并显示名字,双击读取xml数据
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 前言
- 一、讀取本地文件并顯示
- 二、雙擊讀取數(shù)據(jù)
前言
本文主要是為了解決QListWidget讀取本地文件夾中文件,并且顯示的問題。然后雙擊讀取其中xml數(shù)據(jù)
一、讀取本地文件并顯示
如下的函數(shù)是用來讀取本地文件夾中文件,并讀取文件的名字。
QStringList Sensor::getFileNames(const QString &path) {QDir dir(path);QStringList nameFilters;nameFilters <<"*.xml"; //在這換想要讀取的文件的文件格式,可以寫多個格式QStringList files = dir.entryList(nameFilters, QDir::Files|QDir::Readable, QDir::Name);return files; }首先這個是我的文件路徑,現(xiàn)在調(diào)試放在debug中,如果打包成exe直接放在exe根目錄
所以我的路徑使用這樣獲取
使用如下
void Sensor::readfile() {qDebug() << QApplication::applicationDirPath() + "/xml/Sensor";QStringList fileName = getFileNames(QApplication::applicationDirPath() + "/xml/Sensor");qDebug() << fileName;ui->listWidget_xml->clear(); //先清除上一次的數(shù)據(jù)for (int i=0;i<fileName.size();i++) {ui->listWidget_xml->addItem(fileName[i]); //把讀取到的數(shù)據(jù)寫入到QListWidget中}}二、雙擊讀取數(shù)據(jù)
第一步選擇雙擊的槽函數(shù)
槽函數(shù)代碼如下(示例):
void Sensor::on_listWidget_xml_doubleClicked(const QModelIndex &index) {qDebug()<< QApplication::applicationDirPath() + "/xml/Sensor";QString Path = QApplication::applicationDirPath() + "/xml/Sensor";QString file = ui->listWidget_xml->currentItem()->text(); //獲取到item的數(shù)據(jù)Path.append("/"+file);QStringList sensor = GetStringConfigValue(Path);qDebug()<<sensor; // ui->tabWidg_PF; } //獲取字符串字段 QStringList Sensor::GetStringConfigValue(QString str) {if(str == "InitDeviceNo"){ // return getMacPath();}else{QString filePath= str;QStringList names;打開或創(chuàng)建文件QFile file(filePath); //相對路徑、絕對路徑、資源路徑都行if(!file.open(QFile::ReadOnly)){}QDomDocument doc;if(!doc.setContent(&file)){file.close();}file.close();QDomElement root=doc.documentElement(); //返回根節(jié)點QDomNode node=root.firstChild(); //獲得第一個子節(jié)點while(!node.isNull()) //如果節(jié)點不空{if(node.isElement()) //如果節(jié)點是元素{QDomElement domElement =node.toElement(); //轉(zhuǎn)換為元素,注意元素和節(jié)點是兩個數(shù)據(jù)結(jié)構(gòu),其實差不多qDebug() << domElement.nodeName() << ":" << domElement.toElement().attribute("id")<< domElement.toElement().attribute("naming");QString id = domElement.toElement().attribute("id");QString naming = domElement.toElement().attribute("naming");names.append(id);names.append(naming);}node=node.nextSibling(); //下一個兄弟節(jié)點,nextSiblingElement()是下一個兄弟元素,都差不多}return names;} }總結(jié)
以上是生活随笔為你收集整理的QListWidget读取本地文件夹中文件并显示名字,双击读取xml数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt实现Matlab的等差函数linSp
- 下一篇: Jupyter Notebook 代码自