QtNetwork说明(两)使用QT实现360的ctrl+ctrl特征
头文字说明:
<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特征的更多相关文章
- 【技术贴】删除360快捷搜索 ctrl+ctrl
恶心的功能,这么变态!如何删除360快捷键ctrl,桌面跳出360搜索怎么办?360 ctrl 删除 卸载方法: 桌面右下角,在360图标上右键点击设置,进入设置中心. 把 [开启快捷搜索功能,双击C ...
- Qt实现360安全卫士10.0界面(编译时出现的一些问题)
http://www.qtcn.org/bbs/read-htm-tid-57817.html 源码下载:https://git.oschina.net/zhjun5337/Qt360-10.0 或 ...
- PyQt(Python+Qt)学习随笔:QCommandLinkButton的特征及用途
CommandLinkButton是Windows Vista引入的新控件,,它的预期用途与单选按钮类似,用于在一组互斥选项之间进行选择.命令链接按钮不应单独使用,而应作为向导和对话框中单选按钮的替代 ...
- 两个常见Qt编译错误的解决
作者:朱金灿 来源:http://blog.csdn.net/clever101 如果在电脑上安装了两个Qt版本,在编译一个工程时有可能出现如下的编译错误: ERROR: failed to refr ...
- xmake新增对Qt编译环境支持
在最新的xmake v2.2.1版本中,新增了对Qt SDK环境的支持,我们完全可以脱离Qt Creater进行Qt应用程序的开发,甚至配合vscode/idea等编辑器+xmake插件(xmake- ...
- QT UDP聊天小程序
利用QT的UDP技术,实现两个QT程序之间的聊天程序. #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include < ...
- Qt opencv程序运行异常
搭建了两次qt opencv vs ,经常出现程序运行异常.找了几个原因如下: 1.opencv的路径未配置或配置有误. 2.qt中pro文件包含不正确. 3.测试opencv程序不正确.如视频或图片 ...
- 记录下 QT Linux 静态编译遇到的坑
Qt下静态编译Qt,根据我的经验,如果按照Windows下那种直接拿官方sdk安装之后的文件来编译是行不通的,需要直接下载Qt的source包,目前诺基亚的源码叫做qt-everywhere-open ...
- Qt入门(13)——Qt的调用退出
如果我们创建了一个窗口,接下来使这个应用程序在用户让它退出的时候退出. #include <qfont.h>因为这个程序使用了QFont,所以它需要包含qfont.h.Qt的字体提取和X中 ...
随机推荐
- Debian 7设备nginx周围环境、编译并安装和启动
/********************************************************************* * Author : Samson * Date ...
- Java Date API demo
package date; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; /*2015- ...
- Android用户界面设计:框架布局(转)
摘要:框架布局是Android开发者组织视图控件最简单和最有效的布局之一.通过本文,你将学到所有关于框架布局的知识,它们主要用来在屏幕上组织特别的或重叠的视图控件.使用得当的话,很多有趣的Androi ...
- 可视化配置以及Net应用MemCache在win7
MemCache在win7上的可视化配置以及Net应用 惯例科普:MemCache是一套分布式的高速缓存系统,由LiveJournal的Brad Fitzpatrick开发,但目前被许多网站使用以 ...
- android模拟器与PC的端口映射(转)
阅读目录 一.概述 二.实现步骤 回到顶部 一.概述 Android系统为实现通信将PC电脑IP设置为10.0.2.2,自身设置为127.0.0.1,而PC并没有为Android模拟器系统指定IP,所 ...
- JavaScript语言核心之词法结构
编程语言的词法结构是一套基础性规则,用来描述如何使用这门语言来编写程序.作为语法的基础,它规定了诸如变量名是什么样的.怎么写注释,以及程序语句之间如何分割的等规则. 1.1字符集 JavaScript ...
- Oracle 树操作
Oracle 树操作(select…start with…connect by…prior) oracle树查询的最重要的就是select…start with…connect by…prior语法了 ...
- hdu 1814 Peaceful Commission (2-sat 输出字典序最小的路径)
Peaceful Commission Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Oth ...
- HDU1253 胜利大逃亡 BFS
胜利大逃亡 Time Limit : 4000/2000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other) Total Submiss ...
- ASP.NET MVC+EF框架+EasyUI实现权限管理系列(20)-多条件模糊查询和回收站还原的实现
原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(20)-多条件模糊查询和回收站还原的实现 ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇) (1):框架 ...