manatttta
manatttta

Reputation: 3124

Convert any QVariant to QString

I am aware of how to convert a QVariant containing a QString to a QString: How can I convert QVariant to QString and vice versa in Qt?

What I want to ask is how do I convert ANY QVariant into a QString? i.e. even if my QVariant object has an int, is there an easy way to convert it to QString?

Upvotes: 5

Views: 13333

Answers (2)

e.jahandar
e.jahandar

Reputation: 1763

You can use Qstring formating

QVariant qv(1);
QString str = QString ("%1").arg(qv.toInt());

also you it could be more generic like this

if(qv.typeName() == QString("QString"))
   str = QString("%1").arg(qv.toString());
else if(qv.typeName() == QString("int"));
   str = QString ("%1").arg(qv.toInt());
...

or by using qv.type()

if(qv.type() == QVariant::String)
    str = QString("%1").arg(qv.toString());
...

Upvotes: 2

talamaki
talamaki

Reputation: 5472

You can use QVariant::toString for types listed in the method documentation.

int value = 1;
QString s = QVariant(value).toString();

Upvotes: 16

Related Questions