Using QScriptEngine to compute calculations

亡梦爱人 提交于 2019-12-11 19:24:23

问题


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?


回答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.



来源:https://stackoverflow.com/questions/17340555/using-qscriptengine-to-compute-calculations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!