phoenix_title wx.lib.agw.customtreectrl

The customtreectrl module contains the CustomTreeCtrl class which mimics the behaviour of TreeCtrl, with some more enhancements.

Description

CustomTreeCtrl is a class that mimics the behaviour of TreeCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn tree control. Apart of the base functionalities of CustomTreeCtrl (described below), in addition to the standard TreeCtrl behaviour this class supports:

  • CheckBox-type items: checkboxes are easy to handle, just selected or unselected state with no particular issues in handling the item’s children;

  • Added support for 3-state value checkbox items;

  • RadioButton-type items: since I elected to put radiobuttons in CustomTreeCtrl, I needed some way to handle them, that made sense. So, I used the following approach:

    • All peer-nodes that are radiobuttons will be mutually exclusive. In other words, only one of a set of radiobuttons that share a common parent can be checked at once. If a radiobutton node becomes checked, then all of its peer radiobuttons must be unchecked.

    • If a radiobutton node becomes unchecked, then all of its child nodes will become inactive.

  • Hyperlink-type items: they look like an hyperlink, with the proper mouse cursor on hovering;

  • Multiline text items (note: to add a newline character in a multiline item, press Shift + Enter as the Enter key alone is consumed by CustomTreeCtrl to finish the editing and Ctrl + Enter is consumed by the platform for tab navigation);

  • Enabling/disabling items (together with their plain or grayed out icons);

  • Whatever non-toplevel widget can be attached next to an item;

  • Possibility to horizontally align the widgets attached to tree items on the same tree level.

  • Possibility to align the widgets attached to tree items to the rightmost edge of CustomTreeCtrl;

  • Default selection style, gradient (horizontal/vertical) selection style and Windows Vista selection style;

  • Customized drag and drop images built on the fly;

  • Setting the CustomTreeCtrl item buttons to a personalized imagelist;

  • Setting the CustomTreeCtrl check/radio item icons to a personalized imagelist;

  • Changing the style of the lines that connect the items (in terms of wx.Pen styles);

  • Using an image as a CustomTreeCtrl background (currently only in “tile” mode);

  • Adding images to any item in the leftmost area of the CustomTreeCtrl client window.

  • Separator-type items which are simply visual indicators that are meant to set apart or divide tree items, with the following caveats:

    • Separator items should not have children, labels, data or an associated window;

    • You can change the color of individual separators by using SetItemTextColour, or you can use SetSeparatorColour to change the color of all separators. The default separator colour is that returned by SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT);

    • Separators can be selected just like any other tree item;

    • Separators cannot have text;

    • Separators cannot have children;

    • Separators cannot be edited via the EVT_TREE_BEGIN_LABEL_EDIT event.

  • Ellipsization of long items when the horizontal space is low, via the TR_ELLIPSIZE_LONG_ITEMS style (New in version 0.9.3);

  • Tooltips on long items when the horizontal space is low, via the TR_TOOLTIP_ON_LONG_ITEMS style (New in version 0.9.3).

  • Hiding items

And a lot more. Check the demo for an almost complete review of the functionalities.

Base Functionalities

CustomTreeCtrl supports all the TreeCtrl styles, except:

  • TR_EXTENDED: supports for this style is on the todo list (am I sure of this?).

Plus it has 3 more styles to handle checkbox-type items:

  • TR_AUTO_CHECK_CHILD: automatically checks/unchecks the item children;

  • TR_AUTO_CHECK_PARENT: automatically checks/unchecks the item parent;

  • TR_AUTO_TOGGLE_CHILD: automatically toggles the item children.

And two styles you can use to force the horizontal alignment of all the widgets attached to the tree items:

  • TR_ALIGN_WINDOWS: aligns horizontally the windows belonging to the item on the same tree level.

  • TR_ALIGN_WINDOWS_RIGHT: aligns to the rightmost position the windows belonging to the item on the same tree level.

And two styles related to long items (with a lot of text in them), which can be ellipsized and/or highlighted with a tooltip:

  • TR_ELLIPSIZE_LONG_ITEMS: ellipsizes long items when the horizontal space for CustomTreeCtrl is low (New in version 0.9.3);

  • TR_TOOLTIP_ON_LONG_ITEMS: shows tooltips on long items when the horizontal space for CustomTreeCtrl is low (New in version 0.9.3);.

All the methods available in TreeCtrl are also available in CustomTreeCtrl.

Usage

Usage example:

import wx
import wx.lib.agw.customtreectrl as CT

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "CustomTreeCtrl Demo")

        # Create a CustomTreeCtrl instance
        custom_tree = CT.CustomTreeCtrl(self, agwStyle=wx.TR_DEFAULT_STYLE)

        # Add a root node to it
        root = custom_tree.AddRoot("The Root Item")

        # Create an image list to add icons next to an item
        il = wx.ImageList(16, 16)
        fldridx     = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, (16, 16)))
        fldropenidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, (16, 16)))
        fileidx     = il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, (16, 16)))

        custom_tree.SetImageList(il)

        custom_tree.SetItemImage(root, fldridx, wx.TreeItemIcon_Normal)
        custom_tree.SetItemImage(root, fldropenidx, wx.TreeItemIcon_Expanded)

        for x in range(15):
            child = custom_tree.AppendItem(root, "Item %d" % x)
            custom_tree.SetItemImage(child, fldridx, wx.TreeItemIcon_Normal)
            custom_tree.SetItemImage(child, fldropenidx, wx.TreeItemIcon_Expanded)

            for y in range(5):
                last = custom_tree.AppendItem(child, "item %d-%s" % (x, chr(ord("a")+y)))
                custom_tree.SetItemImage(last, fldridx, wx.TreeItemIcon_Normal)
                custom_tree.SetItemImage(last, fldropenidx, wx.TreeItemIcon_Expanded)

                for z in range(5):
                    item = custom_tree.AppendItem(last,  "item %d-%s-%d" % (x, chr(ord("a")+y), z))
                    custom_tree.SetItemImage(item, fileidx, wx.TreeItemIcon_Normal)

        custom_tree.Expand(root)


# our normal wxApp-derived class, as usual

app = wx.App(0)

frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()

app.MainLoop()

Events

All the events supported by TreeCtrl are also available in CustomTreeCtrl, with a few exceptions:

  • EVT_TREE_GET_INFO (don’t know what this means);

  • EVT_TREE_SET_INFO (don’t know what this means);

  • EVT_TREE_ITEM_MIDDLE_CLICK (not implemented, but easy to add);

  • EVT_TREE_STATE_IMAGE_CLICK (no need for that, look at the checking events below).

Plus, CustomTreeCtrl supports the events related to the checkbutton-type items:

  • EVT_TREE_ITEM_CHECKING: an item is being checked;

  • EVT_TREE_ITEM_CHECKED: an item has been checked.

And to hyperlink-type items:

  • EVT_TREE_ITEM_HYPERLINK: an hyperlink item has been clicked (this event is sent after the EVT_TREE_SEL_CHANGED event).

Single and Multiple Selection

If the TR_MULTIPLE style is not set (default) the tree will be in single selection mode where there is always one item selected. When an item is selected a EVT_TREE_SEL_CHANGING event is sent which can be vetoed to prevent the selection from occuring. A EVT_TREE_SEL_CHANGED event is sent out when the selection has successfully changed. If the selection gets cleared by the user or programmatically, the next Idle handler will select the root item ensuring there is a selected item at all times.

If the TR_MULTIPLE style is set the tree can have any number of selected items and can also have no selection.

Drag and Drop

A simplified drag and drop is available and can be initiated by calling event.Allow on the EVT_TREE_BEGIN_DRAG or EVT_TREE_BEGIN_RDRAG events. When the event handler returns, a wx.DragImage of the item will be generated and the user can drag it to other items within the tree. When the user releases the drag button a EVT_TREE_END_DRAG event will be sent and event.GetItem can be called to find out which item the drag ended at. This simplified method is best when only a single item at a time needs to be dragged (i.e. TR_MULTIPLE not set) and only for dragging items within the tree control.

Alternately, the normal wxPython drag/drop can be invoked in the EVT_TREE_BEGIN_DRAG handler in which a wx.DropSource must be generated, followed by a call to DoDragDrop which will block until the drag is finished. This is much more flexible but more complicated to implement.

Note

The class value _DRAG_TIMER_TICKS controls how long the mouse must linger before the drag can start. It defaults to 250 milliseconds which can be far too long for today’s quick ‘swiping’ generation. It can be lowered for a more responsive drag.

Item Windows

Windows and controls can be added to any tree item. This is done with the SetItemWindow. Note that parent of the window/control must be set to the CustomTreeCtrl. The tree then owns the window and will show or hide it with the item it belongs to. The window can be removed with DeleteItemWindow upon which the window is destroyed.

Enabling or disabling the item with EnableItem will also enable or disable its associated window. Alternatively the window itself can be enabled or disabled with SetItemWindowEnabled.

By default item windows are shown immediately after the item text. If the TR_ALIGN_WINDOWS style is set, all windows for a level of the tree will be aligned to the longest text in that level. The TR_ALIGN_WINDOWS_RIGHT style will instead right-align all windows added to the tree.

Keyboard focus in the tree can be difficult to manage once windows are added. Most platforms will shift focus to an item window any time the tree gets focus. This can prevent keyboard control of the tree, or cause the tree to jump uncontrollably to an item with a window when it regains focus. This is due to the tree being based off wx.ScrolledWindow. In the future this may be changed to wx.ScrolledCanvas instead.

Note

On Windows platforms (Windows 7 or newer using Aero theme) it is not recommended to add more than about 1000 windows to the tree. This can cause dramatic slowdowns with the Desktop Window Manager process (dwm.exe) even if the windows are hidden.

Supported Platforms

CustomTreeCtrl has been tested on the following platforms:
  • Windows (Windows XP);

  • GTK (Thanks to Michele Petrazzo);

  • Mac OS (Thanks to John Jackson).

Window Styles

This class takes in a regular wxPython style and an extended agwStyle. The style can be used with normal wxPython styles such as wx.WANTS_CHARS while the agwStyle specifies the behavior of the tree itself. It supports the following agwStyle flags:

Window agwStyle Flags

Hex Value

Description

wx.TR_DEFAULT_STYLE

varies

The set of flags that are closest to the defaults for the native control for a particular toolkit. Should always be used.

wx.TR_NO_BUTTONS

0x0

For convenience to document that no buttons are to be drawn.

wx.TR_SINGLE

0x0

For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.

wx.TR_HAS_BUTTONS

0x1

Use this style to show + and - buttons to the left of parent items.

wx.TR_NO_LINES

0x4

Use this style to hide vertical level connectors.

wx.TR_LINES_AT_ROOT

0x8

Use this style to show lines between root nodes. Only applicable if TR_HIDE_ROOT is set and TR_NO_LINES is not set.

wx.TR_TWIST_BUTTONS

0x10

Use old Mac-twist style buttons.

wx.TR_MULTIPLE

0x20

Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.

wx.TR_HAS_VARIABLE_ROW_HEIGHT

0x80

Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.

wx.TR_EDIT_LABELS

0x200

Use this style if you wish the user to be able to edit labels in the tree control.

wx.TR_ROW_LINES

0x400

Use this style to draw a contrasting border between displayed rows.

wx.TR_HIDE_ROOT

0x800

Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.

wx.TR_FULL_ROW_HIGHLIGHT

0x2000

Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.

Styles from customtreectrl:

TR_EXTENDED

0x40

Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).

TR_AUTO_CHECK_CHILD

0x4000

Only meaningful for checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.

TR_AUTO_TOGGLE_CHILD

0x8000

Only meaningful for checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.

TR_AUTO_CHECK_PARENT

0x10000

Only meaningful for checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.

TR_ALIGN_WINDOWS

0x20000

Flag used to align windows (in items with windows) at the same horizontal position.

TR_ALIGN_WINDOWS_RIGHT

0x40000

Flag used to align windows (in items with windows) to the rightmost edge of CustomTreeCtrl.

TR_ELLIPSIZE_LONG_ITEMS

0x80000

Flag used to ellipsize long items when the horizontal space for CustomTreeCtrl is low.

TR_TOOLTIP_ON_LONG_ITEMS

0x100000

Flag used to show tooltips on long items when the horizontal space for CustomTreeCtrl is low.

The wx.TR_HAS_VARIABLE_LINE_HEIGHT style should be set if item rows might not all be the same height. This can happen if certain rows have a larger font size, multi-line text, or windows added to them. This style will automatically adjust each item’s height to be just big enough to show its contents.

When the wx.TR_HAS_VARIABLE_LINE_HEIGHT is not set, adding a new item with multi-line text or with a window specified will throw an exception. However the tree won’t prevent you from adding multiline text with SetItemText or assigning a window with SetItemWindow to an existing item. It’s generally a bad idea to do either of these without this style as it will result in an ugly tree. By default the wx.TR_HAS_VARIABLE_LINE_HEIGHT is not set. This means that all item rows will use the same height. This is the height of the largest item in the tree. If an item with a larger height is added or revealed, ALL row heights will increase to this larger size. The larger row height remains persistent even if the large items are hidden or deleted. You must call CalculateLineHeight to reset the row height. This somewhat bizarre behavior is why the wx.TR_HAS_VARIABLE_LINE_HEIGHT style is almost always used.

Events Processing

This class processes the following events:

Event Name

Description

EVT_TREE_BEGIN_DRAG

Begin dragging with the left mouse button.

EVT_TREE_BEGIN_LABEL_EDIT

Begin editing a label. This can be prevented by calling Veto.

EVT_TREE_BEGIN_RDRAG

Begin dragging with the right mouse button.

EVT_TREE_DELETE_ITEM

Delete an item.

EVT_TREE_END_DRAG

End dragging with the left or right mouse button.

EVT_TREE_END_LABEL_EDIT

End editing a label. This can be prevented by calling Veto.

EVT_TREE_GET_INFO

Request information from the application (not implemented in CustomTreeCtrl).

EVT_TREE_ITEM_ACTIVATED

The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.

EVT_TREE_ITEM_CHECKED

A checkbox or radiobox type item has been checked.

EVT_TREE_ITEM_CHECKING

A checkbox or radiobox type item is being checked.

EVT_TREE_ITEM_COLLAPSED

The item has been collapsed.

EVT_TREE_ITEM_COLLAPSING

The item is being collapsed. This can be prevented by calling Veto.

EVT_TREE_ITEM_EXPANDED

The item has been expanded.

EVT_TREE_ITEM_EXPANDING

The item is being expanded. This can be prevented by calling Veto.

EVT_TREE_ITEM_GETTOOLTIP

The opportunity to set the item tooltip is being given to the application (call TreeEvent.SetToolTip).

EVT_TREE_ITEM_HYPERLINK

An hyperlink type item has been clicked.

EVT_TREE_ITEM_MENU

The context menu for the selected item has been requested, either by a right click or by using the menu key.

EVT_TREE_ITEM_MIDDLE_CLICK

The user has clicked the item with the middle mouse button (not implemented in CustomTreeCtrl).

EVT_TREE_ITEM_RIGHT_CLICK

The user has clicked the item with the right mouse button.

EVT_TREE_KEY_DOWN

A key has been pressed.

EVT_TREE_SEL_CHANGED

Selection has changed.

EVT_TREE_SEL_CHANGING

Selection is changing. This can be prevented by calling Veto.

EVT_TREE_SET_INFO

Information is being supplied to the application (not implemented in CustomTreeCtrl).

EVT_TREE_STATE_IMAGE_CLICK

The state image has been clicked (not implemented in CustomTreeCtrl).

License And Version

CustomTreeCtrl is distributed under the wxPython license.

Latest Revision: Helio Guilherme @ 09 Aug 2018, 21.35 GMT

Version 2.8

function_summary Functions Summary

BisectChildren

Find index of last child whose Y position is before the given y.

ChopText

Chops the input text if its size does not fit in max_size, by cutting the

DrawTreeItemButton

Draw the expanded/collapsed icon for a tree control item.

EnsureText

Make sure the given text is valid, converting if necessary.

EventFlagsToSelType

Translate the key or mouse event flag to the type of selection we

MakeDisabledBitmap

Creates a disabled-looking bitmap starting from the input one.


class_summary Classes Summary

CommandTreeEvent

CommandTreeEvent is a special subclassing of CommandEvent.

CustomTreeCtrl

CustomTreeCtrl is a class that mimics the behaviour of TreeCtrl, with almost the

DragImage

This class handles the creation of a custom image in case of item drag

GenericTreeItem

This class holds all the information and methods for every single item in

TreeEditTimer

Timer used for enabling in-place edit.

TreeEvent

CommandTreeEvent is a special class for all events associated with tree controls.

TreeFindTimer

Timer used to clear the CustomTreeCtrl _findPrefix attribute if no

TreeItemAttr

Creates the item attributes (text colour, background colour and font).

TreeTextCtrl

Control used for in-place edit.


Functions

BisectChildren(children, y)

Find index of last child whose Y position is before the given y.

Performs a binary search yielding quick results even for very large lists. The implementation is derived from the bisect module. It is used to speed up Paint, HitTest, and Refresh operations by reducing their work to children[n:len(children)] items, where n is the returned index of this search.

Parameters:
  • children (list) – a Python list containing GenericTreeItem objects to search.

  • y (integer) – the logical Y coordinate to look for. This is usually the start of the visible client area (e.g. self.CalcUnscrolledPosition(0, 0)[1]).

Returns:

The integer index before the first item in children whose Y position is on or after y. This will be 0 if children is empty.

Added in version 2.8.



ChopText(dc, text, max_size)

Chops the input text if its size does not fit in max_size, by cutting the text and adding ellipsis at the end.

Parameters:
  • dc – a wx.DC device context;

  • text – the text to chop;

  • max_size – the maximum size in which the text should fit.

Note

This method is used exclusively when CustomTreeCtrl has the TR_ELLIPSIZE_LONG_ITEMS style set.

Added in version 0.9.3.



DrawTreeItemButton(win, dc, rect, flags)

Draw the expanded/collapsed icon for a tree control item.

Parameters:
  • win – an instance of wx.Window;

  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the client rectangle where to draw the tree item button;

  • flags (integer) – contains wx.CONTROL_EXPANDED bit for expanded tree items.

Note

This is a simple replacement of RendererNative.DrawTreeItemButton.

Note

This method is never used in wxPython versions newer than 2.6.2.1.



EnsureText(text)

Make sure the given text is valid, converting if necessary.

This conversion is done as a courtesy for the user, otherwise bad text in the tree will throw a UnicodeDecodeError in calls to dc.GetMultiLineTextExtent() and the tree will not draw correctly and behave bizarrely. This is a frustrating behavior and not clear what causes the issue when it happens.

Parameters:

text – The object to turn into valid text.

Returns:

The text, unmodified if it was valid, converted otherwise.

Added in version 2.8.



EventFlagsToSelType(style, shiftDown=False, ctrlDown=False)

Translate the key or mouse event flag to the type of selection we are dealing with.

Parameters:
  • style (integer) – the main CustomTreeCtrl window style flag;

  • shiftDown (bool) – True if the Shift key is pressed, False otherwise;

  • ctrlDown (bool) – True if the Ctrl key is pressed, False otherwise;

Returns:

A 3-elements tuple, with the following elements:

  • is_multiple: True if CustomTreeCtrl has the TR_MULTIPLE flag set, False otherwise;

  • extended_select: True if the Shift key is pressend and if CustomTreeCtrl has the TR_MULTIPLE flag set, False otherwise;

  • unselect_others: True if the Ctrl key is pressend and if CustomTreeCtrl has the TR_MULTIPLE flag set, False otherwise.



MakeDisabledBitmap(original)

Creates a disabled-looking bitmap starting from the input one.

Parameters:

original – an instance of wx.Bitmap to be greyed-out.

Returns:

An instance of wx.Bitmap, containing a disabled-looking representation of the original item image.