7

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!

CppChris
  • 1,226
  • 9
  • 14

2 Answers2

3

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.

Community
  • 1
  • 1
  • You are right, this is a problem with enums in QVariants. My original implementation was saving the actual (unsigned) integer values in the QVariant. Now I tried the scoped enums, but I ran into this problem with QVariants. However, I switched back to the original implementation with your trick of lowest/highest values in the enum. Thanks. – CppChris Apr 07 '14 at 08:43
0

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));
parsley72
  • 8,449
  • 8
  • 65
  • 98