0

我有这张桌子:

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"
4

1 回答 1

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.....
于 2010-08-19T15:57:37.000 回答