tom
tom

Reputation: 63

How do I get the column names of a QSqlTableModel?

I would like to have something like QString QSqlTableModel::getColumnName(int col).

Upvotes: 6

Views: 8843

Answers (2)

mabg
mabg

Reputation: 2090

After call setTable(), you can obtain field information calling record() method.

QString getColumnName(int col) {
   return sqlTableModel.record().fieldName(col);
}

Upvotes: 4

AJG85
AJG85

Reputation: 16207

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.

Upvotes: 6

Related Questions