Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[Solved] Set Column Width ot QTableView



  • Hello,

    I have a QTableView which receives my custom model called PointSet (PointSet derives from QAbstractTableModel).
    Now I want to set different widths for the columns in my model. Therefore I have overwritten headerData() method like this:

    @QVariant PointSet::headerData(int section, Qt::Orientation orientation, int role) const
    {
    if(orientation == Qt::Horizontal) {

        if(role == Qt::DisplayRole) {        
            switch(section) {
                case 0:
                    return QString("Symbol");
                case 1:
                    return QString("Description");
            }
        }
        else if(role == Qt::SizeHintRole) {
             return QSize(300, 50);
        }
        
    }
    
    return QAbstractTableModel::headerData(section, orientation, role);
    

    }@

    When I execute this code, the column headers of my table indeed have a height of 50 pixels, but no column has a size of 300. The 300 seems to be ignored!
    Anyone knows why setting column width with my approach does not work?

    Thanks!



  • Hi,

    I would try calling "resizecolumtocontents":http://qt-project.org/doc/qt-5.0/qtwidgets/qtableview.html#resizeColumnToContents

    after setting the sizehint



  • That really worked. Thanks a lot Eddy!:)



  • My pleasure.

    Could you please edit your first post and add [solved] to it.


Log in to reply