Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to make a calculator using QJSEngine and I need functions like sqrt, pow, ln, sin etc. In QScript you could define custom functions with a few simple lines of code, but I have no idea how I can achieve this in QJSEngine.

What I have tried:

I've created a js script with all the functions I need in hope of connecting it to the engine, but I'm not sure if it's possible, or (if it is) how can I do it.
Posted
Updated 2-Aug-18 2:32am

1 solution

According to the documentation and the examples at QJSEngine Class | Qt QML 5.11[^] you can pass a function as string to evaluate() and execute the call() method of the returned QJSValue Class | Qt QML 5.11[^]:
C++
QJSEngine myEngine;
QJSValue fun = myEngine.evaluate("(function(a, b) { return a + b; })");
QJSValueList args;
args << 1 << 2;
QJSValue threeAgain = fun.call(args);
 
Share this answer
 
Comments
Member 13020023 4-Aug-18 17:09pm    
What if I need to execute the function inside the program that's being evaluated? For example I define a function, which returns the factorial of a number called myFactorialFunc. Now when I type call evaluate("myFactorialFunc(4)"), I expect the output to be 24.
Jochen Arndt 5-Aug-18 4:08am    
You have to pass the complete function code to evaluate() first and then call that function using either the method from my solution or by performing another evaluate() call on the same engine instance calling that script function.

I have not tried it but for your case you should load your script as shown in the documentation from my link and then call the functions defined in the script with another evaluate() call using the function name and the parameters. But note that the parameters can't be passed by value in this case (are part of the string).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900