How to know thread is running from different button ?
-
Remove
MyThread *
from your constructor. -
@Hiloshi You should really read more carefully what others are writing. What @SGaist said is:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); T3Thread = new MyThread; // Remove MyThread* - else you are declaring a local variable which is completely unrelated to the one in your header! T3Thread->start(); }
And after this change think about where to start the thread: in the code you posted you're doing it twice.
-
I want to study in depth in this question. In the original question, I have a running T3Thread, mainwindow cannot reach T3Thread, thanks for @a-normal-worker 's suggestion, we can make T3Thread as a class member of mainwindow then mainwindow have ability to access T3Thread.
Can we use signal/slot instead of using class member ?
-
What exactly do you want to do with your thread ?
-
Dear @SGaist ,
I am thinking to create a breathing LED in my thread, "run" function is keep turn on/off LED.
I want to put one button on mainwindow to start the thread.I do not want this button to be pressed twice ( or thread will create twice), so in the button I put:
void MainWindow::on_pushButton_3_clicked() { if(T3Thread->isRunning()==false) { MyThread *T3Thread = new MyThread; // local variable T3Thread->start; } else qDebug()<<"T3 thread is running"; }
If I do not want to use class member, can I use signal/slot to know T3Thread is running or not ?
Thanks.
-
@Hiloshi
ok, I think we talk at cross here.Here's a basic setup to check if your thread is running when you press a Button, if its not running the button will start the thread:
//in your header: example.h #include <QThread> #include <qDebug> private: QThread *thread;
//in your source file //Constructor { ui->setupUi(this); thread = new QThread; .... } void on_pushButton_clicked(){ if(thread->isRunning()) qDebug() << "Thread is running"; else{ qDebug() << "Thread started"; thread->start(); } } //Destructor { if(thread->isRunning()){ thread->quit(); thread-> wait(); } ... delete ui; }
-
What is the problem with using a member variable to handle that thread object properly ?
-
There could be ways however you are talking about creating an object somewhere without any reference to it and still want to interact with it. That's bad by design.