Let Qt models meet std::vector>

Datetime:2016-08-23 04:22:28          Topic: Qt           Share

The problem

So. I was stuck with a container of tuples that I wanted to see in a Qt view (QTableView, QtQuick ListView or similar). So how to do that?

Another problem: I haven’t been doing fun things with templates recently.

A solution?

After a bit of hacking, it seems like it can just be done like

typedef std::tuple<std::string, QString> Element;
typedef std::vectorList;
Listlist = { std::make_tuple("first", "second"), 
              std::make_tuple("third", "fourth");
std::unique_ptr<TableModel> magic = createTableModel(list);
QTableViewview;
view.setModel(magic->model());

and … tada:

Of course, we are also QtQuick friendly

std::unique_ptr<ListModel>List>> magic = createListModel(list);
// expose magic->model() to your quickview

and a delegate containing the following

Text {
    text: role0
}
Text {
    text: role1
}

can give:

But enough about creation.

Whattabout manipulation?

Luckily we got you covered. Insert two extra rows at position 1?

autolines = { std::make_tuple("extra", "extra"),
              std::make_tuple("extra2","extra2") };
magic->insertRows(1,lines.begin(), lines.end());

Append a row?

magic->appendRow(std::make_tuple("",""));

Remove 2 rows at position 3?

magic->removeRow(3,2);

Replace the underlying list?

ListnewList;
// fill list
magic->reset(newList);

Read-only looping over the elements?

for(const Element& e : magic->list())
{
    ...
}

The Qt model of course also accepts setData calls.

Future?

If anyone is interested I will polish the code a bit and publish it. If that’s the case, how should I name this thing?

And I did get around doing fun things with templates again.





About List