PDA

View Full Version : QListWidget Insert Items



wallacesoh
21st February 2014, 08:02
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?

.h:


public:
QListWidgetItem *item[2];

.cpp:


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

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

Output (listWidget):


ABC 2

Expected output (listWidget):


ABC 1
ABC 2

d_stranz
22nd February 2014, 17:11
Aside from the fact that your code will blow up or exhibit undefined behavior if there happens to be more than 2 items in the stringlist that match "ABC" and that fact that you obviously haven't shown all of it (like, where is "name" defined, for instance? Must be those unimportant "..." lines) what you do show appears to be OK. If you get the same behavior using the addItem() method instead of insertItem(), then you are doing something somewhere else that messes up the list.

rawfool
24th February 2014, 06:29
wallacesoh

In class .h file, instead of
QListWidgetItem *item[2] do this,
QList<QListWidgetItem*> item;In .cpp file, do this

for(int i = 0; i < strList.size(); i++)
{
item.append(new QListWidgetItem());
....
....
}
// Access the item using at operator like this item.at(i);

This way, you can add QListWidgetItems dynamically without need to predefine the number of items.