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.QListWidgetIt
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.
If you use PyQt5, there is some changes, you must use QtWidgets
for widget not QtGui
. Use this code if using with PyQt5:
Don't forget to import PyQt5:
from PyQt5 import QtCore, QtGui, QtWidgets`
itemN = QtWidgets.QListWidgetItem()
# Create widget
widget = QtWidgets.QWidget()
widgetText = QtWidgets.QLabel("I love PyQt!")
widgetButton = QtWidgets.QPushButton("Push Me")
widgetLayout = QtWidgets.QHBoxLayout()
widgetLayout.addWidget(widgetText)
widgetLayout.addWidget(widgetButton)
widgetLayout.addStretch()
widgetLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
widget.setLayout(widgetLayout)
itemN.setSizeHint(widget.sizeHint())
# Add widget to QListWidget funList
funList.addItem(itemN)
funList.setItemWidget(itemN, widget)