66 lines
1.7 KiB
C++
66 lines
1.7 KiB
C++
#include "widget.h"
|
|
#include <QSqlQuery>
|
|
|
|
Widget::Widget(QWidget *parent)
|
|
: QWidget(parent)
|
|
, _grid(new QGridLayout(this))
|
|
, _countId(new QLabel("NULL"))
|
|
, _nameLabel(new QLabel("name: "))
|
|
, _nameEdit(new QLineEdit())
|
|
, _textLabel(new QLabel("text:"))
|
|
, _textEdit(new QTextEdit())
|
|
, _addBtn(new QPushButton("&ADD"))
|
|
{
|
|
_grid->addWidget(_countId, 0, 0, Qt::AlignHCenter);
|
|
_grid->addWidget(_nameLabel, 1, 0, Qt::AlignRight);
|
|
_grid->addWidget(_nameEdit, 1, 1, Qt::AlignVCenter);
|
|
_grid->addWidget(_textLabel, 2, 0, Qt::AlignRight);
|
|
_grid->addWidget(_textEdit, 2, 1, Qt::AlignHCenter);
|
|
_grid->addWidget(_addBtn, 3, 0, Qt::AlignHCenter);
|
|
setLayout(_grid);
|
|
|
|
connect(_addBtn, &QPushButton::clicked, this, &Widget::addRecord);
|
|
}
|
|
|
|
Widget::~Widget () {}
|
|
|
|
void Widget::init(const QSqlDatabase &db)
|
|
{
|
|
_db = db;
|
|
if (!_db.isOpen()) {
|
|
close();
|
|
return;
|
|
}
|
|
QSqlQuery query(_db);
|
|
if (query.exec("SELECT COUNT(*) FROM random_data")) {
|
|
auto countRecord = query.value(0).toString();
|
|
count = query.value(0).toInt();
|
|
if (!countRecord.isEmpty()) {
|
|
_countId->setText(countRecord);
|
|
}
|
|
}
|
|
show();
|
|
}
|
|
|
|
void Widget::addRecord()
|
|
{
|
|
if (_nameEdit->displayText().isEmpty() || _textEdit->toPlainText().isEmpty()) {
|
|
return;
|
|
}
|
|
if (!_db.isOpen()) {
|
|
return;
|
|
}
|
|
QSqlQuery query(_db);
|
|
query.prepare("INSERT INTO public.random_data (name, text) "
|
|
"VALUES (?, ?)");
|
|
query.addBindValue(_nameEdit->displayText());
|
|
query.addBindValue(_textEdit->toHtml());
|
|
if (!query.exec()) {
|
|
return;
|
|
}
|
|
_nameEdit->clear();
|
|
_textEdit->clear();
|
|
++count;
|
|
_countId->setText(QString::number(count, 10));
|
|
}
|