Can';t在QML javascript文件中编辑对象属性

Can';t在QML javascript文件中编辑对象属性,qml,qtquick2,sailfish-os,Qml,Qtquick2,Sailfish Os,有人能解释一下我在以下设置中的错误吗 想法是在engine.js中开发游戏引擎,UI逻辑在qml文件中 page.qml Page { id: page SilicaGridView { id: listView model: ListModel { id: roleList Component.onCompleted: { Engine.addRoles(roleLi

有人能解释一下我在以下设置中的错误吗

想法是在engine.js中开发游戏引擎,UI逻辑在qml文件中

page.qml

Page {
    id: page
    SilicaGridView {
        id: listView
        model: ListModel {
            id: roleList
            Component.onCompleted: {
                Engine.addRoles(roleList);
            }
        }

        delegate: Rectangle {
            id: delegate
            border.color: model.selected ? Theme.highlightColor : Theme.primaryColor

            Label {
                text: qsTr(model.name)
            }
            MouseArea {
                anchors.fill: parent;
                onClicked: {
                    Engine.selectRole(model);
                }
            }
        }
    }
}
engine.js:

function Role() {
    this.name = "role"
    this.selected = false;
}

function addRoles(list) {
    list.append(new Role());
    list.append(new Role());
}

function selectRole(role) {
    console.log(role.selected) // <-- false
    role.selected = true;
    console.log(role.selected) // <-- false
}
函数角色(){
this.name=“角色”
this.selected=false;
}
功能添加角色(列表){
list.append(新角色());
list.append(新角色());
}
函数selectRole(角色){

Qt Quick中的console.log(role.selected)/视图已经有了跟踪所选项目的方法:

这意味着您不需要在
角色中选择
变量

function Role() {
    this.name = "role"
}

function addRoles(list) {
    list.append(new Role());
    list.append(new Role());
}
您的QML代码无法运行(如果您提供了一个工作示例,它确实会有所帮助),因此我冒昧地让它运行:

import QtQuick 2.3
import QtQuick.Controls 1.1

import "Engine.js" as Engine

ApplicationWindow {
    width: 500
    height: 500

    ListView {
        id: listView
        width: 100
        height: 100
        anchors.centerIn: parent

        model: ListModel {
            id: roleList
            Component.onCompleted: {
                Engine.addRoles(roleList);
            }
        }

        delegate: Rectangle {
            id: delegateItem
            border.color: ListView.isCurrentItem ? "red" : "black"
            width: listView.width
            height: 30

            Label {
                id: label
                text: qsTr(model.name)
                anchors.centerIn: parent
            }
            MouseArea {
                anchors.fill: parent;
                onClicked: {
                    listView.currentIndex = index;
                    print(index, delegateItem.ListView.isCurrentItem)
                }
            }
        }
    }
}
请注意ListView的attached属性的使用。这是一个便利属性,相当于:

delegate: Rectangle {
    border.color: listView.currentIndex == index ? "red" : "black"
}

谢谢你的回答,但这实际上不是我想要的。我没有试图在javascript端实现currentItem。我试图在javascript中保留一些关于引擎状态的信息。到目前为止,我发现selectRole函数的模型不是交给delegat的实际模型e、 另外,我认为javascript会在页面更改之间重置。