Wednesday, September 29, 2010

Convert int to QString

Qt's QVariant helps to convert an integer value to a QString.

toString() method of QVariant returns the variant as a QString, if the variant has type() Int.

Also, QString's number(long x) static method returns a string equivalent of the numeric value of x.

Following example converts a given integer value to QString by using QVariant. And also it creates integer value from QString by using QString::number() static method :


#include <QVariant>
#include <QDebug>
int main() {
    // use QVariant
    int x = 12;
    QVariant var(x);
    QString stringValue = var.toString();
    qDebug() << "String to print-1 :"+stringValue;
    //use QString::number(long n, int base = 10)
    QString stringValue2 = QString::number(x);
    qDebug() << "String to print-2 :"+ stringValue2;
    return 0;
}


When the main method runs following terminal output is generated :

"String to print-1 :12"
"String to print-2 :12"

No comments:

Post a Comment