View Full Version : QMap only works when declared as a pointer

10th February 2013, 10:46

I have a very weird problem with a QMap of the type QMap<QString, QString>(). When I add this as a member to a class, I am not able to add anything to it, I always get the following compile error:

filemodel.cpp:32: error: passing 'const QMap<QString, QString>' as 'this' argument of 'QMap<Key, T>::iterator QMap<Key, T>::insert(const Key&, const T&) [with Key = QString; T = QString]' discards qualifiers [-fpermissive]

When I declare it a pointer member (e.g. QMap<QString, QString> *m_cache), it works.
I don't understand what is wrong, because I use this kind of map in other classes as well, without defining a pointer type.

The only difference is that this class is derived from a QFileSystemModel, but I can't believe that this is the cause for the compile error.

Here is my header file:

#include <QFileSystemModel>
#include <QMap>
#include <QString>

#include "modellerfile.h"

class ModellerFileModel : public QFileSystemModel
explicit ModellerFileModel(QObject* const parent = 0);

int columnCount(const QModelIndex &parent=QModelIndex()) const;
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;

QModelIndex setRootPath(const QString &path);


public slots:

QMap<QString, QString> m_cache;

and this is the method throwing the compile error:

QVariant ModellerFileModel::data(const QModelIndex &index, int role) const
if (!index.isValid())
return QVariant();

QFileInfo fi = fileInfo(index);

if (!m_cache.contains(fi.absoluteFilePath()))
ModellerFile* mfile = new ModellerFile(fi.absoluteFilePath());
if (mfile->isValid())
m_cache.insert(fi.absoluteFilePath(), mfile->name());



The weird thing is, that if I create a map object inside the method for testing purposes, the insert() method of this temporary map works perfectly fine.
Why can't I define the member variable the way I do now, why does it only compile as a pointer type?

I don't understand the problem...

10th February 2013, 10:53
The function is declared as const: ModellerFileModel::data(const QModelIndex &index, int role) const and it modifies state of the object (the map that is part of the object), to fix it you can drop const from function definition (because it's misleading) or add mutable to the QMap declaration (so that it can be modified in const member functions), the correct solution is the first one.

10th February 2013, 10:59
This seems to work, but then the original data() method of the QFileSystemModel doesn't seem to get overwritten. I will try the mutable keyword. Thanks for your quick answer!!!


10th February 2013, 11:12
Yes, you have to keep the const (signatures must match) if you override that member function so you will have to use mutable or your first solution.