Reputation: 3
I have a problem with QThread. Let's say I want to create a class-thread what will make some calculation infinite time. And if i will send a signal, thread will stop calculation and execute something.
// Class-thread
class A: public QThread
{
protected:
void run() { exec(); }
public slots:
void calc() { while (true) {do somethning}}
void display() { display something }
}
// Class Main window
class MainWindow
{
void buttonClick() {emit signalDisplay() }
}
// main file
void main()
{
A * a = new A;
a->start();
a->calc();
MainWindow w;
connect(&w, SIGNAL(signalDisplay()), a, SLOT(display()));
w.show();
}
The problem is that if i call a->calc() it's freeze the application. But I thought that It's working sepparate? Or I miss something ?
Upvotes: 0
Views: 509
Reputation: 3932
So you use the second approach of reimplementing QThread in your class A. I think you have to put your calculation code into run() function and then just call a->start(); Add some signals like A::jobDone(bool success) etc.
When you call your a->calc() directly from main thread of course it will be executed in the thread where you called it.. in this approach only run() function is executed in another thread and this must be started with a->start(). Check the docs there is nice example..
There is also another way:
class A : public QObject {
..
public slots:
void calc();
}
void main()
{
QThread workerThread;
A * a = new A;
a->moveToThread(workerThread);
a->start();
MainWindow w;
connect(&w, SIGNAL(startProcessing()), a, SLOT(calc()));
connect(a, SIGNAL(jobFinished(QByteArray)), &w, SLOT(displayInGuiResults(QByteArray)));
emit w.startProcessing();
w.show();
}
Upvotes: 3