Credentials_manager/PasswordManager/mainwindow.cpp
Daniil 8e9f01a0a3 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	PasswordManager/adddialog.cpp
#	PasswordManager/mainwindow.cpp
#	PasswordManager/mainwindow.h
#	PasswordManager/mainwindow.ui
2021-12-25 08:59:30 +03:00

387 lines
13 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "manager.h"
#include <iostream>
#include <QFileDialog>
#include <QString>
#include <QDateTime>
#include <QtSql>
#include <QFileDialog>
#include<QFile>
const QString MainWindow::fileDialogFilterString = tr("SQLite Database Files (*.sqlite3 *.sqlite *.db *.db3 *.sl3 *.s3db *.sdb *.sqlite2 *.db2 *.sl2 *.s2db)");
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// this->setFixedSize(1080,760);
// manager = new Manager();
dial = new AddDialog();
del = new Del();
connect(dial,SIGNAL(sendText(Record*)),this,SLOT(addRecordSlot(Record*)));
connect(del,SIGNAL(sendText(bool)),this,SLOT(deleteRecordSlot(bool)));
createModel();
ui->tableViewRecords->setEnabled(true);
ui->tableViewRecords->setVisible(true);
crypt = new Cryptographer();
QString qs = crypt->encrypt("current");
qDebug() << qs;
QString sq = crypt->decrypt(qs);
qDebug() << sq;
}
Ui::MainWindow* MainWindow::getUI()
{
return ui;
}
void MainWindow::createModel()
{
model = new QSqlTableModel(this, m_db); // создание редактируемой модели базы данных.
model->setTable("records"); // создание модели таблицы records.
model->select(); // заполнение модели данными.
// Выбор стратегии сохранения изменений в базе данных:
model->setEditStrategy(QSqlTableModel::OnFieldChange); // сохранение происходит при переходе к другому полю.
ui->tableViewRecords->setModel(model); // соединение модели и ее табличного представления в форме.
model->setHeaderData(0, Qt::Horizontal, tr("number"));
model->setHeaderData(1, Qt::Horizontal, tr("name"));
model->setHeaderData(2, Qt::Horizontal, tr("username"));
model->setHeaderData(3, Qt::Horizontal, tr("password"));
model->setHeaderData(4, Qt::Horizontal, tr("URL"));
model->setHeaderData(5, Qt::Horizontal, tr("note"));
model->setHeaderData(6, Qt::Horizontal, tr("time"));
}
void MainWindow::initAppWithDatabaseFile(const QString &dbFileFullPath) {
qDebug() << "dbFileFullPath=" << dbFileFullPath;
if (dbFileFullPath.isEmpty()) return;
connectToDatabase(dbFileFullPath);
createModel();
// setUserInterfaceEnabled(true);
}
void MainWindow::putRecord(Record* record){
query->clear();
qDebug() << "Добавление строки:" <<
query->prepare("INSERT INTO records(id, name, username, password, url, note, time)" \
"VALUES(:id, :name, :username, :password, :url, :note, :time)");
// query->prepare("INSERT INTO employees(id, last_name, first_name, occupation, year_of_admission) " \
// "VALUES(:id, :last_name, :first_name, :occupation, :year_of_admission)");
query->bindValue(":id", getRecordsCount());
query->bindValue(":name", record->getName());
query->bindValue(":username", record->getUsername());
query->bindValue(":password", record->getPassword());
query->bindValue(":url", record->getURL());
query->bindValue(":note", record->getNote());
query->bindValue(":time", record->getTime());
query->exec();
}
Record* MainWindow::getRecord(int index)
{
query->prepare("SELECT * FROM records WHERE id = (:id)");
query->bindValue(":id", index);
query->exec();
// QSqlRecord rec = query->record();
//// query->next();
// std::cout << query->value(1).toString().toStdString();
// std::cout << rec.value(1).toString().toStdString();
// Record* r = new Record(query->value(0).toInt(), query->value(1).toString(), query->value(2).toString(), query->value(3).toString(), query->value(4).toString(), query->value(5).toString());
// qDebug() << "getRecord" ;
// qDebug() << r->toString();
// std::cout << r->toStdString();
QSqlRecord rec = query->record();
query->next();
Record *r = new Record();
r->setId(query->value(rec.indexOf("id")).toInt());
r->setName(query->value(rec.indexOf("name")).toString());
r->setUsername(query->value(rec.indexOf("username")).toString());
r->setPassword(query->value(rec.indexOf("password")).toString());
r->setURL(query->value(rec.indexOf("url")).toString());
r->setNote(query->value(rec.indexOf("note")).toString());
// qDebug() << r->getName() << " << name";
qDebug() << r->toString();
return r;
}
void MainWindow::updateRecord(Record* r)
{
query->prepare("UPDATE records SET name=:name WHERE id=:id");
query->prepare("UPDATE records SET username=:username WHERE id=:id");
query->prepare("UPDATE records SET password=:password WHERE id=:id");
query->prepare("UPDATE records SET url=:url WHERE id=:id");
query->prepare("UPDATE records SET note=:note WHERE id=:id");
query->bindValue(":id", r->getId());
query->bindValue(":name", r->getName());
query->bindValue(":username", r->getUsername());
query->bindValue(":password", r->getPassword());
query->bindValue(":url", r->getURL());
query->bindValue(":note", r->getNote());
}
void MainWindow::deleteRecord()
{
// if (ui->spinBoxID->text().isEmpty())
// return;
int num = ui->tableViewRecords->selectionModel()->selection().indexes().at(0).row();
std::string s = "";
s+=num;
QString id = QString::fromStdString(s);
// QString id = ui->spinBoxID->text();
qDebug() << "id: " << id;
query->clear();
QString z = QString("DELETE FROM records WHERE id =:id ");
QString q = QString("DELETE FROM records WHERE id = (id)" \
"VALUES(:id)");
query->prepare(z);
query->bindValue(":id", num);
qDebug() << "Удаление строки:" <<
query->exec(z);
qDebug() << z;
model->select(); // наполнить модель данными из таблицы, учитывая условия фильтрации и сортировки.
}
int MainWindow::getRecordsCount(){
query->clear();
qDebug() << "query->clear();";
query->prepare("SELECT MAX(r.id) AS 'number_of_records' FROM records AS 'r';");
query->exec();
query->next();
QString count = QString::number(query->value(0).toInt() + 1);
return count.toInt();
}
void MainWindow::connectToDatabase(const QString &dbName)
{
m_db = QSqlDatabase::addDatabase("QSQLITE"); // соединение объекта базы данных с СУБД.
//m_db.setDatabaseName(dbName); // определение имени базы данных.
m_db.setDatabaseName(dbName); // определение имени базы данных.
if (!m_db.open()) // проверка на ошибку при открытии или создании базы данных.
throw "Can't open database!";
query = new QSqlQuery(m_db); // создание объекта для запроса.
if (!m_db.tables().contains("records")) // если в базе не существует таблица records
{ // то создание таблицы records:
qDebug() << "В базе не существует таблица records!";
query->clear(); // очистка запроса.
// id
// name
// username
// URL
// Note
// Time
qDebug() << "Создание таблицы records:" <<
query->exec("CREATE TABLE records(" \
" id TEXT PRIMARY KEY NOT NULL, /* идентификатор */" \
" name TEXT, /* имя */" \
" username TEXT, /* имя пользователя */" \
" password TEXT, /* пароль */" \
" url TEXT, /* web url */" \
" note TEXT, /* примечания */" \
" time INTEGER /* дата добавления */" \
");"); // исполнение запроса на добавление записи.
}
}
// Метод показывающий диалоговое окно для выбора файла для новой базы данных:
void MainWindow::on_actionCreateNewDatabase_triggered()
{
std::cout << "clicked" << std::endl;
QString dbFileFullPath = QFileDialog::getSaveFileName(this, tr("Save SQLite Database File"), "", MainWindow::fileDialogFilterString);
initAppWithDatabaseFile(dbFileFullPath);
model->select();
}
// Метод показывающий диалоговое окно для выбора файла для открытия созданной ранее базы данных:
void MainWindow::on_actionOpenDatabase_triggered()
{
QString dbFileFullPath = QFileDialog::getOpenFileName(this, tr("Open SQLite Database File"), "", MainWindow::fileDialogFilterString);
initAppWithDatabaseFile(dbFileFullPath);
model->select();
QModelIndex index = ui->tableViewRecords->model()->index(0, 0);
ui->tableViewRecords->setCurrentIndex(index);
}
//void MainWindow::initAppWithDatabaseFile(const QString &dbFileFullPath) {
// qDebug() << "dbFileFullPath=" << dbFileFullPath;
// //qDebug() << QSqlDatabase::drivers();
// if (dbFileFullPath.isEmpty()) return;
//}
void MainWindow::on_addButton_clicked()
{
// QSizeGrip(dial.ui.hSp);
dial->show();
// Record record = dial.getRecord();
// std::cout << record.toStdString();
//Record* record = new Record("name", "username", "password", "url", "note", *time);
std::cout << "add" << std::endl;
// manager->putRecord(&record);
QModelIndex index = ui->tableViewRecords->model()->index(getRecordsCount(), 0);
ui->tableViewRecords->setCurrentIndex(index);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
genpass.show();
}
void MainWindow::on_tableView_activated(const QModelIndex &index)
{
}
void MainWindow::on_deleteButton_clicked()
{
del->show();
}
void MainWindow::on_pushButton_5_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_editButton_clicked()
{
int num;
// QItemSelectionModel *select = ui->tableViewRecords->selectionModel();
// if(select->hasSelection()){ //check if has selection
// QModelIndexList selection = select->selectedRows();
// QModelIndex index = selection.at(0);
num = ui->tableViewRecords->selectionModel()->selection().indexes().at(0).row();
qDebug() << ++num;
// }// return selected row(s)
// else
// {
// return;
// }
// num = 0;
Record* r = getRecord(num);
ui->lineEdit_name->setText(r->getName());
ui->lineEdit_username->setText(r->getUsername());
ui->lineEdit_password->setText(r->getPassword());
ui->lineEdit_url->setText(r->getURL());
ui->lineEdit_note->setText(r->getNote());
ui->stackedWidget->setCurrentIndex(2);
}
void MainWindow::on_pushButton_7_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_pushButton_9_clicked()
{
ui->stackedWidget->setCurrentIndex(3);
// qApp->setStyleSheet("QWidget{background-color: #202020;color: #fff;selection-background-color: #ff732d; selection-color: #000;}");
}
void MainWindow::on_action_7_triggered()
{
std::cout << "about" << std::endl;
about.show();
}
void MainWindow::on_pushButton_2_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_actionExit_triggered()
{
QCoreApplication::quit();
}
void MainWindow::on_action_triggered()
{
ui->stackedWidget->setCurrentIndex(1);
}
}
void MainWindow::addRecordSlot(Record *r)
{
putRecord(r);
model->select();
QModelIndex index = ui->tableViewRecords->model()->index(0, 0);
ui->tableViewRecords->setCurrentIndex(index);
}
void MainWindow::deleteRecordSlot(bool flag)
{
deleteRecord();
}
void MainWindow::on_editSaveButton_clicked()
{
Record* r = new Record();
r->setId(ui->tableViewRecords->selectionModel()->selection().indexes().at(0).row());
r->setName(ui->lineEdit_name->text());
r->setUsername(ui->lineEdit_username->text());
r->setPassword(ui->lineEdit_password->text());
r->setURL(ui->lineEdit_url->text());
r->setNote(ui->lineEdit_note->text());
updateRecord(r);
model->select();
ui->stackedWidget->setCurrentIndex(0);
QModelIndex index = ui->tableViewRecords->model()->index(r->getId(), 0);
ui->tableViewRecords->setCurrentIndex(index);
}