Search code examples
qtqmlqtquick2

How can I get a specific value by index from a custom Model in QML?


I'm trying to get the name from a specific user based on an index from the UserModel (which is a list model according to the wiki).

When I attempt to print out the name using console.log("username: {" + userModel.get(userList.currentSelected).name+ "}"), I get the following error:

Main.qml:56: TypeError: Type error

SDDM repository: https://github.com/sddm/sddm/wiki/Theming

I tried userModel.get(0), userModel.at(0), userModel[0] but none of those have worked for me.

Main.qml
import QtQuick 2.15
import SddmComponents 2.0

Item {
    id: root
    focus: true
    Keys.onPressed: (event)=> {
        console.log("Object entries:" + Object.entries(userModel));
        console.log(userModel.itemData(userModel.index(0, 0)));
        console.log("username: {" + userModel.get(0).name+ "}")
    }
}

Edit: here is the output of object.entries:

[[objectName,],[lastIndex,0],[lastUser,],[count,4],[disableAvatarsThreshold,7],[containsAllUsers,true],[objectNameChanged,function() { [native code] }],[dataChanged,function() { [native code] }],[headerDataChanged,function() { [native code] }],[layoutChanged,function() { [native code] }],[layoutAboutToBeChanged,function() { [native code] }],[rowsAboutToBeInserted,function() { [native code] }],[rowsInserted,function() { [native code] }],[rowsAboutToBeRemoved,function() { [native code] }],[rowsRemoved,function() { [native code] }],[columnsAboutToBeInserted,function() { [native code] }],[columnsInserted,function() { [native code] }],[columnsAboutToBeRemoved,function() { [native code] }],[columnsRemoved,function() { [native code] }],[modelAboutToBeReset,function() { [native code] }],[modelReset,function() { [native code] }],[rowsAboutToBeMoved,function() { [native code] }],[rowsMoved,function() { [native code] }],[columnsAboutToBeMoved,function() { [native code] }],[columnsMoved,function() { [native code] }],[submit,function() { [native code] }],[revert,function() { [native code] }],[resetInternalData,function() { [native code] }],[hasIndex,function() { [native code] }],[index,function() { [native code] }],[parent,function() { [native code] }],[sibling,function() { [native code] }],[rowCount,function() { [native code] }],[columnCount,function() { [native code] }],[hasChildren,function() { [native code] }],[data,func tion() { [native code] }],[setData,function() { [native code] }],[headerData,function() { [native code] }],[fetchMore,function() { [native code] }],[canFetchMore,function() { [native code] }],[flags,function() { [native code] }],[match,function() { [native code] }]]


Solution

  • As @smr stated in the comments, userModel.data(userModel.index(0,0), 257) is the correct function.

    QAbstractItemModel::data Qt::ItemDataRole