Personal tools
You are here: Home Developer Resources Knowledgebase How can I change the header text of my model based view?
Document Actions

How can I change the header text of my model based view?



Answer:

In order to change the header text of a model based view you need to reimplement headerData() and return the text you want for the relevant section, orientation and row there. See the documentation:

http://doc.trolltech.com/4.3/qabstractitemmodel.html#headerData

The example below demonstrates how this can be achieved:

#include <QtGui>

class Model : public QAbstractTableModel
{
public:
Model(QObject *parent)
{
QStringList firstRow;
QStringList secondRow;

for (int i = 0; i < 5; i++ ) {
firstRow.insert(i,"Row 1 " + QString::number(i+1));
secondRow.insert(i,"Row 2 " + QString::number(i+1));
}

stringList << firstRow << secondRow;

}

// Returns the number of rows
int rowCount ( const QModelIndex & parent = QModelIndex() ) const
{
return stringList.count();
}

// Returns the number of columns

int columnCount ( const QModelIndex & parent = QModelIndex() ) const
{
return stringList[0].count();

}

// Returns an appropriate value for the requested section, orientation and role
QVariant headerData ( int section, Qt::Orientation orientation, int role) const
{
if (role ==Qt::DisplayRole ) {
if (section == 0 && orientation == Qt::Vertical ) {
return QString("First");
} else if (section == 1 && orientation == Qt::Vertical ) {
return QString("Second");
} else {
return QVariant();
}
} else {
return QVariant();
}
}


// Returns an appropriate value for the requested data.
// If the view requests an invalid index or if the role is not
// Qt::DisplayRole, an invalid variant is returned.
// Any valid index that corresponds to a string for the index's column and row in
// the stringlist is returned

QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const
{
if (!index.isValid())
return QVariant();

if (role != Qt::DisplayRole)
return QVariant();
QStringList list = (QStringList)stringList.at(index.row());
return list.at(index.column());
}

private:

QList<QStringList>stringList;

};

int main(int argc, char **argv)
{
QApplication app(argc, argv);
QWidget widget;

QHBoxLayout *layout = new QHBoxLayout(&widget);

QTableView *tableView = new QTableView(&widget);
Model *model = new Model(tableView);
tableView->setModel(model);

layout->addWidget(tableView);

widget.show();
return app.exec();
}
 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: