用C++保存QTreeWidget多列数据到xml,再读取xml显示为QTreeWidget
时间: 2024-04-29 07:23:25 浏览: 122
QT QTreewidget显示和修改xml文件并导出
以下是一个示例代码,展示如何使用Qt的QXmlStreamWriter和QXmlStreamReader将QTreeWidget的多个列数据保存到XML文件中,并从XML文件中读取并显示在QTreeWidget中。
保存QTreeWidget到XML:
```c++
void MainWindow::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("TreeWidget");
for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) {
QTreeWidgetItem *item = treeWidget->topLevelItem(i);
saveItem(writer, item);
}
writer.writeEndElement();
writer.writeEndDocument();
file.close();
}
void MainWindow::saveItem(QXmlStreamWriter &writer, QTreeWidgetItem *item)
{
writer.writeStartElement("Item");
writer.writeAttribute("text", item->text(0));
for (int i = 1; i < item->columnCount(); ++i) {
writer.writeStartElement("Column");
writer.writeAttribute("index", QString::number(i));
writer.writeCharacters(item->text(i));
writer.writeEndElement();
}
for (int i = 0; i < item->childCount(); ++i) {
QTreeWidgetItem *child = item->child(i);
saveItem(writer, child);
}
writer.writeEndElement();
}
```
从XML加载QTreeWidget:
```c++
void MainWindow::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() == "TreeWidget") {
loadTreeWidget(reader, treeWidget);
}
}
file.close();
}
void MainWindow::loadTreeWidget(QXmlStreamReader &reader, QTreeWidget *treeWidget)
{
while (!reader.atEnd()) {
reader.readNext();
if (reader.isEndElement() && reader.name() == "TreeWidget") {
break;
}
if (reader.isStartElement() && reader.name() == "Item") {
loadItem(reader, treeWidget);
}
}
}
void MainWindow::loadItem(QXmlStreamReader &reader, QTreeWidgetItem *parent)
{
QString text;
QList<QString> columns;
if (reader.attributes().hasAttribute("text")) {
text = reader.attributes().value("text").toString();
}
while (!reader.atEnd()) {
reader.readNext();
if (reader.isEndElement() && reader.name() == "Item") {
break;
}
if (reader.isStartElement() && reader.name() == "Column") {
int index = reader.attributes().value("index").toInt();
QString column = reader.readElementText();
while (columns.size() < index) {
columns.append("");
}
columns[index - 1] = column;
}
}
QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList(text));
for (int i = 0; i < columns.size(); ++i) {
item->setTextAlignment(i + 1, Qt::AlignCenter);
item->setText(i + 1, columns[i]);
}
while (!reader.atEnd()) {
reader.readNext();
if (reader.isEndElement() && reader.name() == "Item") {
break;
}
if (reader.isStartElement() && reader.name() == "Item") {
loadItem(reader, item);
}
}
}
```
阅读全文