Unsolved How to pass additional argument to doWork() Thread
-
I have a simple multithreaded program to perform certain tasks in doWork() function.
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); thread = new QThread(); worker = new Worker(); worker->moveToThread(thread); connect(worker, SIGNAL(valueChanged(QString)), ui->label, SLOT(setText(QString))); connect(worker, SIGNAL(workRequested()), thread, SLOT(start())); connect(thread, SIGNAL(started()), worker, SLOT(doWork())); connect(worker, SIGNAL(finished()), thread, SLOT(quit()), Qt::DirectConnection); while(1) { worker->abort(); // thread->wait(); worker->requestWork(); } }
The fact is I need to pass an additional argument to doWork() function to work with it. I can't find any way to pass the parameter to doWork() function.
My doWork function should be like:
void doWork(int x, Qstring name)
-
Hi
Just make the worker object accept them in another way.
Worker->setData(46,"sigmind");
as the started() signal from the thread, won't have any way to give DoWork any parameters anyway.
(not in a dynamic manner) -
@sigmind since you're using qt 4 syntax, why don't you define a custom signal with default arguments ?
//worker.h signals: void startSignal(int defaultInt = 0, QString defaultString = "default"); //---- connect(thread, SIGNAL(started()), worker, SIGNAL(startSignal())); connect(worker, SIGNAL(startSignal(int, QString)), worker, SLOT(doWork(int, QString)));
Well, I'm still in holiday mode.
Ignore that, simply give your doWork slot default arguments and you can connect it directly to the started signal. -
if the arguments are passed by value and known at the time of connection then you can also use
connect(thread, &QThreadstarted, worker, std::bind(&Worker::doWork,worker,2,QStringLiteral("hello")));