1、listView 需要包括:model+delegate【并且要分开放】【delegate是一个Component->保证可以重复使用】
2、main.qml:基本布局 +
MyModel.qml【注意首字母大写】:数据绑定 +
MyDelegate【首字母大写】:数据样式
eg:
1、文件目录:
2、代码:
main.qml
import
QtQuick 2.7
import
QtQuick.Window 2.2
import
QtQuick.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
import
QtQuick 2.7
//model:数据
ListModel
{
ListElement
{
title:
"张三";
}
ListElement
{
title:
"李四";
}
ListElement
{
title:
"王二";
}
}
MyDelegate.qml
import
QtQuick 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;
}
}
}