基于Qt的Camera模块实现摄像头的热插拔。当只有一个摄像头时,被拔开后再插入能自动恢复相机状态。当有多个摄像头时,拔开当前摄像头会自动设置另外一个摄像头。
connect(&m_checkDeviceListTimer, SIGNAL(timeout()),
this, SLOT(checkDeviceList()));
deviceListChanged()
;void QtCamera::checkDeviceList()
{
QList<QCameraInfo> curCameraInfoList = QCameraInfo::availableCameras();
if ( m_preCameraInfoList.count() != curCameraInfoList.count() ) {
emit deviceListChanged();
}
m_preCameraInfoList = curCameraInfoList;
}
autoRestore()
槽函数绑定设备列表变化信号。connect(this, SIGNAL(deviceListChanged()),
this, SLOT(autoRestore()));
start()
;
当设备不存在则关闭该设备。void QtCamera::autoRestore()
{
if (! m_isStarted) {
return;
}
if (deviceExist(m_curCameraInfo)) {
if (m_camera->status() != QCamera::ActiveStatus) {
QTimer::singleShot(500, m_camera, SLOT(start()));
}
}
else {
if (m_camera->status() == QCamera::ActiveStatus) {
m_camera->stop();
m_camera->unload();
}
}
}
autoSelectDevice()
槽函数连接设备列表变化信号。connect(this, SIGNAL(deviceListChanged()),
this, SLOT(autoSelectDevice()));
void QtCamera::autoSelectDevice()
{
QList<QCameraInfo> curCameraInfoList = QCameraInfo::availableCameras();
if (curCameraInfoList.isEmpty())
return;
if (curCameraInfoList.contains(m_curCameraInfo)) {
selectDevice(m_curCameraInfo);
return;
}
selectDevice(curCameraInfoList.first());
}
https://github.com/aeagean/QtCamera