PDA

View Full Version : Resize the items dynamically when the QListWidget is resized to fill the space



Alundra
9th June 2019, 12:25
Hi everybody,
I have a kind of working solution to have the items resized dynamically to fill the full space of QListWidget but in a very hacky way/ugly way and not that safe.
Here the code, you can see it resizes dynamically and adds the item when the row can add a new item in the row using a max item size:


class CDirectoryListWidgetCustomListDelegate
: public QStyledItemDelegate
{
public:
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override
{
// Constants used for the size calcule.
// 18px is the lowest value before flickering.
// This value was found after experiments.
const int RightMargin = 18;
const QSize ItemPadding = QSize(6, 6);
const int ItemWidth = option.decorationSize.width() + ItemPadding.width();

// Get the list widget using the parent value.
const QListWidget* ListWidget = static_cast<QListWidget*>(parent());

// Compute the max width and the row item count.
const int MaxWidth = ListWidget->viewport()->width() - RightMargin;
const int RowItemCount = std::max(1, MaxWidth / ItemWidth);

// Cases where the padding offset is not needed.
if ((ItemWidth >= MaxWidth) || (RowItemCount >= ListWidget->count()))
return option.decorationSize + QSize(0, option.fontMetrics.height()) + ItemPadding;

// Compute the padding offset and add in the item size to compensate of empty space.
const int PaddingOffset = (MaxWidth - (RowItemCount * ItemWidth)) / RowItemCount;
return option.decorationSize + QSize(PaddingOffset, option.fontMetrics.height()) + ItemPadding;
}

You can see that I have to play with a magic number to avoid flickering...
Any help is welcome if there is a possible way to achieve that correctly with Qt.
Thanks a lot!