一、介绍
在动态视图组件GridView中添加和删除数据以及遇到的问题
二、实现
import QtQuick 2.5
import QtQuick.Window 2.3
Window {
visible: true
id:root
width: 320
height: 240
ListModel {
id:themode
ListElement {number:0}
ListElement {number:1}
ListElement {number:2}
ListElement {number:3}
ListElement {number:4}
ListElement {number:5}
ListElement {number:6}
ListElement {number:7}
ListElement {number:8}
ListElement {number:9}
}//窗口中的初始元素列表
GridView {
anchors.fill:parent
anchors.margins: 20
model: themode
clip: true//一定要设置为true,否则,数据会覆盖其他界面!!!!
cellHeight: 45//每个Grid的高度和宽度属性
cellWidth: 45
delegate: boxcomp
}
Rectangle {//创建add按钮
//z:10
anchors.bottom: parent.bottom
anchors.left: parent.left
anchors.right: parent.right
anchors.margins: 10
height: 40
color: "green"
border.color: "black"
Text {
anchors.centerIn: parent
text: "add"
}
MouseArea {
anchors.fill: parent
onClicked: {
themode.append({number: ++parent.count})//当点击add时,添加一个model元素
}
}
property int count: 9
}
Component {
id:boxcomp
Rectangle {
id:mybox
width: 40
height: 40
color: "yellow"
Text {
anchors.centerIn: parent
text: number
}
MouseArea {
anchors.fill: parent
onClicked: {
themode.remove(index)//移除对应的元素
}
}
GridView.onRemove:SequentialAnimation {
PropertyAction { target: mybox; property: "GridView.delayRemove"; value: true }
NumberAnimation { target: mybox; property: "scale"; to:0; duration: 250; easing.type: Easing.InOutQuad }
PropertyAction { target: mybox; property: "GridView.delayRemove"; value: false }
}
//PropertyAction用于指定动画期间,非动画特性属性的更改。
GridView.onAdd:SequentialAnimation {
NumberAnimation{
target: mybox
property: "scale"
from:0
to:1
duration: 250
easing.type: Easing.InOutQuad
}
}
}
}
}
上述代码中有一些点需要注意:
1、GridView中的clip属性一定要设置为true,否则会出现GridView中的数据透过了按钮的效果
2、 PropertyAction { target: mybox; property: "GridView.delayRemove"; value: true }表示将GridView中的延迟销毁属性设置为true,这样,当删除元素是,因为延迟销毁,所以会播放动画,动画播放完之后,将延迟销毁属性设为false,此时数据被销毁
3、在使用ListView个GridView等动态视图组件时,最好将动态组件写在代码的最前面,否则GridView有可能遮挡其他的组件,导致无法操作组件(因为在qml中,先出现的代码的层级低于后出现代码的层级)
Rectangle {//创建add按钮
//...
}
GridView {
//..
}
如果将add按钮的组件代码写在前面,那么GridView就会遮挡add按钮,从而导致点击add按钮无效,出现这种情况时,画面本身不会有问题,所以,这个问题出现了后,很难排查,所以,一定要将大范围显示组件写在前面来规避这种问题
参考
《qml book》
作者水平有限,如有错误,欢迎指出