Skip to content

Instantly share code, notes, and snippets.

@bennofs
Created August 12, 2015 10:46
Show Gist options
  • Save bennofs/fe06b7b49b564e70de3d to your computer and use it in GitHub Desktop.
Save bennofs/fe06b7b49b564e70de3d to your computer and use it in GitHub Desktop.
Qt QML context object garbage collected
#include <QQmlEngine>
#include <QObject>
#include <QGuiApplication>
#include <QQmlComponent>
#include <QQmlContext>
#include <QQuickWindow>
#include <QDebug>
class App : public QObject
{
Q_OBJECT
public:
virtual ~App() = default;
Q_INVOKABLE bool f() const {
return false;
}
};
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQmlEngine engine;
QQmlComponent component(&engine);
QObject* ctx = new App();
QQmlEngine::setObjectOwnership(ctx, QQmlEngine::JavaScriptOwnership);
engine.rootContext()->setContextObject(ctx);
QObject::connect(&component, &QQmlComponent::statusChanged, [&component, &engine](QQmlComponent::Status status) {
switch(status) {
case QQmlComponent::Ready: {
QObject* obj = component.create();
QQuickWindow* win = qobject_cast<QQuickWindow*>(obj);
engine.setIncubationController(win->incubationController());
break;
}
case QQmlComponent::Error: {
QList<QQmlError> errs = component.errors();
for(QQmlError err : errs) qCritical() << "Error: " << err.toString() << "\n";
}
}
});
component.loadUrl(QUrl::fromLocalFile("main.qml"));
return app.exec();
}
import QtQuick 2.0
import QtQuick.Window 2.2
Window {
Timer {
interval: 1; running: true; repeat: true
onTriggered: {
console.log("call f");
f(); gc();
console.log("done");
}
}
}
$ ./main
qml: call f
qml: done
qml: call f
file:///data/libs/hsqml/member-undefined/main.qml:10: ReferenceError: f is not defined
qml: call f
fish: './main' terminated by signal SIGSEGV (Adressbereichsfehler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment