How to "cast" to the main thread from another?



  • Hi,
    I am creating a new thread once I click on a button in my program.
    Inside this new created thread(-object) I call a method on an object

    void MyThread::run(){
        someObject->execute();
    }
    

    where I do

    void SomeClass::execute(){
        someQWidget->setEnabled(false);
    }
    

    And the program crashes, because I cannot call UI methods from this non-main thread.
    So the question is basically: How can I "say" the main thread, that he should call this method instead? I have to cast to the main thread from the created thread and execute this method there (would be my Idea to solve this). How can I do this?
    Thanks for answers!



  • Emit a signal from the 2nd thread and connect it to a slot in the main thread that calls your UI methods



  • @VRonin
    Works perfectly fine, thank you!!
    Can you explain, why this works? I now emit a signal in my custom thread that is connected to a slot in another class. Is it because I only instaciate objects of this other class in the main thread? So only the main thread holds these objects and so the main thread will execute the slot of the objects of this other class?



  • @Niagarer said in How to "cast" to the main thread from another?:

    So only the main thread holds these objects and so the main thread will execute the slot of the objects of this other class?

    Correct


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.