Question

I'm creating a diagram modeling tool that connects Items to Tasks. Items have Properties (simple name/value relationships) and Tasks have Formulas. I intend to produce a UI for the users to write in a QLineEdit a formula using C++ syntax ( ie, (property1 * property2)/property3), and then output the result. Of course, the formula would have to be somehow parsed and computed to output the result.

My concern with this is if using QScriptEngine is appropriate for this. I've seen that it can be used to perform calculations using evaluate(). Besides the 4 "regular" operations ( +, -, * and /), I only anticipate that probably sqrt() and pow() might be required - but apparently, Math is also usable inside the evaluation string.

Also, I need to store and recover these formulas, so I was considering handling them as QStrings for that purpose, as I will need to write/read them to/from files.

Do you think this is a good approach? What would you suggest as a good read for this type of objectives?

Was it helpful?

Solution

Yes, this approach is good. I've used it for a similar task. Note that QScriptEngine uses JavaScript syntax, not C++ syntax. But JavaScript syntax is powerful and fulfills usual needs of user-defined formulas. It supports regular operators, math functions, brackets, local variables, etc.

You can store a formula in QString. If you need to execute the same formula multiple times, you should use QScriptProgram to compile a formula before executing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top