Paul McLoughlin
Paul McLoughlin

Reputation: 2289

Qt Passing variables between unrelated objects

I am currently learning Qt and I seem to have run into a problem. In my practice project I have 2 classes: MainWindow and Dialog.

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

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

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_pushButtonDialog_clicked();

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

};

#endif // MAINWINDOW_H

MainWindow.cpp

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

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

    dialogInstance = new Dialog(this);
}

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

void MainWindow::on_pushButtonDialog_clicked()
{
    dialogInstance->show();
}

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 = 0);
    ~Dialog();

private:
    Ui::Dialog *ui;
};

#endif // DIALOG_H

Dialog.cpp

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

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

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

My goal is to input a value using the Dialog window, then have the value of that input shown on the MainWindow, I know how to pass variables around within the class using widgets, but I am not sure how to transfer variables between unrelated objects.

Any input would be of great help.

Upvotes: 1

Views: 2502

Answers (1)

Soroush Rabiei
Soroush Rabiei

Reputation: 10868

Try this:

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButtonDialog, SIGNAL(clicked()), this, SLOT(on_pushButtonDialog_clicked()));
    dialogInstance = new Dialog(this);
}
// ...

Upvotes: 1

Related Questions