首页 > 学院 > 开发设计 > 正文

二、ListView - model数据绑定

2019-11-08 01:47:21
字体:
来源:转载
供稿:网友
1、listView 需要包括:model+delegate【并且要分开放】【delegate是一个Component->保证可以重复使用】2、main.qml:基本布局 +MyModel.qml【注意首字母大写】:数据绑定 + MyDelegate【首字母大写】:数据样式eg:1、文件目录:2、代码:main.qmlimportQtQuick 2.7importQtQuick.Window 2.2importQtQuick.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");//ListViewListView{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.qmlimportQtQuick 2.7//model:数据ListModel{ListElement{title:"张三";}ListElement{title:"李四";}ListElement{title:"王二";}}MyDelegate.qmlimportQtQuick 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;}}}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表