13

We have a simple piece of code in our application:

void tAccessPoint::OnStateChanged(QAbstractSocket::SocketState state)
{
    qDebug() << m_ID << " " << state;

For reasons that aren't important here I was attempting to replace the use of qDebug so I used the code from this post C++ format macro / inline ostringstream. But I was surprised to find that when I do this state no longer appears as a text value but rather as a numeric value. qDebug() seems to know what the name of the enum value is rather than just the value. How does it do this, and can I do the same in my code?

Community
  • 1
  • 1
parsley72
  • 8,449
  • 8
  • 65
  • 98

2 Answers2

21

There is no moc magic here, QtNetwork defines explicitly the operator in network/socket/qabstractsocket.h:

QDebug operator<<(QDebug debug, QAbstractSocket::SocketState state) {
    switch (state) {
    case QAbstractSocket::UnconnectedState:
        debug << "QAbstractSocket::UnconnectedState";
        break;
    case QAbstractSocket::HostLookupState:
        debug << "QAbstractSocket::HostLookupState";
        break;
    case QAbstractSocket::ConnectingState:
        debug << "QAbstractSocket::ConnectingState";
        break;
    case QAbstractSocket::ConnectedState:
        debug << "QAbstractSocket::ConnectedState";
        break;
    case QAbstractSocket::BoundState:
        debug << "QAbstractSocket::BoundState";
        break;
    ...
    return debug;
}

But you can use QDebug to send the data to a QString inside your function:

 QString output;
 QDebug(&output) << ...
Pamputt
  • 173
  • 1
  • 11
alexisdm
  • 29,448
  • 6
  • 64
  • 99
10

Maybe this enum to QString convert can be useful :

const QMetaObject & mo = QAbstractSocket::staticMetaObject;
QMetaEnum me = mo.enumerator(mo.indexOfEnumerator("SocketState"));
QString test(me.valueToKey(QAbstractSocket::UnconnectedState));
Amin Kh.
  • 131
  • 2
  • 7
  • 2
    This looks like a very useful technique. Unfortunately, not all enums are registered with moc. For example, QProcess::ProcessError is just an ordinary C++ enum, so no support for converting it to a name :( – tbleher May 31 '13 at 08:22