如何使用QSqlTableModel找到给定复合主键的QModelIndex

时间:2010-08-12 09:38:51

标签: c++ qt qtsql qmodelindex

我有这张桌子:

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();

如何找到给定复合主键的QModelIndex,例如:

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

1 个答案:

答案 0 :(得分:0)

我放弃了QSqlTableModel。最好将QAbstractTableModel子类化并隐藏其中的所有SQL数据库访问。在这种情况下,您将复合主键保留在列表中,然后使用QModelIndex.row()来引用主键的列表索引。

请求的示例。代码未经测试。

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