PDA

View Full Version : How to recover the argument of a signal that triggered a signaltransition...



ClintEastwood
9th October 2013, 23:23
Hello all, I'm using a QStateMachine to manage my application, and sometimes a signal with an argument triggers a transition and I want to get its argument inside of the transition slot, but I do not know how to. Below you can find an example of my problem:

Let's assume we have some kind of socket class that emits a signal every time it receives a new request:



class MySocket:public QTcpSocket
{
Q_OBJECT

public:
...

signals:

void newRequest(int request);

}


Then inside of my application I have a QStateMachine with this transition:



MySocket* mySocket = new MySocket();

QStateMachine machine;

QState *s1 = new QState();
QState *s2 = new QState();

QSignalTransition* s1_s2_transition = s1->addTransition(mySocket, SIGNAL(newRequest(int)), s2);
QObject::connect(s1, SIGNAL(triggered()), this, SLOT(s1_s2_transition_process());

machine.addState(s1);
machine.addState(s2);


What I want to do is to get the int argument emitted with the newRequest signal inside the s1_s2_transition_process() slot:



void MyApplication::s1_s2_transition_process()
{
//here I want to get the int value emitted with the newRequest(int) signal
}


What I did to solve this problem is to store the value in a property in MySocket class before emitting the signal and access it by using a public accesor. This would be MySocket class:



class MySocket:public QTcpSocket
{
Q_OBJECT

public:
int lastRequest;

int getLastRequest() const {return lastRequest;};

signals:

void newRequest(int request);
}

MySocket::extractRequestFromReceivedBytes()
{
...
// the request is extracted and stored in data
...
lastRequest = data;
emit newRequest(lastRequest);
}


And the slot:



void MyApplication::s1_s2_transition_process()
{
int request = mySocket->getLastRequest();
}


I don't like this solution because I think two signals could be emitted from MySocket class very close in time, the second one could overwrite the lastRequest property before the first slot was invoked, and then it would retrieve the second value twice.

Any idea of how to solve this issue or how to redesign my system?

Thanks in advance

anda_skoa
11th October 2013, 11:32
I don't like this solution because I think two signals could be emitted from MySocket class very close in time, the second one could overwrite the lastRequest property before the first slot was invoked, and then it would retrieve the second value twice.

The second signal can only be processed when you have finished prcessing the first, i.e. when you have given the event loop a chance to process the event that will lead to the next signal's emission.

Alternatively you can create your own signal transition class that takes the argument from the signal event and emits its own signal.
See http://qt-project.org/doc/qt-4.8/qsignaltransition.html

Cheers,
_