2017-10-16 112 views
0

我有Foo类从QAbstractListModel派生。和我在qml注册并创建的类Bar。酒吧类持有Foo对象作为财产暴露。无法访问ListView中的QAbstractListModel数据

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。 预期的结果是看委托的文字充满了“测试1”,“测试2”,“TEST3”,但我得到这个:

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

回答

2

QML引擎是正确的,没有定义modelData。在代表内,model定义为不是modelData

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

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