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.

QT       += core gui widgets script


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.


#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;

class Widget : public QWidget

    explicit Widget(QWidget *parent = nullptr);

private slots:
    // Everything is by default, except for this slot, which will execute JavaScript and count variables
    void onExecPushButtonClicked();

    Ui::Widget *ui;

#endif // WIDGET_H


And now the application code itself

#include "Widget.h"
#include "ui_Widget.h"

// We need the following classes
#include <QScriptEngine>
#include <QScriptContext>
#include <QScriptValue>

Widget::Widget(QWidget *parent) :
    ui(new Ui::Widget)
    // Connect signal from button to slot
    connect(ui->execPushButton, &QPushButton::clicked, this, &Widget::onExecPushButtonClicked);

    delete ui;

void Widget::onExecPushButtonClicked()
    // Create a JavaScript engine object
    QScriptEngine engine;
    // Take from it the context in which we will work.
    // In this case, a new context is created.
    QScriptContext* context = engine.pushContext();

    // Take the names of the variables with which to work
    const QString var_1 = ui->nameLineEdit_1->text();
    const QString var_2 = ui->nameLineEdit_2->text();

    // Set the variables by trying to convert the text of the QLineEdit fields to double
    bool ok = false;

    double value = ui->valueLineEdit_1->text().toDouble(&ok);
    if (ok)
        // Set variable with value as properties of the script activation object.
        context->activationObject().setProperty(var_1, value);
        // If the conversion fails, the value will be Undefined.
        context->activationObject().setProperty(var_1, QScriptValue::UndefinedValue);

    value = ui->valueLineEdit_2->text().toDouble(&ok);
    if (ok)
         // Set variable with value as properties of the script activation object.
        context->activationObject().setProperty(var_2, value);
        // If the conversion fails, the value will be Undefined.
        context->activationObject().setProperty(var_2, QScriptValue::UndefinedValue);

    // Run the script

    // We clear the field of output of the result from the previous values
    // Выводим текущее состояние переменных
    ui->resultTextEdit->appendPlainText(var_1 + " = " + context->activationObject().property(var_1).toString());
    ui->resultTextEdit->appendPlainText(var_2 + " = " + context->activationObject().property(var_2).toString());

    // Remove context

    // Since the QScriptEngine is created on the method stack, it will be deleted automatically when the method ends.


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).

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways


Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
May 26, 2020, 11:29 a.m.
Artem Sun-Dun-Chan

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
May 25, 2020, 11:33 a.m.
Mitja Nagibin

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
May 25, 2020, 5:05 a.m.

C++ - Test 001. The first program and data types

  • Result:66points,
  • Rating points-1
Last comments
May 28, 2020, 3:14 p.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Ну в моём примере, который в статье сработало так model->setData(model->index(1, 1), 7); Поскольку model->index(1, 0) - это индекс колонки id, которая скрыта, поэтому…
May 28, 2020, 3:08 p.m.
Mihail A

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Спасибо, завтра првоерю. А model->setData(model->index(1, 0), 7); Тоже заработало?
May 28, 2020, 3:06 p.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Да, метод data всё-таки влиял, я переписал его так и заработало удаление QVariant TableModel::data(const QModelIndex &idx, int role) const{ if (role == Qt::BackgroundColorRole) {…
May 28, 2020, 2:49 p.m.
Evgenij Legotskoj

Django - Tutorial 011. Adding comments to the site based on Django

Он более функциональный и его функционал объективно лучше поддерживается Django. Из первого, что приходит на ум: Это наличие полей типа Array Поддержка полей для JSON …
May 28, 2020, 2:42 p.m.

Django - Tutorial 011. Adding comments to the site based on Django

а в чем явное преимущество postgresql над mysql?)
Now discuss on the forum
May 29, 2020, 1:55 a.m.
Igor' Poroshin

QTablwView + QSqlQueryModel скрыть пустой столбец

Да, понятно. В данном случае лучше использовать серверную процедуру (если такие поддерживаются), в которой будет проверяться наличие всех пустых строк у нужного столбца и вызываться соответ…
May 28, 2020, 6:21 p.m.
Rovshan Gurbanov

Сборка под старые версии Android

У меня SDK почти все версии есть, NDK есть версии 10, 17, 21. Но собирается приложение только с NDK v21 под Android версии 7.0 и выше Версия Qt у меня 5.14.2
May 28, 2020, 7:58 a.m.
Evgenij Legotskoj

Освобождение памяти QMainWindow::setCentralWidget

Да, соглашусь. Просто удаление происходит позже, а не сразу.
May 28, 2020, 5:43 a.m.

При подключении к git как указать пароль?

Нужно сделать ssh-keygen и потом полученый из файла код скопировать в ssh ключ в бикбакете
May 28, 2020, 1:42 a.m.


Да, проблема ушла, спасибо.
© EVILEG 2015-2020
Recommend hosting TIMEWEB