Important: Please read the Qt Code of Conduct -

[PyQt] How can I access QTableModel by primary key index

  • Hello,
    In the following code:

    @row = 3
    col = 4
    value = "Hi"
    self.myQTableModel.setData(self.myQTableModel.index(row, col), value)@

    the row parameter of the index() method is not related to the primary key of my table.

    What I want, is access to the row where pimaryKeyIndex = 3

    is there a way to have instead:
    @self.myQTableModel.setData(self.myQTableModel.index(primaryKeyIndex, col), value) @


  • Many thanks to David Cortesi hwo sent me the following Email:

    is there a way to have instead:
    self.myQTableModel.index(primaryKeyIndex, col), value)

    QAbstractTableModel is extremely abstract! It offers no relational functions, only index() and parent().

    It is up to you to make the table model real by adding code. The documentation says you must implement rowCount, columnCount, and data(), and also setData if you want it to be modifiable.

    But you may implement other functions. In your situation I would implement a method pkRow(keyvalue) which returns the row number that corresponds to a given primary key value. Then your statement becomes,

    self.myModel.setData( self.myModel.index( self.myModel.pkRow(keyvalue), col ), value_for_col)

    To save keystrokes, you could write a pkIndex(keyvalue, col) method (built on top of pkRow). Then:

    self.myModel.setData( self.myModel.pkIndex(keyvalue,col), value_for_col)

    You pkRow method could perhaps cache the recent keyvalues it has seen, to save time.

    Note there is also a class QSqlRelationalTableModel, but it does not have any key-dependent methods either. But if your real data is simple SQL table perhaps you should use that.

Log in to reply