In my Qt application, I have a MainWindow
and a DialogWindow
. The DialogWindow
is for setting up server's IP address and port. While MainWindow
is for performing communication after successful connection.
However, setting up QTcpSocket *socket
in DialogWindow
means that when I close DialogWindow
, the socket
will be destroyed, thus the socket
will be disconnected with the server.
I would like to keep the socket connected to the server after the DialogWindow
was closed. Are there any methods that can achieve this result?
Please give me some comments and ideas on this. I am quite a newbie to 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.cpp
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();
}