/
mainwindow.cpp
503 lines (415 loc) · 17.7 KB
/
mainwindow.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "modifydialog.h"
#include "querygenerator.h"
#include "labeledtext.h"
#include "previewpopup.h"
#include "mysqltablemodel.h"
#include "editdatabasedialog.h"
#include <QWidget>
#include <QSqlDatabase>
#include <QSqlTableModel>
#include <QSqlQuery>
#include <QTableView>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QFrame>
#include <QTextEdit>
#include <QPushButton>
#include <QMessageBox>
#include <QDir>
#include <QSqlRecord>
#include <QStringList>
#include <QMessageBox>
#include <QScrollArea>
#include <QRect>
#include <QDesktopWidget>
#include <QCursor>
#include <QPoint>
#include <QtDebug>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QFileDialog>
#include <QDataWidgetMapper>
#include <QSqlError>
#include <displaywidget.h>
#include <mysqltablemodel.h>
#include "myfield.h"
#include <QFontDatabase>
#include <QFont>
#include "printsetup.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug()<<"Begin Program\n";
QFontDatabase fontDB;
fontDB.addApplicationFont(":/Fonts/CMR_Regular.ttf");
fontDB.addApplicationFont(":/Fonts/CMR_Bold.ttf");
fontDB.addApplicationFont(":/Fonts/CMR_Italic.ttf");
fontDB.addApplicationFont(":/Fonts/CMR_BoldItalic.ttf");
QFont CMRFont = QFont("Computer Modern Roman");
QApplication::setFont(CMRFont);
//Create the central widget where the other frames will be inserted
QWidget *wdgMain = new QWidget(this);
qDebug()<<"Widget Initaited";
setCentralWidget(wdgMain);
//Create the outermost Layout to divide between the table, the preview and the buttons
//QGridLayout *mainLayout = new QGridLayout;
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->setSpacing(10);
mainLayout->setContentsMargins(15,5,15,10);
//The frame for the buttons is created and the ADD Record REMOVE Record and MODIFY Button are added in a QHBOX
QFrame *frmButtons = new QFrame();
frmButtons->setFrameStyle(QFrame::Box | QFrame::Raised);
frmButtons->setLineWidth(1);
//QPushButton *btnAddRecord = new QPushButton("AddRecord",frmButtons);
btnAddRecord->setEnabled(false);
//QPushButton *btnRemoveRecord = new QPushButton("Remove Record",frmButtons);
btnRemoveRecord->setEnabled(false);
//QPushButton *btnModifyRecord = new QPushButton("Modify Record",frmButtons);
btnModifyRecord->setEnabled(false);
//QPushButton *btnPrint = new QPushButton("Export",frmButtons);
btnPrint->setEnabled(false);
QHBoxLayout *btnLayout = new QHBoxLayout;
btnLayout->addWidget(btnAddRecord);
btnLayout->addWidget(btnRemoveRecord);
btnLayout->addWidget(btnModifyRecord);
btnLayout->addWidget(btnPrint);
frmButtons->setLayout(btnLayout);
//The frame for the preview is created
frmPreview->setLayout(prwLayout);
//The Table viewer is created without grid and is added to the main layout
dbTableView=new QTableView(this);
dbTableView->setShowGrid(false);
dbTableView->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding);
//mainLayout->addWidget(dbTableView,0,0,5,4);
//The left frame is created and the table and button frames are added
QVBoxLayout *lftLayout = new QVBoxLayout;
lftLayout->addWidget(dbTableView);
lftLayout->addWidget(frmButtons);
//The main layout is created by adding the left layout and the preview widget
mainLayout->addLayout(lftLayout);
mainLayout->addWidget(scrPreview);
//A value is given to the database and a connetion is made using the custom CreatConnection
//dbName="/Users/Castro/Documents/Svago/Programmazione/Qt/database/movies.sqlite";
//CreateConnection(dbName); //Go to method, return bool
//QSqlQuery querytest (q.createUpdate("Main_table",Update,Where),db);
//Ther preview frame is populated with the labeled text
//preview field is enabeled in order to navigate throught he preview fields array
//The scroll area is set to a fixed width wich allowes to view the whole contents without scrolling to the side
frmPreview->setMinimumWidth(prwLayout->sizeHint().width());
scrPreview->setWidget(frmPreview);
scrPreview->setFixedWidth(frmPreview->width()+20);
wdgMain->setLayout(mainLayout);
wdgMain->show();
createActions();
createMenu();
//The table view signal "current changed" is connected to the slot which changes the selected record
//connect(dbTableView->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)),
//SLOT(currentSelectionChanged(const QModelIndex &)));
connect(dbTableView,SIGNAL(doubleClicked(QModelIndex)),SLOT(recordDoubleClicked(const QModelIndex)));
connect(dbmodel, SIGNAL(modelReset()), this, SLOT(modelHasReset()));
connect(dbmodel, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)), this, SLOT(dataChangeEmitted()));
//connect(dbmodel,SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(rowsInsertedEmitted(QModelIndex,int,int)));
connect(btnAddRecord,SIGNAL(clicked()),SLOT(createNewRecord()));
connect(btnRemoveRecord,SIGNAL(clicked()),SLOT(deleteRecord()));
connect(btnModifyRecord,SIGNAL(clicked()),SLOT(updateRecord()));
connect(btnPrint,SIGNAL(clicked()),this,SLOT(printRecord()));
QDesktopWidget dw;
QRect dwRect = dw.availableGeometry(this);
//dw.availablegeometry(this);
resize(dwRect.size()*0.7);
//QRect mwRect = this->geometry();
move(0.15*dwRect.width(),0.15*dwRect.height());
}
void MainWindow::createActions(){
newAct = new QAction(QIcon(":/newDB_icon.png"), tr("&New Database"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new database"));
connect(newAct, &QAction::triggered, this, &MainWindow::newDB);
openAct = new QAction(QIcon(":/openDB_icon.png"),
tr("&Open Database"), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an exising database"));
connect(openAct, &QAction::triggered, this, &MainWindow::openDB);
exportAct = new QAction(QIcon(":/DB2PDF_icon.png"),tr("&Export Records"), this);
exportAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_E));
exportAct->setStatusTip(tr("Export records as PDF"));
connect(exportAct, &QAction::triggered, this, &MainWindow::printRecord);
editDBAct = new QAction(QIcon(":/editDB_icon.png"),tr("&Edit Database"), this);
//editDBAct->setShortcuts(QKeySequence::New);
editDBAct->setStatusTip(tr("Edit database field"));
connect(editDBAct, &QAction::triggered, this, &MainWindow::editDB);
addRowAct = new QAction(QIcon(":/addRow_icon.png"),tr("&Insert new record"), this);
//editDBAct->setShortcuts(QKeySequence::New);
addRowAct->setStatusTip(tr("Insert a new record in the database"));
connect(addRowAct, &QAction::triggered, this, &MainWindow::createNewRecord);
removeRowAct = new QAction(QIcon(":/removeRow_icon.png"),tr("&Remove selected record"), this);
//editDBAct->setShortcuts(QKeySequence::New);
removeRowAct->setStatusTip(tr("remove selected record(s) from the database"));
connect(removeRowAct, &QAction::triggered, this, &MainWindow::deleteRecord);
nextAct = new QAction(QIcon(":/next_icon.png"),tr("&Go to next record"), this);
//editDBAct->setShortcuts(QKeySequence::New);
nextAct->setStatusTip(tr("Move to the following record"));
connect(nextAct, &QAction::triggered, this, &MainWindow::nextRecord);
previousAct = new QAction(QIcon(":/previous_icon.png"),tr("&Go to previous record"), this);
//editDBAct->setShortcuts(QKeySequence::New);
previousAct->setStatusTip(tr("Move to the previous record"));
connect(previousAct, &QAction::triggered, this, &MainWindow::previousRecord);
}
void MainWindow::createMenu(){
fileMenu = menuBar()->addMenu(tr("&File"));
addToolBar(Qt::TopToolBarArea, toolBar);
toolBar->setIconSize(QSize(26,26));
fileMenu->addAction(newAct);
fileMenu->addAction(openAct);
fileMenu->addAction(exportAct);
exportAct->setEnabled(false);
editMenu = menuBar()->addMenu(tr("&Edit"));
editMenu->addAction(editDBAct);
editMenu->addAction(addRowAct);
editMenu->addAction(removeRowAct);
editDBAct->setEnabled(false);
addRowAct->setEnabled(false);
removeRowAct->setEnabled(false);
toolBar->addAction(newAct);
toolBar->addAction(openAct);
toolBar->addAction(exportAct);
toolBar->addAction(addRowAct);
toolBar->addAction(removeRowAct);
toolBar->addAction(previousAct);
toolBar->addAction(nextAct);
previousAct->setEnabled(false);
nextAct->setEnabled(false);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::printRecord(){
QVector<QSqlRecord> printRecords;
QModelIndexList selRows = dbTableView->selectionModel()->selectedRows();
for (int i =0; i<selRows.count();i++){
printRecords.append(dbmodel->record(selRows[i].row()));
}
PrintSetup *printWidget=new PrintSetup(dbmodel->getFields(),printRecords);
QWidget *compWidget= new QWidget();
QHBoxLayout *test =new QHBoxLayout();
compWidget->setLayout(test);
test->addWidget(printWidget);
compWidget->show();
}
bool MainWindow::CreateConnection(QString dbDir){
//The sql database is created, and defined as SQLite
qDebug()<<"Connection initiated";
db=QSqlDatabase::addDatabase("QSQLITE");
//db.setDatabaseName(QString("%1/%1").arg(dbDir));
QFileInfo *dbFile = new QFileInfo(dbDir);
QDir::setCurrent(dbFile->absolutePath());
qDebug()<<"Set current directory to: "<<dbFile->absolutePath();
db.setDatabaseName(dbFile->fileName());
qDebug()<<db.databaseName();
if (!db.open()){
qDebug()<<"No Connection made to file";
return false;
}
qDebug()<<"DB Created";
dbmodel= new MySqlTableModel(this,db);
//dbmodel->setEditStrategy(QSqlTableModel::OnManualSubmit);
dbmodel->select();
//The main table is loaded. It contains all the main data.
//The table view is prepared by setting the model and other options
dbTableView->setModel(dbmodel);
dbTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
//dbTableView->resizeColumnsToContents();
//The fields array is iterated and each data column in the model is named, while the ones which should not
//be previewd in the table are hidden.
mapper->setModel(dbmodel);
for(int n=0;n<dbmodel->getFields().size();n++){
//dbmodel->setHeaderData(n,Qt::Horizontal,Fields[n][0]);
if(!dbmodel->getField(n).getVisTable()){
dbTableView->hideColumn(n);
}
//Each field is checked to see whether it should appear in the preview frame.
if (dbmodel->getField(n).getVisPreview()){
prwItems.push_back(new DisplayWidget(dbmodel->getField(n),false, frmPreview));
mapper->addMapping(prwItems.last(),n,"Value");
}
}
connect(dbTableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), mapper, SLOT(setCurrentModelIndex(QModelIndex)));
dbTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
//Sets alternating Colors
dbTableView->setAlternatingRowColors(true);
dbTableView->setStyleSheet("alternate-background-color:#99DDFF;background-color:white;");
//sets no triggers to edit the information
dbTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
//qDebug()<<"EDIT StRATEGY "<<dbmodel->editStrategy();
return true;
}
//void MainWindow::currentSelectionChanged(const QModelIndex &index){
//}
void MainWindow::recordDoubleClicked(const QModelIndex index){
updateRecord();
}
QVector<QVector<QString> > MainWindow::getPrimary(){
return Primary_keys;
}
//QVector<QVector<QString> > MainWindow::getFields(){
QVector<MyField> MainWindow::getFields(){
return Fields;
}
void MainWindow::createNewRecord(){
//This slot is linked to the AddRecord QPushButton signal
//The ModfyDialog is created, passing in the parent and the name of the fields
qDebug()<<"Main Window called to create a new record";
qDebug()<<"Currently there are "<<dbmodel->rowCount()<<" rows in the table";
dbmodel->insertRow(dbmodel->rowCount());
qDebug()<<"There are now "<<dbmodel->rowCount()<<" rows in the table";
//dbmodel->insertRow(dbmodel->rowCount(),1,QModelIndex());
qDebug()<<"Setting the mappers index to: "<<dbmodel->rowCount()-1;
ModifyDialog modDialog(this,dbmodel,dbmodel->rowCount()-1);
//If the query is accepted
modDialog.exec();
}
bool MainWindow::deleteRecord(){
qDebug()<<"deleting Record in position: "<<dbTableView->currentIndex().row();
int row = dbTableView->currentIndex().row();
QMessageBox msgBox;
msgBox.setText("Are you sure you want to delete the record?");
//msgBox.setInformativeText("Do you want to save your changes?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No );
msgBox.setDefaultButton(QMessageBox::No);
if (msgBox.exec()==QMessageBox::Yes){
qDebug()<<"Decided to remove record";
dbmodel->removeRows(row,1);
return dbmodel->submit();
}
return false;
}
bool MainWindow::updateRecord(){
//This slot is linked to the AddRecord QPushButton signal
ModifyDialog modDialog(this,dbmodel,dbTableView->currentIndex().row());
modDialog.exec();
return true;
}
bool MainWindow::newDB(){
QFileDialog fileDiag(this, "Open Database");
fileDiag.setFileMode(QFileDialog::AnyFile);
fileDiag.setDefaultSuffix("sqlite");
fileDiag.setDirectory(QStandardPaths::displayName(QStandardPaths::DocumentsLocation));
if (!fileDiag.exec()){
return false;
}
QString fileName = fileDiag.selectedFiles().first();
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//not dbConnection
db.setDatabaseName(fileName);
db.open();
QSqlQuery query;
query.exec("CREATE TABLE \"Fields_table\" (\"Name\" VARCHAR(20) PRIMARY KEY,"
" \"Table\" VARCHAR(20), \"Type\" INT, \"Vis_Preview\" BOOLEAN,"
"\"Vis_Table\" BOOLEAN, \"Position\" INT, \"Primary\" BOOLEAN,"
"\"Comments\" TEXT) ");
QList<FieldEdit*> changes = EditDatabaseDialog::editDatabase(QVector<MyField>(), this);
QVector<MyField> fields;
QVector<MyField> primaryFields;
QStringList extTable;
foreach(FieldEdit *currEdit, changes){
fields.append(currEdit->getField());
if (currEdit->getField().getPrimary())
primaryFields.append(currEdit->getField());
if (currEdit->getField().extTable())
extTable.append(currEdit->getField().getName());
}
return true;
}
bool MainWindow::openDB(){
QFileDialog fileDiag(this, "Open Database");
fileDiag.setFileMode(QFileDialog::ExistingFile);
fileDiag.setNameFilter("Database (*.db *.sql *.sqlite)");
fileDiag.setDirectory(QStandardPaths::displayName(QStandardPaths::DocumentsLocation));
if (!fileDiag.exec()){
return false;
}
QString fileName = fileDiag.selectedFiles().first();
foreach(QWidget* currItem, prwItems){
prwLayout->removeWidget(currItem);
currItem->setParent(NULL);
delete currItem;
}
delete dbmodel;
//dbTableView->setModel();
prwItems.clear();
dbName=fileName;
CreateConnection(dbName); //Go to method, return bool
//for (int i=0;i<prwItems.size();i++){
foreach(QWidget* currItem, prwItems){
//If the field has to be previewed in the preview frame then the field name label is added
//prwLayout->addWidget(prwItems[i]);
//prwItems[i]->show();
prwLayout->addWidget(currItem);
currItem->show();
}
prwLayout->update();
frmPreview->update();
frmPreview->adjustSize();
scrPreview->setFixedWidth(frmPreview->width()+20);
btnAddRecord->setEnabled(true);
btnRemoveRecord->setEnabled(true);
btnModifyRecord->setEnabled(true);
btnPrint->setEnabled(true);
editDBAct->setEnabled(true);
exportAct->setEnabled(true);
addRowAct->setEnabled(true);
removeRowAct->setEnabled(true);
//previewsAct->setEnabled(true);
nextAct->setEnabled(true);
dbTableView->selectRow(0);
qDebug()<<"The layout has: "<<prwLayout->count()<<" Widgets";
}
bool MainWindow::editDB(){
//EditDatabaseDialog *editDBDiag = new EditDatabaseDialog(dbmodel->getFields());
QVector<MyField> avlbFields = dbmodel->getFields();
QList<FieldEdit*> changes = EditDatabaseDialog::editDatabase(avlbFields, this);
qDebug()<<"Got to here with "<<changes.count()<<" changes";
dbmodel->disconnect();
qDebug()<<"Copy database: ";
qDebug()<<QFile::copy(dbName,"db_bckup.sqlite");
CreateConnection(dbName);
bool success = dbmodel->editTableStructure(changes);
if(!success){
qDebug()<<"The edit was not successfull:\n "<<dbmodel->lastError();
dbmodel->disconnect();
qDebug()<<"Delete damaged database:"<<QFile::remove(dbName);
qDebug()<<"Rename backup"<<QFile::rename("db_bckup.sqlite",dbName);
CreateConnection(dbName);
return false;
}
//editDBDiag->show();
bool rewrite = false;
/*foreach(FieldEdit *change, changes){
qDebug()<<change->getField().getName()<<" majorChange: "<<change->mainEdit();
if (change->mainEdit()){
rewrite = true;
break;
}
}
if (rewrite){
QStringList changeCommands = QueryGenerator::multipleChanges("Main_table",changes);
}*/
QFile::remove("db_bckup.sqlite");
dbmodel->disconnect();
CreateConnection(dbName);
return true;
}
#ifndef QT_NO_CONTEXTMENU
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu(this);
menu.exec(event->globalPos());
}
#endif // QT_NO_CONTEXTMENU