Ruslan Polupan
Ruslan PolupanJuly 21, 2019, 2:58 a.m.

IMpos project. Part 007. Displaying information about the connection and the current user. Menu creation. Application settings dialog.

Storing information about the current user

After opening the main window of the application, I would like the status bar to display the name of the current user and information about connecting to the central database.
I also wanted to restrict the user's rights to some actions. Those. a user with a usder_id other than 1 had access to the reduced functionality of the application.
To store the id of the current user, add option 1020. To do this, add another request to the DataBases::connectOptions() method to create an option.

listSQL << "INSERT INTO `options`(`option_id`,`value`,`comment`) VALUES (1020, '1', 'Текущий пользователь системы')";

If you change the parameter 1000 (Use authentication), then it is necessary to set the current user id to 1. I.e. if the password is not asked, then the system works with administrator rights. If the database can do this, then let it do it, so we will instruct SQLite to monitor the value of the parameter being set.
To do this, add a trigger to the database that will monitor the value of option 1000:

listSQL << "CREATE TRIGGER use_login AFTER UPDATE "
                       "ON options WHEN (SELECT value FROM options WHERE option_id =1000) = 'false' OR (SELECT value FROM options WHERE option_id =1000) = 0  "
                       "BEGIN "
                       "UPDATE options SET value = 1 WHERE option_id= 1020; "
                       "END";

If the value is set to 'false' or 0 then the user id is reset to 1.
Let's add an entry to the options table with the user id of the successfully logged in user.

void LoginDialog::on_buttonBox_accepted()
{
    if(ui->comboBoxUser->currentIndex()>=0) {
        if(userPass==ui->lineEditPass->text().trimmed()) {
            qInfo(logInfo()) << QString("Пользователь: %1. Успешный вход в систему.").arg(ui->comboBoxUser->currentText());
            //Запись в таблицу options ID пользователя
            Options opt;
            opt.setOption(1020,QString::number(userID));
            this->accept();
        } else {
            ui->labelInfo->setText("Не верный пароль!");
            qWarning(logInfo()) << QString("Пользователь: %1. Не верный пароль!.").arg(ui->comboBoxUser->currentText());
            ui->lineEditPass->clear();
        }
    }
}

Display connection and current user information

Information about the current user and connection to the database will be displayed in the status bar of the main window.
The void createUI() method will perform the initial setup of the appearance of the main window, we call it in the MainWindow constructor.

void MainWindow::createUI()
{
    //Создаем два QLabels которые поместим в StatusBar
    QLabel *labelUsers = new QLabel();
    QLabel *labelConnections = new QLabel();
    //Получаем данные о текущем пользователе
    QSqlDatabase db = QSqlDatabase::database("options");
    QSqlQuery q = QSqlQuery(db);
    q.exec("SELECT u.fio FROM users u "
           "INNER JOIN options o ON u.user_id = o.value "
           "WHERE o.option_id = 1020");
    q.next();
    labelUsers->setText("Пользователь: "+q.value(0).toString());
    //Получаем данные о текущем подключении
    QSqlDatabase dbcentr = QSqlDatabase::database();
    labelConnections->setText("База данных:"+dbcentr.hostName()+":"+dbcentr.databaseName());
    //Добавляем виджеты в строку состояния
    //Нормальное сообщение
    ui->statusBar->addWidget(labelUsers);
    //Постоянное сообщение
    ui->statusBar->addPermanentWidget(labelConnections);
}

Menu creation

Open the mainwindow.ui form.
In place Write here we write the name of the top-level menu: Tools


Below is the name of the menu item: Options...
The menu and action objects will be added to the list of objects, and the action editor will be displayed at the bottom.


Let's give the objects meaningful names. After that, double-click in the action editor and the action settings window will open.
In it, we set the icon for the menu previously added to the resources and the hot key.

After that, drag the action to the toolbar of the main window.

Right click on the action, select go to slot. We are interested in the triggered() slot. We get a slot that is already associated with selecting a menu item or pressing a button on the toolbar.

void MainWindow::on_actionSettings_triggered()
{

}

Settings dialog

Create a new form class Qt Designer SettingsDialog. In the resource editor, we add the necessary controls, give them meaningful names, and perform the layout.

In MainWindow::on_actionSettings_triggered() we will call the dialog after including the header file of the dialog class.

void MainWindow::on_actionSettings_triggered()
{
    //Создаем объект диалога
    SettingsDialog *settingsDlg = new SettingsDialog();
    //позиционируем диалог по центру главного окна
    settingsDlg->move(this->geometry().center().x() - settingsDlg->geometry().center().x(),
                      this->geometry().center().y() - settingsDlg->geometry().center().y());
    //Отображаем диалог
    settingsDlg->exec();
}

We check.

Implementation of the settings dialog:
settingsdialog.h

#ifndef SETTINGSDIALOG_H
#define SETTINGSDIALOG_H

#include "DataBases/options.h"
#include <QDialog>

namespace Ui {
class SettingsDialog;
}

class SettingsDialog : public QDialog
{
    Q_OBJECT

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

private slots:
    void on_buttonBox_accepted();

private:
    Ui::SettingsDialog *ui;
    Options opt;                        //чтение запись таблицы options
private:
    void createUI();                    //Настройка первоначального интерфейса
};

#endif // SETTINGSDIALOG_H

settingsdialog.cpp

#include "settingsdialog.h"
#include "ui_settingsdialog.h"


SettingsDialog::SettingsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);
    createUI();
}

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

void SettingsDialog::createUI()
{
    //Устанавливаем сотояния в зависимости от значений в таблице
    ui->checkBoxLogin->setChecked(opt.getOption(1000).toBool());
    ui->checkBoxRegions->setChecked(opt.getOption(1010).toBool());
}


void SettingsDialog::on_buttonBox_accepted()
{
    //Записываем в таблицу состояние
    opt.setOption(1000,QVariant(ui->checkBoxLogin->isChecked()).toString());
    opt.setOption(1010,QVariant(ui->checkBoxRegions->isChecked()).toString());
}

Project file:
iMposCh007.zip iMposCh007.zip
Project current state https://github.com/rust3128/iMpos

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!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 9:29 p.m.

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

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

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

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 7:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks