Given an enum:
enum AnEnum { Foo, Bar, Bash, Baz };
Can you iterate over each of these enums using Qt's foreach loop?
This code doesn't compile (not that I expected it to...)
foreach(AnEnum enum, AnEnum)
{
// do nothing
}
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement. If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.
An enumerated type, or enum, is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type. Enums are incredibly useful when portraying status, options, or modes that are exclusive within a grouping.
There is a much simpler version for retrieving the QMetaEnum object (Qt 5.5 and above):
QMetaEnum e = QMetaEnum::fromType<QLocale::Country>();
QStringList countryList;
for (int k = 0; k < e.keyCount(); k++)
{
QLocale::Country country = (QLocale::Country) e.value(k);
countryList.push_back(QLocale::countryToString(country));
}
If it is moced into a QMetaEnum than you can iterate over it like this:
QMetaEnum e = ...;
for (int i = 0; i < e.keyCount(); i++)
{
const char* s = e.key(i); // enum name as string
int v = e.value(i); // enum index
...
}
http://qt-project.org/doc/qt-4.8/qmetaenum.html
Example using QNetworkReply which is a QMetaEnum:
QNetworkReply::NetworkError error;
error = fetchStuff();
if (error != QNetworkReply::NoError) {
QString errorValue;
QMetaObject meta = QNetworkReply::staticMetaObject;
for (int i=0; i < meta.enumeratorCount(); ++i) {
QMetaEnum m = meta.enumerator(i);
if (m.name() == QLatin1String("NetworkError")) {
errorValue = QLatin1String(m.valueToKey(error));
break;
}
}
QMessageBox box(QMessageBox::Information, "Failed to fetch",
"Fetching stuff failed with error '%1`").arg(errorValue),
QMessageBox::Ok);
box.exec();
return 1;
}
foreach
in Qt is definitely just for Qt containers. It is stated in the docs here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With