How to convert std::vector<uint8_t> to QByteArray?

11,202

You need to cast buf.data() instead of buf:

QByteArray* img = new QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());
Share:
11,202
goGud
Author by

goGud

C++ and Qt developer

Updated on July 24, 2022

Comments

  • goGud
    goGud almost 2 years

    I am trying to create QByteArray from std::vector.. I tried;

    std::vector<uint8_t> buf;
    QByteArray img = new QByteArray(reinterpret_cast<const char>(buf), buf.size());
    

    However it gives error;

    error: invalid cast from type 'std::vector<unsigned char, std::allocator<unsigned char> >' to type 'const char'
    
  • johimi
    johimi almost 9 years
    Note .data() is only available in C++11 and later. If your compiler doesn't support this, use &buf[0].
  • goGud
    goGud almost 9 years
    when I use buf.data() it says error: cast from 'unsigned char*' to 'const char' loses precision
  • goGud
    goGud almost 9 years
    ohh.. my mistake, I didnt use char pointer.. thank you very much
  • akira hinoshiro
    akira hinoshiro almost 4 years
    I personally do avoid new and delete wherever I can. You can do on modern compilers like this: [auto img = QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());]