I'm trying to update an image from a thread. As you can see, I'm using mutexes to protect the std::shared_ptr<QImage>
of being rewritten. However, it will not work if the call
painter->drawImage(this->boundingRect(), *qImage);
works asynchronously. I'm getting segfault rigth at the moment of painter->drawImage
, however if I start the debugger, I don't get it, maybe because it's too slow so there's time for the image to be written to screen before it gets overwritten.
Here is CameraView.h
#ifndef CAMERA_VIEW_H
#define CAMERA_VIEW_H
#include <QObject>
#include <QQuickPaintedItem>
#include <QImage>
#include <QPainter>
#include <memory>
#include <mutex>
class CameraView : public QQuickPaintedItem
{
Q_OBJECT
Q_DISABLE_COPY(CameraView)
public:
CameraView(QQuickItem* parent = nullptr) {
}
void updateImage(std::shared_ptr<QImage> qImage);
public slots:
void paint(QPainter *painter) override;
protected:
std::shared_ptr<QImage> qImage;
std::mutex qImageMutex;
};
#endif //CAMERA_VIEW_H
#include "CameraView.h"
Here is CameraView.cpp
//called by worker thread
void CameraView::updateImage(std::shared_ptr<QImage> qImage)
{
std::unique_lock<std::mutex> lk{qImageMutex};
this->qImage= qImage;
}
//called by update() (I guess). and update() is called from the main thread through QMetaObject::invokeMethod, so it runs on the main thread
void CameraView::paint(QPainter* painter)
{
std::unique_lock<std::mutex> lk{qImageMutex};
painter->drawImage(this->boundingRect(), *qImage);
}