开发者

How can i find the QModelIndex for given composite primary key, with QSqlTableModel

I have this table:

QSqlQuery createTblSMS("CREATE TABLE sms_tbl("
            "isRe开发者_C百科ad 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"


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.....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜