Your Search Bar For Shrewd Tips

How Do I Clear Qlistwidget?


To clear a QListWidget, call its clear() method. This removes every item from the widget, along with the current selection. In C++, use listWidget->clear();; in PyQt or PySide, use list_widget.clear(). Clearing a list is straightforward, but the best approach can depend on whether you want to remove all items, only selected items, or just the selection. This guide explains the common options, shows working examples, and covers a few mistakes to avoid.

The Quick Answer: Call clear()

The standard way to clear a Qt QListWidget is to call its clear() function. After the call, the widget contains no items and displays an empty list.

listWidget->clear();

In Python with PyQt or PySide, the equivalent is:

list_widget.clear()

For example, a button’s clicked handler can clear the list when a user requests it. The exact way you connect the button depends on your application, but the operation itself is the same in Qt Widgets: call clear() on the list widget instance you want to empty.

The method is useful for resetting a list before loading new data, removing temporary results, or responding to a “Clear” button. You do not need to loop through every item just to empty the widget. The clear() method handles removing the contents in one call.

Clearing a QListWidget in C++

In a C++ Qt Widgets application, call clear() on the pointer to your QListWidget. For example, if your widget is named listWidget, the call is:

listWidget->clear();

A typical slot might look like this:

void MainWindow::on_clearButton_clicked()
{
    ui->listWidget->clear();
}

Here, ui->listWidget refers to a list widget created in the Qt Designer interface. If you created the widget in code, call clear() on that object instead. Make sure the pointer refers to a valid widget before calling the method.

After clearing, the list widget remains available and can be populated again. For instance, you can add new items later with addItem() or addItems(). Clearing the contents does not remove the widget itself from the window or permanently disable it.

Clearing a QListWidget in PyQt or PySide

In PyQt and PySide, use the same method name without parentheses around a pointer. The following example clears a widget named list_widget:

list_widget.clear()

To connect a button to a clear action, you can connect its clicked signal to the method:

self.clear_button.clicked.connect(self.list_widget.clear)

You can also use a small handler if you want to perform additional work when the list is cleared:

def clear_list(self):
    self.list_widget.clear()
    self.status_label.setText("List cleared")

This pattern is helpful when the application needs to update a status message, reset related controls, or log the user’s action. If you only need to empty the widget, connecting the button directly to clear is simpler.

What Does QListWidget.clear() Remove?

Calling clear() removes all items from the QListWidget. It also clears the selection because there are no remaining items to select. The widget itself stays in place, and its general configuration—such as its size, appearance, and enabled state—remains unchanged.

One important detail is that QListWidget owns the items added to it. When clear() removes those items, Qt deletes them. If your code stores a pointer or reference to a particular item, do not use that pointer after clearing the list. It may refer to an object that no longer exists.

For example, this is unsafe if item is used after the call:

QListWidgetItem *item = listWidget->item(0);
listWidget->clear();
// Do not access item here.

If you need information from an item, copy the value you need before clearing. In Python, avoid keeping and later relying on references to items that have been removed from the widget. When in doubt, retrieve the data again after repopulating the list.

Clear All Items or Clear Only the Selection?

The word “clear” can mean different things in a user interface. Use QListWidget::clear() when you want to remove every item. If you only want to deselect items while leaving them visible, use clearSelection() instead.

listWidget->clearSelection();

In PyQt or PySide:

list_widget.clearSelection()

These methods have different results:

  • clear() removes all items from the list.
  • clearSelection() keeps the items but removes their selected state.
  • setCurrentRow(-1) clears the current item or row, but does not remove the other items.

Choose the method that matches the intended action. If a user clicks “Deselect,” clearing the entire widget would be surprising. If the action is “Remove All,” clearing only the selection would not achieve the expected result.

Remove Selected Items Instead of Clearing Everything

Sometimes you want users to delete only the items they selected. In that case, do not call clear(), because it removes every item. In C++, you can retrieve the selected items and delete them one at a time:

const auto selectedItems = listWidget->selectedItems();

for (QListWidgetItem *item : selectedItems) {
    delete listWidget->takeItem(listWidget->row(item));
}

takeItem() removes an item from the widget and returns it without deleting it. The example deletes the returned item, preventing it from being left without an owner. Copying the list of selected item pointers before modifying the widget also avoids changing the selection collection while iterating over it.

In Python, a similar approach is:

for item in list_widget.selectedItems():
    row = list_widget.row(item)
    list_widget.takeItem(row)

In Python bindings, the returned item is typically managed through the binding’s ownership rules. If you need to preserve a removed item, keep the returned object and handle it deliberately. For ordinary “delete selected” behavior, removing each selected row is usually sufficient.

Clear and Then Repopulate the List

A common use for clear() is refreshing a list with new results. Clear the old items first, then add the updated ones. In C++, you can use addItems() with a list of strings:

listWidget->clear();
listWidget->addItems(newNames);

In PyQt or PySide, the same pattern looks like this:

self.list_widget.clear()
self.list_widget.addItems(names)

If your data is already represented by a collection of objects, loop through it and create a QListWidgetItem for each entry. For example, you may display a friendly label while storing an identifier in the item’s data. Clear the old widget items before adding the new set so stale results are not left visible.

For a large number of updates, consider temporarily disabling updates to reduce unnecessary repainting. In C++, for example:

listWidget->setUpdatesEnabled(false);
listWidget->clear();
listWidget->addItems(newNames);
listWidget->setUpdatesEnabled(true);

Use this optimization only when it is useful, and ensure updates are turned back on even if your code can exit early. For more complex or frequently changing data, a model-based view such as QListView with a suitable model may be a better fit than managing many individual list-widget items.

Check Whether the QListWidget Is Empty

After clearing a list, you may want to check whether it contains any items before showing a message or enabling another control. In C++, check the count:

if (listWidget->count() == 0) {
    // The list is empty.
}

In PyQt or PySide:

if self.list_widget.count() == 0:
    print("The list is empty")

The count() method returns the number of items currently in the widget. It is a direct way to test for an empty list and is also useful before selecting a row or accessing an item by index.

Common Mistakes When Clearing a QListWidget

  • Using the wrong method: Call clear() to remove items, not clearSelection(). The latter only deselects them.
  • Keeping item pointers after clearing: Items removed by clear() are deleted. Do not access old item pointers afterward.
  • Clearing the wrong widget: Confirm that the variable or UI object refers to the list you intend to empty.
  • Using a loop unnecessarily: For removing every item, a single clear() call is simpler than repeatedly deleting rows.
  • Forgetting to repopulate: If clearing is part of a refresh operation, make sure the code that adds updated data runs as intended.
  • Confusing the widget with its data source: Clearing a QListWidget removes its displayed items. It does not automatically erase separate data stored in your own collection, database, or file.

That last point matters when the list is only a visual representation of application data. If you clear the widget but leave the original data unchanged, the list may reappear the next time your application reloads from that source. Update the underlying data separately if the user’s action is meant to delete the actual records, not merely clear the display.

Conclusion

To clear a QListWidget, call clear(): use listWidget->clear(); in C++ or list_widget.clear() in PyQt and PySide. This removes all list items and their selection while leaving the widget ready to use again. Use clearSelection() when you only want to deselect items, and remove selected rows individually when you want to delete only part of the list. Keep in mind that cleared items are removed, so avoid using old item pointers afterward and update any separate data source as needed.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →