Ruslan Polupan
Ruslan PolupanJuly 20, 2019, 3:36 a.m.

IMpos project. Part 006. Connection to the central Fierbird base. Dialogue for setting up a connection to the central bank.

CB connection settings dialog

We will store the connection settings using QSettings in a text file, i.e. using QSettings::IniFormat. In the DataBases class, add the bool connectCenralDB() method in which we implement the connection.
If the connection attempt is unsuccessful, we call the connection settings dialog ConnectionSettingDialog in which it is possible to change the settings.


connectionsettingdialog.h

#ifndef CONNECTIONSETTINGDIALOG_H
#define CONNECTIONSETTINGDIALOG_H

#include <QDialog>

namespace Ui {
class ConnectionSettingDialog;
}

class ConnectionSettingDialog : public QDialog
{
    Q_OBJECT

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

private slots:
    void on_buttonBox_accepted();

    void on_buttonBox_rejected();

private:
    Ui::ConnectionSettingDialog *ui;
private:
    void readConnData();    //Чтение настроек подключения
    void saveConnData();    //Запись настроек подключения
};

#endif // CONNECTIONSETTINGDIALOG_H

connectionsettingdialog.cpp

#include "connectionsettingdialog.h"
#include "ui_connectionsettingdialog.h"
#include "LoggingCategories/loggingcategories.h"
#include "DataBases/databasesettings.h"
#include <QSettings>

ConnectionSettingDialog::ConnectionSettingDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ConnectionSettingDialog)
{
    ui->setupUi(this);
    readConnData();
    qInfo(logInfo()) << "Открытие диалога настройки подключения.";
}

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

void ConnectionSettingDialog::readConnData()
{
    QSettings settings(DataBaseSettings::CONFIG_FILE_NAME,QSettings::IniFormat);
    settings.beginGroup("DATABASE");
    ui->lineEditServer->setText(settings.value("HostName").toString());
    ui->lineEditDatabase->setText(settings.value("DataBase").toString());
    ui->lineEditUser->setText(settings.value("User").toString());
    ui->lineEditPassword->setText(settings.value("Password").toString());
    settings.endGroup();
}

void ConnectionSettingDialog::saveConnData()
{
    QSettings settings(DataBaseSettings::CONFIG_FILE_NAME,QSettings::IniFormat);
    settings.beginGroup("DATABASE");
    settings.setValue("HostName",ui->lineEditServer->text().trimmed());
    settings.setValue("DataBase",ui->lineEditDatabase->text().trimmed());
    settings.setValue("User",ui->lineEditUser->text().trimmed());
    settings.setValue("Password",ui->lineEditPassword->text().trimmed());
    settings.endGroup();
}

void ConnectionSettingDialog::on_buttonBox_accepted()
{
    saveConnData();
    this->accept();
}

void ConnectionSettingDialog::on_buttonBox_rejected()
{
    this->reject();
}

Mетод bool connectCenralDB()

bool DataBases::connectCenralDB()
{
    bool result = true;
    //Указываем имя файла настроек
    QSettings settings(DataBaseSettings::CONFIG_FILE_NAME, QSettings::IniFormat);
    //Создаем подключение по умолчанию к базе данных FireBird
    QSqlDatabase db = QSqlDatabase::addDatabase("QIBASE");

    //Установка параметров подключения из файла настроек
    settings.beginGroup("DATABASE");
    db.setHostName(settings.value("HostName").toString());
    db.setDatabaseName(settings.value("DataBase").toString());
    db.setUserName(settings.value("User").toString());
    db.setPassword(settings.value("Password").toString());
    settings.endGroup();
    //Открываем базу данных, если попытка не удачная вызываем диалог настроек подключения
    if(!db.open()) {
        qCritical(logCritical()) <<  "Не возможно подключиться к базе данных." << endl << "Причина:" << db.lastError().text();
        int rez = QMessageBox::question(nullptr, QObject::tr("Ошибка подключения"),
                              "Не могу установить соединение с базой данных.\nПроверить настройки подключения?",
                              QMessageBox::Yes | QMessageBox::No);
        if(rez == QMessageBox::Yes) {
            ConnectionSettingDialog *connDlg = new ConnectionSettingDialog();
            int result = connDlg->exec();
            if(result == QDialog::Accepted) {
                qInfo(logInfo()) << "Сохранение настроек подключения.";
            }
        }
        //Завершаем работу
        result = false;
    } else {
        qInfo(logInfo()) << "Успешное подключение к центральной базе данных.";
        result = true;
    }

    return result;

}

In main.cpp, before calling the main window, add

    if(!db->connectCenralDB()){
        qInfo(logInfo()) << "Завершение работы. Не удалось подключится к центральной базе.";
        return 1;
    }

We launch the application.
The message appears

After clicking the Yes button, the connection settings window will be displayed. We fill it.

The program is closed. A configuration file appears in the project's build directory.
iMpos.config

[DATABASE]
HostName=192.168.123.11
DataBase=sunoil
User=SYSDBA
Password=sunoil00

When you follow the start, the settings are read and connected to the central database.

Project archive:

iMposCh006.zip iMposCh006.zip

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!

IscanderChe
  • July 20, 2019, 6:26 a.m.

Такой вид диалоговых окон на десятой винде?

Ruslan Polupan
  • July 20, 2019, 6:42 a.m.

Да, такой вид.

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, 6:09 a.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, 1:05 a.m.
EVILEG-CORE. Using Google reCAPTCHA 2001; 98 29 34 priligy buy
i
innorwallNov. 14, 2024, 1 a.m.
PyQt5 - Lesson 007. Works with QML QtQuick (Signals and slots) priligy 30mg Am J Obstet Gynecol 171 1488 505
i
innorwallNov. 13, 2024, 11: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. 13, 2024, 8:03 p.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, 12:39 a.m.
добавить qlineseries в функции priligy amazon canada 93 GREB1 protein GREB1 AB011147 6
i
innorwallNov. 11, 2024, 7:55 a.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, 6:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks