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"

Sunday, September 26, 2010

error: ‘cout’ was not declared in this scope

When using cout and cin for standard output and standard input purposes without "using directive", compiler generates an error message about undeclared cout and cin. In order to get rid of this error message, it is required to add "using namespace std" using directive at a new line.
App.cpp file
#include "App.h"
#include <iostream>
using namespace std;

void App::HelloWorld(){

    cout << "Hello World";

In addition to #include <iostream> preprocessor directive, insertion of "using namespace std" helps to compile successfully.