[SOLVED] QTreeview keyboard behaviour



  • I'm displaying file hierarchies in a QTreeView and usually navigate it with the keyboard. When there are lots of files an a directory, it's very hard to collapse it - you have to scroll up until you hit the parent and hit the "left" key.

    I'm used to the behaviour that hitting left on a "leaf" also collapses its parent. Is there a way to set this behaviour with QTreeView?


  • Moderators

    override the keyPressEvent handler of your tree view:
    @
    void MyTreeView::keyPressEvent(QKeyEvent* event)
    {
    QModelIndex currentIndex = this->currentIndex();
    if( event->key() == Qt::Key_Left && currentIndex.isValid() )
    this->collapse( this->isExpanded( currentIndex ) ? currentIndex : currentIndex.parent() );
    else
    QTreeView::keyPressEvent(event);
    }
    @
    (Not tested though)



  • Thanks a lot - a good and straight forward solution. Why didn't I think of this..?

    There is one issue with the solution - when you hit left now on a "leaf", the current selection vanishes and you're beamed to the root element as soon as you hit another key. The whole behaviour is strange, when you enter the QTreeView with the "Tab" key instead of clicking with the mouse, you need to push "left" twice on leaves to collapse them etc.

    I found that the canonical solution - updating the current element manually to its parent - solves these issues.

    Problem solved - thanks so much!

    Working solution:
    @
    void SirTreeView::keyPressEvent(QKeyEvent* event)
    {
    QModelIndex currentIndex = this->currentIndex();
    if( event->key() == Qt::Key_Left && currentIndex.isValid() )
    {
    if (this->isExpanded( currentIndex ))
    {
    this->collapse(currentIndex);
    } else {
    this->collapse(currentIndex.parent());
    this->setCurrentIndex(currentIndex.parent());
    }
    }
    else
    QTreeView::keyPressEvent(event);
    }
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.