我有Foo
派生自QAbstractListModel
. 以及Bar
我在 qml 中注册和创建的类。Bar 类包含Foo
作为属性公开的对象。
class Foo : public QAbstractListModel
{
Q_OBJECT
public:
explicit Foo(QObject *parent = nullptr) : QAbstractListModel(parent) {
mList.append("test1");
mList.append("test2");
mList.append("test3");
}
virtual int rowCount(const QModelIndex &parent) const Q_DECL_OVERRIDE {
return mList.count();
}
virtual QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE {
return mList.at(index.row());
}
private:
QStringList mList;
};
class Bar : public QQuickItem
{
Q_OBJECT
Q_PROPERTY(Foo* foo READ foo NOTIFY fooChanged)
public:
explicit Bar(QQuickItem *parent = nullptr)
: QQuickItem(parent) {
mFoo = new Foo(this);
}
Foo *foo() const { return mFoo; }
signals:
void fooChanged(Foo *foo);
private:
Foo *mFoo;
};
注册Bar
类型:
qmlRegisterType<Bar>("Custom", 1, 0, "Bar");
qml:
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.0
import Custom 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ListView {
id: someList
model: bar.foo
delegate: Text {
text: modelData
}
}
Bar {
id: bar
}
}
我创建 ListView 并分配 model Foo
。预期的结果是看到用“test1”、“test2”、“test3”填充的委托文本,但我明白了:
ReferenceError: modelData is not defined
ReferenceError: modelData is not defined
ReferenceError: modelData is not defined