How to Clear a QTableWidget in Python?

Estimated read time 2 min read

In PyQt5, you can clear all the rows in a QTableWidget by using the setRowCount() method and passing it a value of 0. This will remove all the rows from the table, effectively clearing it.

Here’s an example of how to use the setRowCount() method to clear a QTableWidget:

from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem

# Create a new QTableWidget
table_widget = QTableWidget()

# Add some rows and columns to the table
for i in range(5):
    for j in range(3):
        item = QTableWidgetItem(f"Row {i}, Col {j}")
        table_widget.setItem(i, j, item)

# Clear the table by setting the row count to 0

In this example, a QTableWidget is created and some rows and columns are added to it using a loop. The setRowCount() method is then used to clear all the rows from the table by setting the row count to 0.

Note that this method only clears the rows from the table, but it does not clear any column headers or other table settings. If you want to clear the entire table, including column headers, you can use the clearContents() method, like this:


This method clears the contents of all cells in the table, as well as any column headers and other settings, and then sets the row count to 0 to clear all rows.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply