My app opens the SQLite database connection when the MainWindow launches and closes it when the MainWindow is destroyed.
How do I access the database connection from other classes. I think I need to use a singleton format but haven't had any luck implementing it.
Here's what I have tried. It errors with.
C:\Users\cbennett\C++\CA_Letter_Generator\letter.cpp:9: error: expected primary-expression before '.' token
QSqlQuery qLetter = MainWindow.getDB().selectAll("letters","ltID=" + QString::number(ID));
^
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
loadButtons();
this->adjustSize();
}
MainWindow::~MainWindow()
{
db.close();
delete ui;
}
void MainWindow::loadButtons(){
db.setDatabaseName(dbPath);
db.open();
//load buttons from db
}
cc_sqlite MainWindow::getDB(){
return db;
}
letter.cpp
Letter::Letter(int ID){
QSqlQuery qLetter = MainWindow.getDB().selectAll("letters","ltID=" + QString::number(ID));
while (qLetter.next()) {
int id = qLetter.value(0).toInt();
QString name = qLetter.value(1).toString();
QString body = qLetter.value(2).toString();
QString sal = qLetter.value(3).toString();
qDebug() << id << name << body << sal;
}
}
letter.h
#ifndef LETTER_H
#define LETTER_H
#include "mainwindow.h"
#include "field.h"
#include "../CC_CPP/cc_sqlite.h"
class Letter
{
public:
Letter();
Letter(int ID);
private:
vector<Field> vFields;
};
#endif // LETTER_H