What is the right way to initialize a QList?

msgmaxim picture msgmaxim · Sep 25, 2013 · Viewed 44.6k times · Source

What is the right way to initialize QList? I want to make this code shorter:

QSplitter splitter;
QList<int> list;
list.append(1);
list.append(1);
splitter.setSizes(list);

But when I use initialization from std::list, it doesn't seem be working:

splitter.setSizes(QList<int>::fromStdList(std::list<int>(1, 1)));

In latter case, the splitter seems to divide in ratio 1:0.

Answer

lpapp picture lpapp · Sep 25, 2013

You could use the following code:

QList<int> list = QList<int>() << 1 << 1;

or initializer list with C++11:

QList<int> list({1, 1});

You can enable the latter with the -std=c++0x or -std=c++11 option for gcc. You will also need the relevant Qt version for that where initializer list support has been added to the QList constructor.