Search code examples
c++qtpointerssignals-slots

Qt Version 5.3 Sending Data from one forum to another


I am trying to send data from a dialog to a mainwindow using signals and slots. i have a lineedit and a button in my dialog and a Qlistwidget in the mainwindow. when I run the program the debugger says that the program unexpectedly finished and that the program crashed. thank you. here is the code i have so far:

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>


namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
Q_OBJECT

signals:

void sendData(const QString &text);

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

private slots:
void on_pushButton_toMainWindow_clicked();

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;
}


void Dialog::on_pushButton_toMainWindow_clicked()
{
emit this->sendData(ui->lineEdit_toMainWindow->text());
}

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();

public slots:

void reciveData(const QString &text);

private slots:
void on_pushButton_dialog_clicked();

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

#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);
connect(dialog,SIGNAL(sendData(QString)),
        this,SLOT(reciveData(QString)));
}

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

void MainWindow::reciveData(const QString &text)
{
ui->listWidget_fromdialog->addItem(text);
}

void MainWindow::on_pushButton_dialog_clicked()
{
dialog = new Dialog(this);
dialog->show();
}

also I have noticed in my research of this topic that there is a way to do this using structs and/or pointers but I cannot find any clear and concise examples of this. thanks again!


Solution

  • You are connecting an uninitialized pointer (dialog) in the MainWindow constructor :

    connect(dialog,SIGNAL(sendData(QString)),
        this,SLOT(reciveData(QString)));
    

    Move the connection part into the on_pushButton_dialog_clicked() slot :

    void MainWindow::on_pushButton_dialog_clicked()
    {
        dialog = new Dialog(this);
        connect(dialog,SIGNAL(sendData(QString)), this, SLOT(reciveData(QString)));
        dialog->show();
    }