Question

I'm trying to use QTreeWidget for a file browser. I want to have separate concepts of selection (items to which operations are applied) and cursor (that can be used for extending selection). Like in Total Commander: red is selection, moving cursor doesn't affect selection unless Shift is pressed.

enter image description here

Is there any neat way to implement this with QTreeWidget? Or not neat but at least working and not requiring to manually handle half the events?

Was it helpful?

Solution

If you set the widget's selection mode to QAbstractItemView::ExtendedSelection then an user will be able to navigate through items without changing selection using arrow keys with pressed Ctrl. If you want to change this behavior, you should reimplement keyPressEvent as follows:

void MyWidget::keyPressEvent(QKeyEvent *event) {
  if (event->key() == Qt::Key_Down ||
      event->key() == Qt::Key_Up) {
    event->setModifiers(Qt::ControlModifier);
  }
  QTreeWidget::keyPressEvent(event);
}

Now when user press Up or Down key, the current item is changed and the selection remains unchanged. I've tested this solution.

Note that there are also pageup, pagedown, home, end (and may be other) keys that change the selection by default. You may need to process these events too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top