Passing QByteArray to a callable QJSValue



  • What is the correct way to pass a QByteArray as a parameter to a callable QJSValue?

    Assuming data is binary format.

    QString title = "Intro";
    QByteArray byteArray;
    // read from file into byteArray
    
    QJSValueList args;
    args << title;
    args << byteArray;
    callback.call(args);
    

    The javascript function will be subsequently be passing this to a C++ function for processing.

    Should i be doing this?

    QString title = "Intro";
    QByteArray byteArray;
    // read from file into byteArray
    
    QJSValueList args;
    args << title;
    args << QString::fromLatin1(byteArray.data(), payload.size());
    callback.call(args);
    


  • workaround:

    1. convert QByteArray to QString(base64 encoded)
    2. decode that string on qml/js side
    QByteArray ba = ...;
    QString encoed(ba.toBase64());
    QJSValueList params { QJSValue(encoed)};
    callback.call(params);
    

    waiting for better anser :)



  • In the event that anyone else comes across this looking for a solution (like I was), Qt 5 and above can convert QByteArray to a Javascript ArrayBuffer.
    To do this, use toScriptValue:

    QJSEngine jsEngine = qjsEngine(this);
    QJSValueList args;
    args << title;
    args << jsEngine->toScriptValue(byteArray);
    callback.call(args);
    

Log in to reply