Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum class in QVariant in QSettings

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!

like image 663
CppChris Avatar asked Apr 03 '14 14:04

CppChris


People also ask

Can I declare enum in class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can we define enum inside a class C++?

Although enumerations are probably the most common type that is nested inside a class, C++ will let you define other types within a class, such as typedefs, type aliases, and even other classes!

How do I find the class name of an enum?

Description. The java.lang.Enum.name() method returns the name of this enum constant, exactly as declared in its enum declaration.

What is difference between enum and enum class?

An enum just spills its contents into the enclosing scope, and is basically a const static integer. This means that the first element of any default enum is the same using the == operator. Enum classes have their own scope, and don't pollute the namespace that they are in.


1 Answers

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.

like image 55
finite graygreen Avatar answered Oct 19 '22 00:10

finite graygreen