本例子中把xml文件作为数据库表。
xml文件名作为函数参数,把不同的xml文件名传入函数,会显示不同的文件内容。
以下为代码:
- void MainWindow::ShowContent(QString FileName)
- {
- LoadXmlContent(FileName);
- ShowContentInView();
-
- }
-
- bool MainWindow::LoadXmlContent(QString FileName)
- {
- QString FilePath = "yourpath/" + FileName + ".xml";
- QFile file(FilePath); // 替换为您实际的文件路径
- if (!file.open(QIODevice::ReadOnly)) {
- qDebug() << "Can not open file。";
- return false;
- }
-
- QDomDocument document;
- if (!document.setContent(&file)) {
- qDebug() << "无法将文件解析为DOM树。";
- file.close();
- return false;
- }
- file.close();
-
- dataVector.clear();
- QDomElement root = document.firstChildElement(); // 获取根元素
-
- // 遍历所有子元素
- QDomNodeList elements = root.childNodes();
-
- for (int i = 0; i < elements.count(); i++) {
- QDomNode elementNode = elements.at(i);
- // 检查节点是否为元素。
- if (elementNode.isElement()) {
- QDomElement element = elementNode.toElement();
-
- QDomNodeList childNodes = element.childNodes();
-
- // 创建一个字典来存储键值对
- std::map
dataMap; -
- for (int j = 0; j < childNodes.count(); j++) {
- QDomNode childNode = childNodes.at(j);
- if (childNode.isElement()) {
- QDomElement childElement = childNode.toElement();
- QString key = childElement.nodeName();
- QString value = childElement.text();
- // 将键值对存入字典
- dataMap[key] = value;
- }
- }
-
- // 将字典存入vector
- dataVector.push_back(dataMap);
- }
- }
-
- // 打印存储的数据
- for (const auto& data : dataVector) {
- for (const auto& pair : data) {
- qDebug() << pair.first << ":" << pair.second;
- }
- qDebug() << "-------------------";
- }
- }
-
- void MainWindow::ShowContentInView()
- {
-
- m_model.clear();
-
- // 设置表头顺序
- QStringList headers = {"name", "len", "type", "value", "reverse", "factor", "isSelected", "dimension", "displaytext", "option", "showPercision"};
- m_model.setHorizontalHeaderLabels(headers);
-
- // 假设您已经有一个包含字典的vector
- //std::vector
> dataVector; -
- // 遍历vector中的每一项
- for (const auto &data : dataVector) {
- // 创建一个新的行
- QList
rowItems; -
- // 使用迭代器遍历字典中的键值对
- for (const QString &header : headers) {
- // 查找当前键
- auto it = data.find(header);
- if (it != data.end()) {
- QString value = it->second;
- rowItems.append(new QStandardItem(value));
- } else {
- // 如果键不存在,添加一个空单元格
- rowItems.append(new QStandardItem(""));
- }
- }
-
- // 将一行添加到模型
- m_model.appendRow(rowItems);
- }
-
-
-
- // 将模型与QTableView关联
- ui->tableView->setModel(&m_model);
-
- QHeaderView *headerView = ui->tableView->horizontalHeader();
- headerView->setSectionResizeMode(QHeaderView::ResizeToContents); // 根据内容调整列宽
- headerView->resizeSection(0, 100);
-
- // 显示窗口
- ui->tableView->show();
-
-
- }