Unsolved Cannot display the data from SQLITE in tableView
-
Hello I create a program that will display my data from SQLITE to tableView. I dont get any error when I run it but when I click the load button it doesn't show the data.
here is my code:
from mainwindow.hnamespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: QSqlDatabase mydb; void connClose() { mydb.close(); mydb.removeDatabase(QSqlDatabase::defaultConnection); } bool connOpen() { QSqlDatabase mydb=QSqlDatabase::addDatabase("QSQLITE"); mydb.setDatabaseName("C:/User/Desktop/GUI/CIMS/Cow DIrectory.db"); if (!mydb.open()){ qDebug()<<("Failed to open the database"); return false; } else{ qDebug()<<("Connected. . . ."); return true; } } from mainwindow.cpp ```MainWindow::MainWindow(QMainWindow *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); mydb=QSqlDatabase::addDatabase("QSQLITE"); mydb.setDatabaseName("C:/Users/Desktop/GUI/CIMS/Cow DIrectory.db"); if (!mydb.open()) ui->label_sql->setText("Failed to open the database"); else ui->label_sql->setText("Connected. . . ."); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_load_clicked() { MainWindow conn; QSqlQueryModel *modal=new QSqlQueryModel(); conn.connOpen(); QSqlQuery* qry=new QSqlQuery(conn.mydb); qry->prepare("Select * from main"); qry->exec(); modal->setQuery(*qry); ui->tableView_cowdirectory->setModel(modal); conn.connClose(); qDebug()<<(modal->rowCount()); }
and I get this when I click the load button.
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
Failed to open the database
QSqlQuery::prepare: database not open
0
get_accChild got a negative varChildID (-14), but did not find it in cache
get_accChild got a negative varChildID (-19), but did not find it in cache -
Hi,
you do not need qry here, you can just domodal->setQuery("select * from main;");
Also, I would swapmodal->setQuery();
line with the next one: first assign model to a view, then set query - once you set a query on this model it gets populated with data and the view should reflect that. -
@drich Why do you open your database twice? Once in bool connOpen() and once in MainWindow::MainWindow(QMainWindow *parent). It is enough to open it only once...
-
Thank you, I already figure it out last night. :)