20200207-02 QML 动态添加子类(TableView 动态添加 Column)

前言:

        本文讲解方法,不适用动态删除添加对象的,这种方法查看链接 动态删减通过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;
};

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值