头文字说明:

<span style="font-size:18px;">#ifndef GOOGLESUGGEST_H
#define GOOGLESUGGEST_H #include <QtGui>
#include <QtNetwork>
#include <QObject> QT_BEGIN_NAMESPACE
class QLineEdit;
class QNetworkReply;
class QTimer;
class QTreeWidget;
QT_END_NAMESPACE //! [1]
class GSuggestCompletion : public QObject
{
Q_OBJECT public:
GSuggestCompletion(QLineEdit *parent = 0);
~GSuggestCompletion();
bool eventFilter(QObject *obj, QEvent *ev);
void showCompletion(const QStringList &choices, const QStringList &hits); public slots: void doneCompletion();
void preventSuggest();
void autoSuggest();
void handleNetworkData(QNetworkReply *networkReply); private:
QLineEdit *editor;
QTreeWidget *popup;
QTimer *timer;
QNetworkAccessManager networkManager;
};
//! [1]
#endif // GOOGLESUGGEST_H</span>

源码:

<span style="font-size:18px;">//made by davidsu33
//2014-10-10
//QT的googlesuggest的改造版本号
//将其改造为360的搜索
//使用工具QNetwork模块, boost的属性树以及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> //常规浏览器查找 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::Popup);
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::Plain);
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(timeout()), 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.isEmpty() || choices.count() != hits.count())
return; const QPalette &pal = editor->palette();
QColor color = pal.color(QPalette::Disabled, 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::doneCompletion()
{
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的编码
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::preventSuggest()
{
timer->stop();
}
//! [8] //! [9]
void GSuggestCompletion::handleNetworkData(QNetworkReply *networkReply)
{
QUrl url = networkReply->url();
QNetworkReply::NetworkError nerror = networkReply->error();
if (!networkReply->error()) {
//解析jason数据,UTF-8编码 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(); //处理成json数据的标准格式 std::wstringstream wstream(wdata); boost::property_tree::wptree pt;
try
{
<strong><span style="color:#ff0000;"> //之前这里崩溃报错 expected array。是由于输入的数据不是标准的json格式
//须要将其规则标准化
boost::property_tree::read_json<boost::property_tree::wptree>(wstream, pt);</span></strong>
}
catch (const boost::property_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::property_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;"> //get_child的键值对。其second仍然是一颗树
//aline = QString::fromStdWString(it->first.data());
//alinesecond = QString::fromStdWString(it->second.data());//ERROR
//aword = QString::fromStdWString(it->get<std::wstring>(L"word"));//ERROR boost::property_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_queries") {
// 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" alt="">

版权声明:本文博客原创文章,博客,未经同意,不得转载。

QtNetwork说明(两)使用QT实现360的ctrl+ctrl特征的更多相关文章

  1. 【技术贴】删除360快捷搜索 ctrl+ctrl

    恶心的功能,这么变态!如何删除360快捷键ctrl,桌面跳出360搜索怎么办?360 ctrl 删除 卸载方法: 桌面右下角,在360图标上右键点击设置,进入设置中心. 把 [开启快捷搜索功能,双击C ...

  2. Qt实现360安全卫士10.0界面(编译时出现的一些问题)

    http://www.qtcn.org/bbs/read-htm-tid-57817.html 源码下载:https://git.oschina.net/zhjun5337/Qt360-10.0  或 ...

  3. PyQt(Python+Qt)学习随笔:QCommandLinkButton的特征及用途

    CommandLinkButton是Windows Vista引入的新控件,,它的预期用途与单选按钮类似,用于在一组互斥选项之间进行选择.命令链接按钮不应单独使用,而应作为向导和对话框中单选按钮的替代 ...

  4. 两个常见Qt编译错误的解决

    作者:朱金灿 来源:http://blog.csdn.net/clever101 如果在电脑上安装了两个Qt版本,在编译一个工程时有可能出现如下的编译错误: ERROR: failed to refr ...

  5. xmake新增对Qt编译环境支持

    在最新的xmake v2.2.1版本中,新增了对Qt SDK环境的支持,我们完全可以脱离Qt Creater进行Qt应用程序的开发,甚至配合vscode/idea等编辑器+xmake插件(xmake- ...

  6. QT UDP聊天小程序

    利用QT的UDP技术,实现两个QT程序之间的聊天程序. #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include < ...

  7. Qt opencv程序运行异常

    搭建了两次qt opencv vs ,经常出现程序运行异常.找了几个原因如下: 1.opencv的路径未配置或配置有误. 2.qt中pro文件包含不正确. 3.测试opencv程序不正确.如视频或图片 ...

  8. 记录下 QT Linux 静态编译遇到的坑

    Qt下静态编译Qt,根据我的经验,如果按照Windows下那种直接拿官方sdk安装之后的文件来编译是行不通的,需要直接下载Qt的source包,目前诺基亚的源码叫做qt-everywhere-open ...

  9. Qt入门(13)——Qt的调用退出

    如果我们创建了一个窗口,接下来使这个应用程序在用户让它退出的时候退出. #include <qfont.h>因为这个程序使用了QFont,所以它需要包含qfont.h.Qt的字体提取和X中 ...

随机推荐

  1. Python网络01 原始Python服务器

    原文:Python网络01 原始Python服务器 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 之前我的Python教程中有人 ...

  2. 并发队列ConcurrentLinkedQueue和阻塞队列LinkedBlockingQueue用法(转)

    在Java多线程应用中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列(先进先出).Java提供的线程安全的Queue可以分为阻塞队列和非阻塞队列,其中阻塞队列的典型例子是BlockingQ ...

  3. c# 硬件开源神器netduino的开发中慎用Cpu.Pin

    最近为了测试netduino开发板的各个端口是否正常使用,让同事写了一些测试程序,结果出了问题,他的测试程序导致开发板无法发布程序进去,按他的结论是开发板有问题,针对这个情况,我们经过仔细分析代码,认 ...

  4. C和指针 (pointers on C)——第三章——数据

    第三章 数据 本章是非常重要的,在特定范围内使用.链接属性.存储类型.const.extern和statickeyword使用.几乎所有的公司是C++在采访的第一个问题. 总结: 具有external ...

  5. A hard puzzle 1097

    Problem Description lcy gives a hard puzzle to feng5166,lwg,JGShining and Ignatius: gave a and b,how ...

  6. NYoj The partial sum problem(简单深搜+优化)

    题目链接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=927 代码: #include <stdio.h> #include & ...

  7. NET使用了UpdatePanel后如何弹出对话框!

    原文:NET使用了UpdatePanel后如何弹出对话框! 在ajax中的UpdatePanel弹出对话窗,可以使用: ScriptManager.RegisterStartupScript(Upda ...

  8. javascript之Style物

    Background 属性 属性                                 描写叙述 background                      在一行中设置全部的背景属性 ...

  9. js的逻辑 OR 运算符- ||

    逻辑or运算大家都很熟悉,都会用.但是在javascript中用的更多,用的更妙.有时候用它来解决兼容问题特别方面.简洁. 比如获取鼠标对象.在 Internet Explorer 里,  event ...

  10. oracle_SQL 实验查询及删除重复记录 依据条件 (row)

    除数据库表中的重复记录 根据条件 ① 创建表准备数据 创建表 tab_test -- Create table create table TAB_TEST ( ID NUMBER, NAME NVAR ...