How do I set the selected item in a 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);
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);
To set current QList raw with the raw text :
ui->List->setCurrentItem(ui->List->findItems("Raw x Content",Qt::MatchExactly)[0]);
精彩评论