Solved Problem with 'for' inside currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
-
Basically i'm trying to go through all the members inside the l_input and l_output in my code (both of them are QListWidget's), both of them have always the same size, but depending on the size of the list the for does no execute all the times it should. Let's see the example below:
void MainWindow::on_lista_questoes_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { QList<QString> in; QList<QString> out; in.clear(); out.clear(); qDebug() << ui->l_input->count(); //THIS PRINTS 6 for (int j = 0; j < ui->l_input->count(); j++) { qDebug() << "inside for"//BUT THIS ONLY PRINTS 3 TIMES in.append(ui->l_input->takeItem(j)->text()); out.append(ui->l_output->takeItem(j)->text()); } }
In this example i'm losting 3 itens of my original l_input and l_output because the for is only executing 3 times, regarding the size of the l_input being 6. Sometimes it saves 4, and in other examples with a 4 size list it only saves 2 itens, the only way i'm able to save all the content is if the l_input and l_output has only 1 item in it. Is it wrong to use for in this slot function? Should I use another kind of loop? Or is there a better way to do it? Thank you.
-
@Zero_emc The problem is not using for in that slot, but taking items while iterating.
1st run:count = 6
j = 0
you take item 02nd run:
count = 5
j = 1
you take item 1 (actually item 2 when count=6)3th run:
count = 4
j = 2
you take item 24th run:
count = 3
j = 3
So the loop will stop without running the inside codeIf you want to do that loop, you should iterate reversely
for (int j = ui->l_input->count() - 1; j >= 0; j--) { in.prepend(ui->l_input->takeItem(j)->text()); out.prepend(ui->l_output->takeItem(j)->text()); }
or save the count first and always take the first item
int count = ui->l_input->count(); for (int j = 0; j < count ; j++) { in.append(ui->l_input->takeItem(0)->text()); out.append(ui->l_output->takeItem(0)->text()); }
Besides, you seems not deleteing the taken items.
ADDED
After having written a lot I realized that you maybe just want do a normal iterating.
If you don't want to take items, just want to get the text, you should useitem(row)
instead oftakeItem(row)
-
@Bonnie Oh, now I see what I did wrong. I did not know
takeItem(row)
would remove the item from the list, rookie mistake.After having written a lot I realized that you maybe just want do a normal iterating.
If you don't want to take items, just want to get the text, you should useitem(row)
instead oftakeItem(row)
You are absolutely correct, I just need the items text, and could easily fix it using
item(row)
. Thank you for the explanation, now I fully understand the difference betweentakeItem(row)
anditem(row)
. Have a nice day!