Simon Defontaine
Simon Defontaine

Reputation: 125

Qt 5.5 Build a custom QTreeView

So, I've been trying to use QTreeView to display some classes I've built myself. The idea is, I want to create a tournament manager, and obtain a view as follows:

-Tournament 1

--Team 1

--Team2

---Player 1

---Player 2

-Tournament 2

And so on and so on. I tried reading this tutorial but I didn't understand at all. I currently have 3 classes: Tournament, which contains a QString and a Team QList; Team, which contains a QString and a Player QList; and finally Player which contains a QString. I also read that my class has to inheritate from QAbstractItemModel, but I don't know how to do it.

Any form of help would be greatly appreciated. Thanks !

Upvotes: 1

Views: 173

Answers (1)

Tomas
Tomas

Reputation: 2210

I think that the QStandardItemModel fits your needs and it's much easier to use than deriving your own model from the QAbstractItemModel.

QStandardItem* itemTournament1 = new QStandardItem("Tournament 1");
QStandardItem* itemTeam1 = new QStandardItem("Team 1");
QStandardItem* itemTeam2 = new QStandardItem("Team 2");
QStandardItem* itemPlayer1 = new QStandardItem("Player 1");

QStandardItemModel* model = new QStandardItemModel;
model->setColumnCount(0);
model->appendRow(itemTournament1);

itemTournament1->appendRow(itemTeam1);
itemTournament1->appendRow(itemTeam2);

itemTeam1->appendRow(itemPlayer1);

// etc.

QTreeView* view = new QTreeView;
view->setModel(model);

Edit 1: Adding custom data

enum CustomRoles
{
    LocationRole = Qt::UserRole,
    AnotherDataRole = Qt::UserRole + 1
};

itemTournament1->setData("France", LocationRole);
itemTournament1->setData(12345, AnotherDataRole);

Upvotes: 1

Related Questions