Qt编写UI界面控制摄像头读视频的代码
时间: 2023-05-11 07:07:25 浏览: 54
以下是一个使用Qt编写UI界面控制摄像头读视频的代码示例:
```cpp
#include <QMainWindow>
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QVBoxLayout>
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QFileDialog>
#include <QMessageBox>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
// 创建摄像头对象
m_camera = new QCamera(this);
// 创建摄像头取景器对象
m_viewfinder = new QCameraViewfinder(this);
m_viewfinder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// 创建摄像头图像捕获对象
m_imageCapture = new QCameraImageCapture(m_camera, this);
// 创建布局管理器
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_viewfinder);
// 创建主窗口中心部件
QWidget *centralWidget = new QWidget(this);
centralWidget->setLayout(layout);
setCentralWidget(centralWidget);
// 设置摄像头取景器为摄像头的视图
m_camera->setViewfinder(m_viewfinder);
// 创建菜单栏
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
// 创建打开动作
QAction *openAction = new QAction(tr("&Open"), this);
fileMenu->addAction(openAction);
connect(openAction, &QAction::triggered, this, &MainWindow::openFile);
// 创建保存动作
QAction *saveAction = new QAction(tr("&Save"), this);
fileMenu->addAction(saveAction);
connect(saveAction, &QAction::triggered, this, &MainWindow::saveFile);
// 创建开始动作
QAction *startAction = new QAction(tr("&Start"), this);
fileMenu->addAction(startAction);
connect(startAction, &QAction::triggered, this, &MainWindow::startCamera);
// 创建停止动作
QAction *stopAction = new QAction(tr("&Stop"), this);
fileMenu->addAction(stopAction);
connect(stopAction, &QAction::triggered, this, &MainWindow::stopCamera);
// 设置窗口标题
setWindowTitle(tr("Camera"));
// 设置窗口大小
resize(640, 480);
}
private slots:
void openFile()
{
// 打开文件对话框
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("Images (*.png *.xpm *.jpg)"));
// 如果文件名不为空,则加载文件
if (!fileName.isEmpty()) {
QImage image(fileName);
if (image.isNull()) {
QMessageBox::information(this, tr("Camera"), tr("Cannot load %1.").arg(fileName));
return;
}
m_viewfinder->setPixmap(QPixmap::fromImage(image));
}
}
void saveFile()
{
// 保存文件对话框
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(), tr("Images (*.png *.xpm *.jpg)"));
// 如果文件名不为空,则保存文件
if (!fileName.isEmpty()) {
QImage image = m_viewfinder->grab().toImage();
if (!image.save(fileName)) {
QMessageBox::information(this, tr("Camera"), tr("Cannot save %1.").arg(fileName));
}
}
}
void startCamera()
{
// 开始摄像头
m_camera->start();
}
void stopCamera()
{
// 停止摄像头
m_camera->stop();
}
private:
QCamera *m_camera;
QCameraViewfinder *m_viewfinder;
QCameraImageCapture *m_imageCapture;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
```
这个代码演示了如何使用Qt编写UI界面控制摄像头读视频的功能,包括打开、保存、开始和停止摄像头等操作。