#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QTcpSocket>
#include <QAbstractSocket>
#include <QMessageBox>
QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
private slots:
void on_pushButton_request_clicked();
void on_pushButton_close_clicked();
//void updateButtonState();
private:
Ui::Dialog *ui;
QTcpSocket *tcpsocket;
public slots:
void dispError(QAbstractSocket::SocketError socketerror);
void opeexec();
};
#endif // DIALOG_H
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
//ui->pushButton_request->setEnabled(false);
// if(!ui->lineEdit_name->text().isEmpty() && !ui->lineEdit_port->text().isEmpty())
// {
// ui->pushButton_request->setEnabled(true);
// }
connect(ui->pushButton_request,SIGNAL(clicked()),this,SLOT(opeexec()));
connect(ui->pushButton_close,SIGNAL(clicked()),this,SLOT(on_pushButton_close_clicked()));
//连接输入框的 textChanged 信号
connect(ui->lineEdit_name, &QLineEdit::textChanged, this, &Dialog:: on_pushButton_request_clicked);
connect(ui->lineEdit_port, &QLineEdit::textChanged, this, &Dialog:: on_pushButton_request_clicked);
tcpsocket=new QTcpSocket(this);
connect(tcpsocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(dispError(QAbstractSocket::SocketError)));
ui->lineEdit_port->setFocus();
// 初始化按钮状态
//updateButtonState();
on_pushButton_request_clicked();
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_request_clicked()
{
//setEnabled(...): 这个方法用于设置按钮的启用状态。如果参数为 true,按钮可用;如果为 false,按钮将被禁用。
ui->pushButton_request->setEnabled(!ui->lineEdit_name->text().isEmpty() && !ui->lineEdit_port->text().isEmpty());
}
void Dialog::dispError(QAbstractSocket::SocketError socketerror)
{
switch (socketerror)
{
case QAbstractSocket::RemoteHostClosedError://远程主机关闭连接
QMessageBox::information(this,"提示","远程主机关闭连接",QMessageBox::Yes);
break;
case QAbstractSocket::HostNotFoundError://找不到主机地址
QMessageBox::information(this,"提示","找不到主机地址",QMessageBox::Yes);
break;
case QAbstractSocket::ConnectionRefusedError://连接被对方拒绝(或者超时)
QMessageBox::information(this,"提示","找不到主机地址",QMessageBox::Yes);
break;
default:
QMessageBox::information(this,"提示",tr("致命错误为:").arg(tcpsocket->errorString()),QMessageBox::Yes);
}
ui->pushButton_request->setEnabled(true);
}
void Dialog::opeexec()
{
ui->lineEdit_name->setEnabled(false);
tcpsocket->abort();//取消已有的连接
tcpsocket->connectToHost(ui->lineEdit_name->text(),ui->lineEdit_port->text().toInt());
}
void Dialog::on_pushButton_close_clicked()
{
close();
}
//void Dialog::updateButtonState()
//{
// 更新按钮的启用状态
// ui->pushButton_request->setEnabled(!ui->lineEdit_name->text().isEmpty() && !ui->lineEdit_port->text().isEmpty());
//}