主要问题:如何将主线程(GUI线程)的一个槽函数(耗时代码),放入子线程中运行?
新手,网上搜索一下,还是不解。目前尝试了一下,想使用信号槽机制,没成功。
希望有人指点,谢谢~
MyThread类
class MyThread : public QThread
{
public:
MyThread(QObject *parent = 0);
protected:
void run();
signals: void sigtest(); //自定义的一个信号
};
MyThread::MyThread(QObject *parent)
: QThread(parent)
{
}
void MyThread::run()
{
static int i=0;
while(true)
{
++i;
QString tp = QString::number(i,10);
emit sigtest();
qDebug()<<"count:"<<tp<<" subThread:"<<currentThreadId();
QThread::sleep(1);
}
}
void MyThread::sigtest() //为什么要写这个才不报错?其他例子好像没有。
{}
MainWindow类(GUI线程部分)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
a = new MyThread;
connect(a,SIGNAL(sigtest()),this,SLOT(TestThreadFunction()),Qt::DirectConnection);
}
void MainWindow::TestThreadFunction() //假设为是一个耗时代码部分,想放到子线程运行
{
ui->label->setText(tr("slot worked!"));
qDebug()<<"slot location:"<<QThread::currentThreadId();
}
void MainWindow::on_pushButton_clicked() //打开子线程的槽函数
{
a->start();
ui->label->setText("thread is started!");
qDebug()<<"Main thread:"<<QThread::currentThreadId();
}
问题1:
void MyThread::sigtest()
{}
为啥要写出信号的实现,不然编译不通过报错如下:mythread.o:-1: In function `MyThread::run()':mythread.cpp:17: 错误:undefined reference to `MyThread::sigtest()':-1: 错误:collect2: ld returned 1 exit status我看其他人的程序,都是直接声明的信号,然后直接emit,为啥上述程序就不行?
版本:Qt4.7.2,Qt Creator 2.1.0
问题2:
不知道为什么信号没反应,run()函数运行后,emit sigtest(),可相应的TestThreadFunction()槽函数没调用。
问题3:
关于connect()函数的第五个参数DirectConnection表示立即在发射信号的线程里执行slot, QueuedConnection表示在接受者所在的线程执行slot。那么,上边程序中信号sigtest()到底是在那个线程发出?线程a对象在GUI线程中,但信号发出代码写在run()次线程中。