qml程序退出时如何通知C++后台线程关闭

qml程序如果存在c++后台线程,那么在关闭qml主窗口时,必须先清理后台线程资源,并退出后台线程之后,才能正常退出程序。否则会报错:QThread: Destroyed while thread is still running

以下是代码:

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    //QGuiApplication app(argc, argv);
    QApplication app(argc, argv);
    app.setWindowIcon(QIcon(":/app.png"));

    //MainBackgroundProcess
    QThread threadProcess;
    MainBackgroundProcess::instance()->moveToThread(&threadProcess);
    QObject::connect(&threadProcess, &QThread::started, [=](){
        MainBackgroundProcess::instance()->init();
    });
    threadProcess.start();
    //QMetaObject::invokeMethod(MainBackgroundProcess::instance(), "slot_init", Qt::QueuedConnection);

    //qml
    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:
  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
QML中使用C++线程显示摄像头可以分为以下几个步骤: 1. 创建一个C++类来处理摄像头捕获和处理的逻辑,例如: ```cpp class Camera : public QObject { Q_OBJECT public: Camera(QObject *parent = nullptr); ~Camera(); public slots: void start(); void stop(); signals: void frameReady(QImage image); private: QThread *m_thread; QCamera *m_camera; QCameraImageCapture *m_imageCapture; bool m_running; void captureFrame(); }; ``` 2. 在QML中创建一个Item用于显示摄像头捕获的图像,例如: ```qml Item { id: cameraView width: 640 height: 480 Image { id: cameraImage width: parent.width height: parent.height fillMode: Image.PreserveAspectFit } } ``` 3. 创建一个QML中的JavaScript函数,在该函数中创建Camera对象,并将其移动到另一个线程中运行,例如: ```qml function startCamera() { var camera = new Camera(); camera.moveToThread(camera.thread); camera.frameReady.connect(function(image) { cameraImage.source = image; }); camera.start(); } ``` 4. 在Camera类的实现中,使用QImage处理摄像头捕获的图像,并通过信号frameReady将处理后的图像传递给QML中的JavaScript函数。 ```cpp void Camera::captureFrame() { while(m_running) { QVideoFrame frame = m_imageCapture->capture(); if(frame.isValid()) { QImage image = QImage(frame.bits(), frame.width(), frame.height(), frame.bytesPerLine(), QVideoFrame::imageFormatFromPixelFormat(frame.pixelFormat())); emit frameReady(image); } } } ``` 5. 在Camera类的start函数中,创建QThread对象并将Camera对象移动到该线程中运行。 ```cpp void Camera::start() { if(!m_running) { m_running = true; m_thread = new QThread(); connect(m_thread, &QThread::finished, this, &Camera::deleteLater); connect(m_thread, &QThread::started, this, &Camera::captureFrame); moveToThread(m_thread); m_thread->start(); } } ``` 6. 在Camera类的stop函数中,停止线程并释放资源。 ```cpp void Camera::stop() { if(m_running) { m_running = false; m_thread->quit(); m_thread->wait(); delete m_thread; m_thread = nullptr; } } ``` 这样,在QML中调用startCamera函数即可启动摄像头捕获和处理,并在cameraImage中显示处理后的图像。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值