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
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
i
innorwallNov. 14, 2024, 8:09 p.m.
Qt/C++ - Tutorial 068. Hello World using the CMAKE build system in CLion ditropan pristiq dosing With the Yankees leading, 4 3, Rivera jogged in from the bullpen to a standing ovation as he prepared for his final appearance in Chicago buy priligy pakistan
i
innorwallNov. 14, 2024, 3:05 p.m.
EVILEG-CORE. Using Google reCAPTCHA 2001; 98 29 34 priligy buy
i
innorwallNov. 14, 2024, 3 p.m.
PyQt5 - Lesson 007. Works with QML QtQuick (Signals and slots) priligy 30mg Am J Obstet Gynecol 171 1488 505
i
innorwallNov. 14, 2024, 1:54 p.m.
Django - Tutorial 003. Model, Template, View on Django Hair follicles are believed to produce approximately 20 individual hair shafts over the life of the follicle as the follicle progresses through cycles of hair production, shedding ejection, invo…
i
innorwallNov. 14, 2024, 10:03 a.m.
How to make game using Qt - Lesson 3. Interaction with other objects what is priligy tablets What happens during the LASIK surgery process
Now discuss on the forum
i
innorwallNov. 14, 2024, 2:39 p.m.
добавить qlineseries в функции priligy amazon canada 93 GREB1 protein GREB1 AB011147 6
i
innorwallNov. 11, 2024, 9:55 p.m.
Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
9
9AnonimOct. 25, 2024, 7:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks