PDA

View Full Version : Enum To QString Conversion



yagabey
5th March 2012, 14:37
Hello,
I am trying to get text representation of SocketState enum.

In the header of my class i registered the enum:


class QSound;
class SoundNode : public QObject
{
Q_OBJECT
public:
Q_ENUMS(QAbstractSocket::SocketState);

In the source:


QMetaObject metaObject ;
metaObject= QAbstractSocket::staticMetaObject;
QMetaEnum metaEnum = metaObject.enumerator(metaObject.indexOfEnumerator ("SocketState" ) );
QString test(metaEnum.valueToKey(QAbstractSocket::Connecti onRefusedError));
qDebug()<<test;

Here qDebug returns an empty string instead of "ConnectionRefusedError". What is going wrong here, any idea?

Thanks in advance..

wysota
5th March 2012, 14:47
SocketState is not a registered Q_ENUM in QAbstractSocket therefore its meta-object doesn't know anything about it. Registering it in your class might (I haven't checked) put it into your class's meta-object and not QAbstractSocket's.

yagabey
5th March 2012, 14:50
Hello Wysota,

Actually I tried that as seen above:


Q_ENUMS(QAbstractSocket::SocketState);

But not working...

MarekR22
5th March 2012, 14:50
If enum has meta data then it shouldn't be a problem.
Your problem is that you definition of enum in one class QAbstractSocket and you try define those meta data in other class SoundNode (use of Q_ENUMS).
So first try use meta data of you class SoundNode, like this:

QMetaEnum metaEnum = SoundNode::staticMetaObject.enumerator(SoundNode:: staticMetaObject.indexOfEnumerator("QAbstractSocket::SocketState" ) );
Q_ASSERT(metaEnum.isValid());
QString test(metaEnum.valueToKey(QAbstractSocket::Connecti onRefusedError));

wysota
5th March 2012, 14:50
Read my post again.

This simple code can be used to list enums registered with a particular class:


#include <QtCore>
#include <QtGui>

int main() {
const QMetaObject & mo = QListView::staticMetaObject;
qDebug() << "Available enums in" << mo.className() << ":" << mo.enumeratorCount();
int i =0;
QMetaEnum en;
while((en = mo.enumerator(i++)).isValid()) {
qDebug() << en.name();
}
return 0;
}

For QListView it returns:


Available enums in QListView : 13
Shape
Shadow
SelectionMode
SelectionBehavior
ScrollHint
EditTriggers
ScrollMode
DragDropMode
Movement
Flow
ResizeMode
LayoutMode
ViewMode
For QAbstractSocket it doesn't return any enums.

yagabey
5th March 2012, 15:09
This gives, assert error..


Read my post again.


Sorry, i think i am missing something. When i declare:

Q_ENUMS(QAbstractSocket::SocketState);

in SoundNode' s header, doesnt it mean that i register that enum for my class?

wysota
5th March 2012, 15:28
Yes. For your class. Not for QAbstractSocket. Open moc_soundnote.cpp and see what's in there regarding SocketState (you can see there is nothing there because there is no real enum in your class).