Qt QML C ++结构的QList作为自定义ListView模型

时间:2011-11-02 13:11:08

标签: qt listview qml qt-quick

我的项目中包含的二进制文件包含结构元素列表:

typedef struct {
    unsigned int   id;
    char           name[SIZE];
} Entry;

从文件中读取数据后,我将所有读取值存储在我的类的以下字段中:

QVector<Entry> entires;

我确实使用以下声明将此列表公开给QML:

Q_PROPERTY(QVector<Entry> FileContents READ getEntries NOTIFY TmpFileUpdated)

接下来是getter和setter方法。

inline QVector<Entry> getEntries () 
{ 
    return this->entires; 
}

inline void setEntries(QVector<entires> entries) 
{ 
    this->entires= entries; 
    emit TmpFileUpdated(); 
}

每次读取文件时,“setEntries”方法用于设置向量并发出信号。

QML中的listview具有附加到模型的Q_PROPERTY FileContents:

ListView {
    id: myListView
    width: 200
    height: 400

    model: myInjectedObject.FileContents

    delegate: Row {
        spacing: 10         
        Text {
            text: model.entry_type // (1)
            font.pixelSize: 12
            horizontalAlignment: "AlignHCenter"
            verticalAlignment: "AlignVCenter"
            height: 20
        }
    }
}

如何访问保存在结构列表中的数据并以QML显示?

更新 在您提出建议后,我稍微更改了代码,现在编译得很好。创建了以下类:

class EntryClass: QObject
{
    Q_OBJECT
    Q_PROPERTY(QString entry_name READ getEntryName)
public:
    inline EntryClass(Entry entrystruct)
    {
        this->entry = entrystruct;
    }
private:
    Entry entry;

    inline QString getEntryName() const
    {
        return this->entry->entry_name;
    }    
};

ListView {
    id: myListView
    width: 200
    height: 400

    model: myInjectedObject.FileContents

    delegate: Row {
        spacing: 10       
        Text {
            text: modelData.entry_name // (1)
            font.pixelSize: 12
            horizontalAlignment: "AlignHCenter"
            verticalAlignment: "AlignVCenter"
            height: 20
        }
    }
}

更新2 好的,经过一些分析,我已经设法找到有效的解决方案。关于上面的ListView声明,它已更新为当前状态(通过引用传递struct不起作用,我不得不使用按值复制)。

这两个答案在某些方面都有所帮助,但由于只有一个可以被接受,我会接受Radon写的第一个。 谢谢你们的指导!

2 个答案:

答案 0 :(得分:4)

QML无法访问“低级”struct类型。

但您可以创建一个继承QObject的类EntryClass,并将idname添加为Qt properties(内部EntryClass可以使用相应的Entry结构实例的数据,例如通过使用指向它的指针)。然后,您应该能够在QML中访问这些属性。

(但我没有测试过)

答案 1 :(得分:0)

Radon是对的,导出到QML的对象需要属性(或Q_INVOKABLE函数)。

此外,QVector也不起作用。您需要使用QDeclarativeListProperty或QVariantList作为属性类型。

相关问题