QList<QString> 未被 QML ListView 用作模型

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

我在 c++ class 中有一个类型为 QList<QString>Q_PROPERTY,它没有在 QML 中显示。 class 看起来像这样:

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();
};

上面的class使用qmlRegisterType注册为QML类型。我尝试使用 属性 作为 ListView 的模型,如下所示:

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

可以不用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();
};

要解决这个问题,当模型是 docs:

指示的列表时,您必须使用 modelData

Models that do not have named roles (such as the ListModel shown below) will have the data provided via the modelData role. The modelData role is also provided for models that have only one role. In this case the modelData role contains the same data as the named role.


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