-1

Well, I have been a new to Qt and I am now using signals and slots. I would like to define a signal

void send(int);

and emit this signal in A.cpp with some int val like '5'

emit send(5);

After that, in B.h, I defined a slot

void receive(int i);

Using the connect function, I connect the signal and slot

connect(a,&a::send,b,&receive);

Then this two just connected and the int value 5 was transferred successfully to slot receive. It can also been used in the area of receive. But what troubles me is, how can I acquire this value or this '5' and use it outside receive function. I am stuck in this step for days, so I wish someone could give me some ideas or instruction, thanks alot.

1 Answers1

2

Assuming your B class looks something like this, create a member and store the received value in there.

class B : public QObject
{
    Q_OBJECT

public:
    explicit B(QObject *parent = nullptr) noexcept : QObject{parent} {}

    void received(int value) { m_receivedValue = value; }

private:
    int m_receivedValue{0};
};

In your methods you can then use the stored value, e.g.

void printReceivedValue() const noexcept { qDebug() << "ReceivedValue:" << m_receivedValue; }


The reason I initially set m_receivedValue to 0 is that you should always initialize values before use. If you just use int m_receivedValue;, that will result in it having a garbage value initially. You can of course choose your own value to indicate "uninitalized" or "unset".

If the value was 0 when you looked at it, then either you sent 0 or read it before the slot was triggered. To make it easier you can print m_receivedValue directly in received, then you will see when it is updated.

Remember signals & slots use the event loop, which means the connected slot will not be called immediately, but rather when the event loop returns. So emitting the signal and directly reading the value will not work unless it's a Qt::DirectConnection.

void received(int value)
{ 
    m_receivedValue = value; 
    printReceivedValue();
}
deW1
  • 5,562
  • 10
  • 38
  • 54
  • Cheers mate, I have tried your solution , but the output is 0, is that right? And why m_receivedValue is defined as `int m_receivedValue{0}` instead of `int m_receivedValue`? – muyuan zhang Dec 04 '20 at 02:00
  • @muyuanzhang I've added some explanation – deW1 Dec 04 '20 at 09:30
  • Thanks for your replying mate, I can understand your updating, the `value` as well as `m_receivedValue` can be printed in function `received`. It is useful. And it's my fault that I should make myself clear, what really confused me is that, both `value` and `m_receivedValue` only live and work in the area of `received`,what if I want to use `value` somewhere else like in a new function `received_2` in Class B, is that possible? – muyuan zhang Dec 04 '20 at 17:55