Skip to content

Instantly share code, notes, and snippets.

@vadimpiven
Created November 22, 2023 15:37
Show Gist options
  • Save vadimpiven/bd6508700bb894f07a37d4eba64758d1 to your computer and use it in GitHub Desktop.
Save vadimpiven/bd6508700bb894f07a37d4eba64758d1 to your computer and use it in GitHub Desktop.
How to use setContextProperty on QQuickWidget to inject JS module in place of QObject (useful for tests)
import QtQuick 2
Rectangle {
width: 400
height: 200
Text {
anchors.centerIn: parent
text: logic.GetText()
}
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit()
}
}
}
#include "logic.h"
Logic::Logic(QObject * parent)
: QObject(parent)
{}
Q_INVOKABLE QString Logic::GetText()
{
return "Click to exit";
}
#pragma once
#include <QObject>
class Logic final
: public QObject
{
Q_OBJECT
Q_DISABLE_COPY_MOVE(Logic)
public:
explicit Logic(QObject * parent);
Q_INVOKABLE QString GetText();
};
export function GetText() {
return "Click to exit";
}
// SPDX-License-Identifier: CC0-1.0
// Creative Commons Zero v1.0 Universal License: https://creativecommons.org/publicdomain/zero/1.0/deed
#include "logic.h"
#include <QApplication>
#include <QObject>
#include <QQmlContext>
#include <QQmlEngine>
#include <QQuickWidget>
#include <QUrl>
#include <QVariant>
#include <memory>
int main(int argc, char * argv[])
{
QApplication app(argc, argv);
auto const widget = std::make_unique<QQuickWidget>();
// set QObject as context property
widget->rootContext()->setContextProperty("logic", new Logic(widget.get()));
// set msj module resembling object as context property
auto const module = widget->rootContext()->engine()->importModule("logic.mjs");
widget->rootContext()->setContextProperty("logic", QVariant::fromValue(module));
widget->setSource(QUrl::fromLocalFile("example.qml"));
widget->show();
QObject::connect(widget->engine(), &QQmlEngine::quit, &app, &QApplication::quit);
return QApplication::exec();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment