PDA

View Full Version : Applying QSqlTableModel to QTableView



SykeS
20th May 2010, 09:28
Hi!

I have QSqlTableModel with sample data from Qt SQL Examples "connection.h" file. If I want to get records using model.record() it works. model.rowCount() works perfectly too. But if I want to apply my model to tableView it doesn't work:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "F:/Qt/2010.01/qt/examples/sql/connection.h"
#include <QtSql>
#include <QDebug>
#include <QMessageBox>
#include <QSqlTableModel>

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

if (!createConnection())
QMessageBox::critical(this, tr("Błąd bazy danych"), tr("Nie można połączyć się z bazą danych."));

QSqlTableModel model;
model.setTable("person");
model.select();

ui->tableView->setModel(&model);

ui->label->setText(model.record(1).value("firstname").toString());
qDebug() << model.rowCount();
}

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

void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}

I post my final result in attachment.

Ps. What are the differences between "QSqlTableModel model;" and "QSqlTableModel *model = new QSqlTableModel;"?

ChrisW67
20th May 2010, 09:34
http://www.qtcentre.org/threads/30845-QSql-quot-Error-opening-database-quot-quot-unable-to-open-database-file-quot