PDA

View Full Version : How to Initialise Static QMap?



ChrisW67
10th February 2010, 08:22
Hi All,

I'm hoping this is not too obvious a question. A static QList can be initialised outside of any method:


class A {
public:
A();
...
private:
static QList<int> m_list;
static QMap<int,QString> m_map;
...
}
and in the cpp file


A::A() { }
...
QList<int> A::m_list = QList<int>() << 1 << 2 << 4;
...
but I cannot see a similar way to initialise the QMap. Can it be done or is it a job for the constructor?

Regards,
Chris W

boudie
10th February 2010, 15:54
You have to do something like this:


m_map.insert(1, "Yo");
m_map.insert(2, "Yes");

ChrisW67
11th February 2010, 00:36
Thanks boudie. That way of loading the map would have to happen inside the class constructor or a method.

rawfool
20th June 2013, 11:43
@ ChrisW67, Did you figure it out how it's done ? I bumped here while searching for the same.
Thank you.

Santosh Reddy
20th June 2013, 13:13
One way is to write a custom class to do so, but yes it is not obvious


// file.h
template <typename Key, typename Value>
class Map : public QMap<Key, Value>
{
public:
Map() : QMap<Key, Value>() { }

Map<Key, Value>& operator()(const Key & key, const Value & value)
{
this->insert(key, value);
return *this;
}
};

class A
{
public:
A()
{
qDebug() << m_list;
qDebug() << m_map;
}
private:
static QList<int> m_list;
static QMap<int, QString> m_map;
};

// file.cpp file
QList<int> A::m_list = QList<int>() << 1 << 2 << 4;
QMap<int, QString> A::m_map = Map<int, QString>()(1, QString("1"))(2, QString("2"))(4, QString("4"));


You could also do it with << operator.