Record Webcam Video in Qt 6 Application using OpenCV

Record Webcam Video in Qt 6 Application using OpenCV

In modern application development, integrating multimedia functionalities like recording webcam video is quite common task. Qt, a powerful C++ framework, provides an extensive set of tools for creating cross-platform applications with a user interface. OpenCV, on the other hand, is a popular library for computer vision and image processing tasks. Combining these two technologies allows developers to create robust applications with advanced multimedia capabilities. This tutorial shows how to record webcam video in Qt 6 application using OpenCV.

The provided code sets up a Qt application that captures video from a webcam using OpenCV. It defines the size of the video frames and the frames per second (fps) for the video capture.

The application creates a window with buttons to start and stop video capture. It establishes connections between these buttons and corresponding functions to control the video capture. A QTimer object is used to continuously capture frames from the webcam at the specified fps. When the start button is clicked, a VideoWriter object is initialized to save the captured frames to an output video file. When the stop button is clicked, the VideoWriter object is released, indicating the end of video capture.

#include <QApplication>
#include <QLabel>
#include <QImage>
#include <QVBoxLayout>
#include <QTimer>
#include <QPushButton>
#include <opencv2/opencv.hpp>

int main(int argc, char *argv[])
    QApplication app(argc, argv);

    QSize size(640, 480);
    int fps = 30;
    int codec = cv::VideoWriter::fourcc('m', 'p', '4', 'v');

    cv::VideoCapture cap(0);
    cap.set(cv::CAP_PROP_FRAME_WIDTH, size.width());
    cap.set(cv::CAP_PROP_FRAME_HEIGHT, size.height());
    if (!cap.isOpened()) {
        std::cout << "Cannot open webcam" << std::endl;

        return -1;

    auto *window = new QWidget();
    QLabel imageLabel;
    QPushButton startButton("Start");
    QPushButton stopButton("Stop");

    cv::VideoWriter video;

    bool started = false;
    cv::Mat frame;
    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, [&]() {
        cap >> frame;
        if (started) {
        QImage qimg(, frame.cols, frame.rows, frame.step, QImage::Format_BGR888);

    QObject::connect(&startButton, &QPushButton::clicked, [&]() {"out.mp4", cv::CAP_FFMPEG, codec, fps, cv::Size(size.width(), size.height()));
        started = true;
    QObject::connect(&stopButton, &QPushButton::clicked, [&]() {
        started = false;

    timer.start(1000 / fps);

    QVBoxLayout layout(window);

    return QApplication::exec();

Leave a Comment

Cancel reply

Your email address will not be published.