天天看點

qt 線程 moveToThread

以前都是重寫的方式來寫線程,後來發現moveToThread的方式也很好用

tcppth.h

#ifndef TCPPTH_H
#define TCPPTH_H

#include <QObject>
#include <QDebug>
#include <QTcpSocket>
#include <QString>
#include <QByteArray>
#include "protocal.h"
#include <QThread>
#include "attctrlpth.h"

class tcpPth : public QObject
{
    Q_OBJECT
public:
    tcpPth();
    ~tcpPth();
    void init(QString ip, int port);
    void tcpStart();
    void tcpClose();
    protocal *P;

protected slots:
    void tcp_read();

signals:


private:
    QTcpSocket *tcpSocket;
    QString IP;
    QString PORT;

    QThread *pth;
};

#endif // TCPPTH_H

           

tcppth.cpp

#include "tcppth.h"

tcpPth::tcpPth()
{
    P = new protocal();
    pth = new QThread();
    tcpSocket = new QTcpSocket(this);
}

tcpPth::~tcpPth()
{

    tcpSocket->close();
    pth->quit();
    pth->wait();
    pth->deleteLater();
}

void tcpPth::init(QString ip, int port)
{

    tcpSocket->connectToHost(ip, port,QTcpSocket::ReadWrite);
    if(!tcpSocket->waitForConnected())
    {
        qDebug()<<"client connect error:"<<ip<<":"<<port;
    }
    else
    {
        qDebug()<<"已連接配接上";
 
        connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(tcp_read()), Qt::QueuedConnection);
    }

}

void tcpPth::tcp_read()
{
    QByteArray array = tcpSocket->readAll();
//    qDebug("size:%d", array.size());
    P->loop_run((uint8_t*)array.data(), array.size());

}


void tcpPth::tcpStart()
{
    this->moveToThread(pth);
    tcpSocket->moveToThread(pth);
    pth->start();
}

void tcpPth::tcpClose()
{
    pth->quit();
    pth->wait();
    pth->deleteLater();
//    tcpSocket->disconnected();
}

           

調用方法:

tcpFly = new tcpPth();
tcpFly->init(qip, qport.toInt());
tcpFly->tcpStart();
           

這是一個tcp moveToThread線程的方法

以上代碼僅展示方法,不能完全移植 編譯 運作,如要使用,親酌情修改!!!