33

How can I convert QVariant to QString and Vice versa?

Thanks

ixM
  • 1,244
  • 14
  • 29
Legend
  • 375
  • 1
  • 3
  • 5

1 Answers1

76

From string:

QString qs;
QVariant qv(qs);

To string:

QString qs = qv.toString();

Tip: reading the help helps.

Paul Wintz
  • 2,542
  • 1
  • 19
  • 33
hamstergene
  • 24,039
  • 5
  • 57
  • 72
  • 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() or QVariant::convert(QVariant::QString) seem to be more helpful, because they return the actual value in the QVariant. – Mr. Developerdude Apr 03 '16 at 01:52
  • 3
    @LennartRolland [the code example in the docs](http://doc.qt.io/qt-4.8/qvariant.html#value) explicitly states `value()` is the same as `toString()`. They both use `canConvert()` and `convert()` internally. – hamstergene Apr 03 '16 at 09:16
  • @hamstergene `toString()` appears to have begun working in qt 4.8; in qt 4.7, `value()` works, while `toString()` does not. So for this kind advice and compatibility, `value()` makes for a better general statement, unless qualified by version. – fyngyrz Oct 17 '16 at 22:43
  • 2
    @hamstergene I thought the help is SO. – Liviu Mar 27 '17 at 12:29
  • This does not work for certain types. For instance, when the QVariant contains a QStringList, .toString() returns a null string. – Thomas Klier Aug 01 '23 at 10:29