diff --git a/widget.cpp b/widget.cpp index 47dfbfd..bc034ab 100644 --- a/widget.cpp +++ b/widget.cpp @@ -31,17 +31,21 @@ void Widget::init(const QSqlDatabase &db) 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); - } - } + updateCount(); show(); } +void Widget::updateCount() +{ + if (!_db.isOpen()) { + return; + } + QSqlQuery query(_db); + if (query.exec("SELECT COUNT(*) FROM random_data") && query.next()) { + _countId->setText(query.value(0).toString()); + } +} + void Widget::addRecord() { if (_nameEdit->displayText().isEmpty() || _textEdit->toPlainText().isEmpty()) { @@ -60,6 +64,5 @@ void Widget::addRecord() } _nameEdit->clear(); _textEdit->clear(); - ++count; - _countId->setText(QString::number(count, 10)); + updateCount(); } diff --git a/widget.h b/widget.h index 1f0eba1..1998b14 100644 --- a/widget.h +++ b/widget.h @@ -26,7 +26,7 @@ private: QLabel *_textLabel = nullptr; QTextEdit *_textEdit = nullptr; QPushButton *_addBtn = nullptr; - quint64 count = 0; + void updateCount(); public slots: void init(const QSqlDatabase &); void addRecord();