user2738748
user2738748

Reputation: 1116

Which model is the most appriopriate in this case for QTreeView?

I want to display the following data in a QTreeView:

  1. Men:

    Mark

    Steve

    James

  2. Women:

    Ann

    Joyce

    Emily

  3. Female teenagers:

    Rebeca

    Alex

  4. Male teenagers:

    Sam

    Ian

I use the Qt library version 4.8.

I'm wondering, which QAbstractItemModel would is suitabe for it?

It looks to me like I should use the QDirModel - this is how I want my QTreeView to look like. But it's dumb: I won't display strings like directories.

It's quite surprising, but although QTreeView provide the features I need, there is no model that seems suitable for my data.

To make it clear: I need something like a QListWidget with these for items. They should be expandable, so that the user could see the names of people of certain type.

Sorry for the stupid example. How can I do it in Qt?

Upvotes: 1

Views: 403

Answers (1)

Tomas
Tomas

Reputation: 2210

For simple tasks the QTreeWidget (without any external model) is good enough.

QTreeWidget* tree = new QTreeWidget(this);

QTreeWidgetItem* itemMen = new QTreeWidgetItem({"Men"});
QTreeWidgetItem* itemMark = new QTreeWidgetItem({"Mark"});
QTreeWidgetItem* itemSteve = new QTreeWidgetItem({"Steve"});

tree->addTopLevelItem(itemMen);
itemMen->addChild(itemMark);
itemMen->addChild(itemSteve);

If you need more control, use the combination of QStandardItemModel + QTreeView.

QStandardItemModel* model = new QStandardItemModel(this);
model->setRowCount(1); // Top level item count.
model->setColumnCount(1);

QTreeView* tree = new QTreeView(this);
tree->setModel(model);

QStandardItem* itemMen = new QStandardItem("Men");
QStandardItem* itemMark = new QStandardItem("Mark");
QStandardItem* itemSteve = new QStandardItem("Steve");

model->setItem(0, 0, itemMen);
itemMen->setRowCount(2);
itemMen->setColumnCount(0);
itemMen->setChild(0, 0, itemMark);
itemMen->setChild(1, 0, itemSteve);

Edit

With the QTreeView::setRootIsDecorated() you can show or hide the controls for expanding and collapsing top-level items.

Upvotes: 2

Related Questions