用C++保存QTreeWidget到xml,再读取xml显示为QTreeWidget
时间: 2024-05-08 22:15:28
浏览: 132
以下是一个示例代码,可以将QTreeWidget保存为XML文件,并从XML文件中读取并显示为QTreeWidget:
#include <QtWidgets>
#include <QtXml>
QDomElement widgetToDomXml(QTreeWidgetItem *item, QDomDocument &doc)
QDomElement element = doc.createElement(item->text(0));
for(int i=0; i<item->childCount(); i++) {
QTreeWidgetItem *child = item->child(i);
element.appendChild(widgetToDomXml(child, doc));
return element;
void widgetFromDomXml(QTreeWidgetItem *parent, QDomElement &element)
QTreeWidgetItem *item = new QTreeWidgetItem(parent);
item->setText(0, element.tagName());
QDomNodeList children = element.childNodes();
for(int i=0; i<children.count(); i++) {
QDomNode childNode = children.item(i);
if(childNode.isElement()) {
QDomElement childElement = childNode.toElement();
widgetFromDomXml(item, childElement);
bool saveTreeWidgetToXml(const QTreeWidget *treeWidget, const QString &fileName)
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly)) {
return false;
QDomDocument doc;
QDomElement root = doc.createElement("TreeWidget");
doc.appendChild(root);
for(int i=0; i<treeWidget->topLevelItemCount(); i++) {
QTreeWidgetItem *item = treeWidget->topLevelItem(i);
root.appendChild(widgetToDomXml(item, doc));
QTextStream stream(&file);
stream << doc.toString();
file.close();
return true;
bool loadTreeWidgetFromXml(QTreeWidget *treeWidget, const QString &fileName)
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly)) {
return false;
QDomDocument doc;
if(!doc.setContent(&file)) {
file.close();
return false;
file.close();
QDomElement root = doc.documentElement();
for(int i=0; i<root.childNodes().count(); i++) {
QDomNode childNode = root.childNodes().item(i);
if(childNode.isElement()) {
QDomElement childElement = childNode.toElement();
widgetFromDomXml(treeWidget->invisibleRootItem(), childElement);
return true;
```