我已经按照这个示例进行了一些更改以在 ListView 中显示 QStringList。所以,我QStringList
在 MyClass.cpp 中有一个,我想在 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.