Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert any QVariant to QString

Tags:

c++

qt

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?

like image 870
manatttta Avatar asked Dec 01 '22 12:12

manatttta


2 Answers

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

int value = 1;
QString s = QVariant(value).toString();
like image 139
talamaki Avatar answered Dec 04 '22 01:12

talamaki


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());
...
like image 44
e.jahandar Avatar answered Dec 04 '22 01:12

e.jahandar