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
Project current state
https://github.com/rust3128/iMpos