Let's say I have this flag:
enum MyEnum
{
AAA = 1,
BBB = 2,
CCC = 4,
DDD = 8
};
Q_DECLARE_FLAGS( MyFlags, MyEnum )
Q_FLAG( MyFlags )
How can I test if a value is valid?
i.e. I'd expected -1 or 16 to be invalid.
For enum, this can be achieved with QMetaEnum::valueToKey which returns a nullptr. But for flags, QMetaEnum::valueToKeys always return a byte array, which has a combination of all the flags (it seems so).
Is there a way to check for the validity of a flag?
The implementation looks like a naive AND operation over the enumeration values. So, in the case of -1 (0x FFFF FFFF), the output from QMetaEnum::valueToKeys()
will be AAA|BBB|CCC|DDD
. In the case of 16 (0b 0001 0000), an empty byte array is returned.
One way you can check the validity of the initial value is to convert the returned keys back to value using QMetaEnum::keysToValue()
. If the returned value from QMetaEnum::keysToValue()
is equal to the initial value, the initial value should be valid.
#include "mainwindow.h"
#include <QMetaEnum>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
auto meta_enum = QMetaEnum::fromType<MyFlags>();
int value_before = 17;
QByteArray keys = meta_enum.valueToKeys(value_before);
qDebug() << keys;
int value_after = meta_enum.keysToValue(keys);
qDebug() << value_after;
}
MainWindow::~MainWindow()
{
}
In the code above, for initial value 17 (0b 0001 0001), the returned keys is AAA
, and value_after
is 1