设计界面原型用定时器模拟程序运行,处理数据的程序运行时间很长,并要实时显示进度,需要使用多线程技术。运行程序出现下面的警告:

 
1
thread

警告无法再另一个进程中开始定时器。在QTimer的官方文档里,有下面一段话:

 
1
.

指出必须在同一个线程里开始和停止定时器,也就是只有在创建定时器的线程里才能接受到timeout()信号。我的代码中使用QObject::moveToThread()方法实现多线程

 

 
1
2
3
4
5
6
7
8
 
;
//TODO:? parent
;
;
;
;
 

 

在LocalDirDataImporterService构造函数中初始化定时器

 

 
1
2
3
4
5
6
7
 
:
//...
//...
;
//...
 

 

在LocalDirDataImporterService::excuteImport()中开启定时器

 

 
1
2
3
4
5
6
7
8
 
)
{
;
;
;
}
 

 

如上,定时器在GUI进程中初始化,无法在子工作进程中开始定时器。需要在子工作进程中初始化定时器。

 

 
1
2
3
4
5
6
7
8
9
 
void LocalDirDataImporterService::excuteImport()
{
    list_timer = new QTimer();
    list_timer->setInterval(1000);
    list_timer->start();
    this->connect(list_timer,SIGNAL(timeout()),this,SLOT(testImportItem()));
}
 

 

这样定时器就可以正常使用了。


 

Stackoverflow上看到另一种方法,将定时器和工作类都移到某个子进程:
http://stackoverflow.com/questions/15835267/qthread-and-qtimer

工作类

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
QObject
{
Q_OBJECT
:
}
 
:
;
 
:
{
;
}
;
 

主程序

 
 
 
 
 
C++
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
)
{
;
 
;
 
;
;
;
;
 
;
;
 
;
;
;
 
;
 
;
}
 

相关文章:

  • 2022-02-18
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案