Add QWidget to QListWidget

后端 未结 2 557
日久生厌
日久生厌 2020-12-28 08:04

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         


        
相关标签:
2条回答
  • 2020-12-28 08:56

    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.

    0 讨论(0)
  • 2020-12-28 08:58

    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)
    

    0 讨论(0)
提交回复
热议问题