FipS
FipS

Reputation: 427

How to configure QTreeView to preserve multiple selection when moving using the arrow keys

I'm using QTreeView with selectionMode set to ExtendedSelection. I'd like to change the default behavior that clears selected items each time an arrow key is used to change the current item (focus).

Is it possible to set it up so that when I use an arrow key to navigate, the selection keeps and only the current item (focus) changes (in the same way as it works when using Ctrl+Arrow). I would basically need to swap the behavior of (Arrow vs. Ctrl+Arrow), or just us Ctrl+Arrow-like behavior even when Ctrl is not pressed.

Is that possible?

Thanks, FipS

Upvotes: 3

Views: 1409

Answers (1)

Chris
Chris

Reputation: 17535

This is a good question, as the functions you need to use are a bit obscure. You're going to have to subclass QTreeView and override the keyPressEvent() function. This should get you on the right track:

class MyTree : public QTreeWidget
{
    Q_OBJECT

    protected:

        void keyPressEvent( QKeyEvent *event )
        {   
            if( event->key() == Qt::Key_Up )
            {   
                selectionModel()->setCurrentIndex( indexAbove(currentIndex()), QItemSelectionModel::NoUpdate );
            }   
            else if( event->key() == Qt::Key_Down )
            {   
                selectionModel()->setCurrentIndex( indexBelow(currentIndex()), QItemSelectionModel::NoUpdate );
            }   
            else
            {   
                QTreeWidget::keyPressEvent( event );
            }   
        }   
};

Upvotes: 2

Related Questions