How to set width of QTableView columns by model?

别说谁变了你拦得住时间么 提交于 2019-12-23 14:59:20

问题


I'm using QTableView with a subclass of QAbstractTableModel as its model. By implementing data() and headerdata() in the subclassed model, it is feasible to control many properties of the table like data, header values, font, and so on.

In my case, I want the model to set the width of each table column. How can this be done?


回答1:


There are two ways:

  1. In your model's data method you can return the role SizeHintRole.

  2. A better 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 am setting the width of column 2 to 128 pixels and I am filling in the height from the item rectangle held in QStyleOptionViewItem.



来源:https://stackoverflow.com/questions/11069611/how-to-set-width-of-qtableview-columns-by-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!