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);
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.
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.
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
Maybe
ui->listWidgetTimeSet->item(1)->setSelected(true);
Try also
ui->listWidgetTimeSet->setCurrentRow(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With