January 12, 2012

aurora aurora
Lab Rat
137 posts

removing row from QTableWidget, showing no effect

 

Hello all,
I’m trying to remove item from QTable widget as shown below….

  1.     for(int m=NewRow;m<ui->tableWidget_ouput->rowCount();m++)
  2.     {
  3.      
  4.     ui->tableWidget_ouput->removeRow(m);
  5.     }

But its effect is not displaying i.e, the removed rows still present in the table….Please tell me , what i’m missing here?

5 replies

January 12, 2012

Andre Andre
Robot Herder
6417 posts

Judging from the code, you were looking for the QTableWidget::clear() method?

January 12, 2012

aurora aurora
Lab Rat
137 posts
Andre wrote:
Judging from the code, you were looking for the QTableWidget::clear() method?

Not just clearing those rows, i want to remove those rows from table….

January 12, 2012

KA51O KA51O
Hobby Entomologist
478 posts

Since the table gets its data from the model I’d say remove them from the model.

January 12, 2012

Andre Andre
Robot Herder
6417 posts
KA51O wrote:
Since the table gets its data from the model I’d say remove them from the model.

QTableWidget provides its own, private model, and a separate API to manipulate the items in that model, so this does not work for QTableWidget.

aurora wrote:

Not just clearing those rows, i want to remove those rows from table….

OK, if you just want to delete specific rows, you should indeed use removeRow. Note however that your loop is wrong. Let’s work through it step by step:

  1. You start with row number NewRow and assing that to m
  2. You remove this row m
  3. Now, row m + 1 moved up in the table, and thus becomes the new row number m
  4. You increment m
  5. You compare m with the rowcount
    1. if m is smaller then rowcount, you continue with step 2
    2. else you exit your loop.

Step 3 is crusial, and probably not what you expected. Because after removing row m, you increment m, you are not going to remove the row that moved to row m after your deletion!

There are two simple ways out of this problem. The general solution for avoiding issues with chaning indexes in lists while iterating over such a list, is to iterate backwards: from the last item forward. If you remove an item while iterating backwards, only indexes of items that you have already iterated over will change, and you don’t care about these. In your case, you can also simply not increment m in your loop. That works because you remove all rows after row NewRow, and thus rowCount() will drop to m.

January 12, 2012

aurora aurora
Lab Rat
137 posts

Oh….Thanks a lot Andre….
Ya i tried backword loop….it works fine now….:)
Thank u so much..!!!

 
  ‹‹ how to build Win64 project using Win32 OS.      Trying to change spinboxdelegate example from spinbox to QTextEdit but it dosn’t show ››

You must log in to post a reply. Not a member yet? Register here!