Qt 创建一个线程执行某个函数

某个函数需要用线程执行时,创建一个一次性的线程,在线程里面调用该函数。



头文件

class TaskThread : public QThread
{
    Q_OBJECT


public:
    TaskThread(QObject *parent = 0);
    ~TaskThread();
    void setFunction(QObject* obj,QString function,QVariant value=NULL);
signals:
    void taskEnd();
public:
    void run();
private:
    int m_index;
    QObject* m_obj;
    QString m_function;
    QVariant m_value;
    QThread *m_Thread;
};


cpp

TaskThread::TaskThread(QObject *parent)
{
    m_index = -1;
    connect(this,SIGNAL(taskEnd()),this,SLOT(deleteLater()));
}
TaskThread::~TaskThread()
{

}

void TaskThread::setFunction(QObject* obj,QString function,QVariant value)
{
    while(m_index != -1)
    {
        QThread::msleep(10);
    }
    m_index = 1;

    m_obj = obj;
    m_function = function;
    m_value = value;
    m_Thread = m_obj->thread();
    m_obj->moveToThread(this);
    start();
}

void TaskThread::run()
{
    QByteArray ba = m_function.toLatin1();
    const char* ch=ba.constData();    
    QMetaObject::invokeMethod(m_obj,ch,Q_ARG(QVariant, m_value));
    m_index = -1;
    m_obj->moveToThread(m_Thread);
    emit taskEnd();
}


阅读更多
个人分类: Qt
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Qt 创建一个线程执行某个函数

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭