要使用摄像头,就需要链接多媒体模块以及多媒体工具模块
需要在.pro文件中添加QT += multimedia multimediawidgets
是用的库文件
QCamera 类用于打开系统的摄像头设备,
QCameraViewfinder 用于显示捕获的视频,
QCameraImageCapture 用于截图。
mainwindows.h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
//摄像头
#include <QCamera>
#include <QCameraImageCapture>QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private:Ui::MainWindow *ui;QCamera *ca;QCameraImageCapture *capture;
};
#endif // MAINWINDOW_H
mainwindows.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
//调用摄像头
#include <QCameraInfo>
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QPixmap>
//弹窗
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);//获取可用摄像头设备并输出在控制台QList<QCameraInfo> infos = QCameraInfo::availableCameras();qDebug() << infos.value(0).deviceName() << ":" <<infos.value(0).description();QString camera = infos.value(0).deviceName();qDebug() << camera;//显示摄像头ca =new QCamera(camera.toUtf8() ,this );ui->camera->show();QCameraViewfinder *v2 = new QCameraViewfinder(ui->camera);v2->resize(ui->camera->size());ca->setViewfinder(v2);v2->show();ca->start();capture = new QCameraImageCapture(ca);capture->capture("home/hua/XXX/.jpg");QMessageBox::information(this, "ok", "ok!");
}MainWindow::~MainWindow()
{delete ui;
}