用C++保存QTreeWidget多列数据到xml,再读取xml显示为QTreeWidget
时间: 2024-05-08 09:17:26 浏览: 57
QT QTreewidget显示和修改xml文件并导出
实现方法:
1.将QTreeWidget的数据保存到xml文件中。
2.从xml文件中读取数据并显示在QTreeWidget中。
下面是示例代码:
保存QTreeWidget多列数据到xml:
```c++
void saveToXml(QTreeWidget *treeWidget, const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QXmlStreamWriter writer(&file);
writer.setAutoFormatting(true);
writer.writeStartDocument();
writer.writeStartElement("tree");
for (int i = 0; i < treeWidget->topLevelItemCount(); i++) {
QTreeWidgetItem *item = treeWidget->topLevelItem(i);
writer.writeStartElement("item");
for (int j = 0; j < item->columnCount(); j++) {
writer.writeStartElement("column");
writer.writeAttribute("index", QString::number(j));
writer.writeCharacters(item->text(j));
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndDocument();
file.close();
}
```
从xml文件中读取数据并显示在QTreeWidget中:
```c++
void loadFromXml(QTreeWidget *treeWidget, const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QXmlStreamReader reader(&file);
while (!reader.atEnd()) {
reader.readNext();
if (reader.isStartElement() && reader.name() == "item") {
QTreeWidgetItem *item = new QTreeWidgetItem();
while (!reader.atEnd()) {
reader.readNext();
if (reader.isStartElement() && reader.name() == "column") {
int index = reader.attributes().value("index").toInt();
item->setText(index, reader.readElementText());
}
if (reader.isEndElement() && reader.name() == "item") {
treeWidget->addTopLevelItem(item);
break;
}
}
}
}
file.close();
}
```
阅读全文