PDA

View Full Version : QListView max number of items in view



ArkKup
1st June 2020, 15:20
Hi, I need to calculate max number of items in current view of QListView. I've wrote code like this:


void MyListView::resizeEvent(QResizeEvent *event)
{
QListView::resizeEvent(event);
qDebug()<<"QListView spacing: " <<this->spacing(); //its 0
qDebug()<<"column: " << this->modelColumn(); //its 0

QFontMetrics fm (this->font());
int fontHeight = fm.lineSpacing();

QRect cr = contentsRect();
int windowHeight = cr.bottom() - cr.top();

int maxItemsCount = windowHeight / fontHeight;
qDebug()<<"max items in view: "<< maxItemsCount; //incorrect :( why?


}

but calculated max number of items is is incorrect. E.g. in case of my window height and font height I get 32 items when in fact current view has 28 items max. Perhaps someone can suggest something, how to calculate it properly?

d_stranz
1st June 2020, 16:19
First, resize event can be called multiple times as its parent widget is calculating the initial layout. So unless isVisible() returns true, you cannot use any of the dimensions for making calculations. So surround all of your code in the resizeEvent() with an "if ( isVisible() )" clause (except the call to the base class method, of course).

Your code does not take into account the margins added around each item, which would result in a larger size (and thus fewer items visible). In any case, since you are using a QListView as the basis for your MyListView, then you are probably also using a QAbstractItemModel to supply information to the view. It is the QAbstractItemModel::data() with the role Qt::SizeHintRole that returns the size of each item and is used to calculate the layout. You should implement that in your model as a call to the base class method, then set a breakpoint to step in and see how the base class calculates the sizes.

ChrisW67
1st June 2020, 22:48
I need to calculate max number of items in current view of QListView.

What problem are you trying to solve by knowing this? There may be a better solution.

ArkKup
2nd June 2020, 06:58
What problem are you trying to solve by knowing this? There may be a better solution.

the problem is I can't load >50.000 items in listview at once so I just want to load items to fill in the current view

d_stranz
2nd June 2020, 17:12
the problem is I can't load >50.000 items in listview at once so I just want to load items to fill in the current view

QListView and QTableView automatically manage the number of items in the view and do not load more than is required to fill the view. They use the methods implemented in QAbstractItemModel to retrieve only what they need. If you are having performance problems, it is probably in your model implementation, not in the views.