PDA

View Full Version : How to show/draw focus & select at the same time



tanminh
6th November 2006, 17:19
Hi,

I'm having difficulty selecting an item and drawing a focus rect on it at the same time.

What I want to do is: in a single-selection mode tree widget if the last selected item does not pass a test when the user clicks a different item I want to move the selection & focus rect back to the last selected item. The last item can be re-selected without problem, however, the focus rect always seems to stay on the item the user just clicked.

Please help if any of you has done this before.


void MyForm::OnTreeWidgetItemSelectionChangedSlot()
{
. . .

//TreeWidget has single selection mode.
//This slot is in response to the itemSelectionChanged signal.

SelectedItemList = TreeWidget->selectedItems();

if (SelectedItemList.count() > 0)
{
//Get the newly selected item.
Item = SelectedItemList[0];

if (LastItem failed the validation test)
{
//Unselect the newly selected item.
Item->setSelected(false);

//Set the selection & focus back to the last item.
LastItem->setSelected(true);
TreeWidget->setCurrentItem(LastItem);
}
else
{
LastItem = Item;
...
}
}
}

Thanks,
TM

jpn
6th November 2006, 18:15
QAbstractItemView behaves so that when a mouse press event is received, the selection is applied first and then the current index is set afterwards changing the selection. So by the time selection change is informed through signal, QAbstractItemView has not yet set the current index. So what happens here is that still if you change the current item to something else, QAbstractItemView comes and resets it back to the pressed index.

One idea to solve this would be to delay the changing of the current item:


// A QTimer with a timeout interval of 0 will time out as soon as all the events in the window system's event queue have been processed
QTimer::singleShot(0, this, SLOT(setLastItemCurrent()));

void MyForm::setLastItemCurrent()
{
// get "LastItem" somehow or store is as a member variable or something..
TreeWidget->setCurrentItem(LastItem);
}

tanminh
6th November 2006, 21:06
By the way, my interpretation of JPN's comments is no matter what we do in the itemSelectionChanged signal handler Qt will set the current item at the end of the mouse press event (that emitted the itemSelectionChanged signal in the first place). Using that idea I was able to do what I wanted with an additional itemClicked signal handler (whose itemClicked signal is fired at the end of a mouse press event, I think). Perhaps not a good way but it does do what I want. Thanks JPN. TM.