David Doria
David Doria

Reputation: 10273

Get a delegate to set the size of a cell in a QTableView

I am using a delegate to display a QPixmap from a QAbstractTableModel in a QTableView, like this:

void LabelDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
  QPixmap pixmap = index.data(Qt::DisplayRole).value<QPixmap>();

  QRect rect = option.rect;
  rect.adjust(rect.width()/3, 0, -rect.width()/3, 0);
  painter->drawPixmap(rect, pixmap, pixmap.rect());
}

However, I want it to make sure that the cell is big enough to display the whole QPixmap. I tried using the sizeHint function:

QSize LabelDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
{
  std::cout << "sizeHint()" << std::endl;
  unsigned int sideLength = 300;
  return QSize(sideLength, sideLength);
}

but it doesn't seem to resize the cell. How would I force the cell size to match the QPixmap size?

Thanks,

David

Upvotes: 0

Views: 2982

Answers (1)

pnezis
pnezis

Reputation: 12321

You should check the resizeColumnsToContents() and resizeRowsToContents slots for QTableView.

Every time an item is added to your model, emit a signal and connect it with a slot that calls these two functions in order to update the geometry of your view.

Upvotes: 1

Related Questions