How to set an item in a QListWidget as initially highlighted?
Asked Answered
D

1

6

I am using QT 5.2 and Have a QListWidget witch displays a list of Strings and I want the first item (at 0) to be initially set to be highlighted. I tried the following:

mUi->listWidget->setCurrentRow(0);
    mUi->listWidget->setCurrentItem(mUi->listWidget->item(0),QItemSelectionModel::Select);
    mUi->listWidget->currentItem()->setSelected(true);
    mUi->listWidget->selectionModel()->select(mUi->listWidget->model()->index(0,0, QModelIndex()),QItemSelectionModel::Select); 

Even if the if the item is selected it is not highlighted. If ofcourse I navigate to the item using mouse (click) or keyboard (tab key) it is highlighted but I want it to be highlighted initially without using mouse or keyboard. How to do it? Thanks in advance.

Decarburize answered 14/4, 2014 at 16:21 Comment(2)
It's been a moment I did not code in Qt, but I feel that you need to refresh your UI in some way. The highlighting action has been push on the stack and calling a refresh will force the action to be called. I think you can use qApp.refresh (something like this), but it might be overkill and there probably is a more elegant solutionMidstream
No, it was not focused. using mUi->listWidget->setFocus(); worked. thanksDecarburize
S
9

You just need to set focus to the list:

if (ui->listWidget->count() > 0) {
  ui->listWidget->item(0)->setSelected(true);
}
ui->listWidget->setFocus();
Sudoriferous answered 14/4, 2014 at 21:51 Comment(2)
Yah, setFocus() sloved the problem. Thanks.Decarburize
using listwidget->item(pos)->setSelected(true) was useful for me when i was iterating through a list of scripts in a list as an interactive progress indicator using "pos" as an index.Wayfarer

© 2022 - 2024 — McMap. All rights reserved.