二、ListView - model数据绑定

来源:互联网 发布:知乎周刊plus网盘 编辑:程序博客网 时间:2024/06/04 19:25
1、listView 需要包括:model+delegate【并且要分开放】【delegate是一个Component->保证可以重复使用】
2、main.qml:基本布局 +MyModel.qml【注意首字母大写】:数据绑定 + MyDelegate【首字母大写】:数据样式
eg:
1、文件目录:


2、代码:
main.qml

importQtQuick 2.7
importQtQuick.Window 2.2
importQtQuick.Controls 2.1
//1、listView需要包括:model+delegate【并且要分开放】
//2、main.qml:基本布局+ MyModel.qml【注意首字母大写】:数据绑定+ MyDelegate【首字母大写】:数据样式

Window{
id:root;
visible:true;
width:640;
height:480;
title:qsTr("listView");

//ListView
ListView{
id:listView;
width:parent.width;
height:parent.height*0.4;
model:MyModel{ //注意:MyModel文件名必须是大写,才可以引用,并且MyModel{}后不能有“
id:myModel
}
delegate:MyDelegate{//MyDelegate同理
id:myDelegate;
}

}

//添加按钮
Button{
id:m_add;
anchors.top:listView.bottom;
anchors.left:parent.left;
width:parent.width;
height:40;
text:qsTr("添加");
onClicked:{
myModel.append({title:qsTr(myInput.text)});
}
}

//删除按钮
Button{
id:m_delete;
anchors{top: m_add.bottom; left: parent.left;}
width:parent.width;
height:40;
text:qsTr("删除");
onClicked:{
myModel.remove(myInput.text,1);
}
}

//输入框
TextInput{
id:myInput;
horizontalAlignment:Text.AlignHCenter;
font.pixelSize:18;
anchors{top: m_delete.bottom;left: parent.left;}
height:40;
width:parent.width;
color:"#c69191";
autoScroll:true;
text:qsTr("请输入");

}
}

MyModel.qml
importQtQuick 2.7

//model:数据
ListModel{
ListElement{
title:"张三";
}
ListElement{
title:"李四";
}
ListElement{
title:"王二";
}

}

MyDelegate.qml
importQtQuick 2.7

//delegate:外观
Component{

Rectangle{
width:parent.width;
height:40;
color:"#4b3b3b";
border.color:Qt.lighter(color);
Text{
id:myText;
anchors.fill:parent;
color:"#f3e3e3";
text:title+ "序号"+index;
font.family:"Consolas";
font.pointSize:14;
horizontalAlignment:Text.AlignHCenter;
verticalAlignment:Text.AlignVCenter;
}
}
}

0 0