How to insert an item at a specific index of QListWidget?
-
wrote on 28 Apr 2025, 15:39 last edited by schrute
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
-
wrote on 29 Apr 2025, 04:06 last edited by
Thank you for pointing this out! I would have never figured it out that passing a parent widget to QListWidgetItem would automatically add it to the list.
-
2/3