How do I set the selected item in a QListWidget?
Asked Answered
S

3

21

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);
Sherd answered 6/6, 2011 at 8:57 Comment(0)
V
31

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
Vulgar answered 6/6, 2011 at 9:21 Comment(2)
Thanks it's work.Now suppose i have one textbox and when i enter text in that and say add it gets added to listbox now i want that text i have added to listbox that should be selected.Sherd
You have set the current item, rather than the selected item. They are different concepts. The current item is what gets moved by tabbing or cursor actions. Selections are set through the Selection Model.Ghastly
G
11

Maybe

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

Try also

    ui->listWidgetTimeSet->setCurrentRow(1);
Goatee answered 6/6, 2011 at 9:18 Comment(1)
The first one works to me, but the second one doesn't, IDK why. upvotedExperiential
M
1

To set current QList raw with the raw text :

ui->List->setCurrentItem(ui->List->findItems("Raw x Content",Qt::MatchExactly)[0]);
Mediocre answered 17/9, 2022 at 2:40 Comment(1)
This is pretty neat. Straight to the point.Grath

© 2022 - 2024 — McMap. All rights reserved.