PDA

View Full Version : QSqlDatabase model can't display data in QTableView



unix7777
11th August 2012, 20:45
Hi,

I'm trying to display model's data from sqlite db in QTableView.
I'm doing the follow but there is nothing inside the tableview.
PLEASE HELP!


#include "clients.h"
#include "ui_clients.h"
#include <QSqlQueryModel>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlTableModel>
#include <QSqlError>
#include <QDebug>

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

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("faktura.sqlite");
db.open();

QSqlQueryModel *model=new QSqlQueryModel();

model->setQuery("SELECT ClientId, ClientName, ClientAddress FROM clients");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("company name"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("address"));

ui->tableView_clients->setModel(model);
ui->tableView_clients->setColumnWidth(0,100);
ui->tableView_clients->setColumnWidth(1,100);
ui->tableView_clients->setColumnWidth(2,100);
ui->tableView_clients->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
ui->tableView_clients->horizontalHeader()->setStretchLastSection(true);
ui->tableView_clients->show();
}


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


void Clients::on_pushButton_add_pressed()
{
GroupsAddDialog *dialog=new GroupsAddDialog(this);
dialog->show();
}

ObiWanKenobe
11th August 2012, 22:37
After line 22 (model->setQuery(...)) add th e following o see, if there is an error:

if (model->lastError().isValid())
qDebug() << model->lastError();

ChrisW67
11th August 2012, 23:55
Also check that "faktura.sqlite" is in the current working directory of the program. This is not necessarily the same as the source directory or the directory containing the executable.