Important: Please read the Qt Code of Conduct -

[SOLVED] Simple SQLite database not working

  • Hi
    I am trying to open a sqlite database and display it in a QTableView but it is not working.
    Here is my code

    #include "SimpleDb.h"
    #include <QSqlError>
    #include <QFile>
    #include <QSqlRelationalTableModel>
    SimpleDb::SimpleDb(QWidget *parent)
    	: QMainWindow(parent)
    	m_qsqlDatabase = QSqlDatabase::addDatabase("QSQLITE","TestDatabase.sqlite");
    	if (
    		QStringList existingTables = m_qsqlDatabase.tables();
    		m_model = new QSqlTableModel;
    		int columnCount = m_model->columnCount();
    		QString err = m_qsqlDatabase.lastError().databaseText();
    		int a;
    		a = 10;

    The string list returned by QStringList existingTables = m_qsqlDatabase.tables(); contains 2 tables and includes the value given to m_model->setTable("Table2");
    However columnCount is zero and no data is shown in my view
    I must be doing something wrong but I cannot see what

    Please can someone let me know what is wrong


  • Hi,

    I think the problem is that you created the database connection with a connection name (the second parameter of addDatabase)

    Try to use addDatabase without the name or passing m_qsqlDatabase to the constructor of QSqlTableModel.

  • @mcosta
    Thanks that works now

Log in to reply