如何将所有列 header 名称插入到 qsqltablemodel table 的列表中?

how to insert all column header names into a list from qsqltablemodel table?

下面是我的数据库模型示例:

db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('book.db')
db.open()

self.model = QtSql.QSqlTableModel(self)
self.model.setTable("card")
self.model.select()

column_names = [ ]

如何从 qsqltablemodel table 中获取所有列 header 名称到列表中?

根据API文档(针对C++版本),record()函数可用于获取空记录,用于提取字段名(reference):

It returns an empty record, having only the field names. This function can be used to retrieve the field names of a record.

从记录中可以得到字段的个数,然后在列表推导表达式中查询每个字段的名称:

record = model.record()
column_names = [ record.fieldName(i) for i in range(record.count()) ]