Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to insert an item at a specific index of QListWidget?

How to insert an item at a specific index of QListWidget?

Scheduled Pinned Locked Moved Solved General and Desktop
qlistwidgetinsertorder
3 Posts 2 Posters 87 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    schrute
    wrote last edited by schrute
    #1

    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
    Screenshot 2025-04-28 at 9.07.58 PM.png
    Does this look like the correct behaviour? I was expecting the final order to be 0,0,0,1,2

    Qt Version - 5.15.8 and 6.8

    1 Reply Last reply
    0
    • Christian EhrlicherC Offline
      Christian EhrlicherC Offline
      Christian Ehrlicher
      Lifetime Qt Champion
      wrote last edited by
      #2

      You can't insert an item which is already inserted: https://doc.qt.io/qt-6/qlistwidgetitem.html#QListWidgetItem-1

      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
      Visit the Qt Academy at https://academy.qt.io/catalog

      1 Reply Last reply
      3
      • S Offline
        S Offline
        schrute
        wrote last edited by
        #3

        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.

        1 Reply Last reply
        1
        • S schrute has marked this topic as solved

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved