QT 自定义信号

自定义信号,需要
1.在singnals:区域下写信号函数,以及函数对应的参数
2. 需要emit关键字进行发射信号
3. 在需要处理该信号的其他类中,建立信号和其信号槽函数connect()
4. 在其他类中创建信号处理槽函数

#include "mythread.h"

myThread::myThread(QTcpSocket *s)
{
    socket = s;
}

// 对线程的run方法进行重写, 相当于线程处理函数
void myThread::run() {
    // 启动线程后,应该建立连接,关于readyRead
    connect(socket, &QTcpSocket::readyRead, this, &myThread::clientInfoHandler);
}


void myThread::clientInfoHandler(){
    // 线程不能对ui进行操作,只能在创建和ui同名的wiget类中操作
    // qDebug()<< socket->readAll();

    // 所以需要在thread中自定义信号,在wiget中用于触发信号和对应槽函数

    QByteArray b = socket->readAll();
    emit sendToWidget(b); // 发起信号
}

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 服务端有QTcpServer库,封装了监听操作
    server = new QTcpServer();

    // 直接监听,内部根据传入的ip和端口进行绑定
    server->listen(QHostAddress::AnyIPv4, SERVER_PORT);

    // 对server进行新的连接信号建立信号槽
    connect(server, &QTcpServer::newConnection, this, &Widget::newClientHandler);

}

Widget::~Widget()
{
    delete ui;
}


void Widget::newClientHandler()
{
    // 将获取到的新的连接套接字中获取客户端ip和端口
    socket = server->nextPendingConnection();
    ui->hostLineEdit->setText(socket->peerAddress().toString());
    ui->portLineEdit->setText(QString::number(socket->peerPort()));


    // 新的消息到来时,connect 数据read和处理信号槽函数
    // connect(socket, &QTcpSocket::readyRead, this, &Widget::clientInfoSlot);

    // 创建线程,来一个连接后,就创建一个线程,在线程中进行socket的数据接收
    myThread* thread = new myThread(socket);
    thread->start();

    // thread线程对象发出信号,widget中建立对应的槽函数
    connect(thread, &myThread::sendToWidget, this, &Widget::threadMessageSlot);
}

void Widget::threadMessageSlot(QByteArray b){
    ui->chatLineEdit->setText(QString(b));
}

void Widget::clientInfoSlot()
{
    ui->chatLineEdit->setText(QString(socket->readAll()));
}

void Widget::on_closeButton_clicked()
{
    socket->close();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值