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

如何在QML中通过索引从SDDM UserModel获取指定用户属性?

解决QML中SDDM UserModel通过索引获取用户属性的TypeError问题

常见原因及对应解决方案

1. 模型未完成初始化就访问

SDDM的UserModel需要异步加载系统用户数据,若在加载完成前调用get()/at()等方法,会返回undefined触发TypeError。

解决方式:监听模型加载状态,确保数据就绪后再访问,比如监听count变化:

UserModel {
    id: userModel
    onCountChanged: {
        if (count > 0) {
            console.log("username: " + getValidUserName(0))
        }
    }
}

function getValidUserName(index) {
    if (index < 0 || index >= userModel.count) return ""
    // 用下文的正确方式获取属性
}

2. 误用ListModel方法访问C++导出模型

SDDM的UserModel是C++实现的QAbstractListModel,并非QML原生ListModel,因此不支持get()/at()方法,也不能直接用[]下标访问。

正确方式是通过roleNames()获取角色ID,再用data()方法读取属性:

// 提前获取name角色的ID
property int nameRole: userModel.roleNames().name

function getUserName(index) {
    if (index < 0 || index >= userModel.count) return ""
    var userIndex = userModel.index(index, 0)
    return userModel.data(userIndex, nameRole)
}

// 调用示例
console.log("username: " + getUserName(userList.currentSelected))

3. 索引值无效

检查userList.currentSelected是否为有效索引(范围0到userModel.count-1),如果是-1(未选中任何项),访问时必然报错:

console.log("current selected index: " + userList.currentSelected)
if (userList.currentSelected >= 0 && userList.currentSelected < userModel.count) {
    console.log("username: " + getUserName(userList.currentSelected))
} else {
    console.log("invalid selected index")
}

完整测试代码片段

import QtQuick 2.15
import org.kde.sddm 1.0

Item {
    width: 200
    height: 200

    UserModel {
        id: userModel
        onCountChanged: {
            if (count > 0) {
                testUserAccess()
            }
        }
    }

    ListView {
        id: userList
        anchors.fill: parent
        model: userModel
        delegate: Text { text: name }
    }

    property int nameRole: userModel.roleNames().name

    function getUserName(index) {
        if (index < 0 || index >= userModel.count) return ""
        var userIndex = userModel.index(index, 0)
        return userModel.data(userIndex, nameRole)
    }

    function testUserAccess() {
        // 测试索引0的用户
        console.log("user at index 0: " + getUserName(0))
        // 测试当前选中项
        if (userList.currentSelected >= 0) {
            console.log("selected user: " + getUserName(userList.currentSelected))
        }
    }
}

内容的提问来源于stack exchange,提问作者imstuff1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:17:24