[Solved] How to connect() between wizardpage and thread
-
Hi!
I am making a GUI app with wizard structure and I have:
- the main.cpp
- the class MainWindow : public QMainWindow basic class
- class BaseWizard : public QWizard
- class BasePage : public QWizardPage
- all the pages(wp1, wp2, wp3 ...) like this: class WP1 : public BasePage
And finally a thread to be able to do some background work when needed:
- class WorkThread : public QThread
So what I need is: In wp2 and wp6 for example, I need to do some background work so I suppose that I have to emit a signal which has to be connected to the workthread slot which does the work... I've do that but seems that there is something wrong with the connection:
@
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
BaseWizard wizard; //this starts the app//this is for the connection between basepage and workthread
BasePage bp;
WorkThread mt;
bp.conexion(&mt);
mt.start();wizard.show(); return app.exec();
}
@@
void BasePage::conexion(WorkThread *mt)
{
connect(this, SIGNAL(swp2()), mt, SLOT(recwp2()));
}void BasePage::SendSignal()
{
emit(swp2());
}
@@
void WorkThread::recwp2()
{
qDebug() << "hi";
//do things
}
@and then in wp2 where I want to do the background work:
@
BasePage::SendSignal();
@I have debugged it and when the program arrives to the emit, then nothing happens. I know that the workthread is running well because if I do this, it prints the message:
@
void WorkThread::run()
{
exec();
}void WorkThread::exec()
{
recwp2();
}@Thank you so much!
-
Hi,
In your case, you don't need to derive your Worker class from QThread. Derive it from QObject and move it to a QThread instance. Assuming that you derived your Worker object from QObject:
@
// in the UI thread
QThread workerThread = new QThread(this);
Worker *worker = new Worker; //Don't set a parent
worker->moveToThread( workerThread );
workerThread->start();// keep a pointer to Worker somewhere
// make connections between wizard pages and Worker object....
//in the destructor
QThread *wt = worker->thread();
worker->deleteLater();wt->quit();
wt->wait();
@You may "this page":http://doc.qt.io/qt-5/threads-technologies.html#choosing-an-appropriate-approach useful.
In your code, you seem to have reimplemented exec(). QThread::exec() runs an event loop so that the signals-slot mechanism works. You have properly rendered QThread useless by reimplementing that function. I'd suggest that you shouldn't derive from QThread until you consider yourself quite experienced with threads.
-
Hi,
To add to ckakman, you are doing your connection on a page that you never show, nor put in your wizard
-
Hi,
Yeah, that works for my problem :D
Thank you!