Evgenii Legotckoi
Evgenii LegotckoiApril 21, 2018, 4:18 p.m.

Qt/C++ - Tutorial 076. Visualizing Mathematical Formulas on Qt

Recently, a rather interesting question appeared on the forum, about how you can visualize formulas in Qt. Unfortunately, I did not have the opportunity to deal with the site and the forum for a long time, but decided that presenting my possible vision of the problem even after a while would be useful.

The question is to visualize the formula, which is written in the form of a line.

For example, you type sqrt(5) in some input field, and in some widget you will display a graphical display of the square root of 5, that is, not the result, but the formula itself. Similar functionality is implemented in Latex and LibreOffice .

It will look like this.

By itself, the task of writing such a functional in my opinion can be quite difficult and time consuming, especially if it comes to implementing a functional with embedded formulas, etc. Therefore, I will focus on the concept that occurred to me to implement the mapping of the simplest variants of formulas, i.e. without nested subformulas.

Basic Provisions

To implement this functionality requires:

  • Using regular expressions to highlight the formula
  • Display the formula on the widget

I believe that for this task the use of regular expressions will be quite appropriate, since you need to correctly parse the string and allocate the instances of the formulas. To create a graphical display of the formula, we'll write a special FormulaWidget class that will contain a regular expression for searching in the formula string, as well as a method that will draw the formula at the specified point on the widget using the QPainter object that will be provided by the widget itself. This method will have to return a new position to draw the next formula so that they do not overlap if several formulas are passed in the row.

To draw formulas, create a class inherited from QWidget and redefine its paintEvent () method, which is responsible for rendering the contents of this widget.

Main application window

As the main application window, the class inherited from QWidget will be used. You select it when creating a project. Also, it will have a graphical form file, in which it will be necessary to arrange widgets of interest to us:

  • QLineEdit - where we write down the formula
  • FormulaWidget - where the formula will be displayed

In the graphical editor, you will need to add the object of a normal widget and use the context menu to convert it to the previously created FormulaWidget class. In the context menu there is for this the item "Promote to ...".

I will not touch the contents of the main.cpp file, because everything is created by default.


#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;

class Widget : public QWidget

    explicit Widget(QWidget *parent = 0);

    Ui::Widget *ui;

#endif // WIDGET_H


To transfer the typed text to the widgets of the formula, we will use the connection of the textChanged signal from QLineEdit to the setFormula slot, which we will create in the FormulaWidget class.

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    ui(new Ui::Widget)
    connect(ui->lineEdit, &QLineEdit::textChanged, ui->formulaWidget, &FormulaWidget::setFormula);

    delete ui;

Classes for drawing formulas

Now consider the class itself for visualizing the formulas and the class of the formula itself. Both of these classes will be located in one header file ( FormulaWidget.h ) and an implementation file ( FormulaWidget.cpp ).



// The visualization class of the formula
class FormulaItem
    explicit FormulaItem(QString value) : m_value(value){}

    static const QString REGULAR_EXPRESSION; // The string of the regular expression for finding the formula
    // Метод отрисовки формулы
    QPoint draw(const QPoint& pos, QPainter& p) const;

    QString m_value; // The value of the formula


const QString FormulaItem::REGULAR_EXPRESSION = "sqrt\\((?<value>\\d+)\\)";

QPoint FormulaItem::draw(const QPoint& pos, QPainter& p) const
    int valueWidth = p.fontMetrics().width(m_value);
    int valueHeight = p.fontMetrics().height();

    p.drawLine(pos.x(), 4 + valueHeight / 2, pos.x() + 5, 4 + valueHeight);
    p.drawLine(pos.x() + 5, 4 + valueHeight, pos.x() + 10, pos.y() + 1);
    p.drawLine(pos.x() + 10, pos.y() + 1, pos.x() + 14 + valueWidth, pos.y() + 1);

    p.drawText(QRect(pos.x() + 12, pos.y() + 4, pos.x() + 12 + valueWidth, pos.y() + 4 + valueHeight), m_value);
    return QPoint(pos.x() + valueWidth + 20, pos.y());

The static constant variable REGULAR_EXPRESSION is a string that contains a regular expression for finding the occurrence of a formula.

In Qt, there are two classes for working with regular expressions:

  1. QRegExp -I used it in an article on writing highlighting the syntax of html markup.
  2. QRegularExpression - about it I have not written articles yet, and this will be the first article with its use

The first class was introduced earlier, the second was introduced only in Qt 5.0. The first, as I understand it, is Qt's own regular expression implementation. And the second class is already the implementation of regular expressions with syntax support exclusively for Perl. At the moment, the documentation recommends using QRegularExpression , and to study the syntax of regular expressions, to study the documentation in Perl.

As for the terrible draw method, its implementation is responsible for the beautiful drawing of the formula with the setting of the position of the value inside the square root. There is enough pseudomathematics for per-pixel rendering of all lines and numbers with the presence of magic numbers. In real projects, try to avoid this and use named constants like PADDING_BOTTOM , OFFSET , etc.

One of the important points in the draw method is that the QPainter object must be passed by reference as an argument, but the reference can not be constant, because this object will be modified. So here everything is in order. From my own experience I will say that this is normal for working with rendering custom widgets, when their QPainter is passed through a non-constant link to other methods.

In the given regular expression there is a named captured value, by which we can extract the value, which is in the root, in order to further draw it.

"sqrt\((? \d+)\)" - in this regular expression, this name is value .



// Class for drawing all formulas
class FormulaWidget : public QWidget
    using BaseClass = QWidget;
    explicit FormulaWidget(QWidget* parent = nullptr);

public slots:
    // Slot for setting the formula
    void setFormula(const QString& formula);

    virtual void paintEvent(QPaintEvent* event) override;

    QList<FormulaItem> m_items;

There are two important methods in the class. The first is to set the line from which we will extract the formulas, and the second overridden method is paintEvent() . The overridden method is responsible for drawing the widget; in it, we will also draw all the formulas. This method is called in the Qt's event handling method stack. Directly this method is never called, it is called when certain events occur, but it is enough to call it the update() method.


FormulaWidget::FormulaWidget(QWidget* parent) :
    // Set the background color of the widget, by default it is the same as in the system design of the OS
    QPalette pal = palette();
    pal.setColor(QPalette::Background, Qt::white);

void FormulaWidget::setFormula(const QString& formula)
    // Clear all formulas

    // Create a regular expression object to find the formula
    QRegularExpression sqrt_value(FormulaItem::REGULAR_EXPRESSION);
    // We seek all occurrences of formula
    QRegularExpressionMatchIterator i = sqrt_value.globalMatch(formula);

    // create all objects of formulas
    while (i.hasNext())
        QRegularExpressionMatch match = i.next();
        if (match.hasMatch())

    // Run the redrawing

void FormulaWidget::paintEvent(QPaintEvent* event)
    // For repainting, the QPainter object is used, 
    // which must necessarily receive the object for rendering which it replies
    QPainter p(this);

    QPoint formulaPos(2, 2);

    // We draw all the formulas that we could find
    for (const FormulaItem& item : m_items)
        formulaPos = item.draw(formulaPos, p);

As a result of this code, the application shown in the screenshot at the beginning of the article will be received.

I also enclose the project code. Download

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!


Only authorized users can post comments.
Please, Log in or Sign up

C++ - Test 002. Constants

  • Result:41points,
  • Rating points-8

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

  • Result:80points,
  • Rating points4

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

  • Result:53points,
  • Rating points-4
Last comments
Evgenii Legotckoi
Evgenii LegotckoiDec. 3, 2023, 7:39 p.m.
Django - Lesson 059. Saving the selected language in user settings It is redirect from untranslated url to translated url. It is normal behavior for mutlilanguage web site based on the Django.
coder55Dec. 2, 2023, 4:34 a.m.
Django - Lesson 059. Saving the selected language in user settings It tries to do language translation in API views. That's why it sends or receives the same API request twice. Do you have any suggestions on this? Example: stripe webhook. "GET /warehouse/…
gr1047Nov. 12, 2023, 9:35 p.m.
Qt/C++ - Lesson 035. Downloading files via HTTP with QNetworkAccessManager Добрый день. Изучаю Qt на ваших уроках. Всё нормально работает на Linux. А под Win один раз запустилось, а сейчас вместо данных сайта получается ошибк "Unable to write". Куда копать, ума не…
DamirNov. 2, 2023, 1:41 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers С CMake всё на много проще: find_package(Boost)
Павел Дорофеев
Павел ДорофеевOct. 29, 2023, 12:48 a.m.
Как написать свой QTableView Итак начинаем писать свои виджеты на основе QAbstractItemView. А что так можно было?
Now discuss on the forum
BlinCTNov. 30, 2023, 8:18 p.m.
Сборка проекта Qt6 из под винды на удаленой машине Всем привет. Сталкнулся с такой странностью: надо собирать проект из под 10 винды на удаленой линуксовой машине, проект строится на QT6, но вот когда cmake генерит свой кеш то вылитает…
Evgenii Legotckoi
Evgenii LegotckoiNov. 19, 2023, 7:14 p.m.
CKEditor 5 и подсветка синтаксиса. Добрый день. Я устал разбираться с CKEditor и просто перешёл на использование самописного markdown редактора...
Виктор Калесников
Виктор КалесниковOct. 20, 2023, 2:29 p.m.
Контакты Android делал в далеком 2017г поэтому особенно ничего не подскажу. Это основные методы получения данных с андроида используя Qt. Там еще какоето колдунство с манифестом. Андроидом давно не занимаюс…
mihamuzOct. 19, 2023, 12:03 a.m.
Скачать Qt 6 Сработал следующий алгоритм. Инстолятор скачал используя это https://freevpnplanet.com/ru/ как расширение браузера. Потом установил это https://freevpnplanet.com/ru/ же на ПК и через инстолятор …

Follow us in social networks