tags:

views:

22

answers:

2

I have this table

    QSqlQuery createTblSMS("CREATE TABLE sms_tbl("
            "isRead BOOLEAN NOT NULL,"
            "readTime DATETIME,"
            "arrivalTime DATETIME NOT NULL,"
            "sender TEXT NOT NULL,"
            "receiver TEXT NOT NULL,"
            "smsContent TEXT,"
            "PRIMARY KEY(arrivalTime, sender, receiver));", QSqlDatabase::database(mConnectionName));

smsModel = new QSqlTableModel(this, QSqlDatabase::database(mConnectionName));
smsModel->setTable("sms_tbl");
smsModel->select();

How can I find the QModelIndex for given composite primary key, for example:

"2010-08 12 12:04:15" "075588455" "077789585".

A: 

same problem here :/

would be great if anybody had a solution.. there must be a way to convert the result indices from a qsqlquery to the corresponding qmodelindex. but i can't find a solution!

philistion
A: 

I gave up on QSqlTableModel. Better to subclass QAbstractTableModel and hide all the SQL database access inside that. In this case you'd keep your composite primary keys in a list and then use QModelIndex.row() to reference the list index of your primary key.

Examples as requested. Code not tested.

NAME = 0    # Name column in db is model column 0
EMAIL = 1   # Email address column in db is model column 1

class MyModel(QAbstractTableModel):
    def __init__(self):
        self.rowrefs = []

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or \
                 not (0 <= index.row() < len(self.tableref)):
            return QVariant() # if index not valid return empty QVariant
        myref = self.rowref[index.row()]
        column = index.column()
        # insert code to look up the db row based on the row id in myref
        # and put data in a list 'dbrow' with list indexes matching model column numbers
        if role == Qt.DisplayRole:
            if column = NAME:
                return QVariant(dbrow[NAME])
            elif column = EMAIL:
                return QVariant(dbrow[EMAIL])
        etc.....
Simon Hibbs
Can you give me short code example, that would be very helpful for me.Thanks for your reply.