V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
h3xz
V2EX  ›  Qt

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

  •  
  •   h3xz · 61 天前 · 466 次点击
    这是一个创建于 61 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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(); });都是在主线程中执行,而其他两种调用方式就能正确在子线程中执行?

    2 条回复    2024-07-08 14:49:03 +08:00
    zonde306
        1
    zonde306  
       61 天前   ❤️ 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
    这个文档就有
    h3xz
        2
    h3xz  
    OP
       61 天前
    @zonde306 原来是这样,非常感谢🙏🙏
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1947 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:19 · PVG 08:19 · LAX 17:19 · JFK 20:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.