Signal and slot wrong value being sent
-
I have written a small program to send data from one form(MainWindow) to another(Dialog) upon a button click. When the button is clicked the value written in the lineedit of MainWindow is to be displayed on a label in Dialog form!
When I click the button a value is displayed on the label but it is not the same as the value entered in the line edit!
following are the respective codes in the 2 header and 2 cpp files!MainWindow.h
class MainWindow : public QMainWindow
{
Q_OBJECTsignals:
void sendIntData(int data);
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();MainWIndow.cpp
void MainWindow::on_pushButton_clicked()
{
Dialog *dialog1=new Dialog(this);dialog1->setModal(true); dialog1->exec(); int o=ui->lineEdit->text().toInt(); emit sendIntData(o); connect(this, SIGNAL(sendIntData(int)),dialog1, SLOT(setIntData(int)));
}
Dialog.h
class Dialog : public QDialog
{
Q_OBJECTpublic slots:
void setIntData(int data);public:
explicit Dialog(QWidget *parent = 0);
~Dialog();Dialog.cpp
DIalog::DIalog(QWidget *parent) :
QDialog(parent),
ui(new Ui::DIalog)
{
ui->setupUi(this);
QString value=QString::number(index);
ui->label->setText(value);
}Dialog::~Dialog()
{
delete ui;
}
void Dialog::setIntData(int data)
{
index=data;}
eg-When I click 3 and press the button I get a value 7237481! How can I correct this?
-
hi
You emit signal before you connect and you leak :)So try something like this
void MainWindow::on_pushButton_clicked() { int value=ui->lineEdit->text().toInt(); // get value Dialog dialog1; // use uses exec() so no need for new connect(this, SIGNAL(sendIntData(int)), &dialog1, SLOT(setIntData(int))); // connect first emit sendIntData(value); // then emit dialog1.exec(); // show it and wait for cancel/ok }
-
Hi,
In this case, why not just call
setIntData (value);
? -
Hi
Yes calling the function directly is actually a better solution in this case.
Its worth mentioning that the so called slots are 100% normal c++ member functions
and can be called without any Qt involvement/use of.void MainWindow::on_pushButton_clicked() { int value=ui->lineEdit->text().toInt(); // get value Dialog dialog1; dialog1.sendIntData(value); dialog1.exec(); }