QListWidget Insert Items

  • I am trying to add two items into my QListWidget dynamically. However, the following codes only allow me to add only the last item into the list. strList.size() contains 4 items. Assuming name contains "ABC 1" and "ABC 2".

    Is my loop incorrect? Or is my method of adding items into the listWidget wrong?

    @ public:
    QListWidgetItem *item[2];@

    @ int num = 0;
    for(int i = 0; i < strList.size(); i++)
    if(strList[i] == "ABC")

            item[num] = new QListWidgetItem();
            ui.listWidget->insertItem(num, item[num]);
            num += 1;

    Output (listWidget):

    bq. ABC 2

    Expected output (listWidget):

    bq. ABC 1
    ABC 2

  • Hi,
    Oke, couple of things. For a QStringList use a iterator instead of the for loop and the [] operator. The [] operator may crash your program bigtime if your loop counter is wrong.
    Also for string comparison use contains("ABC") function.
    For a QListWidget is't not needed to hold the data in a member variable (item list). The QListWidget holds the data, read from there, or when you don't want to do that use a QListView instead and combine with a QAbstractModel subclass to hold your data.
    You also have a memory leak!! When you keep the array of QListWidgetItems and you want to set a new QListWidgetItem you first should delete the old one! Otherwise it is kept in memory.

  • Lifetime Qt Champion


    There are several things that look fishy:

    Why this item table ? There's not real need for it

    What is the exact content of strList ?

    strList[i] == "ABC" will only be true if the content of that element is Exactly ABC.

    There seems to be some code missing in your if statement so there's no way to know how name is created.

    You can also avoid creating new QListWidgetItem since theres also an insertItem method that takes an int and a QString as argument

  • Oke,
    I'll give you a bit of code:
    QStringList::const_iterator IterValue;
    for (IterValue = strList.constBegin(); IterValue < strList.constEnd(); IterValue++)
    if (IterValue->contains("ABC") == true)
    QListWidgetItem * NewItem = new QListWidgetItem;

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.