说明

  1. 同线程时,直接调用回调(block参数没意义)
  2. 创建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();
    }
};

 

posted on 2015-12-10 14:45  淡菊  阅读(1209)  评论(0编辑  收藏  举报