qt - QJSEngine: print to console -
i'm moving qscriptengine
(which deprecated) qjsengine
, , see i'm unable 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 not defined"
in qscriptengine
works.
then, way print console in qjsengine
? can't find in docs. tried use console.log
, console
not defined well.
the print function not implemented in qjsengine. have implement yourself. luckily can write qobjects , make them available in script. (see section "qobject integration" @ http://doc.qt.io/qt-5/qjsengine.html)
here's how i've done it:
create class jsconsole inheriting qobject:
your own console class
jsconsole.h
#ifndef jsconsole_h #define jsconsole_h #include <qobject> class jsconsole : public qobject { q_object public: explicit jsconsole(qobject *parent = 0); signals: public slots: void log(qstring msg); }; #endif // jsconsole_h
jsconsole.cpp
#include "jsconsole.h" #include <qdebug> jsconsole::jsconsole(qobject *parent) : qobject(parent) { } void jsconsole::log(qstring msg) { qdebug() << "jsconsole: "<< msg; }
using it
now create proxy object in js engine using qjsengine.newqobject. after add global object , use it.
qjsengine engine; jsconsole console; qjsvalue consoleobj = engine.newqobject(&console); engine.globalobject().setproperty("console", consoleobj); qjsvalue result = engine.evaluate("console.log('test');");
error logging
i've searched long time errors in c++ code, when made spelling error in js file. following snippet have helped avoid that.
if (result.iserror()) { qdebug() << "result: " << result.property("linenumber").toint() << ":" << result.tostring(); }
ps: first post after years of lurking. i've read tips on writing great answers if i've made mistakes/bad things please tell me.
may code you
Comments
Post a Comment