从QStringList到qml中的ListViewModel

时间:2019-07-17 11:45:39

标签: c++ qt listview qml qstringlist

我跟随this example进行了一些更改,以在ListView中显示QStringList。因此,我在MyClass.cpp中有一个QStringList,我想在MyDialog.qml的ListView中显示这些项目

//// main.cpp ////

int main(int argc, char *argv[])
{

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    MyClass *strListView=new MyClass;
    engine.rootContext()->setContextProperty("strListView", strListView);
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

//// MyClass.h ////

#include <QObject>
#include <QAbstractTableModel>
#include <QModelIndex>
#include <QHash>
#include <QVariant>
#include <QByteArray>
#include <QList>
#include <QDebug>

class MyClass: public QAbstractListModel
{
    Q_OBJECT

public:
    MyClass(QObject *parent=nullptr);

private:
    QStringList str;

///// MyClass.cpp ////

MyClass::MyClass(QObject *parent)
    : QAbstractListModel {parent}
{
str.append("name1");
str.append("name2");
str.append("name3");

    QQuickView view;
    QQmlContext *ctxt = view.rootContext();
    ctxt->setContextProperty("strListView", QVariant::fromValue(str));

    view.setSource(QUrl("qrc:MyDialog.qml"));
}

在qml中,我有2个qml文件:main.qml和MyDialog.qml //// MyDialog.qml ////

...
    Rectangle
    {
id:recList
width:100
height:50

ListView
        {
            width: parent.width
            height: parent.height
            anchors.fill: parent
Text {
                text: modelData
            }
}

它什么都没显示,我得到警告:ReferenceError: modelData is not defined.

1 个答案:

答案 0 :(得分:0)

我认为Qml组件内部的用法应该像这样:

ListView {
     model: myModel;

     Text {
          text: displayRole
     }
}

在您的C ++组件内部,您应该将模型公开给QML文件:

QQmlContext *ctxt = view.rootContext();
ctxt->setContextProperty(myModel,this);

最后,您需要通过在模型上设置Qt::ItemDataRole来映射setRoleNames,例如:

QHash<int, QByteArray> map={{Qt::ItemDataRole::DisplayRole, "displayRole"}};
this->setRoleNames(map);

我还认为,对于如此简单的用例,实际上不必从QAbstractListModel派生。只需使用QStandardItemModel,您就可以自由回家。