QThread within the same class
-
I have a QPushButton and two QLabel's. When the pushbutton is clicked, each QLabel will display over 1000 frames every 500 milliseconds or so making it appear as a video. However, each QLabel will display different frames from different directorie's locations but both QLabels need to display their frames/video at the same time. After some research, I believe I need two threads in order to run them at the same time. I have written the important sections of the code below.
I am not sure how to use Threads here. Will each tread call the same timer or is it two separate ones? I know for sure that both threads need to call the updateLabel but I am not sure how to make this work and where to put the threads.#include "setup.h" #include "ui_setup.h" #include <QFile> #include <QTextStream> #include <QDir> #include <QTimer> #include <QThread> #include <QDebug> setup::setup(QWidget *parent) : QWidget(parent), ui(new Ui::setup) { ui->setupUi(this); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateLabel())); //not sure how this will work directory1 = QString("directory1_name"); directory2= QString("directory2_name"); } void setup::updateLabel(QString directory) { // if fileList is empty // timer->stop else { //save images into vector } ui->label1->setPixmap(images[x]); ui->label1->update(); } void setup::onClickPlay() { QDir myDir(directory1); filelist = myDir.entryList(QStringList("*.png")); //saves all images timer->start(500); } setup::~setup() { delete ui; }
-
In the code you provided I cannot see any threads.
In general there is no need for threads in this case: just use a timer and update the labels on each timer event.A note: in Qt you should NEVER modify UI from another threads! This is not supported.
-
@marlenet15
Strictly speaking you can't unless you callQWidget::repaint()
on each of the widgets manually from the same function/slot. Otherwise Qt will schedule the paint events as it sees fit, which is absolutely fine for most of the cases. Also you can't callQWidget
functions from a separate thread (as @jsulm noted), it must be from the main thread. So @jsulm is absolutely correct that you don't actually need any threads and stand to gain nothing from them.Kind regards.
-
I guess you are right. I will work on this without the Threads. Thank you for your help!