Evgenii Legotckoi
Aug. 13, 2015, 11:29 p.m.

Qt/C++ - Lesson 003. QSettings - How to save application settings?

Saving application settings - this is one of the first things that beginners learn when working with the Qt framework. For this purpose QSettings class that allows you to save the settings or operating system registry or a text file. In this tutorial you will use the easiest option - it is saving the settings in the operating system registry. In order to ensure the visibility of the store the settings in this tutorial use the draft of the lesson QSystemTrayIcon .

Project structure

The project is created as an application Qt Widgets, where files are created by default:

  • Settings.pro
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - source window;
  • main.cpp - the main source file from which the application starts;
  • mainwindow.ui - form of the main application window.

mainwindow.ui

Формочка для QSettings Program We create a mold for the test, in which two of the following objects will be used:

  • trayCheckBox - checkbox to adjust the behavior of the application;
  • saveButton - button to save the settings, perform the Application;

Settings.pro

Still in the lessons not to amend the draft profile.

  1. #-------------------------------------------------
  2. #
  3. # Project created by QtCreator 2015-08-12T09:31:45
  4. #
  5. #-------------------------------------------------
  6.  
  7. QT += core gui
  8.  
  9. greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
  10.  
  11. TARGET = Settings
  12. TEMPLATE = app
  13.  
  14.  
  15. SOURCES += main.cpp\
  16. mainwindow.cpp
  17.  
  18. HEADERS += mainwindow.h
  19.  
  20. FORMS += mainwindow.ui

main.cpp

This file is subject to change, since the start of the program is necessary to make information on the application in the operating system registry.

  1. #include "mainwindow.h"
  2. #include <QApplication>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6. /*For the adequate application of registration in the operating room
  7. * Necessary to establish the organization name, domain, organization,
  8. * As well as the name of the application.
  9. * All settings are stored in the operating system under these
  10. * Accounting application data
  11. * */
  12. QCoreApplication::setOrganizationName(ORGANIZATION_NAME);
  13. QCoreApplication::setOrganizationDomain(ORGANIZATION_DOMAIN);
  14. QCoreApplication::setApplicationName(APPLICATION_NAME);
  15.  
  16. QApplication a(argc, argv);
  17. MainWindow w;
  18. w.show();
  19.  
  20. return a.exec();
  21. }

mainwindow.h

In addition to the methods and objects used in the lesson on QSystemTrayIcon in this file you must add slot to handle pressing, which will be saving settings.

Also, you need to connect to the project header files of the following classes:

  • QSettings;
  • QMessageBox;

And prescribe directives define, to be used when working with QSettings.

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QCloseEvent>
  6. #include <QSystemTrayIcon>
  7. #include <QAction>
  8. #include <QSettings>
  9. #include <QMessageBox>
  10.  
  11. /* Defining */
  12. #define ORGANIZATION_NAME "EVILEG"
  13. #define ORGANIZATION_DOMAIN "www.evileg.ru"
  14. #define APPLICATION_NAME "QSettings Program"
  15.  
  16. #define SETTINGS_TRAY "settings/tray"
  17.  
  18. namespace Ui {
  19. class MainWindow;
  20. }
  21.  
  22. class MainWindow : public QMainWindow
  23. {
  24. Q_OBJECT
  25.  
  26. ////////////////// Methods of lesson QSystemTrayIcon
  27. public:
  28. explicit MainWindow(QWidget *parent = 0);
  29. ~MainWindow();
  30.  
  31. protected:
  32. void closeEvent(QCloseEvent * event);
  33. /////////////////////////////////////////////////////
  34.  
  35. private slots:
  36. void iconActivated(QSystemTrayIcon::ActivationReason reason);
  37.  
  38. /* Slot button that starts saving application settings
  39. * */
  40. void on_saveButton_clicked();
  41.  
  42. private:
  43. Ui::MainWindow * ui;
  44. QSystemTrayIcon * trayIcon;
  45. };
  46.  
  47. #endif // MAINWINDOW_H

mainwindow.cpp

In this class, made the restore application settings when initializing the appearance of the main window and save the settings by pressing the button on saveButton.

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3.  
  4. MainWindow::MainWindow(QWidget *parent) :
  5. QMainWindow(parent),
  6. ui(new Ui::MainWindow)
  7. {
  8. ui->setupUi(this);
  9. this->setWindowTitle(APPLICATION_NAME);
  10.  
  11.  
  12. /* When you create a main window to perform the installation of the initial parameters
  13. * Of the settings saved in the operating system
  14. * */
  15. QSettings settings(ORGANIZATION_NAME, APPLICATION_NAME);
  16. /* Set the state of the checkbox of the application settings for a given key.
  17. * If the key does not exist, it will be set to the default,
  18. * It is false
  19. * */
  20. ui->trayCheckBox->setChecked(settings.value(SETTINGS_TRAY, false).toBool());
  21.  
  22. /* Code from lesson to work with QSystemTrayIcon
  23. * */
  24.  
  25. /* *** */
  26. }
  27.  
  28. MainWindow::~MainWindow()
  29. {
  30. delete ui;
  31. }
  32.  
  33. /* The method of the lesson on working with QSystemTrayIcon
  34. * */
  35. void MainWindow::closeEvent(QCloseEvent * event)
  36. {
  37. /* *** */
  38. }
  39.  
  40. /* The method of the lesson on working with QSystemTrayIcon
  41. * */
  42. void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
  43. {
  44. /* *** */
  45. }
  46.  
  47. /* The method, which accepts key entry beep
  48. * Performs a save and application settings
  49. * */
  50. void MainWindow::on_saveButton_clicked()
  51. {
  52. QSettings settings(ORGANIZATION_NAME, APPLICATION_NAME);
  53. /* Storing information about vklyuchёnnosti folding function
  54. * In the tray is manufactured in accordance with the state of the checkbox.
  55. * */
  56. if(ui->trayCheckBox->isChecked()){
  57. settings.setValue(SETTINGS_TRAY, true);
  58. } else {
  59. settings.setValue(SETTINGS_TRAY, false);
  60. }
  61. settings.sync();
  62.  
  63. /* Dialog message, which indicates the success of
  64. * Save settings
  65. * */
  66. QMessageBox::information(this,
  67. trUtf8("Сохранение настроек"),
  68. trUtf8("Сохранение настроек выполнено успешно"));
  69. }

Conclusion

Upon successful writing the code of the lesson, when you click save settings button, settings will be saved in the operating system registry.

And after the restart settings are restored app. If you save settings checkbox was checked, it will also be marked by the application starts. And the app will behave according to the settings.

Do you like it? Share on social networks!

B
  • Oct. 8, 2018, 8:41 p.m.

Зачем мы добавляли pushButton, если она не используется нигде. Метод on_saveButton_clicked() аналогично нигде не используется и как сигнал не передается?

Evgenii Legotckoi
  • Oct. 9, 2018, 1:03 p.m.

Вот сразу понятно, что Вы первый день в Qt разработке ))) Ничего плохого не имею ввиду )))

on_saveButton_clicked() - это слот, созданный через Qt Designer, в каких-то статьях я уже это пояснял. Не вижу смысла в каждой статье это объяснять. Такие слоты подключаются при сборке через автоматически генерируемые ui хедеры, поэтому pushButton подключён прямо к этому слоту. Так что всё работает.


Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • 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
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html