在QTreeView中设置单元格的大小

时间:2018-08-14 07:30:57

标签: qt qtreeview qabstractitemmodel qabstractlistmodel qstyleditemdelegate

我需要设置:

-minimum height for a cell in QTreeView (25px)
-the height and width to fit with the content of each cell.

我知道我们可以使用Delegate中的sizeHint()或使用Model中的sizeHintRole来实现,但是仍然无法想象函数的外观。这是我的代表中的paint():

const int marginLeft = 10; // margin between text in each cell with the left border
const int marginLeftFirstColumn = 20; //margin between text and the left border in the first column
const int marginRight = 10;

void TableDelegate::paint( QPainter *p_painter, const QStyleOptionViewItem &p_option, const QModelIndex &p_index ) const
{
  QStyleOptionViewItem option = p_option;

  TableDataRow::Type type = static_cast<TableDataRow::Type>( p_index.data( Qt::UserRole ).toInt() );

  QString text = p_index.data( Qt::DisplayRole ).toString();
  QFont font = p_painter->font();
  int col = p_index.column();

  switch ( type )
  {
     case TableDataRow::Type::Data:
     {
        font.setWeight( QFont::Normal );
        p_painter->setFont( font );
        if ( col == 0 )
        {
           option.rect.setRect( option.rect.left() + marginLeftFirstColumn, option.rect.top(), option.rect.width() - marginRight, option.rect.height() );
        }
        else
        {
           option.rect.setRect( option.rect.left() + marginLeft, option.rect.top(), option.rect.width() - marginRight, option.rect.height() );
        }
        break;
     }
     case  TableDataRow::Type::MainCaption:
     {
        p_painter->fillRect( p_option.rect, Qt::gray ); //draw background
        font.setWeight( QFont::Bold );
        p_painter->setFont( font );
        option.rect.setRect( option.rect.left() + marginLeft, option.rect.top(), option.rect.width() - marginRight, option.rect.height() );
        break;
     }
  }
  p_painter->drawText( option.rect, Qt::AlignVCenter | Qt::TextWordWrap, text );
}

QSize TableDelegate::sizeHint( const QStyleOptionViewItem &p_option, const QModelIndex &p_index ) const //this function to compensate the alignment
{
  QSize size = QStyledItemDelegate::sizeHint( p_option, p_index );
  if ( p_index.column() == 0 )
     {
        size.setWidth( size.width() + marginLeftFirstColumn );
     }
     else
     {
        size.setWidth( size.width() + marginLeft );
     }
  return size;
}

你们能帮助我使用Model中的data()函数并更新Delegate中的sizeHint()吗?

1 个答案:

答案 0 :(得分:1)

下面是一个粗略的示例,说明如何使用QAbstractItemModel::data()函数为特定的表格单元设置大小:

QVariant MyModel::data(const QModelIndex & index, int role) const
{
  if (role == Qt::SizeHintRole)
  {
    // An example. Set the size of the first cell.
    if (index.row() == 0 && index.column() == 0)
    {
      return QSize(100, 100);
    }
  }
  else if (role == Qt::DisplayRole)
  {
    // Manage how item should appear.
  }
  return QAbstractItemModel::data(index, role);
}