3

I created a SQLite database called "test.db". It has only one table called "table1" which is not an empty table. I tried to display "table1" in QTableView widget but the widget displayed nothing. The database was connected and Qt Createor didn't detect any error. I don't understand why QTableView displayed nothing at all.

My Code:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtCore>
#include <QSqlDatabase>
#include <QSqlTableModel>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)

{
  ui->setupUi(this);

  QSqlDatabase test = QSqlDatabase::addDatabase("QSQLITE");
  test.setDatabaseName("test.db");

  if (test.open())
  {
    ui->DB_Status->setText("DB is connected.");
  }
  else
  {
    ui->DB_Status->setText("DB is not connected.");
  }

  QSqlTableModel *model = new QSqlTableModel(this,test);
  model->setTable("table1");
  model->setEditStrategy(QSqlTableModel::OnManualSubmit);
  model->select();
  model->setHeaderData(0, Qt::Horizontal, tr("Row1"));
  model->setHeaderData(1, Qt::Horizontal, tr("Row2"));

  ui->tableView->setModel(model);
  ui->tableView->show();
}

I can run the program but QTableView widget diaplay nothing. Where is the problem ?

user3654736
  • 55
  • 1
  • 5
  • You can see what returns the `QString selectStatement()` and use it manually (execute) and see results. The most probable case is that you're querying table (or database) that you think you have data in, but actually you don't. – Googie May 20 '14 at 07:16

1 Answers1

0
test.setDatabaseName("test.db"); // after this line open database connection.
test.open();
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    OP is already doing this, and is testing the result of the `open` call. – 1201ProgramAlarm Sep 19 '16 at 04:00
  • Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". – abarisone Sep 19 '16 at 14:04