[SOLVED] help with signal and slot
-
The following code runs good without any errors but the signal and slot is not working correctly. In the code, the dialog calls the click signal and in the Dialog the function returns a variable. at the mainwindow, the slot should be then called but it is not. Below is a basic example about what i am trying to do. if the slot works correctly it then sets the text to the pushbutton on the mainwindow. I have verified that the function clicked at the mainwindow is never called. Your help is greatly appreciated. thank you in advanced.
dialog.cpp
@#include "dialog.h"
#include "ui_dialog.h"
#include "mainwindow.h"QString pass1 = "pass";
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
clicked();
}Dialog::~Dialog()
{
delete ui;
}const QString Dialog::clicked()
{
emit click();
return pass1;
}
@mainwindow.cpp
@#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialog.h"
QString pass;MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
tt = new Dialog(this);
this->connect(tt, SIGNAL(click()), this, SLOT(clicked()));
tt->show();
}MainWindow::~MainWindow()
{
delete ui;
}void MainWindow::clicked(){
pass = tt->clicked();
ui->pushButton->setText(pass);
}@dialog.h
@#ifndef DIALOG_H
#define DIALOG_H#include <QDialog>
namespace Ui {
class Dialog;
}class Dialog : public QDialog
{
Q_OBJECTpublic:
explicit Dialog(QWidget *parent = 0);
~Dialog();const QString clicked() ;
private slots:signals:
void click();private:
Ui::Dialog *ui;
};#endif // DIALOG_H@
mainwindow.h
@#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
class Dialog;
namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void clicked();private:
Ui::MainWindow *ui;
Dialog *tt;
};#endif // MAINWINDOW_H@
-
A few issues here.
Firs of all, in mainwindow.h, declare clicked() like that:
@
public slots:
void clicked();
@Then, look into your implementation: when click() is emitted, it will invoke mainwindow's clicked(), which will in turn invoke dialog's method of the same name, and finally it will re-emit click() signal. Sounds like a loop to me, but I might have overlooked something.
-
Another problem is, you call clicked() in dialog constructor, which is called in mainwindow BEFORE signal-slot connection. Therefore, your initial signal will not be caught by main window. Mind you, making the connection before dialog instantiation is also wrong - you have to rethink the whole thing.
-
The problem is that you call Dialog::clicked (the function that emits the signal) from the constructor and then you have:
@
tt = new Dialog(this); //signal emited and call all connected slots (NONE)
this->connect(tt, SIGNAL(click()), this, SLOT(clicked())); //and after the first signal emit you connect
@