I'm moving from QScriptEngine
(which is deprecated) to QJSEngine
, and I see that I'm unable to use print
:
QJSEngine engine;
QJSValue val = engine.evaluate(
"print('123');"
);
if (val.isError()){
qDebug() << "error: " << val.toString();
}
qDebug() << "val: " << val.toVariant();
The output is:
error: "ReferenceError: print is not defined"
In QScriptEngine
it works.
Then, what is the way to print something to console in QJSEngine
? Can't find anything in docs. I tried to use console.log
, but console
is not defined as well.
The print function is not implemented in QJSEngine. You will have to implement it yourself. Luckily you can write QObjects and make them available in your script. (See section "QObject Integration" at http://doc.qt.io/qt-5/qjsengine.html)
Here's how i've done it:
Create a class JSConsole inheriting from QObject:
Your own console class
jsconsole.h
jsconsole.cpp
Using it
Now you create a proxy object in the js engine by using QJSEngine.newQObject. After that you add it to your global object and use it.
Error logging
I've searched a long time for errors in my c++ code, when i just made a spelling error in my js file. The following snippet would have helped avoid that.
PS: First post after years of lurking. I've read tips on writing great answers but if I've made some mistakes/bad things please tell me.
May the code be with you