38

How can I convert QVariant to QString and Vice versa?

Thanks

1 Answer 1

81

From string:

QString qs;
QVariant qv(qs);

To string:

QString qs = qv.toString();

Tip: reading the help helps.

5
  • 6
    toString() does NOT return the value in the QVariant as a QString but rather describes the QVariant in a way that might be more suitable for debugging. I have found that QVariant::value<QString>() or QVariant::convert(QVariant::QString) seem to be more helpful, because they return the actual value in the QVariant. Commented Apr 3, 2016 at 1:52
  • 3
    @LennartRolland the code example in the docs explicitly states value<QString>() is the same as toString(). They both use canConvert() and convert() internally. Commented Apr 3, 2016 at 9:16
  • @hamstergene toString() appears to have begun working in qt 4.8; in qt 4.7, value<QString>() works, while toString() does not. So for this kind advice and compatibility, value<QString>() makes for a better general statement, unless qualified by version.
    – fyngyrz
    Commented Oct 17, 2016 at 22:43
  • 2
    @hamstergene I thought the help is SO.
    – Liviu
    Commented Mar 27, 2017 at 12:29
  • This does not work for certain types. For instance, when the QVariant contains a QStringList, .toString() returns a null string. Commented Aug 1, 2023 at 10:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.