比如,想获得socket的状态枚举文字,

如何打印Qt中的枚举所对应的字符串-LMLPHP

代码如下:

    QMetaObject mo=QAbstractSocket::staticMetaObject;
int index=mo.indexOfEnumerator(QString("SocketState").toLatin1().data());
QMetaEnum socketStatusEnum = mo.enumerator(index);
qDebug()<<socketStatusEnum.keyCount();
for (int i=; i<socketStatusEnum.keyCount(); ++i)
{
qDebug()<<socketStatusEnum.key(i);
}

输出为:

Starting F:\exercise\build-untitled19-Desktop_Qt_5_4_0_MinGW_32bit-Debug\debug\untitled19.exe...

UnconnectedState
HostLookupState
ConnectingState
ConnectedState
BoundState
ListeningState
ClosingState

当想要输出当前socket的状态的时候,可以看下面代码

QTcpSocket *socket=new QTcpSocket;
QAbstractSocket::SocketState socketState=socket->state(); const QMetaObject & mo = QAbstractSocket::staticMetaObject;
QMetaEnum me = mo.enumerator(mo.indexOfEnumerator("SocketState"));
qDebug()<<me.valueToKey(socketState);

输出为

Starting F:\exercise\build-untitled10-Desktop_Qt_5_4_0_MinGW_32bit-Debug\debug\untitled10.exe...
UnconnectedState

转自:http://blog.csdn.net/u012199908/article/details/50325571

05-22 12:07