Sunday, January 20, 2013

Convert an int to QString in Qt

Hi,
Today I will show you how to convert an int type to a QString type in Qt.

Here are the steps:



1- We start my dividing the variable on 10 using the modulo operator ( % )
 int_to_convert % x
2- We convert the result to the corresponding character of the result by adding 0x30 in hexadecimal
     or 48 in decimal
ch = (char)(int_to_convert % x + 0x30);
3- We insert "ch" at the beginning of the QString variable using the "insert" function and the position
     is 0.
 output_string->insert(0, ch); //Notice we passed the position 0.
4-  We set the value of the int variable to its value divided by 10
int_to_convert = (int_to_convert / x);
5- This is the final code
void intToString(int int_to_convert, QString * output_string) {
    QChar ch;
    int x = 10;
    while(int_to_convert != 0) {
        ch = (char)(int_to_convert % x + 0x30);
        output_string->insert(0, ch);
        int_to_convert = (int_to_convert / x);
    }
}
 Note:
   I made a header file that you can include it in your program and all you need is to pass it the
   int variable and the address of your QString variable.
Download the header file from here

1 comment: