Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the selected item in a QListWidget?

Tags:

qt

qlistwidget

I am adding two items to a listwidget using the code below. Now I want to set "Weekend Plus" as selected item in the listwidget, how do I do that?

QStringList items;    
items << "All" << "Weekend Plus" ;   
ui->listWidgetTimeSet->addItems(items);
like image 267
Bokambo Avatar asked Jun 06 '11 08:06

Bokambo


People also ask

How do I clear the QT list widget?

QListWidget has a member named clear(). The docs for this method state: void QListWidget::clear () [slot] Removes all items and selections in the view. Warning: All items will be permanently deleted.

What is QListWidget?

QListWidget is a convenience class that provides a list view similar to the one supplied by QListView , but with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list.


2 Answers

You could either do it like this:

QStringList items;
items << "All" << "Weekend Plus" ;
listWidgetTimeSet->addItems(items);
listWidgetTimeSet->setCurrentRow( 1 );

But that would mean that you know that "Weekend Plus is on second row and you need to remember that, in case you other items.

Or you do it like that:

QListWidgetItem* all_item = new QListWidgetItem( "All" );
QListWidgetItem* wp_item = new QListWidgetItem( "Weekend Plus" );
listWidgetTimeSet->addItem( all_item );
listWidgetTimeSet->addItem( wp_item );
listWidgetTimeSet->setCurrentItem( wp_item );

Hope that helps.

EDIT:

According to your comment, I suggest using the edit triggers for item views. It allows you to add items directly by just typing what you want to add and press the return or enter key. The item you just added is selected and now appears as an item in the QListWidget.

listWidgetTimeSet->setEditTriggers( QAbstractItemView::DoubleClicked ); // example

See the docs for more information.

If you want to enter your new item somewhere else, there is a way of course, too. Let's say you have a line edit and you add the item with the name you entered there. Now you want the ListWidget where the item has been added to change to that new item. Assumed the new item is on the last position (because it has been added last) you can change the current row to the last row. (Note that count() also counts hidden items if you have any)

listWidgetTimeSet->setCurrentRow( listWidgetTimeSet->count() - 1 ); // size - 1 = last item
like image 109
Exa Avatar answered Oct 25 '22 00:10

Exa


Maybe

    ui->listWidgetTimeSet->item(1)->setSelected(true);

Try also

    ui->listWidgetTimeSet->setCurrentRow(1);
like image 37
red1ynx Avatar answered Oct 24 '22 23:10

red1ynx