I am new to QT and I can’t figure out why my code is not working. It does not matter whether the camera is connected to the PC or not, my app crashes. The crash is probably caused by m_captureSession
related code lines in mainwindow.cpp
.
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCore>
#include <QtGui>
#include <QtWidgets>
#include <QtMultimedia>
#include <QtMultimediaWidgets>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QScopedPointer<QCamera> m_camera;
QScopedPointer<QMediaCaptureSession> m_captureSession;
};
#endif // MAINWINDOW_H
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_camera.reset(new QCamera(QMediaDevices::defaultVideoInput()));
m_captureSession->setCamera(m_camera.data());
m_captureSession->setVideoOutput(ui->cameraViewfinder);
m_camera->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
.pro file:
QT += core gui multimedia multimediawidgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
Camera permission is granted and the QCamera object successfully connects to my device
QCamera camera(QMediaDevices::defaultVideoInput());
this is a local variable in the constructor. It no longer exists after the constructor is finished. Same withQMediaCaptureSession captureSession;
@drescherjm I updated my code. Now it crashes
With the new code you forgot to allocate the
m_captureSession
som_captureSession->setCamera(m_camera.data());
is dereferencing a null pointer.Yeah, you are right. The solution in my case was giving up the idea of using
QScopedPointer
forQMediaCaptureSession
. Thank you so much for help!You can also use a normal raw pointer and set the parent to the
MainWindow
. That way when theMainWindow
is destroyed all its child objects are destroyed.