Suhair K P
Suhair K P

Reputation: 1

How change receive a signal in Mainwindow from another window

I am designing a system, which contain a Mainwindow and three otherwindows. Mainwindow contain a menu button and four Qlabels. By clicking menu, it will open second window. It contains two buttons. Clicking first button in second window will open third window and clicking second button in second window will open fourth window. Third and fourth window contain two buttons.

When i press first button in third window, i want to set some text in first Qlabel of mainwindow. similarly When i press second button in third window, i want to set some text in second Qlabel of mainwindow. similarly, i want to set Qlabel 3 & 4 based on pressing buttons from fourth window.

I read signals and slot mechanism, and other forums, but i didn't get the flow for connecting signal and slot.

To open new window from previous window I am adding new Qt class and writing

void MainWindow::on_pushButton_3_clicked()
 {
SecDialog secDialog;
secDialog.setModal(true);
secDialog.exec();
 }

in each windows and emitting signal from fourthwindow on button click by

fouthwindow.cpp

void ForthDialog::on_pushButton_clicked()
 {

  emit mode1("Manualset");
 }

i declared this in fourthwindow.h

signals :
   void mode1(QString) ;

How to receive this signal from mainwindow ?

Upvotes: 0

Views: 512

Answers (1)

Adrien Leravat
Adrien Leravat

Reputation: 2789

You can simply make a connection, from a place in your code where both are accessible:

void MainWindow::on_pushButton_3_clicked()
{
    SecDialog secDialog;
    secDialog.setModal(true);
    connect(&secDialog, &SecDialog::mode1, this, &MainWindow::yourSlot);
    secDialog.exec();
}

And then to handle it

void MainWindow::yourSlot()
{
    ui->myLabel->setText("...");
}

A few advices

  • Don't use the auto connect syntax, "on_pushButton_3_clicked()", but explicit connection instead, like above. It's clearer, more flexible, and less error-prone
  • Do use good names for your classes/widgets. Any name expliciting the role of the class is better than ForthDialog. In case these were your real classes names
  • For dialogs when possible, prefer the standard QDialog return codes. Using accept(), reject() or alternatively done(), you can directly read the outcome from the return value of your exec() call

Upvotes: 3

Related Questions