How to set width of QTableView columns by model?

I am using QTableView with a subclass of QAbstractTableModel as my model. By headerdata() data() and headerdata() in a subclassified model, you can control many table properties, such as data, header values, font, etc.

In my case, I want the model to set the width of each column in the table. How can I do that?

+4
source share
1 answer

There are two ways:

  • In your model data method, you can return the SizeHintRole role.

  • The best way would be to subclass QItemDelegate and override the method.

See here ( qitemdelegate.html # sizeHint )

Example -

 QSize ItemDelegate::sizeHint( const QStyleOptionViewItem & option, const QModelIndex & index ) const { QSize sz; if(index.column()==2) { return QSize(128, option.rect().height()); } return QSize(); } 

Here I set the column width from 2 to 128 pixels, and I fill the height from the rectangle of the element stored in QStyleOptionViewItem .

+9
source

All Articles