Qt 耗时操作异步执行:QThread 和 QRunnable 实现详解
在使用Qt框架中,可以使用QThread或者QRunnable来实现耗时操作放在子线程中执行。\n\n使用QThread:\ncpp\n// 创建自定义的线程类\nclass MyThread : public QThread\n{\npublic:\n void run() override\n {\n // 在此处执行耗时操作\n // ...\n }\n};\n\n// 在主线程中创建并启动子线程\nMyThread* thread = new MyThread();\nthread->start();\n\n\n使用QRunnable:\ncpp\n// 创建自定义的任务类\nclass MyRunnable : public QRunnable\n{\npublic:\n void run() override\n {\n // 在此处执行耗时操作\n // ...\n }\n};\n\n// 在主线程中创建并启动子线程\nQThreadPool::globalInstance()->start(new MyRunnable());\n\n\n无论使用QThread还是QRunnable,都需要在相应的run函数中实现耗时操作。需要注意的是,Qt的GUI相关操作只能在主线程中执行,如果需要更新UI,可以通过信号槽机制或者QMetaObject::invokeMethod在子线程中向主线程发送消息,再在主线程中更新UI。
原文地址: https://www.cveoy.top/t/topic/pLf1 著作权归作者所有。请勿转载和采集!