save QTreeWidget to xml with C++
时间: 2024-05-10 11:20:51 浏览: 97
Here is an example code to save the contents of a QTreeWidget to an XML file using C++:
```c++
#include <QtXml>
#include <QTreeWidget>
#include <QTreeWidgetItem>
void saveTreeToXml(QTreeWidget* treeWidget, const QString& fileName)
{
QDomDocument doc;
QDomElement root = doc.createElement("tree");
doc.appendChild(root);
for (int i = 0; i < treeWidget->topLevelItemCount(); ++i)
{
QTreeWidgetItem* topLevelItem = treeWidget->topLevelItem(i);
if (topLevelItem)
{
QDomElement topLevelElement = doc.createElement("item");
root.appendChild(topLevelElement);
saveTreeItemToXml(doc, topLevelElement, topLevelItem);
}
}
QFile file(fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream stream(&file);
stream << doc.toString();
file.close();
}
}
void saveTreeItemToXml(QDomDocument& doc, QDomElement& parentElement, QTreeWidgetItem* item)
{
QDomElement element = doc.createElement("item");
parentElement.appendChild(element);
QDomElement nameElement = doc.createElement("name");
nameElement.appendChild(doc.createTextNode(item->text(0)));
element.appendChild(nameElement);
for (int i = 1; i < item->columnCount(); ++i)
{
QDomElement valueElement = doc.createElement("value");
valueElement.setAttribute("column", i);
valueElement.appendChild(doc.createTextNode(item->text(i)));
element.appendChild(valueElement);
}
for (int i = 0; i < item->childCount(); ++i)
{
QTreeWidgetItem* childItem = item->child(i);
if (childItem)
{
saveTreeItemToXml(doc, element, childItem);
}
}
}
```
This code first creates a new QDomDocument object and adds a root element to it. Then, it iterates through all top-level items of the QTreeWidget and calls a helper function to save each item to the XML document. The helper function recursively saves all child items of each top-level item.
The saveTreeItemToXml function creates a new "item" element in the XML document for the given QTreeWidgetItem. It adds a "name" element with the text of the first column of the item, and then iterates through all remaining columns to add "value" elements with the column number and text of each column. Finally, it recursively calls itself for each child item of the given item.
The resulting XML file will have the following structure:
```xml
<tree>
<item>
<name>Top-level item 1</name>
<value column="1">Value 1</value>
<value column="2">Value 2</value>
<item>
<name>Child item 1</name>
<value column="1">Value 3</value>
<value column="2">Value 4</value>
</item>
<item>
<name>Child item 2</name>
<value column="1">Value 5</value>
<value column="2">Value 6</value>
</item>
</item>
<item>
<name>Top-level item 2</name>
<value column="1">Value 7</value>
<value column="2">Value 8</value>
</item>
</tree>
```
To use this code, simply call the saveTreeToXml function with the QTreeWidget object and a file name as parameters.
阅读全文