c++qtsignals-slotsqlabelqimage

How to continuously update a QLabel with QImage in Qt when a window is open?


I have a scenario where I need to continuously display frames from a QImage in a QLabel when a window is open in a Qt application.

I have 2 classes involved in this scenario:

  1. Camera (where the buffer is generated from a device).
  2. Scenarios (the place where I need to display images from the Camera). Scenarios is not the main window of Qt. It's a form that opens after clicking on button in main window: scenarios_->show();

In my main function, I have written the following code:

...
Scenarios scenarios;
Camera camera(0, argv);
camera.start();
QObject::connect(&camera, SIGNAL(foo(unsigned char *)), &scenarios, SLOT(bar(unsigned char *)));
...

The Camera class emits the signal foo(unsigned char *), which includes:

std::map<unsigned long, unsigned char *> ThermalImages;
unsigned long serial = itDevices->first;
...
getting image
...
emit foo(ThermalImages[serial]);

This part works fine. In the Scenarios class, in the bar slot, I receive the buffer and can create a QImage from it:

QImage thermalImage_;

void Scenarios::bar(unsigned char *thermalImage) {
    thermalImage_ = QImage(thermalImage, 384, 288, QImage::Format_RGB888);
}

Now, here's the problem. I want to display this QImage in a specific QLabel in the Scenarios widget. To check that the buffer is not empty and that the QImage is correctly created, I added a button to the form that displays the image:

void Scenarios::on_button_update_clicked() {
    ui_->label_thermal->setPixmap(QPixmap::fromImage(thermalImage_));
}

If I click the button, I get the current frame displayed. However, my goal is to continuously update the QLabel without having to click the button. I want the video stream to be displayed continuously when the form is open. I need a way to refresh the information in the QLabel automatically every time a new frame is available.

I tried using connect in the constructor of the Scenarios class, but it seems to trigger only once.

How can I resolve this issue so that when the window is open, I immediately see a continuous stream of images in the QLabel without having to click a button?

Thank you for your assistance!


Solution

  • You can use Qtimer (https://doc.qt.io/qt-6/qtimer.html) , init in constructor and connect timer to slot to update slot at regular intervals.

    or you can refer to this for more efficient update , Efficient way of displaying a continuous stream of QImages