Skip to content

Instantly share code, notes, and snippets.

@amfasis
Created March 19, 2019 12:33
Show Gist options
  • Save amfasis/6db36254d204d33670f5dfb274dc139c to your computer and use it in GitHub Desktop.
Save amfasis/6db36254d204d33670f5dfb274dc139c to your computer and use it in GitHub Desktop.
StackOverflow - Create ListView/ListModel from a vector of strings
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "myClass.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
MyClass test;
engine.rootContext()->setContextProperty("myClass", &test);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
import QtQuick 2.11
import QtQuick.Window 2.11
import QtQuick.Controls 1.4
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ListView {
anchors.fill: parent
Component.onCompleted: console.log(myClass.items)
model: myClass.items
delegate: Text {
text: modelData
}
}
}
#include "myClass.h"
MyClass::MyClass(QObject *parent)
: QObject(parent)
{
}
QStringList MyClass::model()
{
return {"test", "hello", "world"};
}
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY(QStringList items READ model CONSTANT)
public:
explicit MyClass(QObject *parent = nullptr);
QStringList model();
};
#endif // MYCLASS_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment