How do I populate values of a static QMap in C++ Qt?

Di Zou picture Di Zou · Nov 16, 2011 · Viewed 34k times · Source

I have this in my C++ header file:

#include <QMap>
#include <QString>

class LogEvent {

public:
    LogEvent();

    enum column_t {TIMESTAMP_COLUMN = 0, TYPE_COLUMN = 1, EVENT_COLUMN = 2,
        FILE_COLUMN = 3};
    static QMap<column_t, QString> COLUMN_NAMES;

    static QMap<column_t, QString> getColumnNames() {
        return LogEvent::COLUMN_NAMES;
    }

    //blah blah blah other functions
};

This is my C++ source file:

#include "LogEvent.h"

LogEvent::LogEvent()
{
    //constructor code
}

//blah blah blah other functions

I want to add values to my static QMap COLUMN_NAMES. Where and how would I do this?

Answer

Luchs picture Luchs · Feb 15, 2015

In the meantime, Qt 5.2 added support for C++11 initializer lists in QMap:

QMap::​QMap(std::initializer_list<std::pair<Key, T> > list)

This means you can initialize your map like this:

static QMap<QString, int> my_map{{"a", 1}, {"b", 2}, {"c", 3}};