1.首先说不正确的姿势是什么?
跨线程乱搞,重新写了qthread,实现了run,然后main里面创建了QTcpSocket,然后传入到run里面。
这种基本运行的时候都会提示你跨线程调用了,对了还有人搞不懂为什么跨线程了,这个可以看看我的博客,有非常明确的说明
https://blog.csdn.net/u013372900/article/details/81676483
还有人强行调用,忽略警告,这个在实际工程肯定不行啊,明确的线程不安全问题,bug!!!!
2.正确的姿势是什么
正确的姿势其实是这样的。
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <Qthread>
#include <QMainWindow>
#include <QTcpSocket>
#include <QDebug>
#include <time.h>
namespace Ui {
class MainWindow;
}
class my_tcp : public QTcpSocket
{
Q_OBJECT
public:
my_tcp()
{
connect(this,SIGNAL(connected()),this,SLOT(slotConnect()));
connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(slotErr(QAbstractSocket::SocketError)));
connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnect()));
connect(this,SIGNAL(readyRead()),this,SLOT(slotReadData()));
}
public slots:
bool start_connt()
{
abort();
connectToHost("192.168.4.149", 6666);
waitForConnected();
return true;
}
private slots:
void displayError(QAbstractSocket::SocketError)
{
qDebug()<<"displayError";
}
void slotConnect()
{
qDebug()<<"slotConnect";
}
void slotErr(QAbstractSocket::SocketError err){
qDebug()<<"slotErr";
}
void slotDisconnect()
{
qDebug()<<"slotDisconnect";
}
void slotReadData()
{
qDebug()<<"slotReadData";
write("hello !\n");
}
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
bool sig_con();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
my_tcp * m_tcp;
QThread * work_th;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_tcp = new my_tcp ;
// ui---线程 交互
connect(this,SIGNAL(sig_con()),m_tcp,SLOT(start_connt()),Qt::BlockingQueuedConnection);
work_th = new QThread();
m_tcp->moveToThread(work_th);
work_th->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
emit sig_con();
}