12

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
}
Cory Klein
  • 40,647
  • 27
  • 164
  • 222
  • What does the error message say ? `enum` type isn't container like data structure to iterate over it's elements. – Mahesh May 03 '12 at 00:44

3 Answers3

16

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;
}
Andrew Tomazos
  • 58,923
  • 32
  • 156
  • 267
2

foreach in Qt is definitely just for Qt containers. It is stated in the docs here.

Anthony
  • 7,940
  • 2
  • 30
  • 45
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));
    }
lp35
  • 158
  • 1
  • 9