I have qml camera widget in camera.qml. the qml component is loaded from a Qt widget "WidgetCamera" that is placed on a stack widget in the background. The widget starts the camera device already at creation.
How to make the camera start only when the widget is shown in the foreground. And vice versa, how release the camera when the widget goes to the background?
camera.qml
Item {
width: 640
height: 360
Camera {
id: camera
}
VideoOutput {
source: camera
anchors.fill: parent
}
}
widgetCamera.h
class WidgetCamera : public QWidget
{
Q_OBJECT
public:
WidgetCamera() {
QQuickWidget *qw= new QQuickWidget;
qw->setSource(QUrl("qrc:///camera.qml"));
// ...
}
}
mainwindow.h
class MainWindow : QMainWindow
{
Q_OBJECT
public:
MainWindow() {
QStackedWidget *sw = new QStackedWidget;
sw->addWidget(new QWidget());
sw->addWidget(new WidgetCamera());
// ...
}
}
QML camera type has start()
, stop()
methods accessible directly inside QML. But to be able to turn the camera on/off at will from c++ side, you should first introduce it as a member in your MainWindow class, eg like this:
#include "widgetCamera.h"
class MainWindow : QMainWindow
{
Q_OBJECT
private:
WidgetCamera* _cameraWidget;
public:
MainWindow() {
QStackedWidget *sw = new QStackedWidget;
sw->addWidget(new QWidget());
_cameraWidget = new WidgetCamera();
sw->addWidget(_cameraWidget);
// PS: Make sure you free your instances correctly, too
// ...
}
}
Now, in your WidgetCamera class, you should also introduce a member variable to access the actual QML widget faster, similar to the above. Let's stick with the "qw" you already gave it.
Then, make sure you give objectNames to all QML children that you want to access (in this case, we want the camera), like this:
Item {
width: 640
height: 360
Camera {
id: camera
objectName: "theCamera"
}
VideoOutput {
source: camera
anchors.fill: parent
}
}
Once you have that, you need a function to enable/disable the capturing of the camera, which could be done like this:
void WidgetCamera::disableCapture() {
QObject* qmlCamera = qw->findChild<QObject*>("theCamera");
QCamera* camera = qvariant_cast<QCamera*>(qmlCamera->property("mediaObject"));
camera->stop();
}
Now, obviously, a lot of this could be improved and optimized (like making the actual c++ QCamera a member of WidgetCamera, etc.), but this should get you started.
As to when you want to call that function to enable/disable the camera, that is completely up to you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.