以下是可以实现该功能的一个示例代码:
#include <QCoreApplication>
#include <QDomDocument>
#include <QFile>
#include <QDebug>
#include <QTreeWidget>
#include <QTreeWidgetItem>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QDomDocument doc("mydocument");
QFile file(":/MyItem.xml");
if (!file.open(QIODevice::ReadOnly))
return 1;
if (!doc.setContent(&file)) {
file.close();
return 1;
}
file.close();
QTreeWidget treeWidget;
treeWidget.setWindowTitle("XML Viewer");
treeWidget.setHeaderLabels(QStringList() << "Tag" << "Attribute" << "Value");
QDomElement root = doc.documentElement();
QTreeWidgetItem *rootItem = new QTreeWidgetItem(&treeWidget);
rootItem->setText(0, root.tagName());
for (QDomNode node = root.firstChild(); !node.isNull(); node = node.nextSibling()) {
QDomElement element = node.toElement();
if (!element.isNull()) {
QTreeWidgetItem *item = new QTreeWidgetItem(rootItem);
item->setText(0, element.tagName());
// Set attribute
QDomNamedNodeMap attrs = element.attributes();
for (int i = 0; i < attrs.count(); ++i) {
QDomAttr attr = attrs.item(i).toAttr();
QTreeWidgetItem *attrItem = new QTreeWidgetItem(item);
attrItem->setText(1, attr.name());
attrItem->setText(2, attr.value());
}
// Set text
if (!element.text().isEmpty()) {
QTreeWidgetItem *textItem = new QTreeWidgetItem(item);
textItem->setText(2, element.text());
}
// Set desc and name as user data
QVariant desc = element.attribute("Desc");
QVariant name = element.attribute("Name");
item->setData(0, Qt::UserRole, desc);
item->setData(1, Qt::UserRole, name);
}
}
QObject::connect(&treeWidget, &QTreeWidget::itemDoubleClicked, [&](QTreeWidgetItem *item, int column) {
QString desc = item->data(0, Qt::UserRole).toString();
QString name = item->data(1, Qt::UserRole).toString();
if (!desc.isEmpty() || !name.isEmpty()) {
qDebug() << "Desc:" << desc << ", Name:" << name;
}
});
treeWidget.expandAll();
treeWidget.resize(640, 480);
treeWidget.show();
return a.exec();
}
该示例代码中,首先加载了一个 XML 文件,然后使用 QTreeWidget 显示了 XML 文件的节点信息。对于每个元素节点,都将其标签、属性和文本显示在树形控件中,并将该节点的 Desc 和 Name 属性值作为用户数据存储在该节点上。最后,通过连接 itemDoubleClicked 信号实现了双击某个节点时获取其 Desc 和 Name 属性值的功能。