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();
});都是在主线程中执行,而其他两种调用方式就能正确在子线程中执行?
1
zonde306 146 天前 1
因为你的 `QObject::connect` 第三个参数 `receiver` 是 `this`,所以用的是主线程(因为与`sender`处于相同线程),文档有说明的,会根据接收方对象所在线程来决定在哪个线程执行 `method`(默认情况下的`type`参数)
详见: https://doc.qt.io/qt-6/qt.html#ConnectionType-enum 以及: https://doc.qt.io/qt-6/qobject.html#connect-2 这个文档就有 |