Evgenii Legotckoi
Evgenii LegotckoiAug. 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.

#-------------------------------------------------
#
# Project created by QtCreator 2015-08-12T09:31:45
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = Settings
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

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.

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    /*For the adequate application of registration in the operating room
     * Necessary to establish the organization name, domain, organization,
     * As well as the name of the application.
     * All settings are stored in the operating system under these
     * Accounting application data
     * */
    QCoreApplication::setOrganizationName(ORGANIZATION_NAME);
    QCoreApplication::setOrganizationDomain(ORGANIZATION_DOMAIN);
    QCoreApplication::setApplicationName(APPLICATION_NAME);

    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

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.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QCloseEvent>
#include <QSystemTrayIcon>
#include <QAction>
#include <QSettings>
#include <QMessageBox>

/* Defining */
#define ORGANIZATION_NAME "EVILEG"
#define ORGANIZATION_DOMAIN "www.evileg.ru"
#define APPLICATION_NAME "QSettings Program"

#define SETTINGS_TRAY "settings/tray"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

////////////////// Methods of lesson QSystemTrayIcon
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

protected:
    void closeEvent(QCloseEvent * event);
/////////////////////////////////////////////////////

private slots:
    void iconActivated(QSystemTrayIcon::ActivationReason reason);

    /* Slot button that starts saving application settings
     * */
    void on_saveButton_clicked();

private:
    Ui::MainWindow          * ui;
    QSystemTrayIcon         * trayIcon;
};

#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.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle(APPLICATION_NAME);


    /* When you create a main window to perform the installation of the initial parameters
     * Of the settings saved in the operating system
     * */
    QSettings settings(ORGANIZATION_NAME, APPLICATION_NAME);
    /* Set the state of the checkbox of the application settings for a given key.
     * If the key does not exist, it will be set to the default,
     * It is false
     * */
    ui->trayCheckBox->setChecked(settings.value(SETTINGS_TRAY, false).toBool());

    /* Code from lesson to work with QSystemTrayIcon
     * */

    /* *** */
}

MainWindow::~MainWindow()
{
    delete ui;
}

/* The method of the lesson on working with QSystemTrayIcon
 * */
void MainWindow::closeEvent(QCloseEvent * event)
{
    /* *** */
}

/* The method of the lesson on working with QSystemTrayIcon
 * */
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
   /* *** */
}

/* The method, which accepts key entry beep
 * Performs a save and application settings
 * */
void MainWindow::on_saveButton_clicked()
{
    QSettings settings(ORGANIZATION_NAME, APPLICATION_NAME);
    /* Storing information about vklyuchёnnosti folding function
     * In the tray is manufactured in accordance with the state of the checkbox.
     * */
    if(ui->trayCheckBox->isChecked()){
        settings.setValue(SETTINGS_TRAY, true);
    } else {
        settings.setValue(SETTINGS_TRAY, false);
    }
    settings.sync();

    /* Dialog message, which indicates the success of
     * Save settings
     * */
    QMessageBox::information(this,
                             trUtf8("Сохранение настроек"),
                             trUtf8("Сохранение настроек выполнено успешно"));
}

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.

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.

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
S

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

  • Result:53points,
  • Rating points-4
S

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

  • Result:57points,
  • Rating points-2
g

C++ - Test 005. Structures and Classes

  • Result:100points,
  • Rating points10
Last comments
J
JonnyJoMay 25, 2023, 8:24 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2023, 10:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
J
JonnyJoMay 21, 2023, 4:49 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
Evgenii Legotckoi
Evgenii LegotckoiMay 21, 2023, 11:57 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
J
JonnyJoMay 20, 2023, 5:27 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, здравствуйте! Подскажите, а почему при нажатии одной клавиши переменная countForSteps увеличивается не на 1, на 4, ведь одно действие даёт увеличение этой переменной только на единицу? …
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiApril 16, 2023, 10:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
АБ
Алексей БобровDec. 15, 2021, 1:03 a.m.
Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 10:11 a.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
Evgenii Legotckoi
Evgenii LegotckoiApril 24, 2023, 9:22 a.m.
Пакеты данных между сервером и клиентами Привет. Если классы имеют что-то общее в полях, а также общую идеологию и их можно вписать в иерархию наследования, то в первую очередь переписать так, чтобы один базовый класс объединял в…

Follow us in social networks