I want to bring live view of camera in C++ inside QT.
I have tried the following code.
In the code below, what happens is that all the cameras connected to the laptop are shown in the combo-box, and then when we select a camera from the combo-box and then click on the
Start button, the live view of the selected camera appears. But black and white live view comes. But I do not want black and white live view. What is to be done is that the original colors should appear in the live view. How do I bring original colors in live view???
What I have tried:
#include <QApplication>
#include <QWidget>
#include <QComboBox>
#include <QPushButton>
#include <QCamera>
#include <QCameraInfo>
#include <QCameraViewfinder>
#include <QVBoxLayout>
#include <QMessageBox>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
QComboBox cameraDropdown;
QPushButton startButton("Start");
QPushButton stopButton("Stop");
QCamera *camera = nullptr;
QCameraViewfinder *cameraViewfinder = new QCameraViewfinder();
QVBoxLayout layout(&window);
layout.addWidget(&cameraDropdown);
layout.addWidget(&startButton);
layout.addWidget(&stopButton);
layout.addWidget(cameraViewfinder);
QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
foreach (const QCameraInfo &cameraInfo, cameras) {
cameraDropdown.addItem(cameraInfo.description());
}
QObject::connect(&startButton, &QPushButton::clicked,
[&]() {
int selectedCameraIndex = cameraDropdown.currentIndex();
if (selectedCameraIndex >= 0) {
QCameraInfo selectedCameraInfo = cameras[selectedCameraIndex];
if (camera) {
camera->stop();
delete camera;
}
camera = new QCamera(selectedCameraInfo);
camera->setViewfinder(cameraViewfinder);
QObject::connect(camera, &QCamera::stateChanged,
[&](QCamera::State state) {
if (state == QCamera::ActiveState) {
} else if (state == QCamera::UnloadedState ||
state == QCamera::LoadedState) {
} else {
QMessageBox::critical(&window,
"Camera Error", "Failed to start the camera.");
}
});
camera->start();
}
});
QObject::connect(&stopButton, &QPushButton::clicked, [&]() {
if (camera) {
camera->stop();
delete camera;
camera = nullptr;
}
});
window.show();
return app.exec();
}