Using QThread and moveToThread properly with QTimer and QTcpSocket

前端 未结 3 1692
星月不相逢
星月不相逢 2021-01-02 22:52

From reading this blog, this blog and some others, Subclassing QThread is bad practice. So I tried to apply this method.

But my problem is that I have a QTimer and a

3条回答
  •  醉梦人生
    2021-01-02 23:32

    There is a much simpler method of achieving all this that follows the same algorithm but doesn't involve all the boilerplating needed to create threads and changing thread affinities, using QRunnable and QThreadPool

    If I convert Merlin069's example, you'll see how it simplifies the code a bit:

    class CommsHandlerIP : public QObject, public QRunnable
    {
        Q_OBJECT
        public:
           void run();
    
        public slots:
            //... any slots
    
        signals:
            //... any signals
    
        private:
           // c++ 11, initialising in headers...
           QTimer* m_pTimer = NULL;
           QTcpSocket* m_pSocket = NULL;   
    };
    
    void CommsHandlerIP::run()
    {
         m_pTimer = new QTimer();
         m_pSocket = new QTcpSocket();
    
         //...
    
         delete m_pTimer;
         delete m_pSocket;
    }
    
    QThreadPool::globalInstance()->start(new CommsHandlerIP);
    

提交回复
热议问题