Home > front end >  convert QList to QString
convert QList to QString

Time:06-22

I want to be able to print a QList to a TextBox with setText(“ “), but I need to convert that list to a string. This may be trivial, but I’m new to cpp and Qt. essentially I want to do the following:

{1,2,3,4} -> “{1,2,3,4}”

CodePudding user response:

QList is just a container. It doesn't know anything about strings. So you'll need to iterate over the list and append each value into the string.

// Assuming QList of integers
QString list2String(const QList<int> &list)
{
    QString s = "{";

    for (auto &value : list)
    {
        s  = QString("%1,").arg(value);
    }

    // Chop off the last comma
    s.chop(1);

    s  = "}";
    return s;
}

CodePudding user response:

Improving a bit on the answer by JarMan. This should be more performant and more Qt-ish.

// Assuming QList of integers
QString list2String(const QList<int> &list)
{
    QStringList strings;
    strings.reserve(list.size());

    for (int i : list)
    {
        strings.append(QString::number(i));
    }

    return QStringLiteral("{%1}").arg(strings.join(','));
}
  • Related