Evgenii Legotckoi
Oct. 12, 2018, 12:04 a.m.

Qt/C++ - Tutorial 084. How to run JavaScript code in a C ++ application using the example of working with two variables

Suppose you are faced with the task of executing JavaScript code in a C++ application. For example, there is a set of output data or variables whose names are known in advance, and there are pieces of JavaScript code that does something with these variables. And there is also an algorithm that, if there are any conditions, it will choose. which javascript code should be run.

Also, you can't just take and rewrite that JavaScript code into C++ code and hardcorely add it to the application. Since there are a lot of such pieces of code, at the same time other people are engaged in their maintenance and constantly add new pieces of code.

That is, in this case, the set of input data and JavaScript code for us is data, in some way the content that we launch using a certain algorithm, according to which we choose, under what conditions to choose one or another for the same set of input variables a piece of javascript code.

I hope that I clearly explained why we need to run the execution of JavaScript code in a C++ application.

I suggest to write an application that has two input fields for variable names, two input fields with input for the values of these variables in double format, in case of entering a value other than double data type, we will set the value to Undefined .

We will also add an TextEdit input field for writing JavaScript code that we will execute in our application.

And the last input field will be called Result (this will be TextEdit ), which will be responsible for the output of the new calculated values of the variables we entered.

Also add a QPushButton, which will run the execution of JavaScript code.

The application will look like the image below.


Project structure

We write a project with a minimal structure. In essence, the project has a structure that is created by default.

The only important difference from the default pro file will be that we need to connect the script module.

This is done in the JSCalculation.pro file.

  1. QT += core gui widgets script

Widget.ui

In this article I will not describe how I created the application form in Qt Designer, this is not so important to us, and it does not apply to the topic of the article. Just list the objects that will be used in the source code of the widget with the name of their class

  • nameLineEdit_1 - QLineEdit
  • nameLineEdit_2 - QLineEdit
  • valueLineEdit_1 - QLineEdit
  • valueLineEdit_2 - QLinEdit
  • execPushButton - QPushButton
  • javaScriptTextEdit - QPlainTextEdit
  • resultTextEdit - QPlainTextEdit

Now let's proceed directly to the implementation of our project.

Widget.h

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5.  
  6. namespace Ui {
  7. class Widget;
  8. }
  9.  
  10. class Widget : public QWidget
  11. {
  12. Q_OBJECT
  13.  
  14. public:
  15. explicit Widget(QWidget *parent = nullptr);
  16. ~Widget();
  17.  
  18. private slots:
  19. // Everything is by default, except for this slot, which will execute JavaScript and count variables
  20. void onExecPushButtonClicked();
  21.  
  22. private:
  23. Ui::Widget *ui;
  24. };
  25.  
  26. #endif // WIDGET_H

Widget.cpp

And now the application code itself

  1. #include "Widget.h"
  2. #include "ui_Widget.h"
  3.  
  4. // We need the following classes
  5. #include <QScriptEngine>
  6. #include <QScriptContext>
  7. #include <QScriptValue>
  8.  
  9. Widget::Widget(QWidget *parent) :
  10. QWidget(parent),
  11. ui(new Ui::Widget)
  12. {
  13. ui->setupUi(this);
  14. // Connect signal from button to slot
  15. connect(ui->execPushButton, &QPushButton::clicked, this, &Widget::onExecPushButtonClicked);
  16. }
  17.  
  18. Widget::~Widget()
  19. {
  20. delete ui;
  21. }
  22.  
  23. void Widget::onExecPushButtonClicked()
  24. {
  25. // Create a JavaScript engine object
  26. QScriptEngine engine;
  27. // Take from it the context in which we will work.
  28. // In this case, a new context is created.
  29. QScriptContext* context = engine.pushContext();
  30.  
  31. // Take the names of the variables with which to work
  32. const QString var_1 = ui->nameLineEdit_1->text();
  33. const QString var_2 = ui->nameLineEdit_2->text();
  34.  
  35. // Set the variables by trying to convert the text of the QLineEdit fields to double
  36. bool ok = false;
  37.  
  38. double value = ui->valueLineEdit_1->text().toDouble(&ok);
  39. if (ok)
  40. {
  41. // Set variable with value as properties of the script activation object.
  42. context->activationObject().setProperty(var_1, value);
  43. }
  44. else
  45. {
  46. // If the conversion fails, the value will be Undefined.
  47. context->activationObject().setProperty(var_1, QScriptValue::UndefinedValue);
  48. }
  49.  
  50. value = ui->valueLineEdit_2->text().toDouble(&ok);
  51. if (ok)
  52. {
  53. // Set variable with value as properties of the script activation object.
  54. context->activationObject().setProperty(var_2, value);
  55. }
  56. else
  57. {
  58. // If the conversion fails, the value will be Undefined.
  59. context->activationObject().setProperty(var_2, QScriptValue::UndefinedValue);
  60. }
  61.  
  62. // Run the script
  63. engine.evaluate(ui->javaScripTextEdit->toPlainText());
  64.  
  65. // We clear the field of output of the result from the previous values
  66. ui->resultTextEdit->clear();
  67. // Выводим текущее состояние переменных
  68. ui->resultTextEdit->appendPlainText(var_1 + " = " + context->activationObject().property(var_1).toString());
  69. ui->resultTextEdit->appendPlainText(var_2 + " = " + context->activationObject().property(var_2).toString());
  70.  
  71. // Remove context
  72. engine.popContext();
  73.  
  74. // Since the QScriptEngine is created on the method stack, it will be deleted automatically when the method ends.
  75. }

Conclusion

You can first enter the names of the variables and their values to make sure that everything works fine without JavaScript code.

Also, the application should not fall and end with errors. If the JavaScript code that you will enter and as shown at the very beginning of the article does not give the result that you expect, then it is probably worth a close look at your JavaScript code, most likely you made a mistake. Also, QScriptEngine supports some standard JavaScript functionality, for example, the Math library (It will also work).

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup