PDA

View Full Version : How can we convert enum to int?



learning_qt
26th January 2010, 15:33
Hello,

I defined an enum, But I hope I can use it as an int in some functions. for example, like getValue(int(enum))?
How can we achieve this?

Thanks

Archimedes
26th January 2010, 15:48
Lets say you have
enum nu { "ZERO", "ONE", TWO" }
The values for the enum constants if you don't specify them are:
ZERO = 0
ONE = 1
TWO = 2
and so on...

This is legal in C++
int i = ONE;
and equal with
int i = 1;

ecanela
26th January 2010, 16:08
Qt has a powerfull introspection system. using QMetaObject can access to all data generated for MOC.
enums, properties, signals and slots declared in the class

the follow code get the the values of the enum ViewportAnchor in the class QGraphicsView



#include <QApplication>
#include <QMetaEnum>
#include <QMetaType>
#include <QGraphicsView>
#include <qDebug>


int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QGraphicsView * examples = new QGraphicsView;

const QMetaObject * dataObject = examples->metaObject();

//get the index of the "ViewportAnchor" enum in the dataObject
int indexViewport = dataObject->indexOfEnumerator("ViewportAnchor");
QMetaEnum enumData = dataObject->enumerator(indexViewport);

qDebug() << "Values of enum " << enumData.name();
for (int x = 0; x < enumData.keyCount(); ++x)
qDebug() << enumData.valueToKey(x);

return a.exec();
}



for use this system in our class in necesary use the macro Q_ENUMS.


class MyClass : public QObject
{
Q_OBJECT
Q_ENUMS(Priority)

public:
MyClass(QObject *parent = 0);
~MyClass();

enum Priority { High, Low, VeryHigh, VeryLow };
void setPriority(Priority priority);
Priority priority() const;
};


the previus post resolved the question,

i read wrong the question. but i hope someone find the post useful.

sorry my poor english