-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbtablewidget.cpp
77 lines (68 loc) · 1.99 KB
/
dbtablewidget.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
#include "dbtablewidget.h"
#include "ui_dbtablewidget.h"
DBTableWidget::DBTableWidget(QString name,
QSqlDatabase& db,
QWidget *parent) :
QWidget(parent),
ui(new Ui::DBTableWidget)
{
ui->setupUi(this);
sql_table_model_ = new QSqlTableModel(parent, db);
sql_table_model_->setTable(name);
sql_table_model_->setEditStrategy(QSqlTableModel::OnManualSubmit);
sql_table_model_->select();
ui->tableView->setSortingEnabled(true);
ui->tableView->setModel(sql_table_model_);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
}
DBTableWidget::~DBTableWidget()
{
delete ui;
}
void DBTableWidget::on_insertButton_clicked()
{
QModelIndex in = ui->tableView->currentIndex();
if (!in.isValid()){
sql_table_model_->insertRow(0);
} else{
sql_table_model_->insertRow(in.row());
}
}
void DBTableWidget::on_removeButton_clicked()
{
QModelIndexList li = ui->tableView->selectionModel()->selectedIndexes();
while (!li.isEmpty()){
sql_table_model_->removeRow(li.takeFirst().row());
}
}
void DBTableWidget::on_submitButton_clicked()
{
if (!sql_table_model_->submitAll()){
qDebug() << sql_table_model_->lastError();
}
}
void DBTableWidget::on_cancelButton_clicked()
{
sql_table_model_->revertAll();
}
void DBTableWidget::on_dupButton_clicked()
{
QModelIndexList li = ui->tableView->selectionModel()->selectedIndexes();
// get sorted row numbers
QList<int> rows;
while (!li.isEmpty()){
QModelIndex in = li.takeFirst();
if (!rows.contains(in.row())){
rows.append(in.row());
}
}
qSort(rows.begin(),rows.end());
// do duplicate
int c = 0; // only works when rows is sorted ascending.
while (!rows.isEmpty()){
int r = rows.takeFirst();
QSqlRecord rec = sql_table_model_->record(r + c);
sql_table_model_->insertRecord(r + c, rec);
++c;
}
}