pythonpython-3.xpyqt5qtableviewqsqltablemodel

How to insert row from list into QSqlTableModel?


Below is my example code.

class UI(QMainWindow):
    def __init__(self):
        super(UI, self).__init__()
        uic.loadUi("tableview.ui", self)
        self.show()

        db = QSqlDatabase.addDatabase('QSQLITE')
        db.setDatabaseName('book.db')
        db.open()

        self.model = QtSql.QSqlTableModel(self)
        self.model.setTable("card")
        self.model.select()
        self.tableView.setModel(self.model)

        self.pushButton.clicked.connect(self.edit_items)
        self.add.clicked.connect(self.add_row)

    def add_row(self):
        data_row = ["name", 30, "M"]
        con = sqlite3.connect('book.db')
        con.execute("INSERT INTO card(name, age, gender) VALUES (?,?,?)", data_row + [''] * (3 -len(data_row)))
        con.commit()

I am using QtSql.QSqlTableModel and QtableView to show the database table data. And inserting the data using with above code. The QtableView is not been updating automatically when new row inserted. It has to be closed and reopened every time to see the update. My question: Is there any possible way to insert data from List to database using QSqlTableModel.


Solution

  • If you want to reload the whole table it is only necessary to use the select method, on the other hand if you want to use QSqlTableModel to insert rows then you must use the QSqlRecord:

    def add_row(self):
        r = self.model.record()
        r.setValue("name", "name")
        r.setValue("age", 30)
        r.setValue("gender", "M")
        self.model.insertRecord(-1, r)
        self.model.select()