如何在 QListWidget 之上添加一个 QListWidgetItem?

how to add a QListWidgetItem on top of the QListWidget?

我正在尝试创建类似于您通常在大多数图像编辑器软件中看到的图层编辑器的东西,为此我需要在 QListWidget 的顶部添加新图层,代码我目前正在尝试的是这个:

def new_layer(self):

    layer = Layer(layer_name="Layer %d" % self.number_of_layers)
    layer_item = QListWidgetItem(self)
    layer_item.setSizeHint(layer.sizeHint())

    if self.number_of_layers % 2 == 0:
        layer_item.setBackground(Qt.darkGray)
    else:
        layer_item.setBackground(Qt.gray)

    self.setItemWidget(layer_item, layer)
    self.insertItem(0, layer_item)

    self.number_of_layers += 1

即使在第 0 行插入 QListWidgetItem 后,当添加新图层时,它仍显示在先前创建的第一个图层下方。我能做些什么来修复它?

根据 docs:

QListWidgetItem::QListWidgetItem(QListWidget * parent = 0, int type = Type)

Constructs an empty list widget item of the specified type with the given parent. If parent is not specified, the item will need to be inserted into a list widget with QListWidget::insertItem().

This constructor inserts the item into the model of the parent that is passed to the constructor. If the model is sorted then the behavior of the insert is undetermined since the model will call the '<' operator method on the item which, at this point, is not yet constructed. To avoid the undetermined behavior, we recommend not to specify the parent and use QListWidget::insertItem() instead.

从上面可以得出结论,您不应将父级传递给 QListWidgetItem,因此您的代码应如下所示:

def new_layer(self):

    layer = Layer(layer_name="Layer %d" % self.number_of_layers)
    layer_item = QListWidgetItem() #remove self
    layer_item.setSizeHint(layer.sizeHint())

    if self.number_of_layers % 2 == 0:
        layer_item.setBackground(Qt.darkGray)
    else:
        layer_item.setBackground(Qt.gray)

    self.insertItem(0, layer_item)
    self.setItemWidget(layer_item, layer)


    self.number_of_layers += 1