How can I iterate through QListWidget items and work with each item?
Asked Answered
C

3

25

In CSharp it's as simple as writing:

listBox1.Items.Add("Hello");
listBox1.Items.Add("There");

foreach (string item in listBox1.Items )
{
    MessageBox.Show(item.ToString());
}

and I can easily add different objects to a list box and then retrieve them using foreach.

I tried the same approach in Qt 4.8.2 but it seems they are different. Though they look very similar at the first. I found that Qt supports foreach so I went on and tried something like:

foreach(QListWidgetItem& item,ui->listWidget->items())
{
    item.setTextColor(QColor::blue());
}

which failed clearly. It says the items() needs a parameter which confuses me. I am trying to iterate through the ListBox itself, so what does this mean? I tried passing the ListBox object as the parameter itself this again failed too:

foreach(QListWidgetItem& item,ui->listWidget->items(ui->listWidget))
{
    item.setTextColor(QColor::blue());
}

So here are my questions:

  • How can I iterate through a QListWidget items in Qt?
  • Can I store objects as items in QListWidgets like C#?
  • How can I convert an object in QListWidgets to string (C#s ToString counter part in Qt) ?

(Suppose I want to use a QMessageBox instead of that setTextColor and want to print out all string items in the QlistWidget.)

Charley answered 31/8, 2012 at 21:18 Comment(0)
N
49

I don't think the items function does what you think it does. It sounds like it's for decoding MIME data, not getting a list of all the items in the widget.

I don't actually see any function to do exactly what you want, sadly. You could probably use findItems as a workaround, but that seems ugly, if not downright abusive... At least you can still use the item function with good old for loops - they're not that much more typing:

for(int i = 0; i < listWidget->count(); ++i)
{
    QListWidgetItem* item = listWidget->item(i);
    //Do stuff!
}

Hope that helps!

Nerissanerita answered 31/8, 2012 at 21:37 Comment(1)
Thanks for this. It is unfortunate that Qt decided to make an items class method that doesn't return a collection of QListWidgetItems like one would expect with an items class method for any other dev library. Confusing and clumsy. I mean, why brag about a foreach() in Qt when they don't even provide a way to iterate the subitems of this widget with it?Colbert
J
5

You can do something like this:

for(int i = 0; i < listWidget->count(); ++i)
{
    QString str = listwidget.item(i)->text();
    //Do stuff!
}
Junker answered 26/8, 2016 at 5:20 Comment(0)
R
2

Try making a pointer to each of the items if you are making the list items in code. But, if you are using the .ui file to make a list item try right clicking it and hitting edit stylesheet. You can edit it very easily that way.

Remotion answered 31/8, 2012 at 23:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.