关闭

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

1274人阅读 评论(0) 收藏 举报
分类:

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



头文件

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();
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6046次
    • 积分:111
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:9篇
    • 译文:0篇
    • 评论:0条
    文章分类