How do I get the column names of a QSqlTableModel?
I would like to have something like 开发者_开发百科QString QSqlTableModel::getColumnName(int col).
You can set column name aliases like so in a QSqlTableModel:
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("First name"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("Last name"));
So likewise then you can retrieve column name aliases like so from a QSqlTableModel:
QString columnName1 = model->headerData(0, Qt::Horizontal, Qt::DisplayRole).toString();
QString columnName2 = model->headerData(1, Qt::Horizontal, Qt::DisplayRole).toString();
QString columnName3 = model->headerData(2, Qt::Horizontal, Qt::DisplayRole).toString();
By default if you do not set an alias the column name will be the equal to what was read from table meta data when initializing your model. Be sure that your section index is a valid column index. Be sure to specify an Orientation of Horizontal for columns and Vertical for rows.
Hope this helps.
After call setTable(), you can obtain field information calling record() method.
QString getColumnName(int col) {
return sqlTableModel.record().fieldName(col);
}
精彩评论