【问题标题】:Qt Signal and slots not working as expectedQt 信号和插槽未按预期工作
【发布时间】:2016-03-16 16:25:34
【问题描述】:

当套接字在等待读取时超时时,它偶尔会失败。但是当它确实失败时,它会继续失败,并且尽管 mpSocket 的断开连接信号连接到 slotDisconnect(),但 slotDisconnected 中的日志消息永远不会被报告。就好像 slotConnected 中的 return 语句没有被命中,而是在一个连续的循环中循环。

void Worker::slotDisconnected()
{
    // Attempt to reconnect
    log("Disconnected from Server. Attempting to reconnect...");

    // fires mpSocket's connect signal (which is connected to slotConnected)
    connectToServer();
}

void Worker::slotConnected()
{
    // Loop forever while connected and receiving messages correctly
    while(1)
    {

        if(mpSocket->bytesAvailable())
        {
            // A message is ready to read
        }
        else if(!mpSocket->waitForReadyRead(mSocketTimeOut))
        {
            // waitForReadyRead returned false - instead of continuing and trying again, we must disconnect as sometimes
            // (for some unknown reason) it gets stuck in an infinite loop without disconnecting itself as it should
            log("Socket timed out while waiting for next message.\nError String: " + mpSocket->errorString());
            msleep(3000);
            mpSocket->disconnect();
            return;
        }
    }
}

信号/插槽的连接方式如下:

connect(mpSocket, &QAbstractSocket::disconnected, this, &TRNGrabberWorker::slotDisconnected);
connect(mpSocket, &QAbstractSocket::connected, this, &TRNGrabberWorker::slotConnected);

有人知道发生了什么吗?将不胜感激

【问题讨论】:

  • 你永远不应该阻塞在“普通”Qt线程中,无论是像while(1)这样的循环,还是像waitForReadyRead()这样的“方便”方法。只是不要。使用QTimer,你需要“无限”重复动作与间隔,并连接像readyRead()这样的信号。这有点乏味,但还是那样做吧(虽然连接到 lambdas 可以使这比在 Qt4 中容易得多)。

标签: qt qt5 qt5.3


【解决方案1】:

要断开与服务器的连接,请使用 mpSocket->disconnectFromHost(); 而不是 mpSocket->disconnect();

实际上mpSocket->disconnect(); 断开了对象mpSocket 的所有信号/插槽。

【讨论】:

  • 啊,很好看! :D 仍然对为什么返回没有被击中感到困惑
  • @Ashley 当您想使用signas/slots 时,请避免在Qt 中使用无限循环。您最好模拟循环QTimer::singleShot(),在每个下一个事件循环周期中,零延迟返回相同的插槽。当您实现自定义无限循环时,您正在破坏 Qt 事件循环系统。作为一种解决方法,在每个循环迭代中至少调用QApplication::processEvents()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多