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

自闭症网瘾萝莉.ら 提交于 2020-02-08 00:28:23

前言:

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

 

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!