[SOLVED] QList<customObcject> saved with QSettings
There is similar topic on the forum LINK but the guy found out different solution.
Im trying to save data using QSettings QList<recipe>. I've read that I need to use Q_DECLARE_METATYPE( Type) I deleted unnecesary data.
Here is my recipe.h
class recipe { public: recipe(); recipe(const recipe &obj); ~recipe(); }; // 1) Q_DECLARE_METATYPE(recipe) //recipe.cpp #include "recipe.h" recipe::recipe() { } recipe::recipe( const recipe &obj) { } recipe::~recipe() { }
When I uncomment 1) I have an error: D:\Projects\FoodBook\recipe.cpp:3: error: expected constructor, destructor, or type conversion before 'Q_DECLARE_METATYPE'
Q_DECLARE_METATYPE(recipe).
What is it that I do wrong? or how would any of you save List of custom class objects to be loaded at startup??
Thanks for your support.
- Charlie_Hdz last edited by
Well, First at all, Q_DECLARE_METATYPE is about the MetaObject System of Qt,this mean that your object "recipe" must be a QObject to work.
- Chris Kawa Moderators last edited by
@Charlie_Hdz No, it doesn't have to be a QObject.
@Michal You don't seem to include <QMetaType> in your header. That's probably it.
This works for me:
#ifndef RECIPE_H #define RECIPE_H #include <QMetaType> class recipe { public: recipe(); recipe(const recipe &obj); ~recipe(); }; Q_DECLARE_METATYPE(recipe) #endif // RECIPE_H
Of course! didn't know macros need includes...thanks!
recipe newRecipe; newRecipe.setName("NotConverted"); qDebug() << "BeforeConvName: " << newRecipe.Name(); QVariant variant = QVariant::fromValue(newRecipe); if(variant.canConvert<recipe>()) { qDebug() << "Can Convert"; recipe anotherNewRecipe = variant.value<recipe>(); qDebug()<<"AfterConvName:"<<anotherNewRecipe.Name(); }
anotherNewRecipe's name shows result: "" . Why?
And by the way, another question:
Why does the customObject (in this case recipe) can't be created dynamically?
If I do so, there is an error and It will not go through.
Some help under the LINK regarding MetaType.
- Chris Kawa Moderators last edited by
Why?
Because your copy constructor does not copy anything?
If I do so, there is an error and It will not go through
What does the error say?
error: invalid application of 'sizeof' to incomplete type 'QStaticAssertFailure<false>' enum {Q_STATIC_ASSERT_PRIVATE_JOIN(q_static_assert_result, __COUNTER__) = sizeof(QStaticAssertFailure<!!(Condition)>)}
I have just read that: Values of a registered type can be constructed dynamically via QMetaType::construct()
There is an example in the link above. Thanks for your help! I will figure it out, still missing pure c++ knowledge ;)