我有一个 Camera 类,目前它只返回连接到计算机的可用摄像头数量。在我的 PhotoProcessor 类 (QWidget) 中创建了一个 Camera 对象,然后移动到另一个线程,因为在检查可用相机时我注意到一些轻微的挂起:
在光处理器.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;
}
相机.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
相机.cpp
#include "camera.h"
Camera::Camera()
{
}
void Camera::GetAvailableCameras()
{
QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
emit CameraCountSignal(cameras.size());
emit CloseCameraThreadSignal();
return;
}
从 photoprocessor.cpp 运行 QCameraInfo::availableCameras() 时,它说连接了一个正确的相机,但是无论我做什么,线程化的 Camera 对象永远无法检测到相机,即相机的大小为零。
这里发生了什么?