Can you iterate over each possible enum value using a Qt foreach loop?
c++, enums, foreach, qt
Solution
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;
}
Problem
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 } ```