Last visit 3 months ago

Dmitrij

Dmitras

  • 0
  • 0
DmitrijDec. 31, 2020, 5:19 a.m.

C++Generating pseudo-random numbers in Qt (QRandomGenerator)

QRandomGenerator

This note is a small addition to the article Generating pseudo-random numbers using the random STD library . The author omitted one of the useful functions of the QRandomGenerator class in it. The generator implementation is as follows:

QRandomGenerator *rg = QRandomGenerator::global();
for(int i = 0; i < 10; i++) {
    qDebug() << rg->bounded(1, 10);
}

The global() function returns a pointer to a ready-to-run random number generator. An alternative to it is the system () function, which implements the possibilities for generating random numbers embedded in the operating system. The bounded(a, b) function returns a random number from a to b. The following functions are also available to us: generateDouble() - returns one random number from the range from 0 to 1, generate() and generate64() - return a random 32 and 64 bit random number, respectively. All of the listed functions will return a new sequence of numbers each time they are run/called.
In my opinion, such a toolkit is able to cover all the needs of an average programmer for generating random numbers without connecting third-party libraries.

DmitrijJune 28, 2020, 8:03 a.m.

QtComputer Geometry with Qt Creator

аналитическая геометрия, C++ геометрия, Qt геометрия, QVector2D, геометрия, компьютерная геометрия, QVector4D, QVector3D

By means of this article, I want to share my experience in using computer geometry, which I have accumulated in the process of working on my dissertation. Not everyone knows Qt Creator contains tools for working with geometry (in particular QVector3D), for which there is no detailed manual in Russian. Therefore, here I will try to summarize the necessary theory and its implementation as briefly as possible.

DmitrijMay 18, 2019, 3:29 p.m.

QtFb3 file reader on Qt Creator

fb3-читака, fb2-читалка, reader, читалка fb3, fb3-reader, формат fb3

Some time ago, I published a fb2 reader project, in the process of working on which I found out that this format is obsolete. Therefore, I began to master new formats and settled on fb3, the fb2 receiver format. In the course of work, I encountered some problems that have not been fully resolved. In addition, despite the fact that books are already appearing in fb3, the format has not been finally approved. Although books already appear. Therefore, I decided to publish the program in its current form and talk about my achievements and failures. Subsequently, I plan a new version with support for the epub format.

DmitrijFeb. 28, 2019, 10:14 a.m.

C++Opening mp3 files using the audiere library

как открыть mp3-файл, звук, audiere, обработка звука, аудио

Библиотека audiere позволяет работать с аудиофайлами различных форматов (wav, mp3 и т.д.). Для работы нам понадобятся файлы audiere.h, audiere.lib, audiere.dll. h-файл подключается в коде программы

#include "audiere.h"

lib-файл линкуем в .pro

LIBS += audiere.lib

dll таскаем за программой.
В рунете легко найти информацию о том, как воспроизвести с её помощью звук. Но абсолютно отсутствует информация, как получить аудиоданные для дальнейшей обработки. Поэтому напишу я, тем более, что это достаточно просто.

DmitrijSept. 22, 2018, 4:16 a.m.

Projects based on QtReader fb2-files on Qt Creator

reader, читалка, fb2-читалка, html, fb2-reader, fb2

Some time ago I wrote an article in which I showed how to open a fb2 file with Qt tools. After some time, I noticed a number of shortcomings in it, which I decided to eliminate. Moreover, I found that some fb2 readers also have disadvantages (namely, incorrect display of tables), which prompted me to write this article. For starters, you can read the last article . We will act on the same principle: we form the book string in html format and place it in the QTextBrowser object.

Let me remind you that in order to create an html document, you need to perform 3 actions: open the tag, fill it with content and close it. Therefore, there are 4 options for us: we rewrite from the source file, rewrite with corrections, do nothing (ignore), and conduct special processing.

DmitrijAug. 29, 2017, 3:26 p.m.

QtOpen fb2-files using Qt

fb2, html, QXmlStreamReader, xml

Currently fb2 is a popular format for storing books. The fb2 file is a special case of xml. The main element of its structure, as for html, is the tag (control words). In this article, I'll show you how to create a simple fb2 file viewer. The project with the source text can be downloaded from the link. .

General information

Tags are divided between block and lowercase. Block tags are grouped in pairs from the opening tag that closes the tag between which the content is located. For example, a paragraph of text is written as

<p>Paragraph text</p>

Inside such a block pair, you can put other tags. Lowercase tags are used for objects in which nothing can be embedded. For example, a pointer to a drawing

<image l:href = “#_0.jpg”/>

contains information: 1) that a drawing needs to be inserted at the given point of the document, 2) a link to this figure. The algorithm for inserting a picture into text is explained below. Distinguish 3 types of tags simply with the help of a slash. At the line tag the slash before the closing bracket, at the closing block after the opening, at the opening block it is absent.

If you want to fully understand, study html. There is some difference between html and fb2, although in many respects they are identical. I will indicate such elements in the course of the narrative. Also note that xml, unlike html, does not use the CSS language, in our case this means that there is no indication in the fb2 file of how the text is formatted (font size and color, paragraph layout, etc.). All this we must (if desired) to implement independently.

Structure of fb2-file

The first <?xml> tag contains technical information about the format, its version, and the encoding used. The second tag covers the whole book. As a rule, in any book there are 2 parts: a description of and the main part of (as in html). Description contains the author's name, title of the book, annotation, etc. The main part contains the titles (the whole book or individual chapters), chapters / parts / sections <section> and text <p> (as in html). </p><pre><pre class="lang-html prettyprint linenums"><?xml …> <FictionBook …> <description> … </description> <body> … </body> … </FictionBook> </pre></pre><p> In addition, you can find the epigraph <epigraph> tags, the <a> link (as in html), the <image/> image and the empty <empty-line></empty-line> line (in html <br/> ). Links can be external and internal. External links as a parameter contain the source URL, internal links contain references to the elements in the text of the file (see the above image tag). Drawings contain similar internal references. </a></epigraph></p><p> After the </p> section, additional elements can be located. So in separate tags <binary> the pictures converted to the text form are placed. </binary></section>

Creating a Reader Program

We will build our program in the following way: we will read the data from the file and convert it to html, then send the generated string to the text field using the setHtml (QString) function. One little lifhack for those who want to learn html: the QTextEdit / QTextBrowser class object can display the formatted document as source text. To do this, open the form editor, click on the object 2 times and switch to the "Source" tab.

To process fb2-files, we will use the QXmlStreamReader class. To work with it, you need to connect the xml and xmlpatterns modules to the project. As an argument, it must be passed a pointer to an object of class QFile.

QFile f(name);
QXmlStreamReader sr(&f);

The opening of the file itself looks like a cycle with sequential reading of lines. We also need 3 variables

QString book;
QString imgId;
QString imgType;

book is needed to store the generated document, imgId and imgType for pasting pictures into text. The QXmlStreamReader class produces several important actions. First, it determines and installs the desired decoder. Second, it separates the tags from the content. Third, it highlights the properties of tags. We can only process the separated data. The readNext () function is used to read the data. All the fragments read to it belong to one of 5 types: StartDocument, EndDocument, StartElement, EndElement and Characters. Of these, 2 are the first to determine the beginning and end of the file, 2 are the next to read the tags and the last to receive the placeholder.

Having received StartDocument, we need to add the header line of the document html and 2 opening tags

book = "<!DOCTYPE HTML><html><body style=\"font-size:14px\">";

When EndDocument is reached, we close the tags opened at the beginning of the file

book.append("</body></html>");

The appearance of StartElement means that the opening or lowercase tag is read. Accordingly, EndElement signals the reading of the closing tag. The name of the tag is determined by calling the function sr.name (). ToString (). To control the structure of the document, we will store a list of all open tags in the thisToken object of the QStringList class. Therefore, in the case of StartElement, appends the name of the current tag to thisToken and deletes it in the case of EndElement. In addition, the opening (or lowercase) tags can contain attributes. The attribute will be read and stored in sr as an array of strings. You can access them using the sr.attributes () method. We need them to add pictures to the text. So, if a tag is found, you need to add a label to the picture in the text.

book.append("<p align=\"center\">"+sr.attributes().at(0).value().toString()+"</p>");

Then, if we find the tag, we need to save its tag and format.

imgId = sr.attributes().at(0).value().toString();
imgType = sr.attributes().at(1).value().toString();

Note that imgId is identical to the tag attribute, except for the absence of a sharp sign (#).

Now we can only put the contents in the string book. Here you can use a different set of rules. For example, ignore the description of a book

if(thisToken.contains("description"))
{
    break; // не выводим
}

or highlight the headings by color, font size and type. Let us dwell only on the pictures. To insert them, you need to form a string of type

QString image = "<img src=\"data:"
        + imgType +";base64,"
        + sr.text().toString()
        + "\"/>";

where sr.text (). toString () contains the contents of the tag. Then you should replace in our line-document the label corresponding to this figure on this line

book.replace("#"+imgId, image);

The algorithm for reading the fb2-file

    while( !sr.atEnd() )
    {
        switch( sr.readNext() )
        {
        case QXmlStreamReader::NoToken:
            qDebug() << "QXmlStreamReader::NoToken";
            break;
        case QXmlStreamReader::StartDocument:
            book = "<!DOCTYPE HTML><html><body style=\"font-size:14px\">";
            break;
        case QXmlStreamReader::EndDocument:
            book.append("</body></html>");
            break;
        case QXmlStreamReader::StartElement:
            thisToken.append( sr.name().toString() );
            if( sr.name().toString() == "image" ) // расположение рисунков
            {
                if(sr.attributes().count() > 0)
                    book.append("<p align=\"center\">"+sr.attributes().at(0).value().toString()+"</p>");
            }
            if(sr.name() == "binary") // хранилище рисунков
            {
                imgId = sr.attributes().at(0).value().toString();
                imgType = sr.attributes().at(1).value().toString();
            }
            break;
        case QXmlStreamReader::EndElement:
            if( thisToken.last() == sr.name().toString() )
                thisToken.removeLast();
            else
                qDebug() << "error token";
            break;
        case QXmlStreamReader::Characters:
            if( sr.text().toString().contains( QRegExp("[A-Z]|[a-z]|[А-Я]|[а-я]") )) // если есть текст в блоке
            {
                if(thisToken.contains("description")) // ОПИСАНИЕ КНИГИ
                {
                    break; // не выводим
                }
                if(thisToken.contains("div"))
                    break;
                if(!thisToken.contains( "binary" ))
                    book.append("<p>" + sr.text().toString() + "</p>");
            }
            if(thisToken.contains( "binary" ) )//для рисунков
            {
                QString image = "<img src=\"data:"
                        + imgType +";base64,"
                        + sr.text().toString()
                        + "\"/>";
                book.replace("#"+imgId, image);
            }
            break;
        }
    }

Our document is ready. It remains only to set the generated string in the text box

ui->textBrowser->setHtml(book);

For the full work of the fb2-reader, you need to add processing links, tables and some other objects. But the above material is sufficient to extract the main contents of the book.

DmitrijAug. 11, 2017, 2:58 p.m.

QtUsing the capabilities of winExtras when working with QML

qt, TaskbarButton, JumpList, qml, ThumbnailToolBar, winextras

Some time ago I wrote several articles about using the QtWinExtras library, which opens access to special features that are available only for Windows. Now I want to say a few words about how to repeat, too, using QML. For this we need to create a Qt Quick project, connect the winextras module in the project

import QtWinExtras 1.0

And use 3 objects: TaskbarButton to create a progress bar and manage it, ThumbnailToolBar for work with buttons on the pop-up window of the taskbar and JumpList (for working with jumpList). Also add FileDialog for the full work of jumpList.

DmitrijAug. 6, 2017, 2:56 p.m.

QtUsing JumpList to store files opened in the application when using Qt

winExtras, jumpList

JumpList, one of the features that are present only in Windows (version 7 and above). In this sheet, in particular, you can store links to the most recently opened files in the application.

DmitrijAug. 5, 2017, 1:13 a.m.

QtUsing the buttons WinThumbnailToolButton when working with Qt on Windows

winextras, QWinThumbnailToolButton, Qt, ThumbnailToolButton, WinThumbnailToolButton

Buttons of class QWinThumbnailToolButton - one of the options available only for Windows (7 and older). You could see such buttons in Windows Media Player

DmitrijJuly 30, 2017, 2:20 p.m.

QtProgress bar on the taskbar icon of a Windows application using Qt

Qt, полоса прогресса, QWinTaskbarProgress, winextras

The Qt library provides a number of platform-dependent features. One of these features for Windows is the use of the progress bar on the taskbar icon. This option is available for the OS since version 7.

To use this and some other features, you need to connect the winextras module,

QT += winextras

connect library

#include <QtWinExtras>

and add macros

QT_FORWARD_DECLARE_CLASS(QWinTaskbarButton)
QT_FORWARD_DECLARE_CLASS(QWinTaskbarProgress)
Card image cap
Pulsum Via

Project for travelers from EVILEG.

Go
Fornex

Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
Share on social networks
Donate

The EVILEG project has switched to a non-commercial basis and will develop solely on the enthusiasm of the site creator, the enthusiasm of users, donations and the hosting referral system

Thank you for your support

Available ways to support the project

PayPal

PatreonYandex.MoneyMore