我第二次问这个问题而且我没有找到一个我不太熟悉qt事件的解决方案。这是我的代码:
class My_worker :public QObject{};
我在该类中有一个函数,它将定期发送带有计时器的数据。
My_worker::process{
Qtimer my_timer=new Qtimer();
my_timer->setInterval(time_ms);
connect(my_timer,SIGNAL(timeout()),this(sendData()))
}
所以使用函数sendData()
我发送的数据已经过了my_timer。这是我完成工作的主题。我在QCoreapplication
课程中创建了这些内容。这样:
class My_Application: public QCoreApplication{};
在构造函数中,我像这样定义信号和威胁。
My_Application::My_Application{
//First I create an object of My_worker
My_worker my_worker=new My_worker();
//Then I create a thread and move my worker to thread
QThread my_thread=new QThread();
my_worker->moveToThread(my_thread);
// then I connect the signals.
connect(my_thread,SIGNAL(started)),my_worker,SLOT(process())); //So starts processing
connect(my_worker,SIGNAL(finished()),my_thread,SLOT(quit()));
connect(my_thread,SIGNAL(finished()),my_thread,SLOT(deleteLater))));
connect(my_worker,SIGNAL(finished()),my_worker,SLOT(deleteLater()));
}
最后我的dataSend()函数是;
void dataSend(){
//do some work
// **if I emit my finished signal here I see that the destructor of my_worker is called**
}
但是我不想在这里发出信号,我想在我的My_Application完成时破坏my_work。
所以在My_Application析构函数中我尝试删除my_worker,因此析构函数是
My_Application::~My_Application(){
cout<<"the destructor called for app"<<endl;
if(my_worker->thread())
connect(my_worker,SIGNAL(destroyed()),my_thread,SLOT(quit()));
my_worker->deleteLater(); // this does not work and does not call my_worker destc.
}
答案 0 :(得分:0)
也许这可能会解决您的问题:
class My_worker :public QObject, public QRunnable{
Q_OBJECT
public:
My_Worker() : loop(0) {}
void run();
public slots:
void sendData();
void quit();
private:
QEventLoop *loop;
};
My_Worker.cpp
void My_Worker::run(){
QTimer timer;
timer.setInterval(time_ms);
connect(&timer, SIGNAL(timeout()), this, SLOT(sendData()));
loop = new QEventLoop;
loop->exec();
delete loop;
}
void My_Worker::quit(){
if (loop){
loop->quit();
}
}
My_Application.cpp
My_Application::My_Application(){
My_worker *my_worker=new My_worker();
connect(this, SIGNAL(aboutToQuit()), my_worker, SLOT(quit()));
QThreadPool::globalInstance()->start(my_worker);
}
有关QThreadPool,QEventLoop和QRunnable课程的详细信息,请参阅文档。