Search code examples
python-3.xpyqt5qlistwidgetqlistwidgetitem

How can I add images in list widget in PyQt5?


tartube image which is written in pygtk

Simply what I am trying to achieve is a thumbnail and some data like shown above the image as an item in ListWidget in PyQt5.

I have the URL of a thumbnail and all the data like title, channel name, etc.

I am able to get the title in a list widget by doing this:

titles = ['title1','title2']
self.listWidget.addItems(titles) 

The design is created by Qt Designer and converted to python using pyuic5.

This is my first question in StackOverflow. Also, I know that I should share code but code is normally generated by pyuic5 in which there is only listWidget (item based).

Thanks in advance.


Solution

  • If you want to put images with text in your QListWidget you need to combine QIcon with Text into a QListWidgetItem like this:

    from PyQt5 import QtGui, QtCore, QtWidgets
    import os
    
    icon_path = os.getcwd() + "\icon.jpg"
    titles = ['title1','title2']
    
    class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
        def __init__(self, *args, **kwargs):
            QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
            
            self.setupUi(self) 
            #add list of strings
            self.listWidget.addItems(titles)
            #create QIcon
            icon = QtGui.QIcon(icon_path)
            #Create the row with Icon + Text
            item = QtWidgets.QListWidgetItem(icon, "Hello this is a test")
            #set size of the item
            size = QtCore.QSize()
            size.setHeight(100)
            size.setWidth(400)
            item.setSizeHint(size)
            #Put the item into the widget
            self.listWidget.addItem(item)
            
    if __name__ == "__main__":
        app = QtWidgets.QApplication([])
        window = MainWindow()
        window.show()
        app.exec_()
    

    And you will get something like this:

    Example