简体   繁体   中英

how to create a thread for the class which is inherited by QWidget?

I want to create a thread for a class which is Inherited by QWidget. Actually, I tried with multiple inheritance with QThread and it fails and I want to run particular member function using thread. How can I achieve this? Does anyone have any idea?

You could use a wrapper class that implements the thread and calls your widget's method:

class MyWidget : public QWidget
{ 
    [...]

    void threadMethod();
};

class MyThread : public QThread
{
    [...]

    MyThread( MyWidget* widget )
      : mWidget(widget)
    {
    }

    void run()
    {
       mWidget->threadMethod();
    }

    MyWidget* mWidget;
};

However, you should not call any QWidget methods in "threadMethod", since the GUI and and thus the widgets belong to the "main" thread, and the QWidget methods are not thread-safe!

It would probably better to keep your widget and thread code completely separate.

一种解决方案可能是使用嵌套类,在该类中,您将从嵌套的run方法传递指向普通窗口小部件类的指针以及所需的所有方法。

Qt classes which belong to the GUI module are not reentrant. They MUST be run from the main thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM