PDA

View Full Version : C++ Mysql QTableView - problem to put MySQL's table's data into the QTableView



yerbaguy
8th December 2015, 13:11
Hallo,

Could I please ask you to have a look at the below pieces of code? I have got a problem to output the content of my mysql's table into the QTableView which (QTableView) I composed using the QtCreator Designer. I mean, the thing is, that after compiling and running the applications there is the QTableView visible with the headers and counted rows but with no content. Could you please point me out where and what I am doing incorrect? I use Qt Creator 3.5.1 (opensource) , Ubuntu 15.10. Thank you.

practice_clients.h




#ifndef PRACTICE_CLIENTS_H
#define PRACTICE_CLIENTS_H

#include <QtSql/QSql>
#include <QCoreApplication>
#include <QtSql/QSqlDriverPlugin>
#include <QDialog>
#include <QDebug>
#include <QFileInfo>

#include <QtSql/qsqldatabase.h>
#include <QtSql/QSqlQuery>
#include <QDebug>
#include <QSqlQueryModel>
#include <QSqlTableModel>
#include <QMessageBox>
#include <QSqlError>



#include <QMainWindow>

namespace Ui {
class Practice_Clients;
}

class Practice_Clients : public QMainWindow
{
Q_OBJECT

public:
explicit Practice_Clients(QWidget *parent = 0);
~Practice_Clients();



private:
Ui::Practice_Clients *ui;

QSqlDatabase practice_clients_db;
//QSqlQuery* query;
//QSqlQueryModel *modal;
//QSqlTableModel table_model;
};

#endif // PRACTICE_CLIENTS_H






and practice_clients.cpp



#include "practice_clients.h"
#include "ui_practice_clients.h"

Practice_Clients::Practice_Clients(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Practice_Clients)
{
ui->setupUi(this);

QSqlDatabase practice_clients_db = QSqlDatabase::addDatabase("QMYSQL");
practice_clients_db.setHostName("127.0.0.1");
practice_clients_db.setDatabaseName("qt_mysql");
practice_clients_db.setUserName("");
practice_clients_db.setPassword("");
practice_clients_db.open();

if (!practice_clients_db.open())
{
qDebug() << "Error";
}

qDebug() << practice_clients_db.open();

QSqlQueryModel *modal = new QSqlQueryModel();

QSqlQuery* query = new QSqlQuery();
query->prepare("SELECT * FROM gkUsers");
query->exec();

modal->setQuery(*query);


ui->tableView->setModel(modal);
//practice_clients_db.close();

//qDebug() << model->rowCount();

}


Practice_Clients::~Practice_Clients()
{
delete ui;
}

anda_skoa
8th December 2015, 15:20
What if you pass the database connection to the query's constructor?

And you probably don't want to leak the query object.

You could also try setting the query and the database on the model using QSqlQueryModel::setQuery, the overload that takes a QString and a QSqlDatabase.

Cheers,
_

jefftee
9th December 2015, 01:07
Your code doesn't do any error checking. You will find/fix bugs much easier if you don't silently ignore the return values from methods. You check that your database is open, but not the result of the prepare and exec methods for example