ListModel QML Type

자유 형식 목록 데이터 소스를 정의합니다. 자세히...

Import Statement: import QtQml.Models

속성

방법

상세 설명

ListModel은 각각 데이터 역할을 포함하는 ListElement 정의의 간단한 컨테이너입니다. 내용은 동적으로 정의하거나 QML에서 명시적으로 정의할 수 있습니다.

모델의 요소 수는 count 속성에서 얻을 수 있습니다. append (), insert(), move(), remove() 및 set() 등 모델의 내용을 조작하기 위한 여러 가지 친숙한 메서드도 제공됩니다. 이러한 메서드는 딕셔너리를 인자로 받아 모델에 의해 ListElement 객체로 변환됩니다.

지정된 엘리먼트의 역할을 설정하고 변경할 수 있는 setProperty() 메서드를 사용하여 모델을 통해 엘리먼트를 조작할 수 있습니다.

ListModel은 QAbstractListModel 에서 상속되며 Q_INVOKABLE 메서드를 제공합니다. 예를 들어 QAbstractItemModel::index 을 사용하여 행과 열에 대한 QModelIndex 을 검색할 수 있습니다.

사용 예

다음 예는 "name" 및 "cost" 역할이 있는 세 개의 요소를 포함하는 ListModel을 보여줍니다.

import QtQuick

ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        cost: 1.95
    }
}

각 요소의 역할(속성)은 소문자로 시작해야 하며 모델의 모든 요소에 공통적으로 적용되어야 합니다. ListElement 문서에서 요소를 정의하는 방법에 대한 자세한 지침을 확인할 수 있습니다.

예제 모델에는 id 속성이 포함되어 있으므로 이 예제의 ListView 같은 보기에서 참조할 수 있습니다:

import QtQuick

Rectangle {
    width: 200; height: 200

    ListModel {
        id: fruitModel
        ...
    }

    Component {
        id: fruitDelegate
        Row {
            spacing: 10
            Text { text: name }
            Text { text: '$' + cost }
        }
    }

    ListView {
        anchors.fill: parent
        model: fruitModel
        delegate: fruitDelegate
    }
}

역할에 목록 데이터가 포함될 수 있습니다. 다음 예에서는 과일 속성 목록을 만듭니다:

ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        cost: 2.45
        attributes: [
            ListElement { description: "Core" },
            ListElement { description: "Deciduous" }
        ]
    }
    ListElement {
        name: "Orange"
        cost: 3.25
        attributes: [
            ListElement { description: "Citrus" }
        ]
    }
    ListElement {
        name: "Banana"
        cost: 1.95
        attributes: [
            ListElement { description: "Tropical" },
            ListElement { description: "Seedless" }
        ]
    }
}

델리게이트는 모든 과일 속성을 표시합니다:

Component {
    id: fruitDelegate
    Item {
        width: 200; height: 50
        Text { id: nameField; text: name }
        Text { text: '$' + cost; anchors.left: nameField.right }
        Row {
            anchors.top: nameField.bottom
            spacing: 5
            Text { text: "Attributes:" }
            Repeater {
                model: attributes
                Text { text: description }
            }
        }
    }
}

목록 모델 수정하기

목록 모델의 콘텐츠는 clear(), append(), set(), insert() 및 setProperty() 메서드를 사용하여 만들고 수정할 수 있습니다. 예를 들어

    Component {
        id: fruitDelegate
        Item {
            width: 200; height: 50
            Text { text: name }
            Text { text: '$' + cost; anchors.right: parent.right }

            // Double the price when clicked.
            MouseArea {
                anchors.fill: parent
                onClicked: fruitModel.setProperty(index, "cost", cost * 2)
            }
        }
    }

콘텐츠를 동적으로 만들 때 사용 가능한 속성 세트는 한 번 설정하면 변경할 수 없습니다. 모델에 처음 추가되는 속성은 모델에서 허용되는 유일한 속성입니다.

작업자 스크립트와 함께 스레드 목록 모델 사용

ListModel을 WorkerScript 와 함께 사용하여 여러 스레드에서 목록 모델에 액세스할 수 있습니다. 이는 목록 수정이 동기식이고 시간이 걸리는 경우 유용합니다. 목록 작업을 다른 스레드로 이동하여 기본 GUI 스레드의 차단을 피할 수 있습니다.

다음은 WorkerScript 을 사용하여 주기적으로 현재 시간을 목록 모델에 추가하는 예제입니다:

        Timer {
            id: timer
            interval: 2000; repeat: true
            running: true
            triggeredOnStart: true

            onTriggered: {
                var msg = {'action': 'appendCurrentTime', 'model': listModel};
                worker.sendMessage(msg);
            }
        }

포함된 파일인 dataloader.mjs 은 다음과 같습니다:

WorkerScript.onMessage = function(msg) {
    if (msg.action == 'appendCurrentTime') {
        var data = {'time': new Date().toTimeString()};
        msg.model.append(data);
        msg.model.sync();   // updates the changes to the list
    }
}

기본 예제의 타이머는 WorkerScript::sendMessage()를 호출하여 작업자 스크립트에 메시지를 보냅니다. 이 메시지가 수신되면 dataloader.mjs 에서 WorkerScript.onMessage() 이 호출되어 현재 시간을 목록 모델에 추가합니다.

외부 스레드에서 sync()를 호출하는 것에 주목하세요. sync ()를 호출해야 하며 그렇지 않으면 해당 스레드에서 목록에 대한 변경 사항이 메인 스레드의 목록 모델에 반영되지 않습니다.

데이터 모델Qt Qml.

속성 문서

count : int [read-only]

모델에 있는 데이터 항목의 수입니다.


dynamicRoles : bool

기본적으로 역할의 유형은 역할을 처음 사용할 때 고정됩니다. 예를 들어 '데이터'라는 역할을 만들고 여기에 숫자를 할당하면 더 이상 '데이터' 역할에 문자열을 할당할 수 없습니다. 그러나 dynamicRoles 속성이 활성화되면 지정된 역할의 유형은 고정되지 않으며 요소마다 다를 수 있습니다.

dynamicRoles 속성은 ListModel 에 데이터를 추가하기 전에 설정해야 하며, 메인 스레드에서 설정해야 합니다.

ListElement QML 구문을 통해 정적으로 정의된 데이터가 있는 ListModel 에는 dynamicRoles 속성을 활성화할 수 없습니다.

동적 역할이 활성화된 ListModel 을 사용하면 상당한 성능 비용이 발생합니다. 비용은 플랫폼마다 다르지만 일반적으로 정적 역할 유형을 사용하는 것보다 4~6배 정도 느립니다.

동적 역할 사용의 성능 비용으로 인해 기본적으로 동적 역할은 비활성화되어 있습니다.


메서드 문서

append(jsobject dict)

목록 모델의 끝에 dict 의 값을 사용하여 새 항목을 추가합니다.

fruitModel.append({"cost": 5.95, "name":"Pizza"})

set() 및 remove()도 참조하세요 .


clear()

모델에서 모든 콘텐츠를 삭제합니다. 특히 get()를 사용하여 검색했을 수 있는 모든 개체를 무효화합니다.

append(), remove() 및 get()도 참조하세요 .


object get(int index)

목록 모델에서 index 에 있는 항목을 반환합니다. 이를 통해 JavaScript에서 항목 데이터에 액세스하거나 수정할 수 있습니다:

Component.onCompleted: {
    fruitModel.append({"cost": 5.95, "name":"Jackfruit"});
    console.log(fruitModel.get(0).cost);
    fruitModel.get(0).cost = 10.95;
}

index 은 목록의 요소여야 합니다.

반환된 객체의 속성 자체도 객체이며, 이 get() 메서드는 요소에 액세스하는 데 사용됩니다:

fruitModel.append(..., "attributes":
    [{"name":"spikes","value":"7mm"},
     {"name":"color","value":"green"}]);
fruitModel.get(0).attributes.get(1).value; // == "green"

경고: 반환된 객체가 유효하게 유지된다는 보장은 없습니다. 이 메서드는 속성 바인딩에 사용하거나 원본 ListModel 의 수정 사항에 걸쳐 데이터를 저장하는 데 사용해서는 안 됩니다.

append() 및 clear()도 참조하세요 .


insert(int index, jsobject dict)

dict 의 값을 사용하여 index 위치에 새 항목을 목록 모델에 추가합니다.

fruitModel.insert(2, {"cost": 5.95, "name":"Pizza"})

index 은 목록의 기존 항목에 있거나 목록의 끝에 있는 항목(추가와 동일)이어야 합니다.

set() 및 append()도 참조하세요 .


move(int from, int to, int n)

n 항목을 from 한 위치 to 다른 위치로 이동합니다.

예를 들어 처음 3개 항목을 목록의 끝으로 이동하려면 from 및 to 범위가 존재해야 합니다:

fruitModel.move(0, fruitModel.count - 3, 3)

append()도 참조하세요 .


remove(int index, int count = 1)

모델에서 index 항목의 count 개수를 삭제합니다.

clear()도 참조하세요 .


set(int index, jsobject dict)

목록 모델에서 index 의 항목을 dict 의 값으로 변경합니다. dict 에 나타나지 않는 속성은 변경되지 않은 상태로 유지됩니다.

fruitModel.set(3, {"cost": 5.95, "name":"Pizza"})

index 가 count()와 같으면 새 항목이 목록에 추가됩니다. 그렇지 않으면 index 이 목록의 요소여야 합니다.

append()도 참조하세요 .


setProperty(int index, string property, variant value)

목록 모델에서 index 에 있는 항목의 propertyvalue 으로 변경합니다.

fruitModel.setProperty(3, "cost", 5.95)

index 은 목록의 요소여야 합니다.

append()도 참조하세요 .


sync()

작업자 스크립트에서 목록 모델을 수정한 후 저장되지 않은 변경 사항을 목록 모델에 씁니다.


© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.