한국어
Qt
 

QML에서 기본적으로 아이템을 리스팅 시킬수 있는 아이템이 ListView이다.

이 글에서는 QML의 ListModel과 이 모델에 동적으로 아이템을 추가, 삭제시켜 뷰(ListView)를 나타내는 방법을 설명한다. ListView를 사용하는 방법을 알아보자.

 

아래 예제는 리스트 모델의 아이템들을 동적으로 삭제시키는 예제이다.

 

ListView를 중첩된 구조로 구현하여 Stack의 모델들에 아이템이 남아있지않으면 group모델의 아이템도 삭제한다.

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    id: root
    visible: true
    width: 500
    height: 150
    title: "ListView"

    ListModel{
        id: groupModel
        ListElement{name: "group1"}
        ListElement{name: "group2"}
        ListElement{name: "group3"}
        ListElement{name: "group4"}
        ListElement{name: "group5"}
    } // group list

    Rectangle{
        id: background
        anchors.fill: parent
        color: "white"
    }

    ListView{
        anchors.left: parent.left
        anchors.right: parent.right
        height: parent.height
        clip: true
        spacing: 20
        orientation: Qt.Horizontal
        model: groupModel

        delegate:
            Item{
            id: stack
            height: 100
            width: 200
            anchors.verticalCenter: parent.verticalCenter

            signal itemEmpty()

            onItemEmpty: {
                console.log("group : " , name)
                groupModel.remove(index)
            }

            ListView{
                model: ListModel{
                    id: stackModel
                    ListElement{name: "item1"}
                    ListElement{name: "item2"}
                    ListElement{name: "item3"}
                    ListElement{name: "item4"}
                }
                anchors.fill: parent
                orientation: Qt.Horizontal

                delegate:
                Rectangle{
                    id: widget
                    width: 200
                    height: 100
                    anchors.horizontalCenter: parent.horizontalCenter
                    y: (index * spacing)
                    z: stackModel.count - index
                    border.width: 1
                    color: "yellow"

                    readonly property int spacing: 5

                    onYChanged: {
                        var value = 1.0 - yRatio()
                        opacity = value.toFixed(1)
                    }

                    function yRatio(){
                        var cal = (index * spacing)
                        var position = Math.abs(y - cal)
                        return (position / height)
                    }

                    PropertyAnimation{
                        id: yPositionUpAni
                        target: widget
                        property: "y"
                        duration: 100
                        to: -120
                        onStopped: {
                            stackModel.remove(index)

                            if(stackModel.count <= 0){
                                stack.itemEmpty()
                            }
                        }
                    }
                    PropertyAnimation{
                        id: yPositionDownAni
                        target: widget
                        property: "y"
                        duration: 100
                        to: index * 5
                        easing.type: Easing.InCubic
                    }

                    MouseArea{
                        anchors.fill: parent
                        drag.target: widget
                        drag.axis: Drag.YAxis
                        drag.maximumY: index * parent.spacing
                        hoverEnabled: true

                        onReleased: {
                            var opacity = parent.yRatio()
                            if(opacity > 0.5){
                                yPositionUpAni.start()
                            }else{
                                yPositionDownAni.start()
                            }
                        }
                    }
                }
            }
        }
    }
}

 

ListModel에는 다음과 같은 Method들을 제공하고 있다.

  • append(jsobject dict)
  • clear()
  • object get(int index)
  • insert(int index, jsobject dict)
  • move(int from, int to, int n)
  • remove(int index, int count = 1)
  • set(int index, jsobject dict)
  • setProperty(int index, string property, variant value)
  • sync() 

append 및 remove등의 Method를 통해 모델을 동적으로 변경 가능하다.

 

예제 소스코드를 보자.

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ListModel{
        id: mymodel
    }

    Text {
        id: count
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.top

        text: qsTr("count: " + mymodel.count)
        font.pixelSize: 25
    }

    Row{
        anchors.horizontalCenter: parent.horizontalCenter
        height: parent.height

        spacing: 20

        Button{
            anchors.verticalCenter: parent.verticalCenter
            text: "append"
            onClicked: {
                // Math.random() 는 0과 1 사이의 난수를 반환하고,
                // Math.ceil()는 소수점 이하를 올려 정수로 만든다.
                // 모델에 아이템을 추가한다.
                mymodel.append({'number': Math.ceil(Math.random() * 10)})
            }
        }

        ListView{
            width: 350
            height: 400
            anchors.verticalCenter: parent.verticalCenter
            spacing: 10
            clip: true // ListView 영역을 벋어난 부분을 자른다.

            model: mymodel

            delegate:
                Rectangle {
                width: parent.width
                height: 50
                color: "white"
                border.width: 1

                Text {
                    anchors.centerIn: parent
                    text: qsTr("number: " + number) // 모델 아이템의 'number'
                    font.pixelSize: 20
                }

                Button{
                    anchors.right: parent.right
                    anchors.rightMargin: 15
                    anchors.verticalCenter: parent.verticalCenter

                    text: "remove"
                    onClicked: {
                        // 클릭한 아이템을 모델에서 삭제
                        mymodel.remove(index)
                    }
                }
            }
        }
    }
}
번호 제목 글쓴이 날짜 조회 수
공지 Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서 운영자 2019.01.05 85850
28 웹기반 Qt Design Viewer [2] file makersweb 2019.10.23 1297
27 OpenGL 렌더링을 QtQuick과 통합하는 방법 file makersweb 2019.10.01 2181
26 QML내에서의 시그널, 슬롯 시스템 makersweb 2019.09.29 6937
25 C++로 구현된 모델을 QML의 ListView에서 참조 file makersweb 2019.09.07 4915
24 QSocketNotifier로 파일 디스크립터의 활동감지 makersweb 2019.08.28 1728
23 열거형(enum)을 QML에서 사용하는 방법과 문자열(QString)로 얻기 makersweb 2019.08.20 3879
22 [Qt] Google Play의 향후 요구 사항을 준수하는 방법 [2] j2doll 2019.07.29 972
21 Qt Quick Controls 2사용 및 스타일 설정 file makersweb 2019.06.07 6241
» QML 강좌 - 동적 Listing (ListView) file makersweb 2019.06.01 10082
19 QtCreator Design으로 GUI만들기 (QML로 만드는 Hello World -2) [1] file makersweb 2019.05.26 14867
18 QML에서 멀티 스레드(multithreading) 프로그래밍 file makersweb 2019.05.25 2650
17 QML과 QtQuick 모듈 개념과 기본 타입들 makersweb 2019.04.26 13388
16 QML 전역 객체 (Global Object) file makersweb 2019.04.10 1048
15 tslib의 ts_calibrate를 응용해서 Qt로 터치보정기능 구현 file makersweb 2019.04.06 1365
14 GPU가 없는 장치에서 Qt Quick을 사용 makersweb 2019.04.02 1857
13 Qml 기본 컴포넌트 강좌 (4) - 모델 리스팅(Listing) file 운영자 2019.02.23 5298
12 Qml 기본 컴포넌트 강좌 (3) - 배치(positioning) 컴포넌트 file 운영자 2019.02.10 4866
11 Qml 기본 컴포넌트 강좌 (2) [2] file makersweb 2019.01.05 8615
10 Qml 기본 컴포넌트 강좌 (1) file makersweb 2019.01.03 12060
9 Qml과 C++로 구현하는 GUI어플리케이션 file makersweb 2018.12.25 13936