在qml应用开发中,经常会用到TableView来显示数据,而有时表格又不是固定的,需要根据不同的情况来变换表格的标题和内容。
本次博客将会介绍怎样在qml中动态的创建TableView。
首先创建一个文件DataShowTable.qml,首字母要大写,这些大家应该都知道吧。
import QtQuick 2.7
import QtQuick.Controls 1.4
TableView{
id: tableview
property var holdMenuModelDataArray: null
backgroundVisible: false;
frameVisible: false;
itemDelegate: StandardTabelItemDelegate{} //添加自己喜欢的代理,这个就不用说了吧
headerDelegate: headerDele; //表头委托
rowDelegate: rowDele; //行委托
model: ListModel{}
//定义表头的委托
Component{
id:headerDele
Rectangle{
id: headerRect;
height: tableview.headerHeight;
border.color: frameBorderColor;
color:"transparent";
radius: 3;
Text{
text: styleData.value
anchors.centerIn: parent
font.family: "微软雅黑";
font.pixelSize: 12;
color: "white";
}
}
}
//定义行的委托
Component{
id:rowDele
Rectangle{
id: rect;
height: 42;
color: "transparent";
}
}
//更新表格标题列高度和role
function updateColumn2Table(arrayData){
if(arrayData.length != 3){
console.log("DataShowTable.qml updateColumn2Table arrayData.length !=3");
return;
}
var arrayTitle = arrayData[0]; //标题数组
var arrayWidth = arrayData[1]; //宽度数组
var arrayRoles = arrayData[2]; //role数组
if(arrayTitle.length != arrayWidth.length || arrayTitle.length > arrayRoles.length){
console.log("arrayTitle argument error in DataShowTable.qml updateColumn2Table(arrayTitle,arrayWidth,arrayRoles)");
return;
}
tableview.model.clear(); //先将model里面的数据清空避免在更新的列里面有相同的role直接显示
var i,str,count = tableview.columnCount;
var sum = new Number(0);
//求出长度累加和以便于按比例分配列宽
for(i =0;i<arrayWidth.length;i++){
sum += arrayWidth[i];
}
var prefix = 'import QtQuick 2.7;import QtQuick.Controls 1.4;TableViewColumn {width: Math.round(tableview.width *'; //创建TableViewColumn的代码
//前缀
//将现在的每列全部删除
for(i=0;i<count;i++){
tableview.removeColumn(0);
}
//循环添加TableViewColumn
for(i=0;i<arrayTitle.length;i++){
str = prefix + arrayWidth[i]/sum +");role:\"" + arrayRoles[i] + "\";title:\"" + arrayTitle[i] + "\"}";
tableview.addColumn(Qt.createQmlObject(str,tableview,"dynamicSnippet1"));
}
}
}
这里还是把itemDelegate的代码也贴出来,让大家清楚全过程。
import QtQuick 2.7
import QtQuick.Controls 1.4
Rectangle{
id: tableCell
anchors.fill: parent;
anchors.margins: 3;
border.color: "blue";
radius:3;
color: styleData.selected ? "transparent" : "#1A4275";
Text{
id: textID;
text:styleData.value ;
font.family: "微软雅黑";
font.pixelSize: 12;
anchors.fill: parent;
color: "white";
elide: Text.ElideRight;
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
}
下面是主界面中的调用
Item {
id: root
property var bankPaySearchTableArray: [["银行卡号","开户行","卡种类型","归属地","止付开始时间","止付结束时间","状态"],
[155,125,110,125,135,135,97],
["card","bank","type","location","opeStartDate","opeEndDate","cardStatus"]]
DataShowTable{
id: table;
anchors.fill: parent
anchors.centerIn: parent
anchors.margins: 18
Component.onCompleted: {
Compone table.updateColumn2Table(bankPaySearchTableArray); //创建表
}
}
重点在于要利用TableView提供的函数addColumn()来添加,而创建的话则使用createQmlObject()。以下为效果图,表中数据未在上面
代码给出