I want the height of a QListView
based on an QAbstractListModel
to fit the contents, if the amount of the items is smaller a given number N. If there are more than N items, it should show only N items. I read a lot of curious tips in the web, but most of them look like hacks. I guess this has something to do with sizeHint()
but in the model view approach there is no ItemWidget in which I could override the sizeHint()
. What is the correct way to achieve this behaviour?
Further, how does this correlate to the size policy of the parent app? This is a second constraint: The contents should not try to use the space they have in the parent widget, but the parent widget should resize to fit the QListView
.
This is not a duplicate to this question, since I can't use QCompleter
.
sizeHint() has to be overridden in the QListView (respectively your subclass of it). The mentioned special behaviour can be implemented there. eg like this:
QSize ProposalListView::sizeHint() const
{
if (model()->rowCount() == 0) return QSize(width(), 0);
int nToShow = _nItemsToShow < model()->rowCount() ? _nItemsToShow : model()->rowCount();
return QSize(width(), nToShow*sizeHintForRow(0));
}
This requires the size hint of the item delegate to be reasonable. In my case:
inline QSize sizeHint ( const QStyleOptionViewItem&, const QModelIndex& ) const override { return QSize(200, 48); }
Now I just have to call updateGeometry() after changing the model.