2

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user3030327
  • 411
  • 1
  • 7
  • 19

1 Answers1

4

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()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • This is working great. Why do we use -1 at "self.model.insertRecord(-1, r)". And Is this only way to insert manually. for example if i have more than 10 or 20 values to insert and that are come from different variables, is there any other way to insert with short code? – user3030327 Aug 13 '20 at 16:53
  • 2
    @user3030327 1) Please do your research before asking, and a good resource in this case is the Qt docs which clearly states: https://doc.qt.io/qt-5/qsqltablemodel.html#insertRecord *Inserts the record at position row. **If row is negative, the record will be appended to the end**. Calls insertRows() and setRecord() internally*, 2) If there was a simpler way I'd already posted it, why don't you use a for-loop? – eyllanesc Aug 13 '20 at 16:58