Qtnetwork instructions (two) using QT to achieve 360 Ctrl+ctrl features

Source: Internet
Author: User

Header text Description:

<span style= "FONT-SIZE:18PX;" > #ifndef googlesuggest_h#define googlesuggest_h#include <QtGui> #include <QtNetwork> #include < Qobject>qt_begin_namespaceclass qlineedit;class qnetworkreply;class Qtimer;class QTreeWidget; qt_end_namespace//! [1]class gsuggestcompletion:public qobject{    q_objectpublic:    gsuggestcompletion (Qlineedit *parent = 0);    ~gsuggestcompletion ();    BOOL EventFilter (Qobject *obj, qevent *ev);    void Showcompletion (const qstringlist &choices, const qstringlist &hits);p ublic slots:    void donecompletion ();    void Preventsuggest ();    void AutoSuggest ();    void Handlenetworkdata (qnetworkreply *networkreply);p rivate:    qlineedit *editor;    Qtreewidget *popup;    Qtimer *timer;    Qnetworkaccessmanager networkmanager;};/ /! [1] #endif//googlesuggest_h</span>

Source:

<span style= "FONT-SIZE:18PX;" >//made by DAVIDSU33//2014-10-10//QT's Googlesuggest retrofit version number//transform it to 360 search//Use tool Qnetwork module, boost property tree and typeof//! [1] #include "googlesuggest.h" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_ parser.hpp> #include <boost/typeof/typeof.hpp> #include <boost/foreach.hpp> #include <sstream>/ /#include <iosfwd> #include <qregexp>//General browser find URL Http://sug.so.360.cn/suggest?callback=suggest_so &encodein=utf-8&encodeout=utf-8&format=json&fields=word,obdata&word=m#define GSUGGEST_URL " http://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json& fields=word,obdata&word=%1 "//#define GSUGGEST_URL" http://google.com/complete/search?output=toolbar&q=%1 "//! [1]//! [2]    Gsuggestcompletion::gsuggestcompletion (Qlineedit *parent): Qobject (parent), editor (parent) {popup = new Qtreewidget;    Popup->setwindowflags (Qt::P opup); Popup->seTfocuspolicy (Qt::nofocus);    Popup->setfocusproxy (parent);    Popup->setmousetracking (TRUE);    Popup->setcolumncount (2);    Popup->setuniformrowheights (TRUE);    Popup->setrootisdecorated (FALSE);    Popup->setedittriggers (qtreewidget::noedittriggers);    Popup->setselectionbehavior (qtreewidget::selectrows); Popup->setframestyle (Qframe::box |    Qframe::P Lain);    Popup->sethorizontalscrollbarpolicy (Qt::scrollbaralwaysoff);    Popup->header ()->hide ();    Popup->installeventfilter (this);    Connect (Popup, SIGNAL (itemclicked (Qtreewidgetitem*,int)), SLOT (Donecompletion ()));    Timer = new Qtimer (this);    Timer->setsingleshot (TRUE);    Timer->setinterval (500);    Connect (timer, SIGNAL (), SLOT (AutoSuggest ()));    Connect (editor, SIGNAL (textedited (QString)), timer, SLOT (Start ())); Connect (&networkmanager, SIGNAL (finished (qnetworkreply*)), this, SLOT (Handlenetworkdata (qnetworkreply*)));} //! [2]//! [3] GsuggestcomPletion::~gsuggestcompletion () {delete popup;} //! [3]//!    [4]bool Gsuggestcompletion::eventfilter (Qobject *obj, qevent *ev) {if (obj! = popup) return false;        if (ev->type () = = qevent::mousebuttonpress) {popup->hide ();        Editor->setfocus ();    return true;        } if (ev->type () = = qevent::keypress) {bool consumed = false;        int key = static_cast<qkeyevent*> (EV)->key ();            Switch (key) {case Qt::key_enter:case qt::key_return:donecompletion ();        consumed = true;            Case Qt::key_escape:editor->setfocus ();            Popup->hide ();        consumed = true;        Case Qt::key_up:case qt::key_down:case qt::key_home:case qt::key_end:case qt::key_pageup:        Case Qt::key_pagedown:break;            Default:editor->setfocus ();            Editor->event (EV);            Popup->hide ();    Break    } return consumed; } return false;} //! [4]//! [5]void gsuggestcompletion::showcompletion (const qstringlist &choices, const qstringlist &hits) {if (choices.i Sempty () | |    Choices.count ()! = Hits.count ()) return;    Const Qpalette &pal = Editor->palette ();    Qcolor color = Pal.color (qpalette::D isabled, Qpalette::windowtext);    Popup->setupdatesenabled (FALSE);    Popup->clear ();        for (int i = 0; i < Choices.count (); ++i) {Qtreewidgetitem * item;        item = new Qtreewidgetitem (popup);        Item->settext (0, choices[i]);        Item->settext (1, hits[i]);        Item->settextalignment (1, qt::alignright);    Item->settextcolor (1, color);    } popup->setcurrentitem (Popup->toplevelitem (0));    Popup->resizecolumntocontents (0);    Popup->resizecolumntocontents (1);    Popup->adjustsize ();    Popup->setupdatesenabled (TRUE);    int h = popup->sizehintforrow (0) * Qmin (7, Choices.count ()) + 3;Popup->resize (Popup->width (), h);    Popup->move (Editor->maptoglobal (qpoint (0, Editor->height ()));    Popup->setfocus (); Popup->show ();} //! [5]//!    [6]void gsuggestcompletion::d onecompletion () {timer->stop ();    Popup->hide ();    Editor->setfocus ();    Qtreewidgetitem *item = Popup->currentitem ();        if (item) {Editor->settext (item->text (0));    Qmetaobject::invokemethod (editor, "returnpressed"); }}//! [6]//!    [7]void gsuggestcompletion::autosuggest () {//utf-8 encoded QString str = Editor->text (); QString url = QString (gsuggest_url). Arg (str); Qurl suggesturl (URL);//suggesturl.setencodedurl (Url.toascii ());//suggesturl.sethost ("http://sug.so.360.cn/"); QString strpath = Suggesturl.encodedpath (); QString strquery = Suggesturl.encodedquery (); Qnetworkrequest Req;req.seturl (Suggesturl);//req.setrawheader ("Accept", "Application/javascript, */*;q=0.8");// Req.setrawheader ("Referer", "http://www.so.com/");//req.setrawheader ("Accept-languAge "," ZH-CN ");//req.setrawheader (" User-agent "," mozilla/5.0 "(compatible; MSIE 9.0; Windows NT 6.1; trident/5.0)//req.setrawheader ("accept-encoding", "gzip, deflate");//req.setrawheader ("Host", "sug.so.360.cn") ;//req.setrawheader ("Cookie", "__HUID=10X%2FLQOE%2B%2FDQLXBKH8JUO9HZQNDDQ5T9E2HQTQHS2HULW%3D; __guid=    132730903.1687894815517624600.1412906141457.4387 "); Networkmanager.get (req);//accept:application/javascript, */*;q=0.8//referer:http://www.so.com///accept-language : zh-cn//user-agent:mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; trident/5.0)//accept-encoding:gzip, deflate}//! [7]//! [8]void gsuggestcompletion::p reventsuggest () {timer->stop ();} //! [8]//! [9]void gsuggestcompletion::handlenetworkdata (qnetworkreply *networkreply) {qurl URL = networkreply->url ();    Qnetworkreply::networkerror nerror = Networkreply->error ();        if (!networkreply->error ()) {//parse Jason data, UTF-8 encode qstringlist choices;        Qstringlist hits; Qbytearray Response (NETworkreply->readall ()); QString strresponse (response); QString StrResponse2 = Qstring::fromutf8 (Response.data (), response.size ()); QString strResponse3 = Qstring::fromascii (Response.data (), response.size ()); Qdebug () <<strResponse; QREGEXP exp ("\\s*suggest_so\\ ((. +) \ \);"); int pos = exp.indexin (strresponse); Qstringlist captexts = exp.capturedtexts (); Assert (Captexts[1].size () > 0); std::wstring wdata = Strresponse.tostdwstring (); Qdebug () <<wdata.c_str (); Qdebug () <<captexts[1];wdata = capTexts[1]. Tostdwstring ();//The standard format for processing JSON data Std::wstringstream wstream (wdata); boost::p roperty_tree::wptree Pt;try{<strong ><span style= "color: #ff0000;" >//here before the crash error expected array. is because the input data is not a standard JSON format//need to standardize its rules boost::p roperty_tree::read_json<boost::p roperty_tree::wptree> (Wstream, PT); </span></strong>}catch (const boost::p roperty_tree::json_parser_error& e) {qdebug () << "What ' s "<<e.what (); Qdebug () <<" message: "<<e.message (). C_STR (); Assert (FALSE);} QString Aline, Alinesecond, aword;std::wstring query_object = pt.get<std::wstring> (L "Query");//boost_foreach ( Boost::p roperty_tree::wptree::value_type &child, Pt.get_child (L "result"))//{//}boost_auto (Child, Pt.get_child (L "result")); For (Boost_auto (it, Child.begin ()); it! = Child.end (); ++it) {<strong><span style= "color: #ff0000;" The key-value pair for the >//get_child. Its second is still a tree//aline = qstring::fromstdwstring (It->first.data ());//alinesecond = Qstring::fromstdwstring (it- >second.data ());//error//aword = Qstring::fromstdwstring (it->get<std::wstring> (L "word"));//ERROR  Boost::p roperty_tree::wptree& childparse = it->second; Aword = qstring::fromstdwstring (childparse.get<std::wstring> (L "word")); Qdebug () <<aword;choices<        <aword;hits<<qstring::null;</span></strong>}//qxmlstreamreader XML (response);        while (!xml.atend ()) {//Xml.readnext (); if (xml.tokentype () = = qxmlstreamreader::startelement)        if (xml.name () = = "Suggestion") {//Qstringref str = xml.attributes (). Value ("Data");        Choices << str.tostring (); }//if (xml.tokentype () = = qxmlstreamreader::startelement)//if (xml.name () = = "Num_qu        Eries ") {//Qstringref str = xml.attributes (). Value (" int ");        Hits << str.tostring ();    }//} showcompletion (choices, hits); } networkreply->deletelater ();} //! [9]</span>
:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzgf2awrzdtmz/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Qtnetwork instructions (two) using QT to achieve 360 Ctrl+ctrl features

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.