说明
- 同线程时,直接调用回调(block参数没意义)
- 创建invoker所在的线程,需要有Qt的消息循环(比如UI线程)
直接上代码
typedef std::function<void()> InvokerFunc; class Invoker: public QObject { Q_OBJECT public: Invoker(QObject *parent=0): QObject(parent) { qRegisterMetaType<InvokerFunc>("InvokerFunc"); } void execute(const InvokerFunc &func, bool block) { if (QThread::currentThread()==thread()) {//is same thread func(); return; } if (block) { metaObject()->invokeMethod(this, "onExecute", Qt::BlockingQueuedConnection, Q_ARG(InvokerFunc, func)); } else{ metaObject()->invokeMethod(this, "onExecute", Qt::QueuedConnection, Q_ARG(InvokerFunc, func)); } } private slots: void onExecute(const InvokerFunc &func) { func(); } };