跳转到内容
彼岸论坛
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[Qt] 关于 QT(C++)通过继承 QObject 的方法实现多线程,子线程调用失效。


已推荐帖子

发表于
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(); });都是在主线程中执行,而其他两种调用方式就能正确在子线程中执行?

  • 游客注册

    游客注册

  • 会员

    没有会员可显示

  • 最新的状态更新

    没有最新的状态更新
  • 最近查看

    • 没有会员查看此页面.
×
×
  • 创建新的...