C++ Qt - When a slot is called, is the function called a new thread?
Asked Answered
M

1

5

I would like to know if the function do_something() is treated as a new thread, when I click on my_button.

connect(my_button, SIGNAL(clicked), this, SLOT(do_something));
Manhattan answered 20/8, 2012 at 5:53 Comment(0)
K
8

The typical signal/slot behavior is determined based on the connection type. When unspecified, it defaults to Qt::AutoConnection and will use the receiver's thread if a direct connection can't be made.

From the docs:

The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.

You can change the connection type at connect time to alter the behavior:

connect(my_button, SIGNAL(clicked), this, SLOT(do_something),
    Qt::QueuedConnection); // always queue

Since you're talking about a button that's emitting the signal, the default connection type of Qt::AutoConnection implies that a direct connection is made and that the do_something slot will be executed immediately as if it had been called directly at the point the button was clicked.

Kinnard answered 20/8, 2012 at 6:0 Comment(4)
I had no idea Qt managed the type of connection. I am reading the documentation, yet something isn't clear: "(default) If the signal is emitted from a different thread than the receiving object." Could you define "from a different thread"? More specifically, I know what and how multi-threading works. I don't know how Qt manages its things, and I am guessing there is a hidden system of threads.Ryder
@Bibi541: No hidden threads, but if you create your own QThread's, they can have their own event loops, and QObjects assigned/created to those threads will have autoconnection slots called on their thread, not the emitting object's thread (usually the main/ui loop for QButtons and the like...)Henleigh
Some notes: A direction connection is just a function call with some connection lookup in between and completely synchronous. A queued connection (without moving objects into different threads consciously) schedules a call in the event loop, but that's still single-threaded.Leverrier
All in all, a slot is never called in a new thread. Even if the thread of the receiver is different from the thread of the sender, this can only be because you yourself created that thread and created the receiving object in that thread. Qt doesn't create any new threads under the hood.Mallon

© 2022 - 2024 — McMap. All rights reserved.