What is the right way to initialize a QList?

47,942

Solution 1

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.

Solution 2

Never use the QList<int>() << 1 << 1; variant, as it's really slow. use always the list({1, 1}) variant.

source: https://www.angrycane.com.br/en/2018/06/19/speeding-up-cornercases/

Share:
47,942
msgmaxim
Author by

msgmaxim

Updated on July 03, 2020

Comments

  • msgmaxim
    msgmaxim almost 4 years

    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.

  • Thomas Ayoub
    Thomas Ayoub about 10 years
    Using Qt 5.2 it throws error: expected expression QList<int> list2({1, 1});
  • László Papp
    László Papp about 10 years
    @ꜱᴀᴍᴏᴛʜ: you need CONFIG+=c++11.
  • Thomas Ayoub
    Thomas Ayoub about 10 years
    I though it was automatically enabled. Thank you !
  • Jack
    Jack almost 8 years
    What is that () in list({1,1})? it give me an syntax error. Should be QList<int> list {1, 1};?