Solved How to convert QList<QByteArray> to QStringList ?
-
How to convert QList<QByteArray> to QStringList ?
I want to use QStringList::filter() function. -
Hi @sonichy
How to convert QList<QByteArray> to QStringList ?
It depends on what character encoding is used in the
QByteArrays
, but assuming they use the local system's 8-bit encoding (for example), you can do it like:QStringList toStringList(const QList<QByteArray> list) { QStringList strings; foreach (const QByteArray &item, list) { strings.append(QString::fromLocal8Bit(item)); // Assuming local 8-bit. } return strings; }
Of course, you can replace the
QString::fromLocal8Bit()
with whatever makes sense for your encoding.I want to use QStringList::filter() function.
The above will work. But if you're only interested in the
QStringList::filter()
overload that takes aQString
pattern, and you want to be case sesnsitive (the default), then you can avoid the string conversions by rolling your own "filtered" function like:QList<QByteArray> filtered(const QList<QByteArray> list, const QByteArray &bytes) { QList<QByteArray> result; foreach (const QByteArray &item, list) { if (item.contains(bytes)) result.append(item); } return result; }
An example of using both the above functions:
const QList<QByteArray> list = { "a", "b", "c", "abc", "123", "123abc" }; const QStringList strings = toStringList(list); qDebug() << "list: " << list; qDebug() << "strings: " << strings; qDebug() << "strings-filtered:" << strings.filter(QLatin1String("b")); qDebug() << "list-filtered: " << filtered(list, "b");
Outputs:
list: ("a", "b", "c", "abc", "123", "123abc") strings: ("a", "b", "c", "abc", "123", "123abc") strings-filtered: ("b", "abc", "123abc") list-filtered: ("b", "abc", "123abc")
Cheers.