• 12972阅读
  • 2回复

在QRunnable发送信号到主线程【已解决】 [复制链接]

上一主题 下一主题
离线daimon0316
 
只看楼主 倒序阅读 楼主  发表于: 2010-10-28
— 本帖被 XChinux 执行加亮操作(2010-10-29) —
QRunnable子类中显示提示信息,用到了GUI,查询资料发现GUI只能在主线程调用,就想通过QRunnable子类发送显示信号到主线程。但一直编译不通过,查资料发现QRunnable与其他QT类不同,并不是继承自QObject。而connect连接器的入参是要求一个QObject对象指针,想想应该是不能这样用的。但网上一些帖子说能够实现,例如:
http://www.qtcn.org/bbs/read.php?tid=23837&fpage=5&toread=&page=1
http://zhbtdy.blog.163.com/blog/static/29035121201091392839126/

如果能够实现,请大叫指点一下。如不能那么这种主线程和其他线程之间如何通讯

代码如下:
1、线程类头文件
  1. #ifndef MYBUSINESS_H
  2. #define MYBUSINESS_H
  3. #include <QRunnable>
  4. class MyBusiness : public QRunnable
  5. {
  6. public:
  7. MyBusiness();
  8. void run();
  9. signals:
  10. void sendShowEmit(QString content);
  11. };
  12. #endif // MYBUSINESS_H


2、线程类cpp文件
  1. #include "mybusiness.h"
  2. MyBusiness::MyBusiness()
  3. {
  4. }
  5. MyBusiness::run()
  6. {
  7. emit sendShowEmit("MyBusiness::run emit.");
  8. }


3、主程序部分相关代码
  1. void MainWindow::showContent(QString content)
  2. {
  3. _MessageShow(content);
  4. }
  5. void MainWindow::timer_thread_done()
  6. {
  7. //执行线程
  8. MyBusiness* thread_bis = new MyBusiness();
  9. connect(thread_bis,SIGNAL(sendShowEmit(QString)),this,SLOT(showContent(QString)));
  10. QThreadPool::globalInstance()->start(thread_bis);
  11. }

[ 此帖被daimon0316在2010-10-29 12:07重新编辑 ]
博客地址 http://blog.sina.com.cn/daimon0316
离线dbzhang800

只看该作者 1楼 发表于: 2010-10-28
1. 因为 QRunnable 不是 QObject 的子类,所以它不能用信号和槽。你要坚信这一点。
    至于别人能用信号和槽,只能说明他使用的多重继承。

不用信号的槽的话,你可以直接使用:
  QMetaObject 的 invokeMethod

http://hi.baidu.com/cyclone/blog/item/1bf8033bbb7498e514cecb50.html

2. 既然要使用信号和槽的话,用QThread可能更合适一点(QRunnable 可能更适合运行大量的小任务)

http://hi.baidu.com/cyclone/blog/item/65f3f603294f2e783812bb51.html
离线daimon0316
只看该作者 2楼 发表于: 2010-10-29
回 1楼(dbzhang800) 的帖子
首先感谢你的回复。

我的业务稍微简单一些,已经通过其他方式解决了。我在程序内部建立了共享消息队列,在主线程中通过定时器取消息进行提示。
博客地址 http://blog.sina.com.cn/daimon0316
快速回复
限100 字节
 
上一个 下一个