我是QThreads的新手,我怀疑在程序完成时删除对象。我的程序有一个派生自QObject的类:
class My_application: public QCoreApplication{
....
....
};
class My_Class: public QObject{
...
...
};
void My_Class::process{
QTimer timer=new QTimer();
timer->setInterval(time);
connect(timer,SIGNAL(timeout()),this,SLOT(dowork()));
timer->start();
}
My_application::My_application:QCoreApplication{
my_class=new My_Class();
QThread thread=new QThread();
my_class->moveToThread(thread);
connect(thread,SIGNAL(started()),my_class,SLOT(process())) ;
connect(my_class,SIGNAL(finished()),thread,SLOT(quit())) ;
connect(thread,SIGNAL(finished()),thread,SLOT(deletelater())) ;
connect(my_class,SIGNAL(finished()),my_class,SLOT(deletelater())) ;
}
void My_Class::dowork(){
//here doing the work with timer elapsed.Doing work with some buffer and send data
//
}
如果我停止我的程序,我发现有些对象没有被正确删除,当我重新启动它时我的程序不起作用。实际上我对Qt线程不太熟悉,我想知道什么时候会调用My_Class的析构函数?我做错了什么?
答案 0 :(得分:0)
您忘记控制计时器的生命周期(My_Class::process
):
connect( this, SIGNAL( destroyed() ), timer, SLOT( deleteLater() ) );
或QTimer timer=new QTimer( **this** );
您应手动删除my_class=new My_Class();
。它不会在线程的finished
信号上删除,因为没有事件循环来处理deleteLater
槽。
我很困惑,您为什么不想将my_class
声明为My_application
的成员?