Important: Please read the Qt Code of Conduct -

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) :
        ui(new Ui::MainWindow)
        thread = new QThread();
        worker = new Worker();
        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);
        //    thread->wait(); 

    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)

  • Lifetime Qt Champion

    Just make the worker object accept them in another way.
    as the started() signal from the thread, won't have any way to give DoWork any parameters anyway.
    (not in a dynamic manner)

  • Moderators

    @sigmind since you're using qt 4 syntax, why don't you define a custom signal with default arguments ?

        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")));

Log in to reply