QML:setProperty没有效果

时间:2016-03-13 07:55:50

标签: qt qml qt5

当我尝试更改包含在ListModel中的项的属性值时,以下代码无效:

Main.qml

import QtQuick 2.0

Item {
    anchors.fill: parent

    ListModel { id: modelCrayon }

    Component.onCompleted: {
        for (var i = 0; i < 10; i++)
            modelCrayon.append( { _tag: i, _source: "resources/crayon-green.png", _selected: false } )
    }

    Column {
        x: -170
        spacing: 0
        Repeater {
            model: modelCrayon
            delegate: Crayon {
                tag: _tag
                source: _source
                selected: _selected
                onCrayonSelected: {
                    for (var i = 0; i < modelCrayon.count; i++) {
                        if (i == tag) continue;
                        modelCrayon.setProperty(i, "_selected", false);
                    }
                }
            }
        }
    }
}

Crayon.qml

import QtQuick 2.0

Image {
    property bool selected
    property int tag
    signal crayonSelected()

    id: crayon
    smooth: true
    fillMode: Image.PreserveAspectFit

    onSelectedChanged: console.debug(tag, selected)

    MouseArea {
        anchors.fill: parent
        onClicked: {
            selected = !selected
            if (selected) crayonSelected()
        }
    }

    states: State {
        name: "selected"; when: selected == true
        PropertyChanges { target: crayon; x: 30 }
    }

    transitions: Transition {
        from: ""; to: "selected"
        PropertyAnimation { property: "x"; duration: 500; easing.type: Easing.InOutQuad }
    }

}

控制台上没有显示任何内容,因此&#34;已选择&#34; var永远不会改变。 我确定有一些显而易见的东西我不知道。

顺便问一下,有没有更聪明的方法将ListModel用作OptionBox?我的意思是我只想要一个项目必须具有所选属性== true。或者,换句话说,保留所选索引的轨迹。

2 个答案:

答案 0 :(得分:0)

这是一个实现我要求的工作代码。但它没有回答为什么没有设置财产。

ListView {
        id: list
        anchors.verticalCenter: parent.verticalCenter
        height: parent.height
        x: -150
        spacing: 0
        orientation: ListView.Vertical
        focus: true
        model: modelCrayon
        delegate: Crayon {
            id: delegate
            source: _source
            selected: ListView.isCurrentItem

            MouseArea {
                anchors.fill: parent
                onClicked: list.currentIndex = index
            }
        }
    }

答案 1 :(得分:0)

我已经测试了您的示例代码(Column版本),它适用于Qt 5.4 / Windows 7 64位。

您的运行环境是什么?