0

我有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
4

1 回答 1

3

QML引擎是对的,modelData没有定义。在委托中,model未定义modelData.

此外,由于您QAbstractListModel尚未定义自己的角色,因此您可以使用默认角色display是您可以使用的默认角色。所以,你ListView应该是这样的:

ListView {
    id: someList
    model: bar.foo
    delegate: Text {
        text: model.display
    }
}
于 2017-10-16T13:07:15.047 回答