[Qt-interest] Initialize const Qt container class

Julien Cugnière julien.cugniere at gmail.com
Mon Oct 25 17:57:30 CEST 2010


2010/10/25 Joshua Grauman <jnfo-c at grauman.com>
>
> Here's what I'd like to do (with standard c types):
>
> struct item
> {
>   char string[20];
>   int list[10];
> };
>
> //the following is nice and readable, easy to modify, etc.
> const struct item items[4] = {
> {"string1",{1,2,3,5,6,0}},
> {"string2",{4,0}},
> {"string3",{2,5,0}},
> {"",{0}}
> };
>
> This makes it very easy to read and change my data initialization. But I'd
> like to do this with Qt classes (QString and QList<int>) instead.

Most Qt containers have an insertion operator, similar to streams :

const QList<int> list = QList<int>() << 1 << 2 << 15 << 3 << 7;

For complex types it's a bit harder, but still possible :

struct Item {
    Item(QString string, QList<int> list) : string(string), list(list) {}
    QString string;
    QList<int> list;
};

const QList<Item> items = QList<Item>()
    << Item("string1", QList<int>() << 1 << 2 << 3 << 5 << 6)
    << Item("string2", QList<int>() << 4)
    << Item("string3", QList<int>() << 2 << 5);

--
Julien Cugnière




More information about the Qt-interest-old mailing list