How to Select Multiple Items in a List Widget in a Qt Widget Application in C++


In this article, we show how to select multiple items in a list widget in a Qt widget application in C++.

A list widget is a widget that lists various items.

By default, only one item can be selected at a time.

However, we can modify this so that multiple items can be selected at once.

This is shown below.

Selecting multiple items in a list widget in a Qt widget application

Selecting multiple items can allow us to work with multiple things at the same time.

So how can we add the functionality to a list widget to be able to select multiple items simultaneously?

So in order to do this, you simply must add the following the statement, ui->listWidget->setSelectionMode(QAbstractItemView::MultiSelection);, to the "widget.cpp" file.

The contents of this file is shown below.

This statement goes underneath, ui->listWidget->setSelectionMode(QAbstractItemView::MultiSelection);

This then allows us to select multiple items simultaneously in a list widget.

Now how do we retrieve what items were selected?

We can do this by adding the following function to the "widgets.cpp" file. This is shown in the following full code for the "widgets.cpp" file.

In this code, we add a function, on_SelectItemsButton_clicked(), which is triggered when the 'Select Items' button is clicked.

In order to get all of the elements, we need to create a list, which stores these values. This is what we do in the line, QList list= ui->listWidget->selectedItems();

This list is called list. This takes all of the selected items from the list widget whose name attribute is listWidget.

All of the selected items are now stored in this list.

To display these elements, we use a for loop to iterate through this list.

We then use the qDebug() function to show the selected items.

Just to show you how you can separate each selected item, you can set up an if statement that checks to see if an item was selected. We have if statements for each of the items in our list widget to check if each is selected.

And this is how to select multiple items in a list widget in a Qt widget application in C++.

Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...