Question

I have a problem with enum classes, QVariants and the QSettings class. There are enum class values that I want to store within a QVariant which goes into a QSettings instance. So, my code actually looks something like this:

enum class Foo
{
    Bar1, Bar2
}
Q_ENUMS(Foo)
Q_DECLARE_METATYPE(Foo)

...

Foo value = Bar2;
QSettings settings;
settings.setValue(QString("Foo"), QVariant::fromValue(value));

At this point in executing the code, an assertion jumps in and complains:

ASSERT failure in QVariant::save: "Invalid type to save", file kernel\qvariant.cpp

Searching the internet, I found out that the class is missing a fitting << and >> operator. But that is not an option for enum classes. I even tried to use

qRegisterMetaType<Foo>("Foo");

but it did not help. Maybe you have some other suggestions/solutions for me. Thanks!

Was it helpful?

Solution

Enums, which are masked unsigned ints, seem to be a problem, see

Qt4 QSettings save enumeration value (for example Qt::CheckState)

The solution there and probably here would be to convert it an unsigned. To check if the static_cast-result back to the enum is valid you might add Foo_lowest and Foo_highest values to the beginning and end of the enum range.

OTHER TIPS

You can use Q_ENUM since Qt 5.5 and not worry about calling qRegisterMetaType():

enum class Foo
{
    Bar1, Bar2
}
Q_ENUM(Foo)

...

Foo value = Foo::Bar2;
QSettings settings;
settings.setValue(QString("Foo"), QVariant::fromValue(value));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top