如何通过模型设置QTableView列的宽度? [英] How to set width of QTableView columns by model?

查看:797
本文介绍了如何通过模型设置QTableView列的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用QTableViewQAbstractTableModel的子类作为其模型.通过在子类模型中实现data()headerdata(),控制表的许多属性(如数据,标头值,字体等)是可行的.

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. 在模型的数据方法中,您可以返回角色SizeHintRole.

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

更好的方法是继承QItemDelegate的子类并重写该方法.

A better way would be to subclass QItemDelegate and override the method.

请参阅此处( qitemdelegate.html#sizeHint )

示例-

QSize ItemDelegate::sizeHint( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    QSize sz;

    if(index.column()==2)
    {
        return QSize(128, option.rect().height());
    }

    return QSize();
}

在这里,我将第2列的宽度设置为128像素,并从QStyleOptionViewItem中保存的项目矩形中填充高度.

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.

这篇关于如何通过模型设置QTableView列的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆