Qt Google Translator
This article shows how to use non-Ajax version of the google translator method to get our text translated.
Article Metadata
Tested with
Devices(s): Emulator
Compatibility
Platform(s): S60 5th Edition, Qt 4.6.2, Qt 4.7
Article
Keywords: QHttp
Created: skumar_rao
(21 Nov 2010)
Last edited: hamishwillee
(11 Oct 2012)
Implementation
- Create a QHttp member to transact with Google server.
-
http = new QHttp(this);
http->setHost("www.google.com");
-
- Connect QHttp::done() member to our own class slot to grab transaction data from Google server.
-
connect(http, SIGNAL(done(bool)), this, SLOT(transaction_done()));
-
- Prepare google translator service Url with to & from languages.
- Prepare text to be added to service.
-
QByteArray textByteArray("text=");
textByteArray.append( text.toUtf8() );
-
- Prepare Request header
-
QHttpRequestHeader header = QHttpRequestHeader("POST", url, 1, 1);
header.setValue("Host", "www.google.com");
header.setValue("User-Agent", "Mozilla/5.0"); // ToDo: change to a value specific to device
header.setValue("Accept-Encoding", "deflate");
header.setContentLength(text.length());
header.setValue("Connection", "Close");
-
- Invoke Http request with header and binary request
http->request(header,textByteArray);
- Once the HTTP gets the response from the service read the http reply to a string
QString replyText;
replyText = replyText.fromUtf8( http->readAll() );
- Now we have to format this string to get the properly format data
-
replyText = replyText.replace(QString("\\\""),QString("\""));
replyText = replyText.replace(QString("\\n"),QString("\n"));
replyText = replyText.replace(QString("\n "),QString("\n"));
replyText = replyText.replace(QString("\\x3c"),QString("<"));
replyText = replyText.replace(QString("\\x3e"),QString(">"));
if( replyText.startsWith( QString("\"") ) ) {
replyText = replyText.remove( replyText.length()-1, 1).remove(0,1);
} else if( replyText.startsWith( QString("[") ) && replyText.endsWith( QString("]") ) ) {
QStringList translatedList;
replyText = replyText.replace(QString("]"),QString(""));
translatedList = replyText.split(QString("["));
replyText = QString("");
for(int i=0,j=0;i<translatedList.count();i++) {
if(translatedList.at(i)!="") {
if(j==0) {
QString translation = translatedList.at(i);
translation = translation.replace("\"","");
translation = translation.replace(",","");
replyText.append( translation );
replyText.append( "\n\n") ;
} else {
QString translation = translatedList.at(i);
QStringList translations = translation.split(",");
for(int y=0;y<translations.count();y++) {
translation = translations.at(y);
translation = translation.replace("\"","");
if(y==0) {
replyText.append( QString( translation + ": ") );
} else {
replyText.append( QString( "\t" + translation + "\n" ) );
}
}
replyText.append( "\n" );
}
j++;
}
}
}
-
Result
Now replyText will contain formatted text that we can use in QTextEdit for display.


(no comments yet)