【问题标题】:Qt QML C++ QList of structs as custom ListView modelQt QML C++ QList of structs 作为自定义 ListView 模型
【发布时间】:2011-11-02 13:11:07
【问题描述】:

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

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 中的列表视图具有附加到模型的 Q_PROPERTY 文件内容:

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 声明,它已更新为当前状态(通过引用传递结构不起作用,我必须使用按值复制)。

这两个答案在某种程度上都有帮助,但由于只能接受一个,我会接受 Radon 写的第一个答案。 谢谢两位的指导!

【问题讨论】:

    标签: qt listview qml qt-quick


    【解决方案1】:

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

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

    (但我没有测试过)

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2014-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多