qtqtmultimediaqt6qcamera

Replace QCameraViewfinder with QVideoWidget in Qt 6


I am trying to port some code to Qt 6's reworked QtMultimedia framework and running into a lot of issues of disappearing APIs.

One of these is QCameraViewfinder, which as I understand it, is a simple viewer of the current QCamera image feed. It used to be a subclass of QVideoWidget, which still exists, and its documentation helpfully states the following:

Attaching a QVideoWidget to a QMediaPlayer or QCamera allows it to display the video or image output of that object.

player = new QMediaPlayer;
player->setSource(QUrl("http://example.com/myclip1.mp4"));

videoWidget = new QVideoWidget;
player->setVideoOutput(videoWidget);

videoWidget->show();
player->play();

Note: Only a single display output can be attached to a media object at one time.

Problem is, there is no way to do QCamera::setVideoOutput(QVideoWidget*) as that function does not exist. Neither can I find an alternative API that connects the two. Is this something that they forgot to provide or am I missing something? I looked through the relevant classes' source code and documentation, but can't for the life of me find the magic incantation that's supposed to give me a simple view into a QCamera's current video feed.


Solution

  • You have to use QMediaCaptureSession:

    #include <QApplication>
    #include <QCamera>
    #include <QMediaDevices>
    #include <QMediaCaptureSession>
    #include <QVideoWidget>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QVideoWidget videoWidget;
        videoWidget.resize(640, 480);
        videoWidget.show();
    
        QCamera camera(QMediaDevices::defaultVideoInput());
        camera.start();
    
        QMediaCaptureSession mediaCaptureSession;
        mediaCaptureSession.setCamera(&camera);
        mediaCaptureSession.setVideoOutput(&videoWidget);
    
        return a.exec();
    }