问题描述
我正在从 QScriptEngine
(已弃用)移到 QJSEngine
,我发现我在无法使用 print
:
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();
输出为:
error: "ReferenceError: print is not defined"
在 QScriptEngine
起作用。
然后,在 QJSEngine中打印内容进行控制台的方式是什么
?在文档中找不到任何内容。我尝试使用 console.log
,但是控制台
也没有定义。
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.
推荐答案
在QJSEngine中未实现打印功能。您将必须自己实施。幸运的是,您可以编写QObjects并使它们在脚本中可用。 (请参见)
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)
这是我的做法:
创建一个类JSConsole从QObject继承:
Create a class JSConsole inheriting from QObject:
jsconsole.h
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
jsconsole.cpp
#include "jsconsole.h"
#include <QDebug>
JSConsole::JSConsole(QObject *parent) :
QObject(parent)
{
}
void JSConsole::log(QString msg)
{
qDebug() << "jsConsole: "<< msg;
}
使用
现在,您可以使用 QJSEngine.newQObject 在js引擎中创建代理对象。
之后,将其添加到全局对象中并使用它。
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');");
错误记录
我已经搜索了当我在js文件中出现拼写错误时,很长时间以来我的c ++代码中的错误。以下代码段将有助于避免这种情况。
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:潜伏多年后的第一篇文章。我已经阅读了编写出色答案的提示,但是如果我犯了一些错误/不好的事情,请告诉我。
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
这篇关于QJSEngine:打印到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!