我有从Foo派生的QAbstractListModel类。我在qml中注册并创建的Bar类。 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并分配模型Foo
预期结果是看到代理文本填充有“ test1”,“ test2”,“ test3”,但是我得到了:

ReferenceError: modelData is not defined
ReferenceError: modelData is not defined
ReferenceError: modelData is not defined

最佳答案

QML引擎正确,未定义modelData。在委托中,定义的model不是modelData

同样,由于您在QAbstractListModel中尚未定义自己的角色,因此可以使用默认角色。 display是您可以使用的默认角色。因此,您的ListView应该如下所示:

ListView {
    id: someList
    model: bar.foo
    delegate: Text {
        text: model.display
    }
}



详细信息:http://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html

10-05 18:35