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

QWidget, Tutorial, Qt, Stylesheet

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:

Introduction

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.

TutorialDialog

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.

TutorialDialog.h

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.

#ifndef TUTORIALDIALOG_H
#define TUTORIALDIALOG_H

#include <QDialog>

namespace Ui {
class TutorialDialog;
}

class TutorialDialog : public QDialog
{
    Q_OBJECT

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

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

private:
    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
};

#endif // TUTORIALDIALOG_H

TutorialDialog.cpp

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

#include <QDebug>

TutorialDialog::TutorialDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TutorialDialog)
{
    ui->setupUi(this);
    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);

    updateButtonsEnabled();
}

TutorialDialog::~TutorialDialog()
{
    // When dialog was destrcucted, we should set up old style to current widget
    returnOldStyle();
    delete ui;
}

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

    m_infoItems.push_back({widget, text});
    updateButtonsEnabled();

    if (m_infoItems.size() == 1)
    {
        setTextAndStyle();
    }
}

void TutorialDialog::onPreviousButtonClicked()
{
    returnOldStyle();
    --m_currentTutorialInfoIndex;
    setTextAndStyle();
    updateButtonsEnabled();
}

void TutorialDialog::onNextButtonClicked()
{
    returnOldStyle();
    ++m_currentTutorialInfoIndex;
    setTextAndStyle();
    updateButtonsEnabled();
}

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)
    {
        m_infoItems[m_currentTutorialInfoIndex].widget->setStyleSheet(m_oldStyleOfWidget);
    }
}

void TutorialDialog::setTextAndStyle()
{
    ui->textBrowser->setText(m_infoItems[m_currentTutorialInfoIndex].text);
    m_oldStyleOfWidget = m_infoItems[m_currentTutorialInfoIndex].widget->styleSheet();
    m_infoItems[m_currentTutorialInfoIndex].widget->setStyleSheet(HIGHLIGHT_STYLE);
}

MainWindow

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.

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    void onStartTutorialButtonClicked();

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

MainWindow.cpp

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

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

MainWindow::~MainWindow()
{
    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
    tutorialDialog.exec();
}

Conclusion

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

Comments

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

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

SB
Dec. 5, 2019, 8:01 a.m.
Sergej Bederin

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

  • Result:60points,
  • Rating points-1
AS
Dec. 4, 2019, 6:39 a.m.
Artur Salmin

C++ - Test 005. Structures and Classes

  • Result:33points,
  • Rating points-10
ST
Dec. 2, 2019, 4:05 p.m.
Sergej Timchenko

Qt - Test 001. Signals and slots

  • Result:68points,
  • Rating points-1
Last comments
Dec. 5, 2019, 4:15 p.m.
Evgenij Legotskoj

В этом слоте ваам нужно будет правильно смаппить координату. У QGraphicsView есть методы mapToScene, mapFromScene. Попробуйте использовать их.
LP
Dec. 5, 2019, 8:30 a.m.
Leonid Pivovarov

А без переопределения qgraphicsScene это сделать возможно? Есть же коорината нажатия кнопки мыши slotCustomMenuRequested(QPoint)
Dec. 5, 2019, 8:11 a.m.
Mihailll

//qDebug()<<"position:"<<event->pos(); //qDebug()<<"position:"<<event->screenPos(); qDebug()<<"position:"<<event->scenePos();
LP
Dec. 5, 2019, 8:09 a.m.
Leonid Pivovarov

Подскажите пожалуйста, К graphicsView я подключил обработку контекстного меню: сonnect(ui->graphicsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotCustomMenuRequest…
Dec. 4, 2019, 3:49 p.m.
Evgenij Legotskoj

resources_big - это флаг для сборки c++ приложения. Если Nuitka не предоставляет какой-либо функционал для прикручивания конфигурационных директив типа CONFIG при компиляции, то сомнева…
Now discuss on the forum
Dec. 5, 2019, 4:12 p.m.
Evgenij Legotskoj

Это уже кастомная стилизация. Придётся отключать обрамление и самостоятельно реализовывать ресайз окна, его перемещение, стиль и т.д. Вот статья, как отключить обрамление окна - QML …
Dec. 5, 2019, 4:27 a.m.
qml_puthon_user

Вот код, вдруг, кому поможет. Код основной формы: import QtQuick 2.12import QtQuick.Controls 2.12import QtQuick.Layouts 1.3import "./Components/Panels" as PanelsApplicationWindow{…
Dec. 5, 2019, 2:50 a.m.
Evgenij Legotskoj

Создавайте новые темы, чтобы не было всё в куче.
Dec. 4, 2019, 10:07 p.m.
qml_puthon_user

Спасибо за помощь! :) Я попытаю надежды в ожидании QtQuick3D от Riverbank'a. :)
V
Dec. 4, 2019, 7:02 a.m.
Vitali

Со временем распаковки соласен - для слабых ноутов это проблема и именно Nuitka мог бы здесь помочь, если бы заработало. А QtlFW - это уже фреймфорк для создания инсталятора из имеющихся па…
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB