简体   繁体   中英

TableView does not load the QSqlQueryModel into it

I'm using a tableView to display some information from a table in my database via a QSqlQueryModel. It connects it creates the actual table, it creates the rows and columns and labels them accordingly, when I use model->rowCount(); in qDebugg() it shows me the proper number of rows, same for columns.

The problems is my columns on each row where information should be displayed is..... well... empty, BLANK, when i have actual data inside the table and i can't figure it out why and did not find a particular solution on videos, online or on stack overflow (only 1 question that gets close to this but it says to use rowCount() to debug the connection and install missing drivers...)

This is what i tried so far:

QString error=nullptr;
    QSqlDatabase db=this->mDbConnection->getDataBase();
    if(!this->mDbConnection->openDatabase(&error)) {
       QMessageBox::critical(this, "Error: ", error);
       return;
    } else {
        qDebug()<<"Connection to database sucess!";
        db.open();
        QSqlQueryModel *model = new QSqlQueryModel();
       model->setQuery("SELECT [UserID],[FullName],[UserName],[Password],[PermissionID]FROM [Restaurant].[dbo].[Users]");
       ui->tableView->setModel(model);
       qDebug()<<model->rowCount();
       //qDebug()<<data(model->createIndex(0,0));
        db.close();
        //cod aici
    }

//mDbConnection is a custom object databaseconnection.cpp:
bool DatabaseConnection::openDatabase(QString *error) {
    this->db.setDatabaseName(QString("DRIVER={%1};SERVER=%2;DATABASE=%3;UID=%4;PWD=%5;Trusted_Connection=%6;").arg(this->conn->getDriver())
        .arg(this->conn->getServer())
        .arg(this->conn->getDatabaseName())
        .arg(this->conn->getUser())
        .arg(this->conn->getPassword())
        .arg(this->conn->getTrustedConnection() ? "Yes" : "No"));

        if(!this->db.open()) {
            if (error!=nullptr) {
                *error = this->db.lastError().text();
            }
            return false;
        }
        return true;
}

QSqlDatabase DatabaseConnection::getDataBase() {
    return this->db;
}

The result is the table from my database with the labels correct and the good number of rows but with everything empty

QSqlDataBase object db needs to be closed in the destructor of the user interface else it won't show up even if you have it loaded in the memory and may behave strange..... So you should use db.open() in the interface constructor and db.close(); in the destructor.

DO NOT PUT them both in a function like this:

void function()
{
db.open()
// code for database here
db.close();
}

it won't work this way and I don't understand yet why

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM