QMap only works when declared as a pointer
Hi,
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:
Quote:
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:
Code:
#include <QFileSystemModel>
#include <QMap>
#include <QString>
#include "modellerfile.h"
class ModellerFileModel : public QFileSystemModel
{
Q_OBJECT
public:
explicit ModellerFileModel
(QObject* const parent
= 0);
QVariant headerData
(int section, Qt
::Orientation orientation,
int role
) const;
signals:
public slots:
private:
QMap<QString, QString> m_cache;
};
and this is the method throwing the compile error:
Code:
{
if (!index.isValid())
{
}
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...
Re: QMap only works when declared as a pointer
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.
Re: QMap only works when declared as a pointer
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!!!
Andi
Re: QMap only works when declared as a pointer
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.