The run method of my QThread is finishing, but I cannot get the signal.
Here is the entire code:
My thread header:
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QDebug>
#include "mydataobject.h"
class MyThread: public QThread
{
Q_OBJECT
public:
MyThread(MyDataObject data,
bool useData);
private:
void run();
signals:
void resultsReady(MyDataObject data);
private:
MyDataObject data;
bool useData;
};
#endif // MYTHREAD_H
My thread code:
#include "mythread.h"
MyThread::MyThread(MyDataObject data, bool useData)
{
this->data = data;
this->useData = useData;
}
void MyThread::run()
{
if( useData )
{
data.calculate(); // Do something
}
emit resultsReady(data);
qDebug() << "Thread finished";
}
My test header:
#ifndef THREADTESTER_H
#define THREADTESTER_H
#include <QDebug>
#include "mythread.h"
class ThreadTester: public QObject
{
Q_OBJECT
public:
ThreadTester();
void runTests();
public slots:
void threadFinished(MyDataObject data);
private:
MyDataObject data;
};
#endif // THREADTESTER_H
My test code:
#include "threadtester.h"
ThreadTester::ThreadTester(){}
void ThreadTester::runTests()
{
qRegisterMetaType<MyDataObject>("MyDataObject");
MyDataObject data;
MyThread* thread = new MyThread(data, true);
connect(thread, SIGNAL(resultsReady(MyDataObject)),
this, SLOT(threadFinished(MyDataObject)));
thread->start();
thread->wait();
}
void ThreadTester::threadFinished(MyDataObject data)
{
qDebug() << "TEST";
this->data = data;
}
Main function:
#include <QApplication>
#include "threadtester.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ThreadTester threadTester;
threadTester.runTests();
return a.exec();
}
Why the public slot threadFinished is never called?
Note: the "Thread finished" message is appearing, but the "TEST" message not.
What happens in your code:
create QApplication
create ThreadTester
run method ThreadTester::runTests which does following:
creates tread object
connect to result
start thread
wait for thread…
now thread does it job and emits the signal
since you connect used default connection method, slot invocation is scheduled to be run in event loop which didn't start yet.
thread completes
…wait for thread completes (probably here you expecting final result, but look what happens later)
event loop is started
event loop executes queued invocation of slot ThreadTester::threadFinished
event loop waits for next events
Related
Hello Im trying to print my result from a thread to textBrower in qtwidget QT but I cant, either I get error or the program wont compile
is there another way ?? how can I change the textBrowser outside of the class's function??
PS BTW I need to keep looping inside the thread cuz actually im getting some data from uart in final program (in this code i just wanna print "lol" which eventually I wanna change it with some other code which take data ) so I cant come out of the loop
eventually i want use some process from another library and show the resault REAL TIME
bool stop;
out::out(QWidget *parent) :
QWidget(parent),
ui(new Ui::out)
{
ui->setupUi(this);
ui->textBrowser->setText("lol");
}
out::~out()
{
delete ui;
}
///////////////////////////////////////////////
class t : public out, public QThread
{
public:
void run()
{
while(1){
qDebug()<<"hi"<<i;
// ui->textBrowser->setText("lol"); I tried to use this but it didnt worked
if(stop==true){
QThread::exec();
}
}
}
};
void mamad1(void){ //this function get called from another cpp file and its for starting the thread
stop=false;
t *b = new t;
b->start();
}
void out::on_pushButton_clicked() // a push button to stop the thread
{
stop=true;
}
I tried make ui in out.h file a public property and use ui->textBrowser->setText("lol"); but it didn't worked the program freezed and i got this
error : (Parent is QTextDocument(0x208d812a510), parent's thread is QThread(0x208d6816de0), current thread is QThread(0x208dac94e10)
I tried to use connect() also and didn't worked or I didn't use it right
The concept of QT the GUI thread is called the master thread. This thread has an event queue. In general, this event queue is populated by internal and external events. Moreover, the queue between threads is an efficient approach for thread communication. The same is true for the worker threads as well. When you call the start method through the worker threads their signal queue is created and ready to be consumed by the corresponding thread.
Let's come back to your question. The solution is simple. From your worker threads, you can just send a signal to the master thread. The master thread will see this event that modifies the GUI item and forwards this signal/event to the slot that is responsible to take action accordingly. Just define a signal in your worker thread and connect your master thread to this signal with a given slot.
UPDATE FOR SOLUTION
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <MyWorkerThread.h>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void setWorkerThread(MyWorkerThread* thread);
void connectToSignals();
public slots:
void handleTextBoxSignal(const QString& text);
private:
Ui::MainWindow *ui;
MyWorkerThread* m_worker_thread{nullptr};
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
void MainWindow::setWorkerThread(MyWorkerThread* thread)
{
m_worker_thread = thread;
}
void MainWindow::connectToSignals()
{
QObject::connect(m_worker_thread,
SIGNAL(changeTextOnUI(QString)),
this,
SLOT(handleTextBoxSignal(QString)));
}
void MainWindow::handleTextBoxSignal(const QString& text)
{
qDebug() << "Text box change signal received with text: " << text;
auto text_box = findChild<QTextEdit*>("myTxtEdit");
if(text_box != nullptr)
{
text_box->setText(text);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
MyWorkerThread.h
#ifndef MYWORKERTHREAD_H
#define MYWORKERTHREAD_H
#include <QObject>
#include <QThread>
class MyWorkerThread : public QThread
{
Q_OBJECT
public:
MyWorkerThread(QObject* parent = nullptr);
void stopThread();
signals:
void changeTextOnUI(const QString& text);
private:
void run() override;
bool m_exit{false};
};
#endif // MYWORKERTHREAD_H
MyWorkerThread.cpp
#ifndef MYWORKERTHREAD_H
#define MYWORKERTHREAD_H
#include <QObject>
#include <QThread>
class MyWorkerThread : public QThread
{
Q_OBJECT
public:
MyWorkerThread(QObject* parent = nullptr);
void stopThread();
signals:
void changeTextOnUI(const QString& text);
private:
void run() override;
bool m_exit{false};
};
#endif // MYWORKERTHREAD_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
MyWorkerThread* worker_thread = new MyWorkerThread();
w.setWorkerThread(worker_thread);
w.connectToSignals();
worker_thread->start();
w.show();
return a.exec();
}
In the above code, you see the full solution to your problem. In the worker thread, we increment a static counter and concatenate it with a string and send it to the master thread that manages the UI elements. We emit a signal and this signal is landed on the slot. This way the master thread updates the text box on the screen per 5 seconds. The worker thread sleeps for 5 seconds at each iteration.
With Qthread in mind I tried the following but it seems everything is still running in the same thread.
main.cpp
#include "widget.h"
#include <QApplication>
#include "core.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
Core core;
Widget w(core);
w.show();
return a.exec();
}
func.h
#ifndef FUNC_H
#define FUNC_H
#include <QDebug>
#include <QThread>
class Func : public QObject
{
Q_OBJECT
public:
explicit Func()
{
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
}
void compute()
{
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
}
};
#endif // FUNC_H
core.h
#ifndef CORE_H
#define CORE_H
#include <QObject>
#include "func.h"
class Core : public QObject
{
Q_OBJECT
QThread thread;
Func* func = nullptr;
public:
explicit Core(QObject *parent = nullptr)
{
func = new Func();
func->moveToThread(&thread);
connect(&thread, &QThread::finished, func, &QObject::deleteLater);
thread.start();
}
~Core() {
thread.quit();
thread.wait();
}
public slots:
void compute(){func->compute();}
signals:
};
#endif // CORE_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "core.h"
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(Core& core)
{
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
core.compute(); // This should run on a different thread ?
}
};
#endif // WIDGET_H
Running I get the output:
int main(int, char **) 0x107567e00
Func::Func() 0x107567e00
Widget::Widget(Core &) 0x107567e00
void Func::compute() 0x107567e00
Above output was from macOS but in Windows I got similar result.
So what am I doing wrong?
You cannot call the slot compute() directly, it will call it in the same thread as runs the code which called it (as you can see in the output).
You need to run the slot via signals/slots mechanism (or with invokeMethod(), but let's ignore this one).
Typically this is done by connecting thread's started() signal to the slot and then calling QThread::start() from the main thread. It will result in slot being called in the secondary thread just after the thread gets started.
I am trying to send signal across threads.
For testing this situation, I wrote a test code.
I am working on ubuntu 16.04 machine and qt version is 4.8.
In my code, three class exists:
1 - timer_class -> in this class, I emit signal in timeout slot.
2 - test_worker -> I am using this class as thread's worker.
3 - main_class -> I create timer_class instance, and also create thread in this class constructor.
I am trying to connect timer_class signal to test_worker slot.
Here is my code:
First; timer_class :
Header File:
#ifndef TIMER_CLASS_H
#define TIMER_CLASS_H
#include <QTimer>
#include <QDebug>
#include <QObject>
class timer_class : public QObject
{
Q_OBJECT
public:
timer_class(QObject *parent = 0);
~timer_class();
void start_timer();
signals:
void dummy_signal();
private slots:
void on_timeout_occur();
private:
QTimer *timer;
};
#endif // TIMER_CLASS_H
Source File :
#include "timer_class.h"
timer_class::timer_class(QObject *parent)
:QObject(parent)
{
timer = new QTimer();
connect(timer, SIGNAL(timeout()), this, SLOT(on_timeout_occur()));
}
timer_class::~timer_class()
{
}
void timer_class::start_timer()
{
timer->start(1000);
}
void timer_class::on_timeout_occur()
{
qDebug() << "timeout occur";
emit dummy_signal();
}
Second, thread_worker class :
Header File :
#ifndef THREAD_WORKER_H
#define THREAD_WORKER_H
#include <QDebug>
#include <QObject>
class thread_worker : public QObject
{
Q_OBJECT
public:
thread_worker(QObject *parent = 0);
~thread_worker();
public slots:
void main_loop();
void on_dummy_signal();
};
#endif // THREAD_WORKER_H
Source File :
#include "thread_worker.h"
thread_worker::thread_worker(QObject *parent)
:QObject(parent)
{
}
thread_worker::~thread_worker()
{
}
void thread_worker::main_loop()
{
forever
{
//qDebug() << "In Main Loop";
}
}
void thread_worker::on_dummy_signal()
{
qDebug() << "dummy signal received";
}
And last, main_class :
Header file :
#ifndef MAIN_CLASS_H
#define MAIN_CLASS_H
#include <QObject>
#include <QDebug>
#include <QThread>
#include "timer_class.h"
#include "thread_worker.h"
class main_class : public QObject
{
Q_OBJECT
public:
main_class(QObject *parent = 0);
~main_class();
private:
QThread *thread;
timer_class *tmr_class;
thread_worker *worker;
};
#endif // MAIN_CLASS_H
Source File:
#include "main_class.h"
main_class::main_class(QObject *parent)
:QObject(parent)
{
tmr_class = new timer_class();
worker = new thread_worker();
thread = new QThread();
worker->moveToThread(thread);
connect(tmr_class, SIGNAL(dummy_signal()), worker, SLOT(on_dummy_signal()));
connect(thread, SIGNAL(started()), worker, SLOT(main_loop()));
thread->start();
tmr_class->start_timer();
}
main_class::~main_class()
{
}
In main.cpp, I just create main_class instance like this :
#include <QCoreApplication>
#include "main_class.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
main_class *main_cl = new main_class();
qDebug() << "executing a.exec";
return a.exec();
}
When I run the application, I saw "timeout occur" in console, but I don't saw "dummy signal received". I can not find problem.
Could you help me about this problem ?
Thanks.
The basic problem is that you're creating a new QThread, moving your timer_class instance onto that thread and then invoking thread_worker::main_loop when the thread starts. Since thread_worker::main_loop is basically a busy-waiting loop...
void thread_worker::main_loop ()
{
forever
{
//qDebug() << "In Main Loop";
}
}
...the QThread never gets a chance to process events thus preventing any signals being received via queued connections.
The correct fix for all of this depends to a large extent on what work (if any) you want thread_worker::main_loop to do.
To get things going in the mean time simply remove the forever loop or comment out the line...
connect(thread, SIGNAL(started()), worker, SLOT(main_loop()));
Having done that you should see the "dummy signal received" messages.
i want to run code in a seperate thread of the main application, for that i hava created some file :
thread2.h
#ifndef THREAD2_H
#define THREAD2_H
#include <QThread>
class thread2 : public QThread
{
Q_OBJECT
public:
thread2();
protected:
void run();
};
#endif // THREAD2_H
thread2.cpp
#include "thread2.h"
thread2::thread2()
{
//qDebug("dfd");
}
void thread2::run()
{
int test = 0;
}
And the main file called main.cpp
#include <QApplication>
#include <QThread>
#include "thread1.cpp"
#include "thread2.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
thread2::run();
return a.exec();
}
But it dosen't work...
Qt Creator tell me : "cannot call member function 'virtual void thread2::run()' without object"
Thanks !
Invoking it like this: thread2::run() is how you would call a static function, which run() is not.
Also, to start a thread you don't call the run() method explicitly, you need to create a thread object and call start() on it which should invoke your run() method in the appropriate thread:
thread2 thread;
thread.start()
...
A simple Thread Class that allows you to pass a pointer to a function is as follows:
typedef struct TThread_tag{
int (*funct)(int, void*);
char* Name;
int Flags;
}TThread;
class Thread : public QThread {
public:
TThread ThreadInfoParm;
void setFunction(TThread* ThreadInfoIn)
{
ThreadInfoParm.funct = ThreadInfoIn->funct;
}
protected:
void run()
{
ThreadInfoParm.funct(0, 0);
}
};
TThread* ThreadInfo = (TThread*)Parameter;
//Create the thread objedt
Thread* thread = new Thread;
thread->setFunction(ThreadInfo);//Set the thread info
thread->start(); //start the thread
I am trying to start a QTimer in a specific thread. However, the timer does not seem to execute and nothing is printing out. Is it something to do with the timer, the slot or the thread?
main.cpp
#include "MyThread.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
MyThread t;
t.start();
while(1);
}
MyThread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QTimer>
#include <QThread>
#include <iostream>
class MyThread : public QThread {
Q_OBJECT
public:
MyThread();
public slots:
void doIt();
protected:
void run();
};
#endif /* MYTHREAD_H */
MyThread.cpp
#include "MyThread.h"
using namespace std;
MyThread::MyThread() {
moveToThread(this);
}
void MyThread::run() {
QTimer* timer = new QTimer(this);
timer->setInterval(1);
timer->connect(timer, SIGNAL(timeout()), this, SLOT(doIt()));
timer->start();
}
void MyThread::doIt(){
cout << "it works";
}
As I commented (further information in the link) you are doing it wrong :
You are mixing the object holding thread data with another object (responsible of doIt()). They should be separated.
There is no need to subclass QThread in your case. Worse, you are overriding the run method without any consideration of what it was doing.
This portion of code should be enough
QThread* somethread = new QThread(this);
QTimer* timer = new QTimer(0); //parent must be null
timer->setInterval(1);
timer->moveToThread(somethread);
//connect what you want
somethread->start();
Now (Qt version >= 4.7) by default QThread starts a event loop in his run() method. In order to run inside a thread, you just need to move the object. Read the doc...
m_thread = new QThread(this);
QTimer* timer = new QTimer(0); // _not_ this!
timer->setInterval(1);
timer->moveToThread(m_thread);
// Use a direct connection to whoever does the work in order
// to make sure that doIt() is called from m_thread.
worker->connect(timer, SIGNAL(timeout()), SLOT(doIt()), Qt::DirectConnection);
// Make sure the timer gets started from m_thread.
timer->connect(m_thread, SIGNAL(started()), SLOT(start()));
m_thread->start();
A QTimer only works in a thread that has an event loop.
http://qt-project.org/doc/qt-4.8/QTimer.html
In multithreaded applications, you can use QTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal. Because of this, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.
You can use the emit signal and start the timer inside the emitted slot function
main.cpp
#include "MyThread.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
MyThread t;
t.start();
while(1);
}
MyThread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QTimer>
#include <QThread>
#include <iostream>
class MyThread : public QThread {
Q_OBJECT
public:
MyThread();
QTimer *mTimer;
signals:
start_timer();
public slots:
void doIt();
void slot_timer_start();
protected:
void run();
};
#endif /* MYTHREAD_H */
MyThread.cpp
#include "MyThread.h"
using namespace std;
MyThread::MyThread() {
mTimer = new QTimer(this);
connect(this,SIGNAL(start_timer()),this, SLOT(slot_timer_start()));
connect(mTimer,SIGNAL(timeout()),this,SLOT(doIt()));
}
void MyThread::run() {
emit(start_timer());
exec();
}
void MyThread::doIt(){
cout << "it works";
}
void MyThread::slot_timer_start(){
mTimer->start(1000);
}
You need an event loop to have timers. Here's how I solved the same problem with my code:
MyThread::MyThread() {
}
void MyThread::run() {
QTimer* timer = new QTimer(this);
timer->setInterval(1);
timer->connect(timer, SIGNAL(timeout()), this, SLOT(doIt()));
timer->start();
/* Here: */
exec(); // Starts Qt event loop and stays there
// Which means you can't have a while(true) loop inside doIt()
// which instead will get called every 1 ms by your init code above.
}
void MyThread::doIt(){
cout << "it works";
}
Here's the relevant piece of the documentation that none of the other posters mentioned:
int QCoreApplication::exec()
Enters the main event loop and waits until exit() is called. Returns
the value that was set to exit() (which is 0 if exit() is called via
quit()). It is necessary to call this function to start event
handling. The main event loop receives events from the window system
and dispatches these to the application widgets. To make your
application perform idle processing (i.e. executing a special function
whenever there are no pending events), use a QTimer with 0 timeout.
More advanced idle processing schemes can be achieved using
processEvents().
I have created an example that calls the timer within a lambda function:
#include <QCoreApplication>
#include <QObject>
#include <QTimer>
#include <QThread>
#include <QDebug>
#include <memory>
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
QThread* thread = new QThread(&app);
QObject::connect(thread, &QThread::started, [=]()
{
qInfo() << "Thread started";
QTimer* timer1 = new QTimer(thread);
timer1->setInterval(100);
QObject::connect(timer1, &QTimer::timeout, [=]()
{
qInfo() << "Timer1 " << QThread::currentThreadId();
});
timer1->start();
});
thread->start();
QTimer timer2(&app);
QObject::connect(&timer2, &QTimer::timeout, [=]()
{
qInfo() << "Timer2 " << QThread::currentThreadId();
});
timer2.setInterval(100);
timer2.start();
return app.exec();
}