PDA

View Full Version : Qt sending variables using signals & slots



Akame.L
27th February 2017, 11:58
Hello,
I want to send a message from a QLineEdit (lineEdit) after clicking a QPushButton (pushButton) from a window (test) and print it to a QLabel (label) in another window (test2).
This is what I've done so far:
test.h


#ifndef TEST_H
#define TEST_H

#include <QMainWindow>
#include "test2.h"
namespace Ui {
class test;
}

class test : public QMainWindow
{
Q_OBJECT

public:
explicit test(QWidget *parent = 0);
~test();
signals:
void notifyValueSent(const QString value);
private slots:
void on_pushButton_clicked();

private:
Ui::test *ui;
};

#endif // TEST_H

test.cpp


#include "test.h"
#include "ui_test.h"

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

}

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

void test::on_pushButton_clicked()
{
QString value = ui->lineEdit->text();
emit notifyValueSent(value);
}

test2.h


#ifndef TEST2_H
#define TEST2_H

#include <QWidget>
#include "test.h"
namespace Ui {
class test2;
}

class test2 : public QWidget
{
Q_OBJECT

public:
explicit test2(QWidget *parent = 0);
~test2();
private slots:
void onValueSent(const QString value);
private:
Ui::test2 *ui;
};

#endif // TEST2_H

test2.cpp


#include "test2.h"
#include "test.h"
#include "ui_test2.h"

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

test2::~test2()
{
delete ui;
}
void test2::onValueSent(QString value){

ui->label->setText(value);
}

main.cpp


#include "test.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
test t;
test2 t2;
QObject::connect(&t,SIGNAL(notifyValueSent(value)),&t2,SLOT(onValueSent(value)));
t.show();
return a.exec();
}

Thank you.

Lesiok
27th February 2017, 12:02
You have to show t2 too.

Akame.L
27th February 2017, 12:43
Even when I do I don't get the result I want.
After clicking the button i want to open t2 & print the message in QLabel

Lesiok
27th February 2017, 13:07
Change line 9 in main to :
QObject::connect(&t,SIGNAL(notifyValueSent(QString)),&t2,SLOT(onValueSent(QString)));

Akame.L
27th February 2017, 13:20
I didn't see that! Thank u :)