0
votes

I have a signal that I want to connect to two slots but execute just one slot at a time. That is to say I have two slots across different files and I want slot 1 to be called first. Later when I emit the same signal again, I want the slot 2 to be called, not the slot 1 this time.

In file 1:

connect(...,SIGNAL(mySignal),...,SLOT(mySlot1()));

In file 2:

connect(...,SIGNAL(mySignal),...,SLOT(mySlot2()));

At first I emit the signal, then I want mySlot1() , to be called alone. Next time when I emit the same signal, I want mySlot2() to be called alone. As is evident, both take the same arguments. I don't want to create a new signal (which would be just like the already made mySignal) for it. Is this possible ? What can I do ?

2
it looks like signal/slot is not what you want for your purposes.Richard Hodges
It might be possible to create a signal "load balancer" object that has a slot that accepts a signal to load balance, and a signal to raise every time the slot receives a signal. It would automatically connect and disconnect slots registered with the load balancer every time load balancer's slot is invoked. I'm not sure how to implement this or if it's possible. Perhaps someone can expand on this.Jordan Melo

2 Answers

2
votes

What you are asking for is for a signal to choose the slots it executes based on some other criteria. It doesn't work that way in Qt. When you emit a signal, ALL of the connected slots are triggered (you don't even get to control the order in which they are triggered).

The only way you could get the behavior you describe is to have mySLot1 disconnect itself from the signal, and connect mySlot2, then have mySlot2 do the opposite, so they ping-pong back and forth.

1
votes

A simple solution would be to add an extra parameter to your signal that specifies which slot should respond to the signal. The signal will read this parameter and decide with an if statement whether or not it should execute its code in response. Each slot will have to respond only to its own, unique value of this parameter.

For example, mySlot1 will only respond if the argument to the parameter is 1. mySlot2 will only respond if the argument to the parameter is 2.

When you raise the signal, you will have to go through these values one by one, choosing a different one each time the signal is raised, so that a different slot will respond to the signal. Essentially, you would be assigning an address to each slot and calling a different slot each time the signal is raised based on its address.

This isn't a very general solution on its own. To generalize it, you would need a way to assign a unique, valid address to each slot and register these addresses with the object that raises the signal. However, this is the only way I can think of solving this problem without creating more signals and slots.