简体   繁体   English

的QList <QString> 不被QML ListView用作模型

[英]QList<QString> not being used as model by QML ListView

I have a Q_PROPERTY of type QList<QString> in a c++ class that is not being shown in QML. 我在QML中未显示的c++类中具有QList<QString>类型的Q_PROPERTY The class looks like this: 该类如下所示:

class FooView : public QQuickItem
{
    Q_OBJECT;
    Q_PROPERTY(QList<QString> myStrings READ myStrings NOTIFY myStringsChanged);

private:
    QList<QString> m_strings;

public:
    FooView(QQuickItem * parent) : QQuickItem(parent), m_strings() {
        m_strings << "String one" << "String two";
    }

    QList<QString> myStrings() const {
        return m_strings;
    }

signals:
    void myStringsChanged();
};

The above class is registered as a QML type using qmlRegisterType . 上面的类使用qmlRegisterType注册为QML类型。 I try to use the property as a model to a ListView like so: 我尝试将属性用作ListView的模型,如下所示:

FooView {
    id: 'foo'
    ListView {
        anchors.fill: parent
        model: foo.myStrings
        delegate: Text {
            text: "Hi" // to be replaced with foo.myStrings[index]
        }
    }
}

Can you not use QList<QString> 's as models? 您不能将QList<QString>用作模型吗? I thought you could since it was listed as a simple list type. 我认为您可以,因为它被列为简单列表类型。

First use QStringList instead of QList<QString> : 首先使用QStringList而不是QList<QString>

class FooView : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QStringList myStrings READ myStrings NOTIFY myStringsChanged)
    QStringList m_strings;
public:
    FooView(QQuickItem * parent=nullptr) :
        QQuickItem(parent)
    {
        m_strings << "String one" << "String two";
    }
    QStringList myStrings() const {
        return m_strings;
    }
signals:
    void myStringsChanged();
};

And going to the problem, you must use modelData when the model is a list as indicated by the docs : 转到问题所在,当模型是docs指示的列表时,必须使用modelData

Models that do not have named roles (such as the ListModel shown below) will have the data provided via the modelData role. 没有命名角色的模型(例如下面显示的ListModel)将具有通过modelData角色提供的数据。 The modelData role is also provided for models that have only one role. 还为只有一个角色的模型提供了modelData角色。 In this case the modelData role contains the same data as the named role. 在这种情况下,modelData角色包含与命名角色相同的数据。


FooView {
    id: foo
    anchors.fill: parent
    ListView {
        anchors.fill: parent
        model: foo.myStrings
        delegate: Text {
            text: modelData
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM