mehulJ
mehulJ

Reputation: 119

How to change Qlistwidget item from row to thumb view like windows_explorer/ Caja with listwidget autosize policy?

I am using QListWidgetItem from pyqt5. I have added couple of images as an item in this widget and I am trying to get these 2 points

1. Item should be in iconView instead of rows. Icon and pixmaps are already added. Just like windows file explorer.

Before : enter image description here After :

enter image description here

2. If MainWindow is getting resized than it should resized listwidget items too.


Here is code example.

from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtGui import *
import sys

class Window(QDialog):
    def __init__(self, parent=None, node=None):
        QDialog.__init__(self, parent, QtCore.Qt.WindowStaysOnTopHint)
        self.ui_list_widget = QListWidget(self)
        self.ui_list_widget.setGridSize(QtCore.QSize(210, 120))
        self.ui_list_widget.setViewMode(QListView.IconMode)
        self.ui_list_widget.setIconSize(QtCore.QSize(200, 200))

        self.mainLayout = QHBoxLayout()
        self.mainLayout.addWidget(self.ui_list_widget)
        self.setup()

    def setup(self):
        index_path = {'image 1': '_image_path_1', 'image 2': '_image_path_2'}
        for name in index_path:
            item = QListWidgetItem()
            item.setText(name)
            self.ui_list_widget.addItem(item)
            
            icon = QIcon()
            icon.addPixmap(QPixmap(index_path[name]), QIcon.Normal, QIcon.On)
            item.setIcon(icon)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    WIN = Window()
    WIN.show()
    app.exec_()

        

Problem

There 2 problems 1st one is listwidget is showing all items in row instead of individuals element just like windows explorer icon view. Now this leads to 2nd issue that is not listwidget item not resizing automatically whenever mainwindow resizes.

Upvotes: 0

Views: 263

Answers (1)

musicamante
musicamante

Reputation: 48231

By default QListView has a Fixed resizeMode, so you need to set it to Adjust to ensure that the it lay outs items everytime the view is resized:

        self.ui_list_widget.setResizeMode(self.ui_list_widget.Adjust)

Then, you are only creating the layout, but you're not setting it. You can achieve this by adding the widget as argument of the layout constructor or by using setLayout().

        self.mainLayout = QHBoxLayout(self)
        # or, alternatively:
        self.setLayout(self.mainLayout)

Upvotes: 1

Related Questions