I created a simple class that allows you to select items in a TreeView by typing the name. It keeps track of your keypresses and selects the first Item in the TreeView that matches your input. It works more or less the same as in Finder or Explorer.
.h
#ifndef _TreeViewTypeAheadSelector_
#define _TreeViewTypeAheadSelector_
#include "../headers.h"
class TreeViewTypeAheadSelector : public KeyListener
{
public:
TreeViewTypeAheadSelector();
~TreeViewTypeAheadSelector();
void setTreeView(TreeView* treeView_);
bool keyPressed (const KeyPress& key, Component* originatingComponent);
private:
String search;
uint32_t lastKeyTime;
TreeView* treeView;
};
.cpp
#include "TreeViewTypeAheadSelector.h"
TreeViewTypeAheadSelector::TreeViewTypeAheadSelector()
: treeView(0),
lastKeyTime(0)
{
}
TreeViewTypeAheadSelector::~TreeViewTypeAheadSelector()
{
}
void TreeViewTypeAheadSelector::setTreeView(TreeView* treeView_)
{
if (treeView != 0)
treeView->removeKeyListener(this);
treeView = treeView_;
if (treeView != 0)
treeView->addKeyListener(this);
}
bool TreeViewTypeAheadSelector::keyPressed (const KeyPress& key, Component* originatingComponent)
{
//let treeview handle keypress first, this will handle navigation with arrow keys etc.
if (treeView->keyPressed(key))
{
search = String::empty;
return true;
}
//if the treeview didn't consume the keypress we will use it
uint32_t now = Time::getMillisecondCounter();
if (now - lastKeyTime > 1250) //clear search string when no key has been pressed for 1.25 seconds
search = String::empty;
search += key.getTextCharacter();
lastKeyTime = now;
//try to find the first item that matches the search string
for (int i=0; i<treeView->getNumRowsInTree(); ++i)
{
TreeViewItem* item = treeView->getItemOnRow(i);
if (item != 0)
{
if (item->getUniqueName().startsWithIgnoreCase(search))
{
item->setSelected(true, true);
treeView->scrollToKeepItemVisible(item);
break;
}
}
}
return true;
}
Usage
typeAheadSelectorVideo.setTreeView(fileTreeComponent);
Does anyone ever created some code that allows you to select multiple files/items in a TreeView with the keyboard.
So using Shift and Arrow up and down to select multiple items, shouldn’t be too hard i guess and it would be a nice addition to the TreeView code.