Evgenii Legotckoi
Evgenii LegotckoiOct. 11, 2018, 2:04 p.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.

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

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

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

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

Widget.cpp

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) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    // Connect signal from button to slot
    connect(ui->execPushButton, &QPushButton::clicked, this, &Widget::onExecPushButtonClicked);
}

Widget::~Widget()
{
    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);
    }
    else
    {
        // 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);
    }
    else
    {
        // If the conversion fails, the value will be Undefined.
        context->activationObject().setProperty(var_2, QScriptValue::UndefinedValue);
    }

    // Run the script
    engine.evaluate(ui->javaScripTextEdit->toPlainText());

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

    // Remove context
    engine.popContext();

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

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

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.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 2:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

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

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks