-1

I can't get this to work. Anyone knows how to make it work?

void MainWindow::on_pushButton_clicked()
{

    int sum1 = ui->lineEdit->text().toInt();
    int sum2 = ui->lineEdit_2->text().toInt();

    ui->label_4->setText(sum1 + sum2);
}

Error:

C:\Qt\Tools\QtCreator\bin\Mellemrubrik\mainwindow.cpp:26: error: C2664: 'QLabel::setText' : cannot convert parameter 1 from 'int' to 'const QString &' Reason: cannot convert from 'int' to 'const QString' No constructor could take the source type, or constructor overload resolution was ambiguous

László Papp
  • 51,870
  • 39
  • 111
  • 135
Giefdonut
  • 99
  • 1
  • 2
  • 10
  • Please tell us what problems you are experiencing. It is not easy for us to help when the problem description is "Doesn't work" :) – Magnus Hoff Nov 14 '13 at 17:35
  • 1
    Not enough jquery. =) If you can write this post, why you can't understand the compiler message? "cannot convert parameter 1 from 'int' to 'const QString &'" - so compiler can't convert your integer to Qt QString. You need to convert from int to QString explicitly. – JustAnotherCurious Nov 26 '13 at 04:36
  • As it is written in the error message, it cannot convert from int to string, you need to cast the (sum1 + sum2) to a string like the solutions mentioned below, using QString::number – Majid khalili Jan 01 '20 at 11:41

3 Answers3

3

In general, you can convert multiple numeric types to QStrings like so:

int val1, val2;
QString result = QString("val1=%1 val2=%2 sum=%3").arg(val1).arg(val2).arg(val1+val2);

But for numbers, this is also possible:

int val1, val2;
QString result = QString::number(val1+val2);

You can see Qt's documentation for more info!

Alex Reinking
  • 16,724
  • 5
  • 52
  • 86
  • What are the generic "quantities" not being numbers here? QString::number() is basically equivalent in functionality, and more concise (and more performant probably, too). So I'd always use the second variant. – Frank Osterfeld Nov 14 '13 at 17:47
  • The advantage to .arg() in some cases is your ability to chain them. I just updated my example to reflect this. – Alex Reinking Nov 14 '13 at 17:49
0

You can try this

int v1,v2;
v1=ui->lineEdit->text().toInt():
v2=ui->lineEdit_2->text().toInt()
QString result = QString::number(v1+v2);
ui->label->setText(result);
L_J
  • 2,351
  • 10
  • 23
  • 28
  • you should try and add a brief textual description to your code block. Perhaps taking "You can try this" out of the code block, and expanding slightly on the sentence. – bad_coder Jan 01 '20 at 11:56
0

Would setNum as shown below do?

int v1,v2;
v1=ui->lineEdit->text().toInt():
v2=ui->lineEdit_2->text().toInt()
ui->label->setNum(v1+v2);