PDA

View Full Version : Passing data from a QDialog to a QMainWindow using signal/slots



mairimmart
28th November 2013, 22:53
I've read in other posts some piece of code to transfer data from a QDialog to QMainWindow, but it didn't work :(
Here is what I've done, and I don't know what's wrong of if maybe I shouldn't use signals/slots to do that...
Any help will be very welcomed :o

MainWindow.cpp:

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

ui->lineEdit->setAlignment(Qt::AlignRight);

Dialog *dialog = new Dialog(this);
QObject::connect(dialog, SIGNAL(validate(QString)), this, SLOT(validate(QString)));

}

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

void MainWindow::on_Open_clicked()
{
Dialog *dialog = new Dialog;
dialog->setModal(true);
dialog->exec();

}

void MainWindow::validate(QString data){
ui->lineEdit->setText(data);

}

MainWindow.h:

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

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

private slots:
void on_Open_clicked();
void validate(QString data);

private:
Ui::MainWindow *ui;
};

Dialog.cpp:


Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);

ui->lineEdit->setAlignment(Qt::AlignRight);
}

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

void Dialog::on_Ok_clicked(){
emit validate(ui->lineEdit->text());
}

Dialog.h:


class Dialog : public QDialog
{
Q_OBJECT

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

private slots:
void on_Ok_clicked();

signals:
void validate(QString data);

private:
Ui::Dialog *ui;
};

It's as if the signal and slot wasn't well coded, because when I debug it, it didn't go to the slot when the signal is emited...

Thanks a lot in advance...

stampede
28th November 2013, 23:07
You create a new dialog in main window's constructor and never exec it, it is useless.
Remove it from the constructor and connect to instances created in on_Open_clicked() slot:

void MainWindow::on_Open_clicked()
{
Dialog *dialog = new Dialog (this); // remember to set parent !
dialog->setModal(true);
connect(dialog, SIGNAL(validate(QString)), this, SLOT(validate(QString)));
dialog->exec();

}

anda_skoa
30th November 2013, 00:19
QDialog::exec() always sets modality to true, so no need to do that explicitly :)

Cheers,
_