0
votes

I'm using a QtableView to display and edit data from a QsqlTableModel. Everything's fine : data from a postgreSQL table is displayed, and user can edit it and save modifications.

I want to add a row when uses click on a button. I use the insertRecord method from my QslTableModel. The row is correctly added in the QTableView.

My problem is : I want to insert a value from a query in the first cell of this new row. (to automatically populate an unique identifier).

This is my code :

def ajoutlgn(self):
    query_idNewLine = QtSql.QSqlQuery(self.db)
    if query_idNewLine.exec_('SELECT sp_idsuivi+1 FROM bdsuivis.t_suivprev_tablo ORDER BY sp_idsuivi DESC LIMIT 1'):
        while query_idNewLine.next():
            identifiant = query_idNewLine.value(0)
            #print identifiant

    record = QtSql.QSqlRecord()
    record.setValue(1,identifiant)
    self.model.insertRecord(self.model.rowCount(), record)

The value is not inserted in the new row (but if I enter a value by hand, it works perfectly). Nevertheless, the query is OK (as I can see with the « print identifiant » line, which returns the expected integer).

Do you see what I'm doing wrong ?

Are there other methods to insert programmatically a value in a QTableView cell?

Or do I have to use a QitemDelegate ?

Thanks for advance.

1
Use QSqlQueryModel: model = QSqlQueryModel(), model.setQuery('SELECT sp....'), tv.setModel(model) - eyllanesc
Thanks for your answer. It was my first try. But I was not able to save modifications with this type of model, and I was told that this model is bugged in Qt4. And I can't work with QT5. That's why I used a QsqlTableModel. - V Damoy
Who told you that he has errors in Qt4, have you tried it? I have tried it and in general I had no problems. many of the classes of Qt have bugs, like any library, and even so we use it, if we do not run into those bugs there are no problems, and until now I have not run into any, and have you asked QSqlQuery do not have bugs? :P - eyllanesc
already remember, QsqlQueryModel is only read, but you can make a small modification so that it is also written, later I will publish a response making it possible to write in the database with that model. - eyllanesc
Thanks. I'll try with this model. I confused with QsqlRelationnalTableModel, which I tried unsuccessfully. I look forward to your answer with writing possibilities. :-) - V Damoy

1 Answers

0
votes

Finally I found the solution :

This line creates a record, but not a record for my QsqlTableModel

    record = QtSql.QSqlRecord()

I replaced it with this one, and it works perfectly :

    record = self.model.record()