class MyThread : public QObject{
Q_OBJECT
void work(){
qDebug()<<"MyThread::work() thread id: "<<QThread::currentThreadId()<<"\n";
}
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
qDebug()<<"main thread id: "<<QThread::currentThreadId()<<"\n";
QThread* subThread = new QThread;
MyThread* my_thread = new MyThread;
my_thread->moveToThread(thread1);
my_thread->start();
qDebug()<<"00000000";
my_thread->work();
connect(ui->pushButton, &QPushButton::clicked, my_thread, &MyThread::work);
connect(ui->pushButton, &QPushButton::clicked, this, [=]{
qDebug()<<"11111111";
my_thread->work();
});
connect(ui->pushButton, &QPushButton::clicked, my_thread, [=]{
qDebug()<<"22222222";
my_thread->work();
});
}
程序执行结果:
main thread id: 0x1a70
00000000
MyThread::work1() thread id: 0x1a70
11111111
MyThread::work1() thread id: 0x1a70
MyThread::work1() thread id: 0x698
22222222
MyThread::work1() thread id: 0x698
请问为何在主窗口中直接调用 my_thread 和
connect(ui->pushButton, &QPushButton::clicked, this, [=]{
my_thread->work();
});都是在主线程中执行,而其他两种调用方式就能正确在子线程中执行?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.