1、使用ui创建一个普通的桌面,放入两个Qcombox,一个按键,UI如下:
2、在.pro中添回摄像头的引用:
QT += multimedia multimediawidgets
3、mainwindows.h文件内容如下:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class QCamera;
class QCameraViewfinder;
class QCameraImageCapture;
class QCameraInfo;
class QCameraViewfinderSettings;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QCamera *camera;
QCameraViewfinder *viewfinder;
QCameraImageCapture *imageCapture;
QList<QCameraInfo> cameras;
QList<QSize> mResSize = {};
};
#endif
4、mainwindos.cpp内容如下:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("Camera");
setFixedSize(600,400);
cameras = QCameraInfo::availableCameras();
if (cameras.count() > 0) {
for(const QCameraInfo &cameraInfo:cameras) {
qDebug() << cameraInfo.description();
}
camera = new QCamera(cameras.at(0));
}
viewfinder = new QCameraViewfinder(this);
camera->setViewfinder(viewfinder);
viewfinder->resize(600,350);
imageCapture = new QCameraImageCapture(camera);
camera->start();
QCameraViewfinderSettings set;
set.setResolution(640, 480);
set.setMaximumFrameRate(60);
camera->setViewfinderSettings(set);
for(const QCameraInfo &cameraInfo:cameras) {
qDebug() << "CameraInfo:" << cameraInfo;
ui->cameraSel->addItem(cameraInfo.description());
}
ui->cameraSel->setCurrentIndex(0);
mResSize = camera->supportedViewfinderResolutions();
for (const QSize &msize:mResSize) {
qDebug() << msize;
ui->resolutionSel->addItem(QString::number(msize.width(), 10) + "*" + QString::number(msize.height(), 10));
}
ui->resolutionSel->setCurrentIndex(0);
connect(ui->cameraSel, QOverload<int>::of(&QComboBox::activated), [=](int index){
camera->stop();
delete camera;
camera = new QCamera(cameras[index]);
camera->setCaptureMode(QCamera::CaptureStillImage);
camera->setViewfinder(viewfinder);
camera->start();
for (int i = 0; i < mResSize.size(); i++) {
ui->resolutionSel->removeItem(0);
}
mResSize.clear();
mResSize = camera->supportedViewfinderResolutions();
for (const QSize &msize:mResSize) {
qDebug() << msize;
ui->resolutionSel->addItem(QString::number(msize.width(), 10) + "*" + QString::number(msize.height(), 10));
}
ui->resolutionSel->setCurrentIndex(0);
});
connect(ui->resolutionSel, QOverload<int>::of(&QComboBox::activated), [=](int index){
QCameraViewfinderSettings reset;
reset.setResolution(mResSize[index]);
camera->setViewfinderSettings(reset);
});
connect(ui->screenShot, &QPushButton::clicked, [=](){
camera->setCaptureMode(QCamera::CaptureStillImage);
delete imageCapture;
imageCapture = new QCameraImageCapture(camera);
QString fileName = QFileDialog::getSaveFileName();
camera->searchAndLock();
imageCapture->capture(fileName);
camera->unlock();
});
}
MainWindow::~MainWindow()
{
delete ui;
}
具体的代码见注释。
5、编译下载到开发板,效果如下!