在我的Qt应用程序中,我有一个MainWindow
和DialogWindow
。 DialogWindow
用于设置服务器的IP地址和端口。 MainWindow
用于在成功连接后执行通信。
但是,在QTcpSocket *socket
中设置DialogWindow
意味着当我关闭DialogWindow
时,socket
将被破坏,因此socket
将与服务器断开连接。
我想在DialogWindow
关闭后保持套接字连接到服务器。有什么方法可以达到这个目的?
请给我一些意见和想法。我是Qt的新手。
DialogSetup.cpp
DialogSetup::DialogSetup(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogSetup)
{
ui->setupUi(this);
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()),this, SLOT(wasconnected()));
connect(socket,SIGNAL(disconnected()),this,SLOT(wasdisconnected()));
}
DialogSetup::~DialogSetup()
{
delete ui;
}
void DialogSetup::on_pushButtonConnect_clicked()
{
m_strIPAdd = ui->lineEditIPAdd->text();
m_strPort = ui->lineEditPort->text().toInt();
socket->connectToHost(m_strIPAdd,m_strPort);
if(!socket->waitForConnected(10000))
{
ui->labelStatus->setText("Error");
QMessageBox::information(this,"Error",socket->errorString());
}
}
void DialogSetup::wasconnected()
{
socket->write("Hello server!");
ui->labelStatus->setText("Connected!");
ui->pushButtonDisconnect->setDisabled(false);
}
void DialogSetup::wasdisconnected()
{
ui->labelStatus->setText("Disonnected!");
}
void DialogSetup::on_pushButtonDisconnect_clicked()
{
socket->close();
}
主窗口
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionSetup_triggered()
{
dialogsetup = new DialogSetup(this);
dialogsetup->show();
}
最佳答案
将套接字移到对话框类之外。像这样:
void MainWindow::on_actionSetup_triggered()
{
socket = new QTcpSocket(this); //declared as private in MainWindow
dialogsetup = new DialogSetup(socket, this);
connect(socket,SIGNAL(connected()), dialogsetup, SLOT(wasconnected()));
connect(socket,SIGNAL(disconnected()), dialogsetup ,SLOT(wasdisconnected()));
dialogsetup->show();
}
对话框类存储指向套接字的指针并对其进行操作:
DialogSetup::DialogSetup(QTcpSocket *socket, QWidget *parent) :
QDialog(parent),
socket_(socket),
ui(new Ui::DialogSetup)
{
ui->setupUi(this);
}
DialogSetup::~DialogSetup()
{
delete ui;
}
void DialogSetup::on_pushButtonConnect_clicked()
{
m_strIPAdd = ui->lineEditIPAdd->text();
m_strPort = ui->lineEditPort->text().toInt();
socket_->connectToHost(m_strIPAdd,m_strPort);
if(!socket_->waitForConnected(10000))
{
ui->labelStatus->setText("Error");
QMessageBox::information(this,"Error",socket->errorString());
}
}
void DialogSetup::wasconnected()
{
socket_->write("Hello server!");
ui->labelStatus->setText("Connected!");
ui->pushButtonDisconnect->setDisabled(false);
}
void DialogSetup::wasdisconnected()
{
ui->labelStatus->setText("Disonnected!");
}
void DialogSetup::on_pushButtonDisconnect_clicked()
{
socket_->close();
}
关于c++ - 关闭DialogWindow后如何让QTcpsocket保持连接?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31134181/