0

Here is a function that get the translation from google translate and return the result:

QString QGoogleTranslate::translate(const QString &keyword, const QString &from, const QString &to)
{
    //Locate the translation in the map
    QMap<QString, QPair<QString, QString> >::iterator itr = translations.find(keyword);
    if(itr != translations.end())
    {
        if(itr.value().first == to) {
            result = itr.value().second;
            return result;
        }
    }

    //Translate URL
    QString url = QString("http://translate.google.com/translate_a/t?client=t&text=%0&hl=%1&sl=%2&tl=%1&multires=1&prev=enter&oc=2&ssel=0&tsel=0&uptl=%1&sc=1").arg(keyword).arg(to).arg(from);

    QNetworkAccessManager manager;
    QNetworkRequest request(url);
    QNetworkReply *reply = manager.get(request);

    //Get reply from Google
    do
    {
        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
    } while (!reply->isFinished());

    //Convert to string
    result = reply->readAll();
    reply->close();

    //Free memory
    delete reply;

    //Remove [[[" from the beginning
    result = result.replace("[[[\"", "");

    //Extract final translated string
    result = result.mid(0, result.indexOf(",\"") - 1);

    //Add the translation to the map so we don't need to make another web request for a translation
    translations[keyword] = QPair<QString, QString>(to, result);

    return result;
}

But as you see there's a do while loop that stops application until reply->isFinished(), and when I use SIGNAL(finished()) from QNetworkReply instead of do while loop, that's not gonna work!

How can I do that without any interruption?

4

2 回答 2

0

如果你想要一个“阻塞”的方式,你可以使用QEventLoop

processEvents使用以下模式代替代码中的无限循环:

QEventLoop loop;
connect( reply, &QNetworkReply::finished, &loop, &QEventLoop::quit );
loop.exec();

对于响应工作,您可以使用QJsonObject和其他。

于 2014-08-21T10:05:29.533 回答
0

稍后将所有内容移动到一个插槽并将其连接到reply'sfinished()信号,您需要将回复存储为一个字段。

您将需要一个发出结果的新信号。

在某些时候,您要么需要一个 processEvents 循环,要么一直返回到线程的事件循环。

于 2014-08-21T09:22:39.187 回答