简体   繁体   中英

Using QCamera/QCameraInfo from a QThread

I have a Camera class that at the moment simply returns how many available cameras there are connected to the computer. A Camera object is created my PhotoProcessor class (QWidget) and then moved to another thread because I noticed some slight hanging when checking for available cameras:

in photoprocessor.cpp

void PhotoProcessor::GetAvailableCameras()
{
    //Create new camera to go and fetch number of cameras.
    Camera *camera_connection = new Camera;

    //Create thread and send away.
    QThread *thread = new QThread;
    camera_connection->moveToThread(thread);
    connect(camera_connection, SIGNAL(CameraCountSignal(int)), this, SLOT(CameraCountSlot(int)));
    connect(thread, SIGNAL(started()), camera_connection, SLOT(GetAvailableCameras()));
    connect(camera_connection, SIGNAL(CloseCameraThreadSignal()), thread, SLOT(quit()));
    connect(camera_connection, SIGNAL(CloseCameraThreadSignal()), camera_connection, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();

    return;
}

camera.h

#ifndef CAMERA_H
#define CAMERA_H

#include <QObject>
#include <QCamera>
#include <QCameraInfo>

class Camera : public QObject
{
    Q_OBJECT

public:
    Camera();

public slots:
    void GetAvailableCameras();

signals:
    void CameraCountSignal(int);
    void CloseCameraThreadSignal();
};

#endif // CAMERA_H

camera.cpp

#include "camera.h"

Camera::Camera()
{

}

void Camera::GetAvailableCameras()
{  
    QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
    emit CameraCountSignal(cameras.size());
    emit CloseCameraThreadSignal();
    return;
}

When running QCameraInfo::availableCameras() from photoprocessor.cpp it says that there is a single camera connected which is correct, however no matter what I do, the threaded Camera object can never detect the camera ie size of cameras is zero.

What is happening here?

After a year, I decided to revisit this issue again.

I think in my actual code I created a QCamera object and when the thread was deleted, I deleted incorrectly and after the thread finished, I could not longer find any cameras using QCameraInfo::availableCameras().

Setting the parent of the new QCamera object explicitly fixed this issue for me ie

QCamera *camera = new QCamera(QCameraInfo);
camera->setParent(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM