PDA

View Full Version : QListWidget add QListWidgetItem



fellobo
20th February 2006, 19:50
My code seems right but doesn't display anything in my QListWidget. So, what am I doing wrong? Thanks for the help



QListWidgetItem add1("item 1", 0, 1);
QListWidgetItem add2("item 2", 0, 2);
QListWidgetItem add3("item 3", 0, 3);
QListWidgetItem add4("item 4", 0, 4);
list_widget->addItem(&add1);
list_widget->addItem(&add2);
list_widget->addItem(&add3);
list_widget->addItem(&add4);



What I think should happen is this: I would have a QListWidget (made from a form) that shows item 1 to item 4... I am trying to use the type as an ID so that if item 1 is a different language then I have the ID not the string.

What happens is I don't see anything in my QListWidget (it is empty right after adding them all.) I am using QT 4.0

fellobo
20th February 2006, 20:30
okay, so I figured it out... With the help of another QT programmer.

You can't mess with the type (I am not too sure as to why but that is why it isn't working.)

here is the solution we found:



// make the ListWidgetItems, and assign them to the list_widget
QListWidgetItem add1("item 1", list_widget);
QListWidgetItem add2("item 2", list_widget);
QListWidgetItem add3("item 3", list_widget);
QListWidgetItem add4("item 4", list_widget);

// add a QVariant to the LIstWidgetItem
add1.setData(Qt::UserRole, QVariant(1));
add2.setData(Qt::UserRole, QVariant(2));
add3.setData(Qt::UserRole, QVariant(3));
add4.setData(Qt::UserRole, QVariant(4));

// to get that number back out
list_widget->item(selected_list_widget)->data(Qt::UserRole).toInt());


Long live the QT

wysota
20th February 2006, 20:33
And this works? Hmm... seems odd, as you're allocating objects on the stack. They should get deleted upon returning from the function, causing those items to be removed from the list.

This should work too:


list_widget->addItem(new QListWidgetItem("item1"));
list_widget->addItem(new QListWidgetItem("item2"));
list_widget->addItem(new QListWidgetItem("item3"));

fellobo
20th February 2006, 20:37
ah, yes, my apologies that code wasn't correct....


// make the ListWidgetItems, and assign them to the list_widget
QListWidgetItem *padd1 = new QListWidgetItem("item 1", list_widget);
QListWidgetItem *padd2 = new QListWidgetItem("item 2", list_widget);
QListWidgetItem *padd3 = new QListWidgetItem("item 3", list_widget);
QListWidgetItem *padd4 = new QListWidgetItem("item 4", list_widget);

// add a QVariant to the LIstWidgetItem
padd1->setData(Qt::UserRole, QVariant(1));
padd2->setData(Qt::UserRole, QVariant(2));
padd3->setData(Qt::UserRole, QVariant(3));
padd4->setData(Qt::UserRole, QVariant(4));

// to get that number back out
list_widget->item(selected_list_widget)->data(Qt::UserRole).toInt();