[Qt-interest] QAbstractItemModel::setHeaderData() and headerData()

Andre Somers andre at familiesomers.nl
Fri Jan 29 15:39:22 CET 2010


j wrote:
> hi there,
>
> Im a bit confused as to how to set the header data
> of a model. I have a class A that inherits from both
> QAbstractTableModel and QTableView 
I think this is where your design error is!
Don't do this please. It is not supported by Qt to inherit from QObject 
twice. Furthermore,  you are confusing the different roles the 
components play. A model is something very different from a view. If you 
want to combine them in a single class, you should a has-a instead of an 
is-a relation.

> that has an
> initialisation function in which I call
> ...
> setHeaderData( 0, Qt::Horizontal, QObject::tr("property") );
> ...
> I did not implement the headerData function.
>   
QAbstractItemModel does not store anything by default. It is up to you 
to implement these functions to do something useful. In this case, you 
probably should have implemenented the headerData function. After you 
fix the mistake above, of course. Or, perhaps you should use a less 
basic class than QAbstractItemModel?
> unfortunately, the header shows '0' in section 0,
> where I expect it to display 'property'.
>
> when I do implement headerData like this:
>
> QVariant A::headerData( int section,
>      Qt::Orientation orientation,
>      int role ) const
> {
>      if( role == Qt::DisplayRole )
>      {
>          switch( section )
>          {
>                  case 0: return( QString( "property" ) );
>                  case 1: return( QString( "type" ) );
>                  case 2: return( QString( "value" ) );
>          }
>      }
>      return QAbstractItemModel::headerData( section, orientation, role );
> }
>
> and omit the setHeaderData call in the initialisation routine,
> all is fine, and the header displays what I expect.
>
> what's going on ?
>   
QAbstractItemModel is, just like the name suggests and the documentation 
states, an *abstract* interface. It needs implementation by you (or one 
of the standard subclasses) to do anything useful! The implementation 
above looks like a reasonable start.

André




More information about the Qt-interest-old mailing list