问题
I have loop that is supposed to try to connect to each IP from range:
for(...){
socket->connectToHost(addres,port);
do stuff....
if(socket->waitForConnected(2000))
{
do stuff...
if(socket->waitForReadyRead(1000))
{
do stuff...
}
else do stuff...
}
do stuff ......
}
During connection atempts UI freezes, because there is no event processing in the meantime. I tried to add QCoreApplication::processEvents(); inside the loop, however it still freezes for long time during waitForConnected, and I also tried to use timers, but this also wont work as QT needs event processing to use timers in the first place. Is there any way to provide event processing (prevent UI from freezing) during conection, or using some non-blocking alternative for waitForConnection?
回答1:
The best approach is to use QTcpSocket
in an asynchronous mode by connecting the signals of the socket to relevant slots :
connect( socket, SIGNAL(connected()), this, SLOT(onConnected()) );
connect( socket, SIGNAL(readyRead()), this, SLOT(tcpReady()) );
connect( socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(tcpError(QAbstractSocket::SocketError)) );
And handle your application logic in the slots :
void MyClass::onConnected()
{
...
}
void MyClass::tcpError(QAbstractSocket::SocketError error)
{
...
}
You can also use a local event loop using QEventLoop
and connect the signals connected
, error
, ... of your QTcpSocket
to the quit slot of QEventLoop
. This way when the socket is connected or an error is occured, the local event loop quits and the rest gets executed :
socket->connectToHost(addres,port);
QEventLoop loop;
loop.connect(socket, SIGNAL(connected()), SLOT(quit()));
loop.connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(quit()));
loop.exec();
//...
I should not that it's the standard pattern for "blocking wait without blocking the UI".
回答2:
Please write out 100 times 'I must not wait in GUI event-handlers'.
Use async signals or thread off the comms.
来源:https://stackoverflow.com/questions/27787130/qt-even-processing-while-waitforconnected-is-running