【问题标题】:QList<QString> not being used as model by QML ListViewQList<QString> 未被 QML ListView 用作模型
【发布时间】:2018-08-15 16:46:57
【问题描述】:

我在 c++ 类中有一个 QList&lt;QString&gt; 类型的 Q_PROPERTY,它没有在 QML 中显示。该类如下所示:

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

上面的类使用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&lt;QString&gt;'s 作为模型吗?我认为你可以,因为它被列为简单列表类型。

【问题讨论】:

  • m_strings()?在构造函数中。
  • m_string() 覆盖你的m_strings &lt;&lt; "String one" &lt;&lt; "String two"; 所以你使用的是空列表
  • @Phiber m_strings &lt;&lt; "String one" &lt;&lt; "String two"; 它在m_string() 之后运行,尽管m_string() 是不必要的,因为默认情况下列表为空

标签: c++ qt qml qtquick2


【解决方案1】:

首先使用QStringList而不是QList&lt;QString&gt;

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

没有命名角色的模型(例如所示的 ListModel 下面)将通过 modelData 角色提供数据。这 还为只有一个角色的模型提供了 modelData 角色。在 在这种情况下,modelData 角色包含与命名角色相同的数据。


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

【讨论】:

  • no qstringlistmodel 是否与 qml 兼容?
  • @Mike QStringList 和 QStringListModel 都受支持。
猜你喜欢
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多