I'm currently working on serializing objects to QML and I am looking for a way to retrieve the source code of functions defined within a QML object. Let's consider the following example in QML (test.qml
):
import QtQml 2.2
QtObject {
function foo() {
return 42;
}
}
From this, I have created a QObject
: obj
.
Is there any method (even if unconventional) to access the source code of the method foo
within obj
, without directly parsing the original QML file where obj
was instantiated from?
I am open to utilizing classes like QQmlComponent
that were involved in creating
obj</code, as long as no manual parsing is required. Alternatively, is there a way to extract the function's source code from the <code>test.qml
file itself without having to build a custom parser? I prefer not to make assumptions about the content or complexity of test.qml
(e.g. it might differ from the example provided and may not be simplistic enough for regex or other lightweight parsers).
If we assume QML operates similarly to JavaScript, I attempted the following:
QQmlExpression expr(engine.rootContext(), obj, "foo.toString()");
QVariant sourceCode = expr.evaluate();
Unfortunately, this approach did not yield the desired results.
Edit: Referring to http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.2, the behavior of the toString
method for function objects is implementation-specific. In the case of QML, the output is as follows:
QVariant(QString, "function() { [code] }")
Given the limitations in accessing the code through JS or C++, I am now exploring possibilities beyond the public Qt API.