Search code examples
python-3.xsqlitepyqt5qtableviewqtsql

How to remove row from Qtableview and SQLite using with QSqlTableModel?


Below is the code i am using:

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSql import *
from PyQt5 import uic
import sys
import sqlite3


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()

        DBModel = QSqlQueryModel()
        DBModel.setQuery("select * from card",db)
        self.tableView.setModel(DBModel)


        self.dbmodel = DBModel
        self.pushButton.clicked.connect(self.removeRow)

                
    def removeRow(self):
        tmodel = QSqlTableModel()
        selected = self.tableView.selectedIndexes()

        rows = set(index.row() for index in selected)
        rows = list(rows)
        rows.sort()
        first = rows[0]

        tmodel.deleteRowFromTable(first)



app = QApplication(sys.argv)
window = UI()
app.exec_()

This code is unable to delete selected row in the Qtableview and SQLite. I am trying use QSqlTableModel, getting no error but its not working not deleting the row. I missed something. How to solve this problem?


Solution

  • Calling deleteRowFromTable was useless, because you didn't select any table; note that you should not use that function anyway (from the docs:

    This is a low-level method that operates directly on the database and should not be called directly. Use removeRow() or removeRows() to delete values.

    You should use QSqlTableModel instead of QSqlQueryModel. Remember that if any change happens from code, the model requires to be repopulated using select() in order to the view to be correctly updated.

    class UI(QMainWindow):
        def __init__(self):
            super(UI, self).__init__()
            # ...
    
            DBModel = QSqlTableModel()
            DBModel.setTable("card")
            DBModel.select()
            self.tableView.setModel(DBModel)
    
            self.dbmodel = DBModel
            self.pushButton.clicked.connect(self.removeRow)
    
        def removeRow(self):
            selected = self.tableView.selectedIndexes()
    
            rows = set(index.row() for index in selected)
            rows = list(rows)
            rows.sort()
            first = rows[0]
    
            self.dbmodel.removeRow(first)
            self.dbmodel.select()