I am new to StackOverflow and am wondering if I am doing this correctly:
I am writing a simple Qt application for testing multithreading (I'm also a complete newbie). I created MainWindow, which contains widgets, and the MyThread class, which subclasses QThread and overrides the run () method.
The application simply displays two buttons: "Start Counter" and "Stop Counter" and a text field. When "start counter" is pressed, the workflow is created and runs in the background, continuously increasing the counter in the while loop and signaling to the main thread (where the graphical user interface is) with the updated value. When the “Stop counter” is pressed, the signal is sent to the main thread, which stops the while loop, and the counter stops until the “Start counter” is pressed again.
This works great ... but is this the best way? I am new to this and read a lot of people saying “not subclasses of QThread”, and other people say “subclassing QThread” and this is a bit confusing. If this is not the best way to implement such things (start a loop with intensive calculation in the background thread with the "start" and "stop" buttons), what is it? If I do it wrong, how do I do it right? I do not want to study wrong.
Thanks! And here is the code:
Mythread.h
#ifndef MYTHREAD_H #define MYTHREAD_H #include <QThread> #include <QMutex> class MyThread : public QThread { Q_OBJECT public slots: void stopRunning(); protected: virtual void run(); signals: void signalValueUpdated(QString); private: bool isRunning; };
Mythread.cpp
#include "MyThread.h"
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QApplication> #include <QPushButton> #include <QHBoxLayout> #include <QLineEdit> #include "MyThread.h" class MainWindow : public QWidget { Q_OBJECT public: MainWindow(QWidget *parent = 0); private: //Widgets QHBoxLayout * boxLayout; QPushButton * startButton; QPushButton * stopButton; QLineEdit * lineEdit; MyThread thread; }; #endif
mainwindow.cpp
#include "MainWindow.h" MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { boxLayout = new QHBoxLayout(this); startButton = new QPushButton("Start Counter", this); stopButton = new QPushButton("Stop Counter", this); lineEdit = new QLineEdit(this); boxLayout->addWidget(startButton); boxLayout->addWidget(stopButton); boxLayout->addWidget(lineEdit); qDebug("Thread id %d",(int)QThread::currentThreadId());
c ++ multithreading qt4 qthread
evdc
source share