gpt4 book ai didi

c++ - Qt中正确的线程方式

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:21:58 25 4
gpt4 key购买 nike

我有耗时的图像加载(图像很大),并且在加载时对其进行了一些操作。我不想阻止应用程序 GUI。

我的想法是在另一个线程中加载图像,发出图像已加载的信号,然后使用该图像重绘 View 。

我的方法:

void Window::loadImage()
{
ImageLoader* loaderThread = new ImageLoader();
connect(loaderThread,SIGNAL(imageLoaded()),this,SLOT(imageLoadingFinished());
loaderThread->loadImage(m_image, m_imagesContainer, m_path);
}
void Window::imageLoadingFinished()
{
m_imagesContainer->addImage(m_image);
redrawView();
}

class ImageLoader : public QThread
{
Q_OBJECT
public:
ImageLoader(QObject *parent = 0) : m_image(NULL), m_container(NULL)

void loadImage(Image* img, Container* cont, std::string path)
{
m_image = img;
m_container = cont;
...
start();
}
signals:
void imageLoaded();
protected:
void run()
{
//loading image and operations on it
emit imageLoaded();
}
protected:
Image* m_image;
Container* m_container;
}

我是基于 Qt 中的 quedcustomtype 示例编写这段代码的。在 stackoverflow 中搜索和搜索时,我还发现子类化 QThread 不是一个好主意。

那么问题是正确的做法是什么?正如我所说,我希望在另一个线程中完成非阻塞 GUI、加载和操作,并发出表示加载已完成的信号。发出信号后,应重新绘制 View 。我对多线程知之甚少,但想了解或有足够的知识来了解基本思想。

最佳答案

使用QtConcurent框架。

#include <QtConcurentRun>
#include <QFutureWatcher>

//....
class Window: public QWidget /*or something*/
{
//....
private:
QFutureWatcher<QImage> _wacther; //this object will signal when loading finished
};

//...

void Window::loadImage()
{
connect(&_watcher, SIGNAL(finished(), SLOT(finishLoading());
_wacther.setFuture(QtConcurent::run<QImage>(this, &Window::doLoadImage));
}

QImage Window::doLoadImage() //this function will be executed in the new thread. SHOULD BE Thread Safe
{
return someImage;
}

void window::finishLoading()
{
QImage result = _watcher.result();
}

关于c++ - Qt中正确的线程方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13878745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com