Adding functionality to the Tree Widget

Next, let's move on to the Tree Widget. It is actually not that different from the List Widget. Let's take a look at the following code:

QTreeWidgetItem* treeItem = new QTreeWidgetItem; 
treeItem->setText(0, "My Test Item"); 
ui->treeWidget->addTopLevelItem(treeItem); 

It's pretty much the same as the List Widget, except we have to set the column ID in the setText() function. This is because the Tree Widget is somewhere between a List Widget and a Table Widget—it can have more than one column but can't have any rows.

The most obvious distinction between a Tree Widget and other view widgets is that all its items can contain children items, recursively. Let's look at the following code to see how we can add a child item to an existing item in the Tree Widget:

QTreeWidgetItem* treeItem2 = new QTreeWidgetItem; 
treeItem2->setText(0, "My Test Subitem"); 
treeItem->addChild(treeItem2); 

It's really that simple! The final result looks like this: