QT Access MainWindow SQLite Variable from Another Class

北城以北 提交于 2020-01-06 19:53:35

问题


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

来源:https://stackoverflow.com/questions/42210272/qt-access-mainwindow-sqlite-variable-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!