Add QWidget to QListWidget

eric picture eric · Oct 5, 2014 · Viewed 21.3k times · Source

I am trying to make a QListWidget in which each item is a simple widget that contains text and a pushbutton. I use the following:

itemN = QtGui.QListWidgetItem() 
#Create widget
widget = QtGui.QWidget()
widgetText =  QtGui.QLabel("I love PyQt!")
widgetButton =  QtGui.QPushButton("Push Me")
widgetLayout = QtGui.QHBoxLayout()
widgetLayout.addWidget(widgetText)
widgetLayout.addWidget(widgetButton)
widgetLayout.addStretch()
widget.setLayout(widgetLayout)
#Add widget to QListWidget funList
funList.addItem(itemN)
funList.setItemWidget(itemN, widget)

The problem is, nothing shows up. I get a blank line that I can navigate using my keyboard, but it is blank. When the widget contains just a pushbutton, it works, so it isn't as if the pushbutton alone is messing things up. Are there limits on the complexity of widgets that setItemWidget can handle? Perhaps I need to go beyond the convenience classes, as suggested in some of the related posts below?

Related posts

pyqt adding a widget to a QListWidget
Note the previous post has a similar title to mine, but seems to be a relatively poorly expressed question about a complex pastiche of code from QtDesigner (mixed with some custom stuff). It is not clear at all that this is actually the question the person should have been asking. While the title makes it seem like a duplicate, the question (I pray) is not.

I would say something similar about this post.

QListWidgetItem with Radio Button

QListView/QListWidget with custom items and custom item widgets

Adding Custom Widget to QListWidget in QT click issue in QT?

pyqt adding a widget to a QListWidget

http://www.qtcentre.org/threads/8660-Drawing-a-widget-in-QItemDelegate-s-paint-method

http://developer.nokia.com/community/discussion/showthread.php/211634-Adding-a-button-inside-QListWidgetItem

Answer

Kosovan picture Kosovan · Oct 5, 2014

Try this:

itemN = QtGui.QListWidgetItem() 
#Create widget
widget = QtGui.QWidget()
widgetText =  QtGui.QLabel("I love PyQt!")
widgetButton =  QtGui.QPushButton("Push Me")
widgetLayout = QtGui.QHBoxLayout()
widgetLayout.addWidget(widgetText)
widgetLayout.addWidget(widgetButton)
widgetLayout.addStretch()

widgetLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
widget.setLayout(widgetLayout)  
itemN.setSizeHint(widget.sizeHint())    

#Add widget to QListWidget funList
funList.addItem(itemN)
funList.setItemWidget(itemN, widget)

As you can see, you need setSizeConstraint to the layout and setSizeHint to item.