Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all rows from QTableWidget

I am trying to delete all rows from a QTableWidget . Here is what I tried.

for ( int i = 0; i < mTestTable->rowCount(); ++i )
{
    mTestTable->removeRow(i);
}

I had two rows in my table. But this just deleted a single row. A reason could be that I did not create the the table with a fixed table size. The Qt Documentation for rowCount() says,

This property holds the number of rows in the table.

By default, for a table constructed without row and column counts, this property contains a value of 0.

So if that is the case, what is the best way to remove all rows from table?

like image 548
vinayan Avatar asked Apr 06 '13 07:04

vinayan


People also ask

How do I get rid of QTableWidgetItem?

takeItem() sets the view of the item to null , releasing the ownership to the caller. Because of this, the above code in the item's destructor model->removeItem(this); will not be called. This means that you need to manually delete the QTableWidgetItem .


3 Answers

Just set the row count to 0 with:

mTestTable->setRowCount(0);

it will delete the QTableWidgetItems automatically, by calling removeRows as you can see in QTableWidget internal model code:

void QTableModel::setRowCount(int rows)
{
    int rc = verticalHeaderItems.count();
    if (rows < 0 || rc == rows)
        return;
    if (rc < rows)
        insertRows(qMax(rc, 0), rows - rc);
    else
        removeRows(qMax(rows, 0), rc - rows);
}
like image 71
alexisdm Avatar answered Oct 18 '22 02:10

alexisdm


I don't know QTableWidget but your code seems to have a logic flaw. You are forgetting that as you go round the loop you are decreasing the value of mTestTable->rowCount(). After you have removed one row, i will be one and mTestTable->rowCount() will also be one, so your loop stops.

I would do it like this

while (mTestTable->rowCount() > 0)
{
    mTestTable->removeRow(0);
}
like image 30
john Avatar answered Oct 18 '22 02:10

john


AFAIK setRowCount(0) removes nothing. Objects are still there, but no more visible.

yourtable->model()->removeRows(0, yourtable->rowCount());
like image 14
damkrat Avatar answered Oct 18 '22 00:10

damkrat