Solved Emitting custom signal
-
Hi,
I have the following mainwindow.h:#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QDebug> #include <QString> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget* parent = 0); ~MainWindow(); private slots: void display(); void on_pushButton_clicked(); signals: void myMessage(QString msg); private: Ui::MainWindow* ui; }; #endif // MAINWINDOW_H
and the following mainwindow.cpp:
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(display())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::display() { qDebug() << "Entered display"; //works emit myMessage ("Signal emitted from pushbutton"); } void MainWindow::on_pushButton_clicked() { emit myMessage ("Signal emitted from pushbutton"); qDebug() << "Entered on_pushButton_clicked";//works }
Everything works except it does not emit the myMessage signal. Where did I make a mistake?
Thank you fro your help. -
Hi gabor53 ,
Where did you connect the emitted signal? The signal is sent, but you didn't 'receive' it
Do something like this in the constructor :
```
connect(this, SIGNAL(myMessage(QString)), this, SLOT(showMessage(QString)));where showMessage is a slot that takes the QString from you signal and shows it id with qDebug().
-
@Eddy
This is what worked for me:#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(display())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::display() { qDebug() << "Entered display"; //works QString msg = "Signal emitted from pushbutton."; emit myMessage (msg); } void MainWindow::on_pushButton_clicked() { emit myMessage ("Signal emitted from pushbutton"); qDebug() << "Entered on_pushButton_clicked";//works connect(this, SIGNAL(myMessage(QString)), this, SLOT(showMessage(QString))); } void MainWindow::showMessage(QString msg) { qDebug() << "Signal message: " << msg; }
Thank you for your help.
-
@gabor53 well done.
You could also use other signal slots mechanisms by fine tuning some things. More info can be found in the docs signalsandslots-syntaxes
-
Hi,
Watch out, in
on_pushButton_clicked
you'll be calling the connect method every time you click on the button so you are going to have multiple calls the the slot cumulating.That connect statement should be in the constructor of your MainWindow class.