[英]QList<QString> not being used as model by QML ListView
我在QML中未显示的c++
类中具有QList<QString>
类型的Q_PROPERTY
。 该类如下所示:
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<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
:
没有命名角色的模型(例如下面显示的ListModel)将具有通过modelData角色提供的数据。 还为只有一个角色的模型提供了modelData角色。 在这种情况下,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.