Qt Signal-Slot Connection: Passing Data from Main Window to Dialog

Qt Signal-Slot Connection: Passing Data from Main Window to Dialog

Abstract:** In this article, we will explore how to use the signal-slot mechanism in Qt to pass data from a main window to a dialog. We will create a simple example using C++ and Qt 5.15.2.

Introduction

Qt's signal-slot mechanism is a powerful way to communicate between objects in a Qt application. In this article, we will demonstrate how to use signals and slots to pass data from a main window to a dialog.

The Example

Our example consists of a main window (MainWindow) and a dialog (Dialog). The main window has a Send signal that is emitted when a button is clicked. This signal is connected to the Receive slot in the dialog, which displays the received data.

Here is the code for the main window (mainwindow.h):

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "dialog.h"

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
 Q_OBJECT

public:
 MainWindow(QWidget *parent = nullptr);
 ~MainWindow();

private:
 Ui::MainWindow *ui;
 Dialog *dialog;

signals: // added
 void Send(int data); // added
};
#endif // MAINWINDOW_H

And here is the code for the dialog (dialog.h):

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
 Q_OBJECT

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

private:
 Ui::Dialog *ui;

private slots: // added
 void Receive(int data); // added
};

#endif // DIALOG_H

In the main window's constructor, we connect the Send signal to the Receive slot in the dialog:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
 : QMainWindow(parent)
 , ui(new Ui::MainWindow)
{
 ui->setupUi(this);
 dialog = new Dialog;
 connect(this, SIGNAL(Send(int)), dialog, SLOT(Receive(int))); // connected
 emit Send(999); // emitted
 dialog->setModal(true);
 dialog->exec();
}

In the dialog's constructor, we implement the Receive slot:

#include "dialog.h"
#include "ui_dialog.h"

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

void Dialog::Receive(int data)
{
 qDebug() << data;
}

In this article, we demonstrated how to use the signal-slot mechanism in Qt to pass data from a main window to a dialog. By connecting the Send signal to the Receive slot, we can communicate between objects and update the UI accordingly.

This example is just a simple demonstration of the power of signal-slot connections in Qt. With this knowledge, you can create more complex and robust applications that can handle communication between different parts of your program.