Script in Qt does not return the correct value

I am trying to use a script in Qt, here is a very simple code.

QCoreApplication a(argc, argv);

double x;

cout<<"Please enter a number: ";
cin>>x;
QFile file("cube.js");
if(!file.open(QIODevice::ReadOnly))
    abort();

QTextStream in(&file);
in.setCodec("UTF-8");
QString script=in.readAll();
file.close();
QScriptEngine interpreter;
QScriptValue operand(&interpreter,x);
interpreter.globalObject().setProperty("x",operand);
QScriptValue result=interpreter.evaluate(script);
cout<<"The result is "<<result.data().toInt32()<<endl;

return a.exec();

The contents of cube.js is only one line:

return x*x*x;

I run this program, but always returns zero. Can someone tell me what's wrong with that? The contents of the file are read correctly.

Regards,

+5
source share
1 answer

You are invoking a global Javascript return, which is not valid. You can use QScriptEngine::hasUncaughtExceptionit QScriptValue QScriptEngine::uncaughtExceptionto identify errors in javascript code.

You also call result.data()which is intended to store internal data. So the script should be

x*x*x

And printout:

cout<<"The result is "<<result.toInt32()<<endl;
+6
source

All Articles