How to Use Non Static function in QtConcurrent::run() Method
-
I was Declare One Non Static Function Like:
void MainWindow::Call_Me()
{
ui->label_1->setText("Welcome");
}Now I Want to Use this Function In My PushButton ClickEvent Method
void MainWindow::on_pushButton_clicked()
{
QFuture<void> future_1 = QtConcurrent::run(Call_Me());
}Plzz Help Me
-
Why?!
Whats wrong with
void MainWindow::on_pushButton_clicked() { ui->label_1->setText("Welcome"); }
Or if you must call it as a function:
void MainWindow::on_pushButton_clicked() { Call_Me(); }
You tell us nothing about why you think QFuture is necessary. Your GUI code is running in the main GUI thread, right?
-
@Kent-Dorfman But I want To Run This Function Parallel
-
@Ketan__Patel__0011 said in How to Use Non Static function in QtConcurrent::run() Method:
void MainWindow::on_pushButton_clicked()
{
QFuture<void> future_1 = QtConcurrent::run(Call_Me());
}OK, so given your creation of QFuture as a local variable in the method, would you expect the result to be available after the method exits?
-
Hi,
On a side note: don't modify GUI elements from other threads. Use signals and slots to transfer the data back to the GUI elements.
-
You should note that
Call_Me
as a member method has an implicit parameterthis
which you need to pass. Out of the top of my head I would try something like this (though untested):...QtConcurrent::run(std::mem_fn(&MainWindow::Call_Me), this);
Usually, if you pass a function to another function it is actually a function pointer. So, you have to give the address of the function (hence the
&
). Also, member functions live in a class scope and you have to name the full scope. Finally,std::mem_fn
helps to make the implicit argument the first argument of the function call.However, as said before GUI functions need to be executed in the GUI thread (which is basically the thread that
main
is running in). So, you can do computations inCall_Me
, but you cannot callsetText
directly becauselabel_1
is part of the GUI. I guess this is only a small example (and hopefully not what you are really trying to do) because the overhead of calling into a different thread is a lot worse than just executing a small portion of code (setText
in this case).If you do have to call a GUI functions from a different thread, you actually have to queue them into the GUI thread. This would like something like this (again: untested):
QMetaObject::invokeMethod(ui->label_1, SLOT(setText(QString())), Qt::QueuedConnection, Q_ARG(QString, "Welcome"))
Maybe using a lambda instead is slightly easier:
QMetaObject::invokeMethod(qApp, [this](){ ui->label_1->setText("Welcome"); }, Qt::QueuedConnection);
-
Just in case, the documentation of QtConcurrent::run shows exactly how to call a member function on an object.