3

I'm playing around with PyQt6 and QSQL.

The code down here was meant to load a sqlite3 database into a QTableView

But instead, it will load only the headers of a table into the table view.

What do I have to correct in order to display the data along with the headers?

import sys

from PyQt6 import QtWidgets
from PyQt6.QtSql import QSqlDatabase, QSqlTableModel
from PyQt6.QtWidgets import QDialog, QApplication, QMessageBox
from PyQt6.uic import loadUi


def createConnection() -> bool:
    con = QSqlDatabase.addDatabase('QSQLITE')

    con.setDatabaseName('data\\data.sqlite3')

    print(con.database())
    if not con.open():
        QMessageBox.critical(
            None,
            'QTableView Example - Error!',
            'Database Error: %s' % con.lastError().databaseText(),
        )
        return False
    return True


class MainWindow(QDialog):
    def __init__(self):
        super(MainWindow, self).__init__()
        loadUi('resources\\forms\\tabletutorial.ui', self)
        # Set the window title
        self.setWindowTitle('QTable Example')

        # Create the model
        model = QSqlTableModel(self)
        # Set the table to display

        model.setTable('MOCK_STAFF_DATA')
        # model.setTable('MOCK_STUDENT_DATA')
        # Set the data model for table widget
        self.tableView.setModel(model)

        # Adjust column widths to their content
        self.tableView.resizeColumnsToContents()


def run():
    app = QApplication(sys.argv)
    if not createConnection():
        sys.exit(1)
    mainwindow = MainWindow()
    widget = QtWidgets.QStackedWidget()
    widget.addWidget(mainwindow)
    widget.setFixedHeight(1000)
    widget.setFixedWidth(1500)

    widget.show()

    try:
        sys.exit(app.exec())

    except:
        print('Exiting')


run()
Gregorick
  • 61
  • 1
  • 1
  • 4
  • 1
    As explained [in the documentation](https://doc.qt.io/qt-6/qsqltablemodel.html#details): "at the end, you must call select() to populate the model with data." – musicamante Oct 08 '22 at 18:27

0 Answers0