Skip to content

Instantly share code, notes, and snippets.

@jniemann66
Last active October 23, 2017 04:50
Show Gist options
  • Save jniemann66/335a3a18279047903670310ffbdc12d5 to your computer and use it in GitHub Desktop.
Save jniemann66/335a3a18279047903670310ffbdc12d5 to your computer and use it in GitHub Desktop.
emitting Qt Signal from inside Obj-C++

in someheader.h (to be #included on the Qt/C++ side):


#include <QObject>

namespace SomeNamespace {

struct SomeViewControllerImpl;

class SomeWrapper : public QObject
{
    Q_OBJECT
    SomeViewControllerImpl* impl;

public:
    SomeWrapper();
    ~SomeWrapper();
    // some other functions ...
    
private:
    void onSomeEvent(Foo someParameter); // callback function

signals:
    void someEvent(Foo foo);

};

} // namespace SomeNamespace

in .mm implementation file:

#include "someheader.h"
#include <functional>

@interface SomeViewController : UIViewController <SomeViewDelegate>
// ...
@property (nonatomic, assign) std::function<void(Foo someParameter)> someCallback;
// ...
@end

@implementation SomeViewContoller

// ... 

- someEvent {
    
    Foo value = ... ;
  
   // call the callback:
    if(self.someCallback != nil) {
        self.someCallback(value);
    }
}

// ...

@end


namespace SomeNamespace {

struct SomeViewControllerImpl
{
    SomeViewController* someViewController;
};

// C++ wrapper Implementation


// constructor:
SomeWrapper::SomeWrapper() : impl(new SomeViewControllerImpl) {

    UIViewController* rootController = [UIApplication sharedApplication].keyWindow.rootViewController;
    NSLog(@"View controller loaded.");
    impl->someViewController = [[SomeViewController alloc] init];
    
    @try {
        NSLog(@"Starting SomeViewController ...");
        // ...
        
        // present SomeViewController:
        [rootController presentViewController:impl->someViewController animated:YES completion:nil];
       
        // register the callback (capture member function, this pointer and an arg): 
        [impl->someViewController setSomeCallback:(std::bind(&SomeWrapper::onSomeEvent, this, std::placeholders::_1))];
    }

    @catch (NSException *exception) { // ... }
}

SomeWrapper::~SomeWrapper() {
    if(impl) {
        [impl->someViewController release];
    }
    delete impl;
}

void SomeWrapper::onEvent(Foo foo) {
    emit someEvent(foo);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment