标签:str sig http push mamicode xpl button public void
1、在.pro文件中加入一句
QT += network
2、.h文件
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QTcpSocket> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void readData(); void sendData(); void disconnecting(); void connecting(); void showConnect(); private: Ui::MainWindow *ui; QTcpSocket *socket; }; #endif // MAINWINDOW_H
.cpp文件
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->pushButton_2->setEnabled(false); socket = new QTcpSocket; connect(socket,SIGNAL(readyRead()),this,SLOT(readData())); connect(socket,SIGNAL(connected()),this,SLOT(showConnect())); connect(socket,SIGNAL(disconnected()),this,SLOT(disconnecting())); connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(connecting())); connect(ui->pushButton_2,SIGNAL(clicked(bool)),this,SLOT(sendData())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::connecting() { if(ui->pushButton->text()=="连接") { QString ip = ui->lineEdit->text(); quint16 port = ui->lineEdit_2->text().toUInt(); socket->connectToHost(ip,port); } else { socket->close(); } } void MainWindow::showConnect() { ui->pushButton->setText("断开"); ui->pushButton_2->setEnabled(true); } void MainWindow::readData() { QByteArray data = socket->readAll(); ui->textEdit->setText(data); } void MainWindow::sendData() { QString str = ui->textEdit_2->toPlainText(); socket->write(str.toStdString().c_str(),str.length()); } void MainWindow::disconnecting() { ui->pushButton->setText("连接"); ui->pushButton_2->setEnabled(false); }
运行结果:
标签:str sig http push mamicode xpl button public void
原文地址:https://www.cnblogs.com/caozewen/p/12174008.html