QT even processing while waitForConnected is running

为君一笑 提交于 2019-12-11 03:01:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!