Qt 示例学习--1. 1 qml实现list

来源:互联网 发布:coc法师塔升级数据 编辑:程序博客网 时间:2024/05/01 23:19

开头

之前学习了Qt的第一个示例,其中使用到了quick,基本理解思路,但并不是很理解qml的使用,遂仿照例子自己写了个list

实作

  1. 新建Qt Quick Application
  2. 实作main.qml(并添加图片资源,图片均添加的是Qt例子中的图片)
    分析main.qml:
import QtQuick 2.3import QtQuick.Window 2.2import QtQuick.Controls 1.4import QtQuick.Controls.Styles 1.4import QtQuick.Layouts 1.2Window {    visible: true    width: 400    height: 640    ListModel {        id: listModel    }    MouseArea {        anchors.fill: parent        onClicked: {            //Qt.quit();        }    }    ListView {        width: parent.width        anchors.top: parent.top        anchors.bottom: foot.top        model: listModel        Component.onCompleted: {            listModel.append({"name": "a", "number": "111"})            listModel.append({"name": "b", "number": "111"})        }        delegate: listDelegate        add: Transition { NumberAnimation { properties: "y"; from: root.height; duration: 250 } }        removeDisplaced: Transition { NumberAnimation { properties: "y"; duration: 150 } }        remove: Transition { NumberAnimation { property: "opacity"; to: 0; duration: 150 } }    }    Row {        id: foot        anchors.bottom: parent.bottom        width: parent.width        height: 50        Button {            text: "add"            height: parent.height            width: parent.width / 2            onClicked: {                var name = "%1"                listModel.append({"name": name.arg(listModel.count), "number": "111"})            }        }        Button {            text: "remove"            height: parent.height            width: parent.width / 2            onClicked: {                listModel.remove(0, 1)            }        }    }    Component {        id: listDelegate        BorderImage {            width: parent.width; height: 70            source: mouse.pressed ? "qrc:/src/delegate_pressed.png" : "qrc:/src/delegate.png"            MouseArea {                id: mouse                anchors.fill: parent                hoverEnabled: true            }            CheckBox {                x: 20                anchors.verticalCenter: parent.verticalCenter                text: qsTr("")                style: CheckBoxStyle {                    indicator: Image {                        source: control.checked ? "qrc:/src/checkbox_checked.png" : "qrc:/src/checkbox.png"                    }                }            }            Text {               width: parent.width ; height: 70               text: "name : " + name + " number : " + number               font.pointSize: 13               verticalAlignment: Text.AlignVCenter               horizontalAlignment: Text.AlignHCenter            }        }    }}

主体为ListView和底部的Row 布局(Row布局中仅添加两个按钮用于添加删除list项目)
为了在ListView中展示内容指定了ListModel和自定义的Delegate用于控制展示。
通过代码可以看到,这里Delegate控制较c++代码进行设置要方便很多~~
最后上效果图:
最终效果图

0 0
原创粉丝点击