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
#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 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.
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 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.
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 but if I've made some mistakes/bad things please tell me.
May the code be with you