You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解析XML文件并在QML ListView中展示患者信息?

把XML患者信息展示到QML ListView的实现方案

1. 解析XML数据

QML自带XmlListModel,不用写C++代码就能直接解析XML,适合新手快速上手。先根据你的XML结构定义数据模型:
假设你的XML结构类似(如果实际节点名不同,对应修改路径即可):

<patients>
    <patient>
        <id>P001</id>
        <name>张三</name>
        <age>45</age>
        <diagnosis>高血压</diagnosis>
    </patient>
    <patient>
        <id>P002</id>
        <name>李四</name>
        <age>32</age>
        <diagnosis>糖尿病</diagnosis>
    </patient>
</patients>

对应的XmlListModel代码:

XmlListModel {
    id: patientModel
    source: "patients.xml" // XML文件路径,和QML同目录直接写文件名,资源文件加qrc:/前缀
    query: "/patients/patient" // XPath定位到每个患者节点

    // 提取每个字段
    XmlRole { name: "id"; query: "id/string()" }
    XmlRole { name: "name"; query: "name/string()" }
    XmlRole { name: "age"; query: "age/string()" }
    XmlRole { name: "diagnosis"; query: "diagnosis/string()" }
}

2. 用ListView渲染条目

创建ListView绑定上面的模型,自定义delegate来实现你想要的条目样式:

ListView {
    width: 400
    height: 600
    model: patientModel
    spacing: 10
    padding: 10

    // 每个患者的条目模板
    delegate: Rectangle {
        width: parent.width
        height: 100
        color: "#f5f5f5"
        radius: 8
        border.color: "#ddd"
        border.width: 1

        Column {
            anchors.fill: parent
            anchors.margins: 15
            spacing: 5

            Text {
                text: "患者ID: " + id
                font.bold: true
                font.pointSize: 12
            }
            Text {
                text: "姓名: " + name
                font.pointSize: 11
            }
            Text {
                text: "年龄: " + age + "岁"
                font.pointSize: 11
            }
            Text {
                text: "诊断: " + diagnosis
                font.pointSize: 11
                color: "#666"
            }
        }
    }
}

3. 关键注意点

  • 路径要正确:如果XML是Qt资源文件,source要写成qrc:/patients.xml;本地文件确保和QML文件在同一目录,或者用绝对路径。
  • 适配你的XML结构:如果XML里的节点名、层级和示例不同,修改query和XmlRole里的XPath路径即可。比如如果患者信息是用属性存的(<patient id="P001" name="张三"/>),XmlRole的query要改成@id、@name这种格式。
  • 样式自由调整:可以根据需求修改条目背景色、字体、布局,甚至添加按钮、图标等元素。

内容的提问来源于stack exchange,提问作者Phạm Hồng Nhung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:45:10