Qt Quick中的ListView
扫描二维码
随时随地手机看文章
ListView 3要素:
model : 负责每一个行的 数据 delegate:负责每一个行的 外观3.与外界如何交互,删除和添加数据(通过model和js)
通过JavaScript控制边线,0,2,4,6…..才显示边框,用来显示每一行的界限,界限颜色用Qt自带的函数就可以了
JavaScript代码:
Myhelp.js
.pragma library
function 求余数(date) {
var ret =date%2;
console.log("余数:"+ret);
if(ret==0)
{
return 1;
}
return 0;
}
Window {
visible: true
width: 240;
height: 320;
//导出listview的model 供按钮使用 由于在一个文件中,不需要了
ListView{
id:list_view;
anchors.left: parent.left;
anchors.top: parent.top;
width: parent.width;
height: 180;
model:m_listmodel;
delegate:delegete1;
}
//ListView的model
ListModel{
id:m_listmodel;//model对象中 有数组ListElement 存储所有的列表数据对象
ListElement{name:"hello"}
}
//listview的代理
Component{
id:delegete1;
Rectangle{
width: parent.width;
height: 40;
color: "#4b3b3b"
border.color: Qt.lighter(color) //颜色暗淡些 不然显得有点粗
//当序号为2的倍数才有边框用来分割
border.width: MyHELP.求余数(index);
Text {
anchors.fill: parent;
id: m_txt;
color: "#f3e3e3"
text:name+"序号"+index;
font.family: "Consolas"
font.pointSize: 14
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
}
}
//新建按钮用来测试
Button{
id:m_btn;
anchors.top: list_view.bottom;
anchors.left:parent.left;
width: parent.width;
height: 40;
text: qsTr("添加");
onClicked: {
m_listmodel.append({name:qsTr(m_input.text)});
}
}
Button{
id:m_delete;
anchors.top: m_btn.bottom;
anchors.left:parent.left;
width: parent.width;
height: 40;
text: qsTr("删除");
onClicked: {
m_listmodel.remove(m_input.text,1);//删除指定的项 第二个参数:删除个数 1就行了不然乱
}
}
TextInput{
id:m_input;
horizontalAlignment: Text.AlignHCenter
font.pointSize: 14
anchors.left:m_delete.left;
anchors.top: m_delete.bottom;
height: 40;
width: parent.width;
color: "#c69191"
autoScroll: true;
text: qsTr("请输入")
}
}