Skip to content

Instantly share code, notes, and snippets.

@mitchcurtis
Created April 27, 2021 12:01
Show Gist options
  • Save mitchcurtis/aaf3d57f07cea4dda151468b06333146 to your computer and use it in GitHub Desktop.
Save mitchcurtis/aaf3d57f07cea4dda151468b06333146 to your computer and use it in GitHub Desktop.
Create C++ type via QQmlComponent and createWithInitialProperties
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
class Bean : public QObject
{
Q_OBJECT
Q_PROPERTY(qreal roundness READ roundness WRITE setRoundness NOTIFY roundnessChanged)
Q_PROPERTY(QStringList sprouts READ sprouts WRITE setSprouts NOTIFY sproutsChanged)
public:
qreal roundness() const
{
return mRoundness;
}
void setRoundness(qreal roundness)
{
qDebug() << "setRoundness called with" << roundness;
if (roundness == mRoundness)
return;
mRoundness = roundness;
emit roundnessChanged();
}
QStringList sprouts() const
{
return mSprouts;
}
void setSprouts(const QStringList &sprouts)
{
qDebug() << "setSprouts called with" << sprouts;
if (sprouts == mSprouts)
return;
mSprouts = sprouts;
emit sproutsChanged();
}
signals:
void roundnessChanged();
void sproutsChanged();
private:
qreal mRoundness = 0.0;
QStringList mSprouts;
};
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<Bean>("App", 1, 0, "Bean");
QQmlComponent component(&engine);
component.setData("import App 1.0; Bean {}", QUrl());
const QStringList sprouts = { "Little Sprout", "Big Sprout" };
Bean *bean = qobject_cast<Bean*>(component.createWithInitialProperties({
{ "roundness", 1.0 },
{ "sprouts", sprouts }
}));
if (!bean) {
qWarning().noquote() << component.errorString();
return 1;
}
qDebug() << bean->roundness() << bean->sprouts();
return app.exec();
}
#include "main.moc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment