How to insert an item at a specific index of QListWidget?
Solved
General and Desktop
-
I need to insert an item at a specific index in a QListWidget, however it seems the QListWidget::insertItem function is not working correctly. I have created a sample application with the following code in which I am able to reproduce the issue
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // Create a QListWidget QListWidget *listWidget = new QListWidget(this); for (int row: {0, 1, 2, 0, 0}) { auto item = new QListWidgetItem(listWidget); listWidget->insertItem(row, item); auto widget = new QLabel("Item " + QString::number(row), listWidget); widget->setAlignment(Qt::AlignCenter); listWidget->setItemWidget(item, widget); } // Set the QListWidget as the central widget setCentralWidget(listWidget); }
I get the following output for the above code
Does this look like the correct behaviour? I was expecting the final order to be 0,0,0,1,2Qt Version - 5.15.8 and 6.8
-
You can't insert an item which is already inserted: https://doc.qt.io/qt-6/qlistwidgetitem.html#QListWidgetItem-1
-