1

I have been using QTableView and QSqlTableModel. When running the program, I don't see populated results on QTableView. Here's the code so far:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QTime>
#include <QSqlTableModel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void initDB();

private Q_SLOTS:

    void updateResults();

private:
    Ui::MainWindow *ui;
    QStringList qslHeaders;
    QSqlTableModel *tableModel;
    QSqlDatabase database;
};

#endif // MAINWINDOW_H

The MainWindow.cpp looks like this:

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

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

    connect(ui->btnSubmit, SIGNAL(clicked(bool)), this, SLOT(updateResults()));
    initDB();
}

void MainWindow::updateResults()
{
    QString itemToSearch = ui->lineEditQuery->text();

    if(itemToSearch.trimmed().isEmpty()) return;

    tableModel->setFilter("item like '"+ itemToSearch +"%'");

    QTime start = QTime::currentTime();
    tableModel->select();

    int diff;

    diff = start.elapsed() - QTime::currentTime().elapsed();
    qDebug() << QString("TableView load time for %1 records: ").arg(tableModel->rowCount()) << QString::number(diff/1000.0, 'g', 6) << " seconds";

}

void MainWindow::initDB()
{
    QString path = "C:\\Users\\sqlite_dbs\\ENTRIES.db";
    database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName(path);

    if (!database.open())
    {
        qDebug() << "Error: connection with database fail";
    }
    else
    {
        qDebug() << "Database: connection ok";
    }

    tableModel = new QSqlTableModel(this, database);
    tableModel->setTable("metadata");
    ui->tableViewSearchResults->setModel(tableModel);
}

When a user enters a search string into lineEditQuery and clicks on Submit button, it's supposed to populate the view with table data. However, I don't see any changes on the QTableView except the header data. The headers seem to be correctly loaded as columns from the SQL table.

Also, qDebug() prints the following:

Database: connection ok "TableView load time for 256 records: " "0.063" seconds

Which indicates that the model does carry data.

EDIT #1: I checked the boolean value returned by select() and it seems to return true.

Hari Mohan
  • 53
  • 8

0 Answers0