Qt主线程发送图片给子线程
时间: 2024-11-18 10:06:49 浏览: 30
在Qt中,主线程通常用于处理用户界面交互和UI相关的任务,而子线程用于执行耗时操作,如网络请求、图像处理等,以避免阻塞UI。如果你想从主线程发送图片到子线程,可以采用信号槽(Signal-Slot)机制或者使用QThread和QRunnable。
**1. 使用信号槽(推荐):**
主线程通过`emit`信号将图片数据传递给子线程。首先,在主线程的类里定义一个信号:
```cpp
class MainThread : public QObject {
public slots:
void sendImage(QImage image);
};
```
然后在`sendImage`方法中创建并发射信号:
```cpp
void MainThread::sendImage(QImage image) {
emit imageReady(image);
}
// 某处触发这个信号
QImage img;
// ...加载或生成图片
sendImage(img);
```
在子线程类中,连接这个信号,并在槽函数中接收图片:
```cpp
class WorkerThread : public QThread, public QObject {
public:
WorkerThread(MainThread *parent) : QThread(parent), m_parent(parent) {}
private slots:
void receiveImage(const QImage &image) {
// 在这里处理图片
processImage(image);
}
signals:
void imageReceived(const QImage &image);
protected:
void run() override {
// 这里等待主线程信号
connect(m_parent, &MainThread::imageReady, this, &WorkerThread::receiveImage);
// 主循环等待信号直到结束
while (!isInterruptionRequested()) {
m_parent->wait();
}
}
private:
MainThread *m_parent;
};
```
**2. 使用QThread和QRunnable(较复杂):**
创建一个继承自`QObject`的类,里面包含处理图片的方法,并设置成`QRunnable`的实例。在主线程中创建`QRunnable`实例并交给`QThread`执行:
```cpp
class ImageProcessor : public QObject, public QRunnable {
public:
ImageProcessor(QImage img, WorkerThread *thread) : m_image(img), m_thread(thread) {}
void run() override { processImage(m_image); }
private:
QImage m_image;
WorkerThread *m_thread;
};
// 发起处理图片
ImageProcessor processor(img, workerThread);
workerThread.start(); // 启动子线程
processor.wait(); // 等待子线程完成
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)