Evgenij LegotskojDec. 1, 2019, 2:22 p.m.

Qt/C++ - Tutorial 090. How to make a learning dialogue with highlighting widgets in the program


I suggest studying a small application in which a dialog box will be created, thanks to which the user can be trained in the functionality of your program, step by step explaining which program widget is responsible for what.

To implement such functionality, you need to create an application window that will have the buttons "Previous widget", "Next widget", "Close window". Before starting, widgets will be transferred to this window in the sequence in which they should be presented to the user in your program, as well as text messages that will describe the widgets.

The program will look like this:


As we agreed, we will create a tutorial dialog that will accept a sequence of widgets that we need to talk about.
In this case, the current widget will be highlighted by overriding its styles, that is, the red border of the widget will be set.
I’ll say right away that redefining styles through stylesheet can entail a complete redefinition of the styles of some widgets under some platforms, so it’s better to create a fully customized application style or redefine widgets with an override of the paintEvent method. In any case, for a more beautiful highlight, you will have to do significant work on styling the application, but for the purpose of the training article, I will show only a minimal redefinition of styles.


A dialog is created in the Qt graphic designer to not clutter up useful code. That is, the dialogue itself is formed using the ui file. It will look like this. You can take the program code in the EVILEG example repository at the end of the article.


In the header file of the dialog box, you will need to use the TutorialInfo structure, which will store the pointer to the widget, as well as its description.
We will also need a variable that will store the old style of the current widget and the index of the current widget.


#include <QDialog>

namespace Ui {
class TutorialDialog;

class TutorialDialog : public QDialog

    explicit TutorialDialog(QWidget *parent = nullptr);

    // add widget and text information about this widget to tutorial dialog
    void addWidgetToTutorial(QWidget* widget, const QString& text);

    void onPreviousButtonClicked(); // slot which reacts on click of previous button
    void onNextButtonClicked();     // slot which reacts on click of next button
    void updateButtonsEnabled();    // update actual enabled status of buttons
    void returnOldStyle();          // return old style to widget, which was highlighted
    void setTextAndStyle();         // set text information to tutorial dialog and set highlight style to widget

    Ui::TutorialDialog *ui;

    // This structure contains text information aboout some widget
    struct TutorialInfo
        QWidget* widget;
        QString text;

    // highlight style
    const QString HIGHLIGHT_STYLE {"border: 1px solid red"};
    QVector<TutorialInfo> m_infoItems;      // vector of widgets in tutorial
    int m_currentTutorialInfoIndex {-1};    // index of current highlighted widget
    QString m_oldStyleOfWidget;             // old widget style



#include "TutorialDialog.h"
#include "ui_TutorialDialog.h"

#include <QDebug>

TutorialDialog::TutorialDialog(QWidget *parent) :
    ui(new Ui::TutorialDialog)
    setModal(true);                 // this dialog should be modal
    setWindowFlags(Qt::Window);     // but it doesn`t create shadow on mainwindow

    connect(ui->closeButton, &QPushButton::clicked, this, &TutorialDialog::close);
    connect(ui->previousButton, &QPushButton::clicked, this, &TutorialDialog::onPreviousButtonClicked);
    connect(ui->nextButton, &QPushButton::clicked, this, &TutorialDialog::onNextButtonClicked);


    // When dialog was destrcucted, we should set up old style to current widget
    delete ui;

void TutorialDialog::addWidgetToTutorial(QWidget* widget, const QString& text)
    if (m_infoItems.empty())
        m_currentTutorialInfoIndex = 0;

    m_infoItems.push_back({widget, text});

    if (m_infoItems.size() == 1)

void TutorialDialog::onPreviousButtonClicked()

void TutorialDialog::onNextButtonClicked()

void TutorialDialog::updateButtonsEnabled()
    ui->previousButton->setEnabled(m_currentTutorialInfoIndex != -1 && m_currentTutorialInfoIndex > 0);
    ui->nextButton->setEnabled(m_currentTutorialInfoIndex != -1 && m_currentTutorialInfoIndex < m_infoItems.size() - 1);

void TutorialDialog::returnOldStyle()
    if (m_currentTutorialInfoIndex != -1)

void TutorialDialog::setTextAndStyle()
    m_oldStyleOfWidget = m_infoItems[m_currentTutorialInfoIndex].widget->styleSheet();


And then we will need to create this dialog in the launch slot of the tutorial dialog, as well as add widgets and information about these widgets to the dialog.



#include <QMainWindow>

namespace Ui { class MainWindow; }

class MainWindow : public QMainWindow

    MainWindow(QWidget *parent = nullptr);

    void onStartTutorialButtonClicked();

    Ui::MainWindow *ui;
#endif // MAINWINDOW_H


#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "TutorialDialog.h"
#include "TutorialDialog.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    connect(ui->startTutorialButton, &QPushButton::clicked, this, &MainWindow::onStartTutorialButtonClicked);

    delete ui;

void MainWindow::onStartTutorialButtonClicked()
    TutorialDialog tutorialDialog;  // Create tutorial dialog

    // Add widgets to tutorial dialog
    tutorialDialog.addWidgetToTutorial(ui->projectStructureTreeView, tr("This is project structure"));
    tutorialDialog.addWidgetToTutorial(ui->createProjectButton, tr("Create new project using this button"));
    tutorialDialog.addWidgetToTutorial(ui->openProjectButton, tr("Open your project using this button"));
    tutorialDialog.addWidgetToTutorial(ui->infoWidget, tr("Here You will see some information about objects in your project"));

    // Start tutorial dialog


To develop the idea of a learning window, you can use either the inheritance of all widgets used in the program with an override of the paintEvent method to add and remove a highlighted border, or completely override all the styles used by the widgets so that when installing stylesheet those styles that were not planned to break.

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.
- company blog
Support the author Donate


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

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

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

  • Result:73points,
  • Rating points1

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

  • Result:64points,
  • Rating points-1

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

  • Result:86points,
  • Rating points6
Last comments

QML - Lesson 016. SQLite database and the working with it in QML Qt

Добрый день! можно как то обойтись без метода updateModel()? После вызова этого метода происходит перерисовка страницы(если я правильно понимаю), и все элементы, например, CheckBox перерисовываю…

QML - Lesson 016. SQLite database and the working with it in QML Qt

Добрый день, пытаюсь разобраться и подргнать пример под себя. Есть бд с огромным количеством полей. В приложении на виджетах при использовании QTableView все работает и путем простого sql запрос…

Django - Tutorial 039. Adding private messages and chats on the site - Part 2 (Dialogue and chat counter with unread messages)

Добавляйте поле файла в модель сообщения. И в форме сообщения указывайте, что поле с файлом.

Django - Tutorial 023. Like Dislike system using GenericForeignKey

все, я со всем разобрался!) Извините!)
Now discuss on the forum

Наследование QWidget

Это утверждение ничего не значит. Наличие методов и т.д. не делает обязательным наследование в том виде, в котором вы его изначально попытались сделать. Тем более, если у вас будет два видж…

Динамическое заполнение StackLayout в qml

Всем привет. Пытаюсь решить такую задачку, есть TabBar и его кнопки. StackLayout{ currentIndex: tabBar.currentIndex A {id: tabA} B {id: tabB} C {id: tabC} D {id: ta…

QML: изменение стиля при наведении и при нажатии на кнопку

enabled = false перестанет быть активной и не будет ни на что реагировать) Хм.. по-моему пробовал такое. Проверю ещё раз после работы. Ура, спасибо большо…

Динамическое наполнение StackView QML

Во затупил))) Спасибо за все))) StackView.push("ModuleTip1.qml") ну или в сложной иерархии StackView.push("qrc:/folder/ModuleTip1.qml") и всего делов... Не пойму, почему сра…

QEventLoop тормозит при удалении экземпляра

Думаю, что нет. Лучше вообще без исключений, но не всегда возможно.
© EVILEG 2015-2020
Recommend hosting TIMEWEB