Evgenii Legotckoi
Dec. 2, 2019, 1:22 a.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:


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.

  1. #ifndef TUTORIALDIALOG_H
  2. #define TUTORIALDIALOG_H
  3.  
  4. #include <QDialog>
  5.  
  6. namespace Ui {
  7. class TutorialDialog;
  8. }
  9.  
  10. class TutorialDialog : public QDialog
  11. {
  12. Q_OBJECT
  13.  
  14. public:
  15. explicit TutorialDialog(QWidget *parent = nullptr);
  16. ~TutorialDialog();
  17.  
  18. // add widget and text information about this widget to tutorial dialog
  19. void addWidgetToTutorial(QWidget* widget, const QString& text);
  20.  
  21. private:
  22. void onPreviousButtonClicked(); // slot which reacts on click of previous button
  23. void onNextButtonClicked(); // slot which reacts on click of next button
  24. void updateButtonsEnabled(); // update actual enabled status of buttons
  25. void returnOldStyle(); // return old style to widget, which was highlighted
  26. void setTextAndStyle(); // set text information to tutorial dialog and set highlight style to widget
  27.  
  28. Ui::TutorialDialog *ui;
  29.  
  30. // This structure contains text information aboout some widget
  31. struct TutorialInfo
  32. {
  33. QWidget* widget;
  34. QString text;
  35. };
  36.  
  37. // highlight style
  38. const QString HIGHLIGHT_STYLE {"border: 1px solid red"};
  39. QVector<TutorialInfo> m_infoItems; // vector of widgets in tutorial
  40. int m_currentTutorialInfoIndex {-1}; // index of current highlighted widget
  41. QString m_oldStyleOfWidget; // old widget style
  42. };
  43.  
  44. #endif // TUTORIALDIALOG_H
  45.  

TutorialDialog.cpp

  1. #include "TutorialDialog.h"
  2. #include "ui_TutorialDialog.h"
  3.  
  4. #include <QDebug>
  5.  
  6. TutorialDialog::TutorialDialog(QWidget *parent) :
  7. QDialog(parent),
  8. ui(new Ui::TutorialDialog)
  9. {
  10. ui->setupUi(this);
  11. setModal(true); // this dialog should be modal
  12. setWindowFlags(Qt::Window); // but it doesn`t create shadow on mainwindow
  13.  
  14. connect(ui->closeButton, &QPushButton::clicked, this, &TutorialDialog::close);
  15. connect(ui->previousButton, &QPushButton::clicked, this, &TutorialDialog::onPreviousButtonClicked);
  16. connect(ui->nextButton, &QPushButton::clicked, this, &TutorialDialog::onNextButtonClicked);
  17.  
  18. updateButtonsEnabled();
  19. }
  20.  
  21. TutorialDialog::~TutorialDialog()
  22. {
  23. // When dialog was destrcucted, we should set up old style to current widget
  24. returnOldStyle();
  25. delete ui;
  26. }
  27.  
  28. void TutorialDialog::addWidgetToTutorial(QWidget* widget, const QString& text)
  29. {
  30. if (m_infoItems.empty())
  31. {
  32. m_currentTutorialInfoIndex = 0;
  33. }
  34.  
  35. m_infoItems.push_back({widget, text});
  36. updateButtonsEnabled();
  37.  
  38. if (m_infoItems.size() == 1)
  39. {
  40. setTextAndStyle();
  41. }
  42. }
  43.  
  44. void TutorialDialog::onPreviousButtonClicked()
  45. {
  46. returnOldStyle();
  47. --m_currentTutorialInfoIndex;
  48. setTextAndStyle();
  49. updateButtonsEnabled();
  50. }
  51.  
  52. void TutorialDialog::onNextButtonClicked()
  53. {
  54. returnOldStyle();
  55. ++m_currentTutorialInfoIndex;
  56. setTextAndStyle();
  57. updateButtonsEnabled();
  58. }
  59.  
  60. void TutorialDialog::updateButtonsEnabled()
  61. {
  62. ui->previousButton->setEnabled(m_currentTutorialInfoIndex != -1 && m_currentTutorialInfoIndex > 0);
  63. ui->nextButton->setEnabled(m_currentTutorialInfoIndex != -1 && m_currentTutorialInfoIndex < m_infoItems.size() - 1);
  64. }
  65.  
  66. void TutorialDialog::returnOldStyle()
  67. {
  68. if (m_currentTutorialInfoIndex != -1)
  69. {
  70. m_infoItems[m_currentTutorialInfoIndex].widget->setStyleSheet(m_oldStyleOfWidget);
  71. }
  72. }
  73.  
  74. void TutorialDialog::setTextAndStyle()
  75. {
  76. ui->textBrowser->setText(m_infoItems[m_currentTutorialInfoIndex].text);
  77. m_oldStyleOfWidget = m_infoItems[m_currentTutorialInfoIndex].widget->styleSheet();
  78. m_infoItems[m_currentTutorialInfoIndex].widget->setStyleSheet(HIGHLIGHT_STYLE);
  79. }
  80.  

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

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5.  
  6. QT_BEGIN_NAMESPACE
  7. namespace Ui { class MainWindow; }
  8. QT_END_NAMESPACE
  9.  
  10. class MainWindow : public QMainWindow
  11. {
  12. Q_OBJECT
  13.  
  14. public:
  15. MainWindow(QWidget *parent = nullptr);
  16. ~MainWindow();
  17.  
  18. private:
  19. void onStartTutorialButtonClicked();
  20.  
  21. Ui::MainWindow *ui;
  22. };
  23. #endif // MAINWINDOW_H
  24.  

MainWindow.cpp

  1. #include "MainWindow.h"
  2. #include "ui_MainWindow.h"
  3. #include "TutorialDialog.h"
  4. #include "TutorialDialog.h"
  5.  
  6. MainWindow::MainWindow(QWidget *parent)
  7. : QMainWindow(parent)
  8. , ui(new Ui::MainWindow)
  9. {
  10. ui->setupUi(this);
  11. connect(ui->startTutorialButton, &QPushButton::clicked, this, &MainWindow::onStartTutorialButtonClicked);
  12. }
  13.  
  14. MainWindow::~MainWindow()
  15. {
  16. delete ui;
  17. }
  18.  
  19. void MainWindow::onStartTutorialButtonClicked()
  20. {
  21. TutorialDialog tutorialDialog; // Create tutorial dialog
  22.  
  23. // Add widgets to tutorial dialog
  24. tutorialDialog.addWidgetToTutorial(ui->projectStructureTreeView, tr("This is project structure"));
  25. tutorialDialog.addWidgetToTutorial(ui->createProjectButton, tr("Create new project using this button"));
  26. tutorialDialog.addWidgetToTutorial(ui->openProjectButton, tr("Open your project using this button"));
  27. tutorialDialog.addWidgetToTutorial(ui->infoWidget, tr("Here You will see some information about objects in your project"));
  28.  
  29. // Start tutorial dialog
  30. tutorialDialog.exec();
  31. }
  32.  

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.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup