Wt  4.10.4
Treelist example

In this example we will step through the code of the Tree List example. The source code of the entire example is available as leaves of the tree. Note that Wt offers a Tree List widget as part of the library (see WTreeNode), of which this example is a stripped down version.

The example in particular demonstrates the use of stateless slot learning to simultaneously implement client-side and server-side event handling in C++.

The tree is constructed as a hierarchy of tree nodes. A single tree node is implemented in the class TreeNode. TreeNode uses the helper class IconPair for rendering icons that have a state (such as the expand/collapse icons). We start with a walk-over of this class.

IconPair: a pair of icons that reflects state.

For the implementation of the tree list expand/collapse icons, as well as the label icons (such as the folder icon), we use the IconPair class. It takes a pair of icons and shows only one at a time. Passing clickIsSwitch = true to the constructor will make the icon react to click events to switch the current icon.

This is the class definition of IconPair:

class IconPair : public WCompositeWidget
IconPair(const std::string icon1URI, const std::string icon2URI,
bool clickIsSwitch = true);
void setState(int num);
int state() const;
WImage *icon1() const { return icon1_; }
WImage *icon2() const { return icon2_; }
void showIcon1();
void showIcon2();
WContainerWidget *impl_;
WImage *icon1_;
WImage *icon2_;
EventSignal<WMouseEvent> *icon1Clicked;
EventSignal<WMouseEvent> *icon2Clicked;
int previousState_;
void undoShowIcon1();
void undoShowIcon2();

IconPair is a composite widget, implemented as a WContainerWidget which contains two WImage objects. The class defines two slots: IconPair::showIcon1() and IconPair::showIcon2(), which show the respective icon, while hiding the other icon.

Although Wt is a C++ (server-side) library, it can also generate client-side JavaScript code for instant visual response. This example will use this capability to implement all of the tree navigation at the client-side for those clients that support JavaScript – as if it were implemented as a JavaScript library. But since everything is still plain C++ code, it works regardless of what technology is available or lacking at the client side. Think of a stateless slot implementation as creating a forked implementation, with JavaScript in the client for visual response – when JavaScript is available, and C++ at the server. When no JavaScript is available, everything happens at the server.

The key concept behind Wt's capability to implement things at the client-side is stateless slot implementations. A stateless slot is, besides a normal C++ function that may be connected to a signal, a C++ function that promises to always have the same behaviour (until it is reset, as we will see later).

This applies to the two functions showIcon1() and showIcon2(), as they simply set the corresponding icon, irrespective of any application state. The library offers two methods for stateless slot implementations: AutoLearned and PreLearned. An AutoLearned stateless slot will only "become client-side" after the first invocation. Applied to our tree widget, this would mean that the first click on any icon would require a round-trip to the server the first time only. An AutoLearned stateless slot simply requires an indication that the particular slot confirms to the contract of being stateless. A PreLearned stateless slot, on the other hand, is "client-side" from the first invocation. To implement a PreLearned stateless however, we need to do some extra work by providing methods that exactly undo the effect of the slot. We provide here two such undo methods: undoShowIcon1() and undoShowIcon2().

Enough talk! Let's look at the implementation, starting with the constructor.

IconPair::IconPair(const std::string icon1URI, const std::string icon2URI,
bool clickIsSwitch)
: WCompositeWidget(),
auto impl = std::make_unique<WContainerWidget>();
impl_ = impl.get();
icon1_ = impl_->addWidget(std::make_unique<WImage>(icon1URI));
icon2_ = impl_->addWidget(std::make_unique<WImage>(icon2URI));
icon1Clicked = &icon1_->clicked();
icon2Clicked = &icon2_->clicked();

IconPair inherits from WCompositeWidget. A composite widget is a widget which is composed from other widgets, in a way not exposed in its API. In this way, you may later change the implementation without any problem.

Notice how we constructed three widgets that are used in the implementation: two images (icon1_ and icon2_), and a container (impl_) to hold them. The images are added to the container by passing the container as the last argument in their constructor.

WCompositeWidget requires to set the implementation widget, which is in our case a WContainerWidget:


We declare the slots showIcon1() and showIcon2() as stateless slots, allowing for client-side optimisation, and offer an undo function which facilitates a PreLearned client-side implementation.

The calls to WObject::implementStateless() state that the slots showIcon1() and showIcon2() are stateless slots, and their visual effect may be learned in advance. The effect of these statements is merely an optimization. Any non-visual effects of these slots are still propagated and executed, as expected.

implementStateless(&IconPair::showIcon1, &IconPair::undoShowIcon1);
implementStateless(&IconPair::showIcon2, &IconPair::undoShowIcon2);

Next, we declare the widget to be an inline widget. An inline widget will be layed out following the natural flow of text (left to right). This does not really matter for our example, since TreeNode will do the layout with a WTable, but we do so to provide consistency with a WImage which is also inline by default.


The initial state is to show the first icon:


To react to click events, we connect signals with slots:

if (clickIsSwitch) {
icon1_->clicked().connect(icon1_, &WImage::hide);
icon1_->clicked().connect(icon2_, &WImage::show);
icon2_->clicked().connect(icon2_, &WImage::hide);
icon2_->clicked().connect(icon1_, &WImage::show); //
void hide()
Hides the widget.
Definition: WWidget.C:195
void show()
Shows the widget.
Definition: WWidget.C:201

We change the cursor to a pointer to hint that clicking these icons may do something useful.

} //
@ PointingHand
Pointing hand, CSS 'pointer' cursor.

We also change the cursor to a pointer to hint that clicking these icons will in fact perform an action.

The rest of the class definition is:

void IconPair::setState(int num)
if (num == 0) {
} else {
int IconPair::state() const
return (icon1_->isHidden() ? 1 : 0);
void IconPair::showIcon1()
previousState_ = (icon1_->isHidden() ? 1 : 0);
void IconPair::showIcon2()
previousState_ = (icon1_->isHidden() ? 1 : 0);
void IconPair::undoShowIcon1()
void IconPair::undoShowIcon2()
} //

Note the implementations of undoShowIcon1() and undoShowIcon2(): they simply, but accurately, reset the state to what it was before the respective showIcon1() and showIcon2() calls.

TreeNode: an expandable tree node.

TreeNode contains the implementation of the tree, as a hierarchy of tree nodes. The layout of a single node is done using a 2x2 WTable:

| +/- | label           |
|     | child1          |
|     | child2          |
|     | child3          |
|     |       ...       |

The TreeNode manages a list of child nodes in a WContainerWidget which will be hidden and shown when the node is expanded or collapsed, and children are collapsed when the node is expanded.

This is the TreeNode class definition:

class TreeNode : public WCompositeWidget
TreeNode(const std::string labelText,
TextFormat labelFormat,
std::unique_ptr<IconPair> labelIcon);
void addChildNode(std::unique_ptr<TreeNode> node);
void removeChildNode(TreeNode *node, int index);
const std::vector<TreeNode *>& childNodes() const { return childNodes_; }
void collapse();
void expand();
std::vector<TreeNode *> childNodes_;
TreeNode *parentNode_;
WTable *layout_;
IconPair *expandIcon_;
WImage *noExpandIcon_;
IconPair *labelIcon_;
WText *childCountLabel_;
WContainerWidget *expandedContent_;
void adjustExpandIcon();
bool isLastChildNode() const;
void childNodesChanged();
bool wasCollapsed_;
void undoCollapse();
void undoExpand();
enum ImageIndex { Middle = 0, Last = 1 };
static std::string imageLine_[];
static std::string imagePlus_[];
static std::string imageMin_[];
}; //
Enumeration that indicates the text format.
Definition: WGlobal.h:715
@ Middle
Middle button.

The public interface of the TreeNode provides methods to manage its children, and two public slots to expand or collapse the node. Remember, a slot is nothing more than a method (and the public slots: does not actually mean anything, except providing a hint to the user of this class that these methods are made to be connected to signals).

We start with the implementation of the constructor:

TreeNode::TreeNode(const std::string labelText,
TextFormat labelFormat,
std::unique_ptr<IconPair> labelIcon)
: parentNode_(nullptr),

We start with declaring stateless implementations for the slots. It is good practice to do this first, since it must be done before any connections are made to the slots.

// pre-learned stateless implementations ...
implementStateless(&TreeNode::expand, &TreeNode::undoExpand);
implementStateless(&TreeNode::collapse, &TreeNode::undoCollapse);

We will implement the treenode as 2 by 2 table.

We create all icons. Since currently the node is empty, we only show the no-expand version (which is simply a horizontal line).

The expanded content is a WContainerWidget.

We create the label and child count text widgets:

Now we add all widgets in the proper table cell, and set the correct alignment.

Finally, we connect the click events of the expandIcon to the expand and collapse slots.

WTable::elementAt(int row, int column) is used repeatedly to add or modify contents of the table cells, expanding the table geometry as needed. Finally, we make connections from the expand and collapse icons to the slots we define in the TreeNode class.

Again, we optimize the visual effect of expand() and collaps() in client-side JavaScript, which is possible since they both have an effect independent of application state. Typically, one will start with a default dynamic slot implementation, and indicate stateless implementations where desired and possible, using one of the two mechanisms of stateless slot learning.

The "business logic" of the TreeNode is simply to manage its children. Whenever a child is added or removed, adjustments to its look are updated by calling childNodesChanged().

The expand icon of the last child is rendered differently, as it needs to terminate the vertical guide line. To keep the implementation simple, we simply let every child reset its proper look by calling adjustExpandIcon().

When getting a first child, or losing the last child, the expand icon changes too.

We also update the childCount label.

Finally, we call WObject::resetLearnedSlots(). Because the expand() slot depends on the number of children, because it needs to collapse all children – this slot is not entirely stateless, breaking the contract for a stateless slot. However, we can get away with still implementing as a stateless slot, by indicating when the state has changed.

The implementation of the collapse slot is as follows:

First we record the current state, so the undo method can exactly undo what happened.

Next, we implement the actual collapse logic:

Similarly, the implementation of the expand slot. However, in this case we need to collapse all children as well.

Since we implement these slots as prelearned stateless slots, we also need to define the undo functions. Note that Because expand() also collapses all child nodes, the undo function of expand() is not simply collapse() and vice-versa.

Finally, the adjustExpandIcon() function sets the correct images, which depends on how the node relates to its siblings. The last node looks a bit different.

We set the expand icon images:

Then, we set the vertical guide line if not the last child, and nothing if the last child:

Finally, we select the correct icon, depending on whether the node has children:

And that's it. By using the TreeNode class in a hierarchy, we can create a tree widget. The tree widget will be implemented entirely in JavaScript, if available, and otherwise as plain HTML. In any case, client-side and server-side state are completely synchronized, and identical by definition since they are derived from the same C++ code.