0

I have this code for a window with two labels (label and lblclicount) and one button (butprint) It is a small tutorial i found on youtube i just add some text arround the variable that count the numbre of clic the user makes . I just want to learn C++ I know how to do this with VisualBasic. Here is the link of the tutorial : https://www.youtube.com/watch?v=Gi3VuB--vjU and bellow i try to explain the things i don't really understand but it works.

void MainWindow::on_butprint_clicked()
{
    static int nbrclic = 0;
    QString strnbrclic, texte;
    nbrclic++;
    ui->label->setText("Hello World");
    strnbrclic.sprintf("%i", nbrclic);
    texte= "Vous avez cliqué " + strnbrclic + " fois.";
    ui->lblcliccount->setText(texte);

}

I was thinking i can do ui->lblclicount->setText("Vous avez cliqué " + nbrclic + " fois."); (but it doesn't work.)

instead of having to do

strnbrclic.sprintf("%i", nbrclic);
texte= "Vous avez cliqué " + strnbrclic + " fois.";

I think i understand that strnbrclic.sprintf("%i", nbrclic); convert the integer nbrclic in a string and after i add my text and the variable value of nbrclic in a new one ith the line

texte= "Vous avez cliqué " + strnbrclic + " fois.";

I'm french and i'm sorry if my question is not simple to understand.

Thanks in advance

2 Answers2

1

To convert an int to a string you can simply do to_string(your_int_here)

Alternatively, just use <iostream>. to_string is part of the standard <string> library, so either declare you're using namespace std or use it as std::to_string

If you're using QString as part of the Qt Core library, then to get it into the standard std::string format you can call your_variable_here.toStdString() as described in their documentation at https://doc.qt.io/qt-5/qstring.html

thanat0sis
  • 185
  • 1
  • 12
1

SetText() takes a string as an argument. In the example provided by you it works because in the first place there is a sprintf instruction:

strnbrclic.sprintf("%i", nbrclic);

Which effectively writes nbrclic (an integer value) into a string strnbrclic

Then you have:

texte= "Vous avez cliqué " + strnbrclic + " fois.";

Which concatenates three strings (strnbrclic is an int written into a string), so there is no type error.

What you tried to do in your code (the one which does not work), was to concatenate two strings and integer value which is not possible. For your example to work, you need to write the nbrclic into a string.