Pyqt5 Changing the order of items added within the Qlistwidget

Asked

Viewed 146 times

0

Hello I was wondering if it is possible to change the order of entries of the items within the Qlistwidget, Currently when I insert a new item within the Qlistwidget it and fixed at the top and the others are played just below it, wanted to do this inversion of the first being thrown down and the last fixed at the top. What’s the best way to do that? My code is like this.

self.listWidget = QtWidgets.QListWidget(self.testPage)
self.listWidget.setGeometry(QtCore.QRect(10, 10, 341, 341))
self.listWidget.setObjectName("listWidget")
self.listWidget.setStyleSheet("background-color:#000000;\n"
                                        "color:#ffffff;\n")


def loop_msg(self, username, msg):
    self.widget = QWidget()
    self.layout_main = QHBoxLayout()
    #--------------img--------------------
    self.iconQLabel = QtWidgets.QLabel()
    self.iconQLabel.setStyleSheet("background-color:#000000;")
    self.iconQLabel.setFixedSize(59,59)
    self.iconQLabel.setPixmap(QtGui.QPixmap("./img/v2.png"))

    self.layout_right = QVBoxLayout()
    self.layout_right_down = QHBoxLayout()  
    self.layout_right_down.addWidget(QLabel(msg))
    self.layout_main.addWidget(self.iconQLabel)
    self.layout_right.addLayout(self.layout_right_down) 
    self.layout_main.addLayout(self.layout_right)
    self.widget.setLayout(self.layout_main) 
    self.item = QListWidgetItem()
    self.item.setSizeHint(QSize(70, 70))
    self.listWidget.addItem(self.item)
    self.listWidget.addItem("   {}".format(username))
    self.listWidget.setItemWidget(self.item, self.widget)

1 answer

4


It is the expected behavior, according to the documentation.

https://doc.qt.io/qt-5/qlistwidget.html

If you don’t want an item at the end you should use insertItem and not addItem.

self.listWidget.insertItem( 0, self.item)

0 being the desired position.

There are other strange things in your code (it seems to me that the loop is inserting a label in the layout and not a text in the list, which seems like a bad idea). Anyway, the logic is the same, the layout also has a insert in place of add.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.