PDA

View Full Version : Selecting items in a QTreeWidget with the keyboard



Berryblue031
18th May 2011, 11:56
In my QTreeWidget I have hooked up the itemClicked(QTreeWidgetItem*, int) to a slot onClicked(QTreeWidgetItem*, int) this works perfect for detecting selection with the mouse.

I would like to allow keyboard navigation selection of my QTreeWidget, but I can't find a similar signal for when I select items via the keyboard (i.e. press space when the item has focus). Is there a signal I am overlooking that fires when items are selected via the keyboard and passes a pointer to the selected item?

Berryblue031
18th May 2011, 12:55
As an update I implemented the following solution, though I still find it odd that there was no built in mechanism (that I could find anyways)




//I was already inheriting QTreeWidget
//because this is a special built tree that I use in multiple places
class ProductTreeWidget: public QTreeWidget
{
...
};

void ProductTreeWidget::keyPressEvent(QKeyEvent* event)
{
QTreeWidget::keyPressEvent(event);
switch (event->key())
{
case Qt::Key_Space:
case Qt::Key_Select:
if(currentItem())
{
emit QTreeWidget::itemClicked(currentItem(), 0);
}
}
}



If anybody can see any obvious flaws to this approach pls post :)

Vlada
19th June 2013, 10:12
Well, this is on old thread, however not solved satisfactorily. You chose an overly complicated solution which I believe is not completely reliable. The easiest and most correct is to hook to QTreeView::selectionModel() signal called currentChanged(QModelIndex,QModelIndex). Example: connect(myTreeView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(myTreeSelectionChanged(QModelIndex)));

I am using QTreeView but QTreeWidget would be the same because it inherits from QTreeView. This solution works for me without any problems. Anyway you might also need to explore other signals of the selectionModel, they might be of some use for you.