Theodore Tang
Theodore Tang

Reputation: 1021

Qt connect mainwindow and dialog using signal and slot

I am trying to connect mainwindow and dialog using signal and slot. I am very new to qt. I have a lineEdit and a pushButton in mainwindow.ui, a lineEdit in dialog.ui. And I have those very basic code:

mainwindow.h:

signals:
    void sendString(QString);


mainwindow.cpp:

void MainWindow::on_pushButton_clicked()
{
    Dialog *mDialog = new Dialog(this);
    emit sendString(ui->lineEdit->text());
    connect(this, SIGNAL(sendString(QString)), mDialog, SLOT(showString(QString)));
    mDialog->show();
}


dialog.h:

private slots:
    void showString(QString);


dialog.cpp:

void Dialog::showString(QString str)
{
    ui->lineEdit->setText(str);
}


But after I clicked the pushButton, the dialog showed, but nothing changed in the lineEdit.
I hope I explain this clearly enough?
Can someone explain to me why and how to solve this? Thanks.

Upvotes: 0

Views: 1481

Answers (2)

saeed
saeed

Reputation: 2497

emit signal after connect

void MainWindow::on_pushButton_clicked()
{
    Dialog *mDialog = new Dialog(this);
    connect(this, SIGNAL(sendString(QString)), mDialog, SLOT(showString(QString)));
    mDialog->show();

    emit sendString(ui->lineEdit->text());
}

Upvotes: 0

thomas
thomas

Reputation: 330

You have to create the connection before the emit.

But in your case you dont need the signal of the of the mainwindow at all. You invoke the showString method directly.

Upvotes: 0

Related Questions