JavaScriptOwnership上下文对象是垃圾回收

时间:2015-08-12 11:17:19

标签: qt qml qt5 qtquick2

以下程序演示了我遇到的问题:

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;

    QObject* ctx = new App();
    QQmlEngine::setObjectOwnership(ctx, QQmlEngine::JavaScriptOwnership);
    engine.rootContext()->setContextObject(ctx);

    QQmlComponent component(&engine);
    QObject::connect(&component, &QQmlComponent::statusChanged, [&](auto status) {
        if(status == QQmlComponent::Ready) component.create(); 
        if(status == QQmlComponent::Error) {
          for(auto err : component.errors()) qCritical() << "Error: " << err.toString();
        }
    });
    component.loadUrl(QUrl::fromLocalFile("main.qml"));

    return app.exec();
}

使用QML文档:

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)

这是预期的行为吗?什么时候可以安全地使用QQmlEngine :: JavaScriptOwnership?

0 个答案:

没有答案