Why Application terminates when choosing a row from the QTableView
-
My application closes when I select a row from the QTableView, which I load, from a PostgreSQL DB.
When selecting a row, other data should be shown in the controls below, from another table, I leave the code:#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QSqlDatabase> #include <QSqlError> #include <QSqlQueryModel> #include <QSqlQuery> QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACE class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = nullptr); ~Widget(); void data(int id); bool getConection(); void dataMonitoreo(int id); private slots: void on_tableView_clicked(const QModelIndex &index); private: Ui::Widget *ui; QSqlDatabase db; QSqlQueryModel *model; }; #endif // WIDGET_H#include "widget.h" #include "ui_widget.h" #include <QDebug> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); data(25); } Widget::~Widget() { delete ui; } bool Widget::getConection() { db=QSqlDatabase::addDatabase("QPSQL"); if(!db.isDriverAvailable("QPSQL")){ qDebug()<<db.lastError().text(); return false; } db.setDatabaseName("monitoreo_db"); db.setHostName("localhost"); db.setPassword("2311046"); db.setPort(5432); db.setUserName("postgres"); if(!db.open()){ qDebug()<<"Failed to open database.\n"<<db.lastError().databaseText(); return false; } return true; } void Widget::dataMonitoreo(int id) { getConection(); QSqlQuery qry; qry.prepare("SELECT codigo_estacion,fecha_muestra,hora_muestra FROM datos_monitoreo" " WHERE id_estacion=?"); qry.addBindValue(id); if(!qry.exec()){ qDebug()<<qry.lastError().text(); qDebug()<<qry.lastError().nativeErrorCode(); return; } qry.next(); ui->lineEdit->setText(qry.value(0).toString()); ui->dateEdit->setDate(qry.value(1).toDate()); ui->timeEdit->setTime(qry.value(2).toTime()); } void Widget::data(int id) { getConection(); QSqlQuery qry; qry.prepare("SELECT id_estacion, codigo_estacion, fecha_muestra, id_cliente " "FROM datos_monitoreo WHERE id_cliente=?;"); qry.addBindValue(id); if(!qry.exec()){ qDebug()<<qry.lastError().text(); qDebug()<<qry.lastError().nativeErrorCode(); return; } model=new QSqlQueryModel; model->setQuery(qry); ui->tableView->setModel(model); } void Widget::on_tableView_clicked(const QModelIndex &index) { dataMonitoreo(model->index(index.row(),0).data(Qt::DisplayRole).toInt()); }

-
Use a debugger and see where exactly it crashes.
Also don't open the database more than once. -
-
Use a debugger and see where exactly it crashes.
Also don't open the database more than once.@Christian-Ehrlicher Thanks, I solved the problem, it was the connection to the database, the multiple call to it, you're right.
-
Most likely, I think, is the QSqlDatabase that the QSqlQueryModel was implicitly constructed on has been disconnected. This is Christian Erlicher's point.
If it is crashing on the call to dataMonitoreo() then possibly model is an invalid pointer.