How to set the selected item in a QListWidget?

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

QStringList items; items << "All" << "Weekend Plus" ; ui->listWidgetTimeSet->addItems(items); 
+6
source share
2 answers

You can do it as follows:

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

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

Or you do it like this:

 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 this helps.

EDIT:

According to your comment, I suggest using edit triggers to view items. It allows you to add items directly, simply by 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 a QListWidget.

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

See the docs for more information.

If you want to introduce your new item to another location, of course, there is a way. Say you have a line edit, and you add an item with the name you entered there. Now you want ListWidget to add an item to modify this new item. Assuming the new item is at the last position (since it was added last), you can change the current line to the last line. (Note that count() also counts hidden elements, if you have any)

 listWidgetTimeSet->setCurrentRow( listWidgetTimeSet->count() - 1 ); // size - 1 = last item 
+13
source

Can

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

Try also

  ui->listWidgetTimeSet->setCurrentRow(1); 
+6
source

Source: https://habr.com/ru/post/889852/


All Articles