Qt读取xml文件并把内容显示到QTableview上

编程入门 行业动态 更新时间:2024-10-26 20:22:06

Qt读取xml文件<a href=https://www.elefans.com/category/jswz/34/1744082.html style=并把内容显示到QTableview上"/>

Qt读取xml文件并把内容显示到QTableview上

本例子中把xml文件作为数据库表。

xml文件名作为函数参数,把不同的xml文件名传入函数,会显示不同的文件内容。

以下为代码:

void MainWindow::ShowContent(QString FileName)
{LoadXmlContent(FileName);ShowContentInView();}bool MainWindow::LoadXmlContent(QString FileName)
{QString FilePath = "yourpath/" + FileName + ".xml";QFile file(FilePath); // 替换为您实际的文件路径if (!file.open(QIODevice::ReadOnly)) {qDebug() << "Can not open file。";return false;}QDomDocument document;if (!document.setContent(&file)) {qDebug() << "无法将文件解析为DOM树。";file.close();return false;}file.close();dataVector.clear();QDomElement root = document.firstChildElement(); // 获取根元素// 遍历所有子元素QDomNodeList elements = root.childNodes();for (int i = 0; i < elements.count(); i++) {QDomNode elementNode = elements.at(i);// 检查节点是否为元素。if (elementNode.isElement()) {QDomElement element = elementNode.toElement();QDomNodeList childNodes = element.childNodes();// 创建一个字典来存储键值对std::map<QString, QString> dataMap;for (int j = 0; j < childNodes.count(); j++) {QDomNode childNode = childNodes.at(j);if (childNode.isElement()) {QDomElement childElement = childNode.toElement();QString key = childElement.nodeName();QString value = childElement.text();// 将键值对存入字典dataMap[key] = value;}}// 将字典存入vectordataVector.push_back(dataMap);}}// 打印存储的数据for (const auto& data : dataVector) {for (const auto& pair : data) {qDebug() << pair.first << ":" << pair.second;}qDebug() << "-------------------";}
}void MainWindow::ShowContentInView()
{m_model.clear();// 设置表头顺序QStringList headers = {"name", "len", "type", "value", "reverse", "factor", "isSelected", "dimension", "displaytext", "option", "showPercision"};m_model.setHorizontalHeaderLabels(headers);// 假设您已经有一个包含字典的vector//std::vector<std::map<QString, QString>> dataVector;// 遍历vector中的每一项for (const auto &data : dataVector) {// 创建一个新的行QList<QStandardItem *> rowItems;// 使用迭代器遍历字典中的键值对for (const QString &header : headers) {// 查找当前键auto it = data.find(header);if (it != data.end()) {QString value = it->second;rowItems.append(new QStandardItem(value));} else {// 如果键不存在,添加一个空单元格rowItems.append(new QStandardItem(""));}}// 将一行添加到模型m_model.appendRow(rowItems);}// 将模型与QTableView关联ui->tableView->setModel(&m_model);QHeaderView *headerView = ui->tableView->horizontalHeader();headerView->setSectionResizeMode(QHeaderView::ResizeToContents); // 根据内容调整列宽headerView->resizeSection(0, 100);// 显示窗口ui->tableView->show();}

更多推荐

Qt读取xml文件并把内容显示到QTableview上

本文发布于:2023-11-15 21:06:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606351.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并把   文件   内容   Qt   xml

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!