Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you iterate over each possible enum value using a Qt foreach loop?

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
}
like image 476
Cory Klein Avatar asked May 03 '12 00:05

Cory Klein


People also ask

How do I iterate over an enum?

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.

Can we iterate over enum in C++?

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.

What is enum in Qt?

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.


3 Answers

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));
    }
like image 119
lp35 Avatar answered Oct 08 '22 11:10

lp35


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;
}
like image 16
Andrew Tomazos Avatar answered Oct 12 '22 01:10

Andrew Tomazos


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

like image 2
Anthony Avatar answered Oct 12 '22 00:10

Anthony