Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the column names of a QSqlTableModel?

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

like image 209
tom Avatar asked Jan 04 '11 16:01

tom


2 Answers

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.

like image 174
AJG85 Avatar answered Nov 04 '22 09:11

AJG85


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

QString getColumnName(int col) {
   return sqlTableModel.record().fieldName(col);
}
like image 27
mabg Avatar answered Nov 04 '22 09:11

mabg