在qthread中的Sleep调用阻止UI线程

时间:2011-05-24 15:52:27

标签: subclassing qthread

您好 我正在QT 4.6.2中实现一个简单的线程GUI应用程序。我在没有继承它的情况下使用QThread。我在start()函数中调用了usleep()函数,但这会导致GUI冻结。我该如何解决这个问题。以下是代码

#ifndef ECGREADER_H
#define ECGREADER_H
#include<QObject>
class ecgreader : public QObject
{
    Q_OBJECT

public:
    ecgreader(QObject *parent=0);
    ~ecgreader();
public Q_SLOTS:
    void start();
Q_SIGNALS:
    void finished();
};
#endif // ECGREADER_H

下面是start()函数

void ecgreader::start()
{
   int i= system("ls>output.txt");
   SLEEP(10000);
   if(i==0)
   {
       emit finished();
   }
}

最后在这里开始调用

void Application::onbtnclicked()
{
    QThread* thread=new QThread;
    ecgreader* reader=new ecgreader;
    reader->moveToThread(thread);
    connect(thread,SIGNAL(started()),reader,SLOT(start()));
    connect(reader,SIGNAL(finished()),thread,SLOT(quit()));
    connect(reader,SIGNAL(finished()),reader,SLOT(deleteLater()));
    connect(reader,SIGNAL(finished()),thread,SLOT(deleteLater()));
    reader->start();
}

请帮忙

1 个答案:

答案 0 :(得分:2)

你有两个问题:首先你创建了线程,但是你从未启动它。其次,你直接在阅读器上调用start()而不是发出信号。

我认为你的意思是调用thread-&gt; start()而不是reader-&gt; start():

void Application::onbtnclicked()
{
    QThread* thread=new QThread;
    ecgreader* reader=new ecgreader;
    reader->moveToThread(thread);
    connect(thread,SIGNAL(started()),reader,SLOT(start()));
    connect(reader,SIGNAL(finished()),thread,SLOT(quit()));
    connect(reader,SIGNAL(finished()),reader,SLOT(deleteLater()));
    connect(reader,SIGNAL(finished()),thread,SLOT(deleteLater()));
    thread->start();
}