PDA

View Full Version : Problem adding two float values and converting it to a QString



OvrDrv
12th July 2012, 05:32
My goal is to have the user input a value (stored in the amount variable), add the value to the total variable and then output the total to a label. The value seems to be multiplied instead of added. When testing with the value of 1, total is automatically 2, 4, 6, etc. If anyone can please point out the problem, I would appreciate it. Also, this is my first Qt application so if there is a better way of doing this, I would love the advice. Thank you in advance.

main.cpp


#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

return a.exec();
}


mainwindow.h


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QWidget>

namespace Ui {
class MainWindow;


}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
float amount;
float total;
};

#endif // MAINWINDOW_H

mainwindow.cpp


#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
amount=0.00;
total=0.00;

connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(on_pushButton_clicked()));
}

MainWindow::~MainWindow()
{
delete ui;
}


void MainWindow::on_pushButton_clicked()
{
amount = ui->lineEdit->text().toFloat();
total += amount;
ui->label->setText(QString::number(total, 'f', 2));
}

folibis
12th July 2012, 06:45
on_pushButton_clicked() called twice
read this - http://www.qtcentre.org/threads/25528-twice-execution-of-click-on-pushbutton
Just change on_pushButton_clicked to something else

ChrisW67
12th July 2012, 06:50
By naming the slot on_pushButton_clicked() the Designer UI code has automatically connected the clicked() signal of the pushButton object to it. You then manually connect the signal to the slot, resulting in two connections. Each time you press the button the slot is called twice.

OvrDrv
12th July 2012, 07:41
Problem solved :). Thank you very much for your help.