Important: Please read the Qt Code of Conduct -

Converting object to string

  • What do I need to provide to be able to convert my object to a string in something like console.debug? At the moment, printing out my QObjectList gives me @KeyValue(0x196bdc0),KeyValue(0x18f8d40),KeyValue(0x18f90e0),KeyValue(0x1955d40)@
    I'd like to convert that to
    @KeyValue(0x196bdc0, Key="A", Value=1),KeyValue(0x18f8d40, Key="B", Value=2),KeyValue(0x18f90e0, Key="C", Value=3),KeyValue(0x1955d40, Key="D", Value=4)@

  • Moderators

    In QML and C++, I often add ::toString() method to various classes to make them print well and easy. You can probably do the same, although it's hard to be exact without seeing your code.

  • So is that an explicit call?
    In my example above I have a QObjectList model of KeyValue classes. Basically just pairs. The output I got was by doing

    I'm guessing to produce something similar I'd have to loop and print item.toString then.

    Or to go off on a tangent I'm wondering if the javascript interpreter has some default stringify method that can be overridden similar to Rubys "inspect": method

  • Moderators

    I'm no expert on JavaScript, sorry.

    Yes, your thinking on .tsoString() is correct.

  • If you need the toString-method only for quick debugging in QML you can use a JS loop to go though the object and print all properties with their values in most cases. or write a special function if you want to print only some properties of course.

    It sometimes sucks that JS only prints [Object object] for objects by default :D
    here my solution:
    // register this function once
    Object.prototype.print = function() {
    for (var p in this) {
    var v = this[p]
    if (typeof v === "object")
    else if (typeof v !== "function")
    console.log(p, v)

    // instead of console.log(obj) use
    that will recursively print all properties with their values to the console. That is just a simple JS function, you can modify that to your liking and print what you want. :)

    of course you can also write a c++ function and call it from QML if you prefer that.

  • Best method for me:


    JSON global object is part of ES5(EcmaScript 5), it's in core JS functionality.

  • Is there an easy way to print QML object by JavaScript?

    The following code does not work, and no response after being executed.

    import QtQuick 2.1
    import QtQuick.Controls 1.0

    ApplicationWindow {
    id: root
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    menuBar: MenuBar {
        Menu {
            title: qsTr("File")
            MenuItem {
                text: qsTr("Exit")
                onTriggered: Qt.quit();
    Text {
        id: mytext
        text: qsTr("Hello World")
        anchors.centerIn: parent
    Component.onCompleted: {


  • Happened here too. Probably you should submit a bug report.
    Doesn't happen to cpp exported object or js object

Log in to reply