Can you iterate over each possible enum value using a Qt foreach loop?
foreach
in Qt is definitely just for Qt containers. It is stated in the docs here.
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;
}
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));
}