2
votes

I have one MainWindow and one Class; I want to send data between them using custom signal and slot. I can't seem to figure it out, I need help.

Here is my code: MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <iostream>
#include "receive.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
signals:
    void sendit(QString name);
private slots:
    void on_send_button_clicked();
    void display(QString e)
    {        
     std::cout<<"Here is where I am called this "<<e.toStdString()<<std::endl;
    }

private:
    Ui::MainWindow *ui;

};
#endif // MAINWINDOW_H

MainWindow.cpp

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

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);    
   Receive *r = new Receive();
   connect(this, SIGNAL(sendit(QString)), r, SLOT(display(QString)));

}

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


void MainWindow::on_send_button_clicked()
{
    emit sendit(ui->lineEdit->text());

}

receive.h

#ifndef RECEIVE_H
#define RECEIVE_H

#include <iostream>
#include <QDialog>

class Receive : public QDialog
{
public:
    Receive();
private slots:
    void display(QString e);
};

#endif // RECEIVE_H

receive.cpp

#include "receive.h"
#include "mainwindow.h"

Receive::Receive()
{

}

void Receive::display(QString e)
{    
 std::cout<<"Here is where I am called this "<<e.toStdString()<<std::endl;
}

When I run this program, I get this message:

06:26:29: Starting C:\Users\Troy\Documents\build-tests-Desktop_Qt_5_14_1_MinGW_32_bit-Debug\tests.exe ... QObject::connect: No such slot QDialog::display(QString) in ..\tests\mainwindow.cpp:11 QObject::connect: (sender name: 'MainWindow')

How do I get this done, please?

Thank you for your help.

2
Receive is missing the Q_OBJECT macroFrank Osterfeld

2 Answers

2
votes

Your slot in Receive needs to be public not private. Much the same as other class members, private slots can only be used by the class itself.

If you use the modern connect syntax you'll get a better compile time error:

connect(this, &MainWindow::sendit, r, &Receive::display);

You also need to make sure you add Q_OBJECT to every Qt class, it is missing from Receive.

0
votes

you class Receive need Q_OBJECT, the slots need to be public functions

class Receive : public QDialog
{
    Q_OBJECT
public:
    Receive();
public slots:
    void display(QString e);
};