Adding function to listener in different class

I’m very confused about how the addListener function works in combination with ofxGui. Right now i can only manage to add functions to be executed in the same class as the Gui, like this:

Gui::Gui() {
testButton.addListener(this, &Gui::testFunction);

Though what i really want is to call a function in a different class, when the testButton is pressed. Like this:

testButton.addListener(this, &ofApp::testFunction);

Unfortunately this doesn’t work. Is there any documentation on how to use the addListener function, or how should I approach doing this?

Thanks in advance, Aart

You need to give listener class’ instance & listener class method. if the class is ofApp: (ofApp instance, ofApp::method)

I think had the same issue. here is the solution:

// this works:
gain.addListener(this, &ofApp::setGain);

// this does not work:
gain.addListener(this, &Camera::setGain);

the compiler says:

Severity    Code    Description    Project    File    Line    Suppression State
Error    C2661    'ofAddListener': no overloaded function takes 4 arguments    ofApp    g:\openFrameworks\libs\openFrameworks\types\ofParameter.h    425    

As @Rancs says you need to give the instance of the function you are calling. Im my case:

// this works:
gain.addListener(&camera, &Camera::setGain);

I still don’t completely get this. When you say:
gain.addListener(&camera, &Camera::setGain);

As the first argument you dereference Camera, so i assume Camera here is an instance of some class you created. But then as the second argument you use &Camera::setGain. why do you have to use the enter namespace operator here if this is an instance of a class, wouldnt you just say &Camera.setGain.

I only see entering the namespace of a class as being useful when it’s a static fucntion youre using, but that doesn’t even seem to be a requirement here.

Not sure if I understand well your question. But just to clarify, lowercase camera is the instance and uppercase Camera is the name of the class. So as @Rancs says you need to give listener class’ instance & listener class method.

Basically you have to tell the listener which function you want to use &Camera::setGain (the setGain function of the Class Camera. Thta’s why you use the :: ) and a pointer to the actual object you want to call this function on (&camera).

1 Like