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

标签 c++ multithreading qt qthread

我有耗时的图像加载(图像很大),并且在加载时对其进行了一些操作。我不想阻止应用程序 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/

相关文章:

c++ - 未指定的错误找不到作者

c++ - 在文件扩展名和应用程序之间创建关联性?

javascript - #onmessage 和 #postmessage 如何在主线程和 HTML5 的 webworkers 之间进行通信?

C++ pThread 程序未运行完成

c++ - boost::this_thread::get_id 在 exit() 调用期间不返回 id

c++ - 如何将 QGraphicsScene 动画渲染到电影文件中?

c++ - 覆盖boost中的验证方法不适用于样式集

c++ - 初始化 boost::shared_ptr<A> 类型变量的正确方法

c++ - QDialog : need pressed button or return value

c++ - QVector 和 std::vector 的大小方法