Created
March 19, 2019 12:33
-
-
Save amfasis/6db36254d204d33670f5dfb274dc139c to your computer and use it in GitHub Desktop.
StackOverflow - Create ListView/ListModel from a vector of strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "myClass.h" | |
MyClass::MyClass(QObject *parent) | |
: QObject(parent) | |
{ | |
} | |
QStringList MyClass::model() | |
{ | |
return {"test", "hello", "world"}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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