Important: Please read the Qt Code of Conduct -

How to insert a newline character in QString and display it using qDebug()?

  • Hi,
    I want to insert a '-' char at every 4th Position in a QString, and a newline at every 80th Position to Display it with qDebug().
    The following code does not work, it insersts "\n" as normal string. I tried QChar('\n'), only '\n' or "\n" but without success.
    How to do that?


        QString reply = QString(CommandsList[i].Reply.toHex()).toUpper(); // reply contains hex characters
        for(unsigned j=4;j < reply.size(); j=j+5)
                reply.insert(j, QString("\n"));
                reply.insert(j, QChar('-'));
        qDebug() << reply;

  • Moderators

    How to do that?

    You are already doing it. The problem is not in the string. It's how you're viewing it. qDebug() is meant for debugging. It escapes the non-text characters in case you want to see what they are. If you want to see the text in a formatted way use qDebug().noquote() or the std output stream.
    For example:

    QString s = "hi\thello";
    qDebug() << s;             //prints "hi\thello"
    qDebug().noquote() << s;   //prints hi	hello

    Oh, and please don't use qDebug() for output in production code. It's not Qt's replacement of standard streams. What and how it outputs may change in the future. It did actually lately and it caused a major discussion on the mailing list because people were using it for regular output instead of just debugging.

  • Thank you! It works now as expected. And I use it only for debug purposes.

Log in to reply