Reputation: 27
I am trying to connect to a local database and show a table in QTableView. I am currently getting a connection to my database but whenever I try to append my query to the QTableView box i am getting QSqlError("", "Unable to find table projects", "")
. When I run SELECT * FROM projects
in DB browser for SQLite, the entry I have in that table shows up. Here is my mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "purchaseorder.h"
#include <QtSql>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
PurchaseOrder *newpo = new PurchaseOrder();
QSqlDatabase db;
bool openDB(){
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("projectmanager.db");
if(!db.open())
{
qDebug()<<"Error opening database" << db.lastError();
return false;
}else{
qDebug()<<"Connection Established.";
return true;
}
}
void closeDB(){
db.close();
//db.removeDatabase(QSqlDatabase::defaultConnection);
}
private slots:
void on_actionProject_2_triggered();
private:
Ui::MainWindow *ui;
PurchaseOrder purchaseorder;
};
#endif // MAINWINDOW_H
Here is a snippet of my mainwindow.cpp:
#include "mainwindow.h"
#include <QDebug>
#include <QSqlQueryModel>
#include <QtSql>
void MainWindow::on_actionProject_2_triggered() // Load PROJECT table
{
QSqlTableModel* modal = new QSqlTableModel();
MainWindow conn;
conn.openDB();
modal->setTable("projects");
modal->select();
ui->tableView->setModel(modal);
qDebug()<<modal->lastError();
conn.close();
}
I believe everything is working up until. modal->setTable("projects");
Also I have my projectmanager.db
file stored in /db/projectmanager.db
but when I put that in my db path it does not connect but it will connect the way I have it? Thank you for any help, all is appreciated.
Desc. of projects:
CREATE TABLE `projects` ( `project_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`project_name` TEXT,
`client` INTEGER,
`lead_employee` INTEGER,
`description` TEXT,
`start_date` TEXT,
`deadline` TEXT,
`status` INTEGER )
Upvotes: 1
Views: 2190
Reputation: 243897
You have to open the connection before creating the model, on the other hand it is not necessary to create another MainWindow, so the solution is:
void MainWindow::on_actionProject_2_triggered()
{
openDB();
QSqlTableModel *modal = new QSqlTableModel;
modal->setTable("projects");
modal->select();
ui->tableView->setModel(modal);
closeDB();
}
Upvotes: 1