Search code examples
c++qtqstringqtcoreqdebug

Printing Qt variables


I'm programming in Qt, but I'm more accustomed to PHP.

So with that in mind, how do I 'echo' or 'print' out the contents of a QStringList or QString to ensure the contents are as expected?

I'm building a GUI application. Is there anyway to print the contents?

Obviously in PHP, you can print_r on an array, is there anything similar for a QStringList? And echo a variable, again, anything similar to QString?

I can provide code if needs be.

Thanks.


Solution

  • main.cpp

    #include <QStringList>
    #include <QDebug>
    
    int main()
    {
        QStringList myStringList{"Foo", "Bar", "Baz"};
        qDebug() << myStringList;
        QString myString = "Hello World!";
        qDebug() << myString;
        return 0;
    }
    

    main.pro

    TEMPLATE = app
    TARGET = print-qstringlist
    QT = core
    CONFIG += c++11
    SOURCES += main.cpp
    

    Build and Run

    qmake && (n)make
    

    Output

    ("Foo", "Bar", "Baz")
    "Hello World!"
    

    If you need to drop the noisy brackets and double quotes generated by qDebug, you are free to either use QTextStream with custom printing or simply fall back to the standard cout with custom printing.