QAbstractTableModel, headerData() never gets called, how to set headers properly?



  • I implemented an QAbstractTableModel to show a huge data set in a QTableView. I wanted to set the column headers by returning the desired QString in headerData()
    To my suprise, headerData() never gets called at all.

    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole)
    	{ throw std::exception(); }
    

    This never throws.
    I dont do anything with my QTableView, only setModel(), and my Model doesn't do anything but reimplenting the three necessary methods rowCount(), columnCount(), and data().

    What's the purpose of reimplementing headerData()? How do i set headers properly in QAbstractTableModel?



  • When you instanciate the module, do you add the columns?
    if columnCount() returns 0 headerData() will never be called



  • @VRonin
    Thanks for respone. My column count is implemented like this:

    	int columnCount(const QModelIndex& parent = QModelIndex()) const
    	{
    		return parent.isValid() ? 0 : m_tableData.GetColumnCount();
    	}
    

    I'm not sure about the " parent.isValid() ? 0 : " part, i took it from another example how to implement a subclass of QAbstractTableModel. I'm not sure what it does, and if it's necessary. It might be the problem.

    When i call "setModel", "m_tableData.GetColumnCount()" is non-zero. Also my table gets filled with data properly, so columncount can't be 0.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Unless you made a typo here, your headerData function has the wrong signature, it's a const method



  • @SGaist

    Damn, never trust examples on the internet.

    Thanks, problem solved.

    Is there a way to mark a thread as "solved"?



  • if you are ok with C++11, using the override keyword in the declaration prevents this type of mistakes


  • Lifetime Qt Champion

    Qt provides Q_DECL_OVERRIDE which extends to the override keyword if C++11 is used and to nothing otherwise


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.