Search code examples
pythonpyqtpyqt5qtsql

How to connect QSqlTableModel with QTableView?


i want a simple example of connecting QSqlTableModel with QTableView , connecting the QSqlTableModel to dataset file (*.db) then connecting it to QTableView ?

semi code:

from PyQt5 import QtWidgets, QtGui, QtCore, QtSql


class Main(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        layout = QtWidgets.QVBoxLayout()
        self.table = QtWidgets.QTableView()

        layout.addWidget(self.table)
        self.setLayout(layout)





if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    main = Main()
    main.resize(600, 600)
    main.show()
    app.exec_()

Solution

  • The process is:

    • Open the database through QSqlDatabase
    • Then load the table into the model, and
    • at the end set the model in the view.
    if __name__ == '__main__':
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
    
        db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
        db.setDatabaseName("/path/of/database.db")
        if not db.open():
            sys.exit(-1)
    
        model = QtSql.QSqlTableModel()
        model.setTable("your_table")
        model.select()
    
        view = QtWidgets.QTableView()
        view.setModel(model)
        view.show()
    
        sys.exit(app.exec_()
    

    Note: In the case of sqlite if the database does not exist then it will create it so db.open() rarely returns false.