Search code examples
c++qtqt5qlistwidgetqlistwidgetitem

How to Resize QListWidget's gridSize to make items fill the viewPort evenly?


I want to fill the viewport evenly of QListWidget which am using in iconMode to get grid layout for item.

Everything work fine but the problem is when resizing the mainWindow the listWidget waits to get the width so new item in the row can get space. Shown in the image below: am getting this type of behaviour by QListWidget

And expecting this: enter image description here

This is what i tried so far

   void MainWindow::resizeEvent(QResizeEvent* event)
   {
    if(ui->listWidget->count()>0){
       float items_that_can_fill_view = ui->listWidget->width() /(330+ui->listWidget->spacing());
       float total_width_of_items  = items_that_can_fill_view*330;
       float remaining_width = ui->listWidget->width()-total_width_of_items;
       float evenly_distributed_width = remaining_width/items_that_can_fill_view;
       ui->listWidget->setGridSize(QSize(330+evenly_distributed_width,ui->listWidget->item(0)->sizeHint().height()));
   }
   event->accept();
   }

In the above code am changing the gridSize at runtime of app by resizing the width of mainWindow. I choosed float instead of int as type to make changes very precisely. also 330 is the width of each item in listWidget.
Please help.
I'm using Qt 5.8.


Solution

  • I got the desired result by replacing the listWidget's width to its viewport's width. code below makes the grid evenly cover the whole view:

       if(ui->listWidget->count()>0){
          float i = ui->listWidget->viewport()->width() /(330+ui->listWidget->spacing());
          float iw  = i*330;
          float r = ui->listWidget->viewport()->width()-iw;
          float even_dist_w = (r/i)-5;
          ui->listWidget->setGridSize(QSize(330+even_dist_w,162));
      }
    

    where,

    i = total number of items that the view can show horizontally;

    iw = tatal width of all items(i);

    r = remaining space left in view after items are drawn;

    even_dist_w = space that is to be added to gridSize;

    Finally we set the gridSize to listWidget. this results in a view like below:(check the space is evenly distributed among the cloumns)

    enter image description here