handle keyevent in multi-threading application with Qt+OpenCV

  • I have a multi-threading application written in C++ with Qt5.7 and OpenNI. It has a main thread that starts a second thread which capture frame from a .oni recording file (asus xtion pro live) does some processing and through the Qt signal-slot mechanism pass the frame to the main thread, which display it using imshow(). What I want to do is to implement a pause key, so pressing for example 'p' the processing pause. I am thinking of something like this:

    void Camera::run(){
      while(!cameraStop && this->device.isValid())
          try {
            if (!buttonPause) {
                emit sigFrameImageReady(frame);
                if (cv::waitKey(1)==112){
          catch(std::exception &ex) {
            std::cerr << "getFrame()" << ex.what() << std::endl;

    In this way it doesn't work, I think that's because the frame is displayed by another thread (the main one), the waitKey() here simply blocks the entire process, but if I put it in the main thread, just after imshow() in this way:

    void Process::FrameImageReady(cv::Mat FrameImage)
      if (modedebug)
        cv::imshow("bgr", FrameImage);
      if (cv::waitKey(10)==112){

    waitkey seems to be ignored (image displaying works fine).. any idea? Perhaps it is better to use a Qt function do it ?
    It is a console application, the GUI part is only for debugging purpose.

  • Qt Champions 2016

    Since you've subclassed QThread and you're not using an event loop you're pretty much forced to use the low-level "solution", that is blocking with a primitive. See here for example code with a QSemaphore .

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.