Reputation: 888
I am using QSettings to store a list of pointers to a custom class, but I get a memroy error when I try to read back from the QSettings. I have done the following:
Declare my custom class as metatype:
Q_DECLARE_METATYPE(QCustomAction*)
Q_DECLARE_METATYPE(QList<QCustomAction*>)
Register custom class as metatype and its operator:
qRegisterMetaType<QCustomAction*>("QCustomAction*");
qRegisterMetaTypeStreamOperators<QCustomAction*>("QCustomAction*");
qRegisterMetaType<QList<QCustomAction*>>("QList<QCustomAction*>");
qRegisterMetaTypeStreamOperators<QList<QCustomAction*>>("QList<QCustomAction*>");
Overload Stream Operator:
QDataStream &operator<<(QDataStream &out, QCustomAction* const obj)
{
out << obj->m_actionName << obj->m_lastIndex;
return out;
}
QDataStream &operator>>(QDataStream &in, QCustomAction* obj)
{
in >> obj->m_actionName >> obj->m_lastIndex;
return in;
}
After that, my code compiles without errors and I can save the list by calling:
myQSettings.setValue("ActionsList",QVariant::fromValue<QList<QCustomAction*>>(someList));
The I read the values as:
someList = myQSettings.value("ActionsList").value<QList<QCustomAction*>>();
I get a memory error when I read the value. My guess is that there are some problems witht the overloaded operators. Can anybody give me a clue of what I am doing wrong?
Upvotes: 2
Views: 489
Reputation: 9176
Let me explain.
For example: If you save an int Qt will take an int from you and it will store that int in some way to disk (by operator). On loading on the other hand Qt will create an int, load its value from disk (by operator) and return that int to you.
For your pointers Qt will try to do it the same way: Qt will take a pointer from you and it will store that pointer in some way to disk (by your operator - that accesses the object corresponding to that pointer). On loading on the other hand Qt will create a uninitialized pointer and will try to load its value from disk (by your operator) and to return it to you. However what it would need to do is to create an object to initialize the pointer.
You may not store/load objects by pointer/reference. Always store/load copy-by-value objects only! Try to convert your action into a copy-by-value object and store/load that kind of object.
Upvotes: 2