[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)
    {
    	ui.setupUi(this);
    	m_qsqlDatabase = QSqlDatabase::addDatabase("QSQLITE","TestDatabase.sqlite");
    	m_qsqlDatabase.setDatabaseName("TestDatabase.sqlite");
    	if (m_qsqlDatabase.open())
    	{
    		QStringList existingTables = m_qsqlDatabase.tables();
    		m_model = new QSqlTableModel;
    		m_model->setTable("Table2");
    		m_model->select();
    		int columnCount = m_model->columnCount();
    		ui.tableView->setModel(m_model);
    	}
    	else
    	{
    		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

    Thanks



  • 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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.