PDA

View Full Version : Qt4 set and read header data in tableView



teele
22nd September 2015, 07:25
I tried the Cities example in the book C++ -GUI Programming with Qt 4 first ed., and i tried to set a header data string by using the row

cityModel.setHeaderData(0, Qt::Horizontal, QObject::tr("Name"));

in the main.cpp file.

The code can be compiled and run without any complaints but the added code has not any effects.

The code is

#include <QHeaderView>
#include <QTableView>

#include "citymodel.h"

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QStringList cities;
cities << "Arvika" << "Boden" << "Eskilstuna" /*<< "Falun"
<< "Filipstad" << "Halmstad" << "Helsingborg" << "Karlstad"
<< "Kiruna" << "Kramfors" << "Motala" << "Sandviken"
<< "Skara" << "Stockholm" << "Sundsvall" << "Trelleborg" */ ;
QStringList layers;
layers << "l1" << "l2" << "l3" << "l4";

CityModel cityModel;
cityModel.setCities(cities);
cityModel.setLayers(layers);

QTableView tableView;
tableView.setModel(&cityModel);
tableView.setAlternatingRowColors(true);
tableView.setWindowTitle(QObject::tr("Cities"));

cityModel.setHeaderData(0, Qt::Horizontal, QObject::tr("Name")); // <------

tableView.show();

return app.exec();
}

How should you set and read header data in this case?

teele

prasad_N
22nd September 2015, 07:47
It didn't work because view will take header data from model as you set model & implemented header data in model.

try this: you need to do all the manipulations in model only


QVariant CityModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole)
{

if((0 == section ) && (orientation == Qt::Horizontal)
return QVariant("Name");
else
return cities[section];
}
return QVariant();
}