0

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?

Joum
  • 3,189
  • 3
  • 33
  • 64

1 Answers1

1

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.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • Thank you for your reply! Actually, when I mentioned the storing process, I forgot to mention that the idea is to store the formula, and then recover it to be used in a potentially different context, ie, using the same example as in the question, but with different properties. Do you have any insight you can share for this scenario? – Joum Jun 27 '13 at 12:31
  • You can alter `engine->globalObject()`. Every property added to this object can be visible for all formulas running by this engine. – Pavel Strakhov Jun 27 '13 at 12:38