miyou995
miyou995

Reputation: 87

how to update QListView when using it with QSqlQueryModel?

i'm instantiating a QListView from a QSqlQuery model, but when adding a new item it adds it to the database but doesn't add it to the view, here is my code

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setGeometry(900,180,800,600)
        self.setWindowTitle("Media Display")
        self.setWindowIcon(QIcon('favicon.png'))
        self.model = QSqlQueryModel()
        self.model.setQuery("SELECT path FROM fichiers")
        
        self.listview = QListView()
        self.listview.setModel(self.model)
        self.listview.setModelColumn(1)



    def addImage(self):
        fichier_base, _ = QFileDialog.getOpenFileName(self, 'select video', QDir.homePath(),"Images (*.png *.xpm *.jpg *.jpeg)")


            query = QSqlQuery()
            query.exec(
                f"""INSERT INTO fichiers (path) VALUES ('{fichier_base}')"""
            )
            print('paaath', fichier_base)
            self.model.layoutChanged.emit()

        

Upvotes: 0

Views: 451

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

First of all don't use f-string to create the queries as your code will be susceptible to SQL Injection, instead use placeholders. On the other hand, QSqlQueryModel is a reading model that is reset when you establish a query, so a possible solution is to establish the query again:

def addImage(self):
    fichier_base, _ = QFileDialog.getOpenFileName(
        self, "select video", QDir.homePath(), "Images (*.png *.xpm *.jpg *.jpeg)"
    )
    if not fichier_base:
        return
    query = QSqlQuery()
    query.prepare("""INSERT INTO fichiers (path) VALUES (?)""")
    query.addBindValue(fichier_base)
    if query.exec_():
        last_query = self.model.query().executedQuery()
        self.model.setQuery("")
        self.model.setQuery(last_query)
    else:
        print(query.lastError().text())

Upvotes: 1

Related Questions