前言:
本文讲解方法,不适用动态删除添加对象的,这种方法查看链接 动态删减通过JavaScript
应用场景如:TableView 动态添加 Column
正文:
The data property allows you to freely mix visual children and resources in an item. If you assign a visual item to the data list it becomes a child and if you assign any other object type, it is added as a resource.
翻译:QML 中的 data 属性本质上是 list<QObject> 数据对象列表,所有可视化部分属于 children 部分,非可视化属于 resources 部分
//推荐标准写法:
Item {
Text {}
Rectangle {}
Timer {}
}
//上面写法代替下面这种写法:
instead of :
Item {
children: [
Text{}
Rectangle {}
]
resources: [
Timer {}
]
}
It should not generally be necessary to refer to the data property, as it is the default property for Item and thus all child items are automatically assigned to this property
翻译:就是所有子类类目编译都会自动分配好,不需要关注这件事
TableView 中动态添加 column 代码如下
TableView {
id: rectTableView
resources: {
var roleList = rectTableView.model.userRoleNames
var temp = []
for (let i of roleList) {
temp.push(columnComponent.createObject(rectTableView, {"title":i}))
}
return temp
}
}
// x.h
class A : public QAbstractTableModel {
Q_OBJECT
Q_PROPERTY(QStringList listValue READ getUserList CONSTANT)
public:
explicit A (QObject *parent = nullptr) : QAbstractTableModel(parent){
}
QStringList getUserList() {
return QStringList {"xx", "yy"};
}
int rowCount(QModelIndex*)
int columnCount(const QModelIndex &parent = QModelIndex()) const {return 1};
int rowCount(const QModelIndex &parent = QModelIndex()) const {return 3};
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const {return "1"};
private:
QStringList listValue;
};