Momergil
Momergil

Reputation: 2281

How to externally call a signal in Qt?

I know how to call a signal from inside the class where the signal is located: by using emit. But what if I want to call it externally, from the parent object?

The reason why I want to do is is because a given QPushButton is connected to a slot which picks the button that called it by using sender(). Now I want the same functionallity of that slot to be called but not after a manual click in the button, but from within the code itself. Normally I would just programatically call for the slot, but because of the usage of sender(), that way is invalid: calling the slot directly will not give it the id of the button.

So how could I "externally" ask for the object for it to emit one of its signals? That is, how can I make my QPushButton emit its clicked() signal from within the code, not by clicking the button with the mouse?

Upvotes: 1

Views: 2242

Answers (3)

Jeremy Friesner
Jeremy Friesner

Reputation: 73091

The Qt headers contain this interesting line (in qobjectdefs.h):

#define emit

Which means that presence or absence of the emit keyword has no effect on the code, it's only there to make it more obvious to the human reader that you are emitting a signal. That is to say:

 emit clicked();

is exactly the same (as far as the C++ compiler is concerned) as

 clicked();

Given that, if you want your button to emit its clicked() signal, it's just a matter of doing this:

 myButton->clicked();

(although if you wanted to be clever about it, this would work equally well):

 emit myButton->clicked();

Upvotes: 1

Nazar554
Nazar554

Reputation: 4195

Seems that Qt Test module is just for this case. Check out this tutorial on simulating GUI events. Basically you use QTest::​mouseClick and pass pointer to your push button.

Upvotes: 0

Juraj Majer
Juraj Majer

Reputation: 577

You cannot emit signal directly from the parent object.

Only the class that defines a signal and its subclasses can emit the signal. (http://qt-project.org/doc/qt-4.8/signalsandslots.html#signals)

You can define a method in your QPushButton emitClicked() where you emit the signal. Then you call emitClicked() on instance of your QPushButton from the code.

Upvotes: 1

Related Questions