TableView 不会将 QSqlQueryModel 加载到其中

TableView does not load the QSqlQueryModel into it

我正在使用 tableView 通过 QSqlQueryModel 在我的数据库中显示来自 table 的一些信息。它连接它创建实际的 table,它创建行和列并相应地标记它们,当我在 qDebugg() 中使用 model->rowCount(); 时它向我显示正确的行数,对于列也是如此。

问题是我应该显示信息的每一行的列是......好吧......空的,空白的,当我在 table 中有实际数据时我无法计算找出原因并且没有在视频,在线或堆栈溢出上找到特定的解决方案(只有 1 个问题接近这个但它说使用 rowCount() 调试连接并安装缺少的驱动程序......)

这是我到目前为止尝试过的:

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;
}

结果是来自我的数据库的 table,标签正确,行数不错,但所有内容都是空的

QSqlDataBase 对象 db 需要在用户界面的析构函数中关闭,否则即使将它加载到内存中也不会显示,并且可能表现得很奇怪..... 所以你应该在接口构造函数中使用 db.open() 和 db.close();在析构函数中。

不要将它们都放在这样的函数中:

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

这样不行,我还不明白为什么