使用QML使用fileUrl创建动态图像ListElement

时间:2015-04-19 11:36:08

标签: qt listview qml qtquick2 filedialog

我是QML编程的新手。我想在点击ListElement的“打开”按钮后,在ListModel中创建FileDialog的动态图片。我的问题是,在添加第二图像时,第一图像也被第二图像替换。如何单独更新Image内的ListElement?这是我的代码:

  Component{
    id:delegate
    Item{
        height: 100
        visible: true
        width :100

        Rectangle{
            id: list
            height: 100
            width:height
            color : "#20292A"
            border.color: "#3A8A86"
            border.width: 4
            radius: 3
            visible:true
            Image{
                x: 3
                y: 3
                height : 95
                visible: true
                width : height
                source:mod[index]//fileDialog.fileUrl

            }
        }
    }
}
ListModel{
    id:mod
}
Rectangle{
    id:listdata
    x: 180
    y: 577
    height: 100
    width:841
    color : "#20292A"
    border.color: "#3A8A86"
    border.width: 4
    radius: 3
    visible:true

    Row{
        y: 4
        height:90
        width:841
        anchors.fill: list
        spacing: 50
        visible: true

        ListView{
            id:view
            x: 193
            y: 1
            width: 841
            height: 90
            model:mod
            clip: true
            delegate: delegate
            anchors.fill: listdata
            anchors.bottomMargin: 78
            visible: true
            interactive: true
            anchors.leftMargin: 190
            anchors.left: window.left
            anchors.bottom: window.bottom

            orientation: Qt.Horizontal
            layoutDirection : Qt.LeftToRight
            anchors.horizontalCenter: window
            anchors.verticalCenter: window
            spacing: 50


        }
    }   
}    

FileDialog {
            id: fileDialog
            selectExisting: fileDialogSelectExisting.checked

            modality: fileDialogModal.checked ? Qt.WindowModal : Qt.NonModal
            title: "Please choose a file"
            onAccepted: {
                console.log("You chose: " + fileDialog.fileUrls)
                mod.append(fileDialog.fileUrls)
            }
            onRejected: {
                console.log("Canceled")
                Qt.quit()
          }
        }

1 个答案:

答案 0 :(得分:2)

QML ListModel需要追加的JSON字典 http://doc.qt.io/qt-5/qml-qtqml-models-listmodel.html

它不是容器,因此您无法访问数组的索引。

要使其正常工作,首先需要更改附加功能以存储json:

mod.append({"fileUrl": fileDialog.fileUrl.toString()})

然后,您可以通过其JSON名称访问委托调用中的元素:

source: fileUrl

您不必担心代理中的索引位置,它总是会访问当前元素。