主界面为显示框,两个下拉框,一个是所有相机,一个是相机支持的分辨率
系统根据UI界面自动生成的部分不再描述,以下为其他部分源码
widget.h
#include <QWidget>
#include <QMouseEvent>
class QCamera;
class QCameraViewfinder;
class QCameraImageCapture;
class QCameraInfo;
class QCameraViewfinderSettings;namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();private:Ui::Widget *ui;QCamera *camera; //相机QCameraViewfinder *viewfinder; //取景器QList<QCameraInfo> cameras; //相机列表QList<QSize> mResSize = {}; //分辨率列表
};
main.cpp
#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QCamera>
#include <QCameraInfo>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QList>
#include <QFileDialog>
#include <QDebug>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);cameras = QCameraInfo::availableCameras();if(cameras.count() > 0) {camera = new QCamera(cameras.at(0));}viewfinder = new QCameraViewfinder(this);camera->setViewfinder(viewfinder);viewfinder->resize(600, 350);camera->start();//添加初始化的相机选项for(const QCameraInfo &cameraInfo:cameras) {ui->comboBox_cam->addItem(cameraInfo.description());}ui->comboBox_cam->setCurrentIndex(0);//添加初始化相机的分辨率选项mResSize = camera->supportedViewfinderResolutions();for (const QSize &msize:mResSize) {ui->comboBox_format->addItem(QString::number(msize.width(), 10) + "*" + QString::number(msize.height(), 10));}ui->comboBox_format->setCurrentIndex(0);QCameraViewfinderSettings init;init.setResolution(mResSize[0]);camera->setViewfinderSettings(init);connect(ui->comboBox_cam,QOverload<int>::of(&QComboBox::activated),[=](int index){camera->stop();delete camera;camera=new QCamera(cameras[index]);camera->setViewfinder(viewfinder); //设置取景器camera->start();//删除前相机的所有分辨率内容for (int i = 0; i < mResSize.size(); i++) {ui->comboBox_format->removeItem(0);}mResSize.clear();mResSize = camera->supportedViewfinderResolutions();for (const QSize &msize:mResSize) {ui->comboBox_format->addItem(QString::number(msize.width(), 10) + "*" + QString::number(msize.height(), 10));}ui->comboBox_format->setCurrentIndex(0);QCameraViewfinderSettings reset;reset.setResolution(mResSize[0]);camera->setViewfinderSettings(reset);});connect(ui->comboBox_format, QOverload<int>::of(&QComboBox::activated), [=](int index){//重新设置摄像头参数QCameraViewfinderSettings reset;reset.setResolution(mResSize[index]);camera->setViewfinderSettings(reset);});}
Widget::~Widget()
{delete ui;
}
运行效果图