Gerstmann
Gerstmann

Reputation: 5518

How to convert TBuf8 to QString

I've tried to convert using the following code:

template< unsigned int size >
static QString
TBuf82QString( const TBuf8< size > &buf )
{
   return QString::fromUtf16(
      reinterpret_cast<unsigned short*>(
         const_cast<TUint8*>(
            buf.Ptr() ) ), buf.Length() );
}

But It always returns something like ?????b.

EDIT: Changed code example

Upvotes: 0

Views: 452

Answers (2)

Gareth Stockwell
Gareth Stockwell

Reputation: 3122

Using a template probably isn't a good solution, since it will result in a new instantiation of this block of code within your application binary, for every size of input string which is converted. Since the output type (QString) contains no compile-time constant, this means you end up with code bloat, for no gain.

A better approach would be to leverage the fact that TBuf8<N> inherits from TDesC8:

QString TBuf2QString(const TDesC8 &buf)
{
    return QString::fromLocal8Bit(reinterpret_cast<const char *>(buf.Ptr()),
                                  buf.Length());
}

TBuf<16> foo(_L("sometext"));
QString bar = TBuf2QString(foo);

Upvotes: 1

James
James

Reputation: 9278

TBuf8 is used for binary data or non-Unicode strings. TBuf16 is used for Unicode strings. TBuf is conditionally compiled and will always be TBuf16 as Symbian OS is natively Unicode.

Try using QString::fromLocal8Bit() with TBuf8::Ptr()

Upvotes: 1

Related Questions