Starl1ght
Starl1ght

Reputation: 4493

Convert QString to QByteArray with forced locale

I need to convert QString to QByteArray using cp1251 locale without toLocal8bit() function.

I.e. on my current PC default locale is cp1251 -> QString::toLocal8bit() is working great, but once I switch locale to something different -> I cannot use toLocal8Bit(). I've read documentation about QTextCodec and stuff, but it seems very obscure to me.

So, the question is - how do I convert from QString to QByteArray using specified locale?

Any help and explanation will be very welcome.

Upvotes: 1

Views: 1989

Answers (1)

huysentruitw
huysentruitw

Reputation: 28091

As you found out yourself, you'll need QTextCodec for this. What you want to do should be as simple as this:

QString src = "My test string";
QTextCodec *codec = QTextCodec::codecForName("Windows-1251");
QByteArray encodedString = codec->fromUnicode(src);

Upvotes: 3

Related Questions