Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to access the parent thread's vriable from child QThread



  • I have a class MyClass wich starts a QThread class named Worker. I have a vriable in MyClass that I want to access from child thread. Is this possible and if yes, how?

    class MyClass{
    public:
        MyClass(){
             thread = new Worker(this);
            thread->start();
       }
    private:
        Worker *thread;
       int vriable; // this the vriable that I want to access from child thread
    };
    
    class Worker : public QThread {
        Q_OBJECT
    public:
        Worker(QOject *parent = 0) : QThread(parent){}
        void run() {
              // I want to access vriable here
       }
    };
    

  • Qt Champions 2019

    @Mohammadreza99A Why do you want to access a private variable from another class?
    Don't do that, use getter/setter.
    When using threads you would need to synchronise the access to avoid race conditions.
    Better would be to use signals/slots to exchange data between MyClass and Worker.


Log in to reply