PAYATHON 2026

如何以编程方式创建 ListModel 并收集命令输出

数据小陈

结论: 问题通常不在 ListModel {} 本身,而在 onRead 回调里用错了 this。在 SplitParser 的 onRead 中,this 不能可靠地指向外层的 Process,所以 this.data 是 undefined。改用 Process 的 id 引用模型,并给 ListModel.append() 传入带角色的对象,例如:

cpu_usage.data.append({ value: Number(input) })

原因

  1. this 指向不对。data 是 Process 的属性,不是 SplitParser 的属性,使用 cpu_usage.data 最稳妥。
  2. ListModel.append() 需要对象。直接写 append(parseFloat(input)) 传入的是数字,不是带角色名的对象;应写成 append({ value: parseFloat(input) })。
  3. console.log 可能看不到。QML 的 console.log 一般会进入 Quickshell/Qt 的日志通道,可能被日志级别过滤,也可能输出到启动 Quickshell 的终端或服务日志里。

修改示例

Row {
    id: cpu_usage_widget
    anchors.right: tray.left
    padding: 3
    spacing: 4

    Repeater {
        model: cpu_usage.data

        Rectangle {
            width: 12
            height: 24
            color: inactive
            radius: 2

            Rectangle {
                anchors.bottom: parent.bottom
                width: 12
                height: index
                color: active
                radius: 2
            }
        }
    }

    Process {
        id: cpu_usage
        property ListModel data: ListModel {}

        command: ["cpu_usage", "--all"]
        running: true

        stdout: SplitParser {
            onRead: input => {
                const v = parseFloat(input);
                if (!isNaN(v)) {
                    cpu_usage.data.append({ value: v });
                }
            }
        }
    }
}

如果柱高要表示采集到的值,把内层 Rectangle 的 height: index 改成 height: value,再按实际范围做缩放。原代码里的 index 只是 Repeater 的序号,不是 CPU 使用率。

查看 console.log

  • 从终端启动 Quickshell 时,查看启动它的终端输出。
  • 作为 systemd 用户服务运行时,查看对应服务日志,例如 journalctl --user -u <你的服务名> -f。
  • 可以临时把 console.log 换成 console.warn 或 console.error,确认是不是日志级别把信息过滤掉了。
  • 同时确认 cpu_usage --all 确实有输出并以换行分隔,否则 SplitParser 的 onRead 可能不会触发。

注意事项

  • 不要依赖 this 在信号处理器中指向外层对象,优先使用 id。
  • append() 的参数是对象;角色名要与 delegate 中访问的名称一致。
  • 如果只想保留最新值,在 append 前调用 cpu_usage.data.clear(),或改用单个 property real 保存最新值。
  • 如果每行输出都要累计,当前 ListModel 方案可以;但 Repeater 会为每个元素创建一个柱。

备注:内容仅供参考。