本人亲测使用moveToThread()的方式可以;不存在报错,警告
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
SocketThread *worker = new SocketThread;
worker->moveToThread(&workerThread);
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
connect(this, &Widget::operate, worker, &SocketThread::run1);
connect(worker, &SocketThread::resultReady, this, &Widget::handleResults);
workerThread.start();
emit operate();
qDebug()<<"main"<
#ifndef WIDGET_H
#define WIDGET_H
#include
#include"socketthread.h"
#include
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
QThread workerThread;
public slots:
void handleResults(const QString &);
signals:
void operate();
};
#endif // WIDGET_H
#include "socketthread.h"
#include"QDebug"
#include
#include
SocketThread::SocketThread(QObject *parent) : QObject(parent)
{
//start();
}
SocketThread::~SocketThread()
{
// quit();
// wait();
}
void SocketThread::OnNewConnection()
{
qDebug()<<"new connection";
socket_ptr = std::make_shared();
socket_ptr = static_cast<std::shared_ptr<QTcpSocket> >(server_ptr->nextPendingConnection());
connect(socket_ptr.get(),QTcpSocket::readyRead,this,OnRead);
socket_list->push_back(socket_ptr);
qDebug()<<QThread::currentThreadId();
}
void SocketThread::OnRead()
{
qDebug()<<"ready read";
qDebug()<<QThread::currentThreadId();
QByteArray arr;
QTcpSocket *socket_ptr = static_cast<QTcpSocket*>(sender());
arr = socket_ptr->readAll();
socket_ptr->write(arr);
qDebug()<
}
void SocketThread::run1()
{
socket_list = new std::list<std::shared_ptr<QTcpSocket>>();
server_ptr = std::make_shared();
server_ptr->listen(QHostAddress::Any,5000);
connect(server_ptr.get(),QTcpServer::newConnection,\
this,SocketThread::OnNewConnection);
qDebug()<<QThread::currentThreadId();
}
#ifndef SOCKETTHREAD_H
#define SOCKETTHREAD_H
#include
#include
#include
#include
#include
class SocketThread : public QObject
{
Q_OBJECT
public:
explicit SocketThread(QObject *parent = 0);
~SocketThread();
signals:
public slots:
void OnNewConnection();
void OnRead();
public slots:
void run1();
private:
std::list<std::shared_ptr<QTcpSocket>> *socket_list;
std::shared_ptr<QTcpSocket> socket_ptr;
std::shared_ptr<QTcpServer> server_ptr;
signals:
void resultReady(const QString &result);
};
#endif // SOCKETTHREAD_H