简单的摄像头测试类
头文件camerawidget.h
cpp
#ifndef CAMERAWIDGET_H
#define CAMERAWIDGET_H
#include <QWidget>
#include <QList>
#include <QCamera>
#include <QCameraInfo>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QCameraViewfinderSettings>
#include <QVBoxLayout> // Include the QVBoxLayout header
#include <QCameraImageCapture>
QT_BEGIN_NAMESPACE
namespace Ui { class CameraWidget; }
QT_END_NAMESPACE
class CameraWidget : public QWidget
{
Q_OBJECT
public:
explicit CameraWidget(QWidget *parent = nullptr);
~CameraWidget();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::CameraWidget *ui;
QCamera* myCamera;
QCameraViewfinder* vf;
QCameraImageCapture *imageCapture;
void openDevice();
void closeDevice();
};
#endif // CAMERAWIDGET_H
源文件camerawidget.c
cpp
#include "camerawidget.h"
#include "ui_camerawidget.h"
#include <QGraphicsItem>
CameraWidget::CameraWidget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::CameraWidget)
{
ui->setupUi(this);
ui->label->setText("摄像头类型");
myCamera = nullptr;
imageCapture = nullptr; // 初始化图像捕获对象
QString str ;
// 查找所有可用的摄像头信息
QList<QCameraInfo> infos = QCameraInfo::availableCameras();
foreach(QCameraInfo info, infos){
qDebug() << info.description() << info.deviceName();
// Check and set orientation property if available
if(info.deviceName()=="HLC3086-RGB"){
qDebug()<<info.deviceName()+"测试";
QVariantMap properties = myCamera->property("properties").toMap();
if (properties.contains("orientation")) {
myCamera->setProperty("orientation", properties.value("orientation"));
}
}
ui->comboBox->addItem(info.deviceName());
}
setFixedSize(800,700);
setWindowTitle("摄像头测试");
// Create a layout and set it as the main layout for the widget
QVBoxLayout *mainLayout = new QVBoxLayout(this);
ui->frame->setLayout(mainLayout);
}
void CameraWidget::on_pushButton_clicked()
{
closeDevice();
openDevice();
}
void CameraWidget::on_pushButton_2_clicked()
{
closeDevice();
}
void CameraWidget::openDevice(){
if (myCamera == nullptr) {
myCamera = new QCamera(ui->comboBox->currentText().toUtf8(), this);
vf = new QCameraViewfinder(this);
vf->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
qDebug()<<ui->comboBox->currentText().toUtf8();
myCamera->setViewfinder(vf);
// Add the viewfinder to the layout
ui->frame->layout()->addWidget(vf);
myCamera->start();
}
}
void CameraWidget::closeDevice(){
if (myCamera != nullptr) {
myCamera->stop();
delete myCamera; // Clean up the camera
myCamera = nullptr;
// Remove the viewfinder from the layout
ui->frame->layout()->removeWidget(vf);
delete vf; // Clean up the viewfinder
vf = nullptr;
}
}
CameraWidget::~CameraWidget()
{
delete ui;
}