31

How can I convert QVariant to QString and Vice versa?

Thanks

ixM
  • 1,244
  • 12
  • 29
Legend
  • 355
  • 1
  • 3
  • 5

1 Answers1

72

From string:

QString qs;
QVariant qv(qs);

To string:

QString qs = qv.toString();

Tip: reading the help helps.

Paul Wintz
  • 2,168
  • 1
  • 17
  • 30
hamstergene
  • 23,424
  • 5
  • 53
  • 71
  • 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. – Lennart Rolland Apr 03 '16 at 01:52
  • 2
    @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