使用QtWebKit 做一个简单的浏览器.

mybrowserUI.ui

 <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>522</width>
<height>336</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QWebView" name="webView">
<property name="url">
<url>
<string>about:blank</string>
</url>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>522</width>
<height>23</height>
</rect>
</property>
<widget class="QMenu" name="menu_F">
<property name="title">
<string>文件【&amp;F】</string>
</property>
<widget class="QMenu" name="menu">
<property name="title">
<string>新建</string>
</property>
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/worm.gif</normaloff>:/img/resource/worm.gif</iconset>
</property>
<addaction name="actionNew_Windows"/>
</widget>
<addaction name="menu"/>
<addaction name="actionResoures"/>
<addaction name="separator"/>
<addaction name="actionClose"/>
</widget>
<widget class="QMenu" name="menuAbout">
<property name="title">
<string>关于【&amp;A】</string>
</property>
<addaction name="actionAboutUS"/>
</widget>
<widget class="QMenu" name="menu_2">
<property name="title">
<string>工具【&amp;T】</string>
</property>
<addaction name="actionLLink"/>
<addaction name="separator"/>
<addaction name="actionshot"/>
</widget>
<addaction name="menu_F"/>
<addaction name="menu_2"/>
<addaction name="menuAbout"/>
</widget>
<widget class="QToolBar" name="toolBar">
<property name="windowTitle">
<string>toolBar</string>
</property>
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionBack"/>
<addaction name="actionForward"/>
<addaction name="actionRefresh"/>
<addaction name="actionPause"/>
<addaction name="actionHome"/>
<addaction name="separator"/>
<addaction name="actionGo"/>
</widget>
<action name="actionClose">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/birthday.gif</normaloff>:/img/resource/birthday.gif</iconset>
</property>
<property name="text">
<string>关闭</string>
</property>
</action>
<action name="actionBack">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/back.png</normaloff>:/img/resource/back.png</iconset>
</property>
<property name="text">
<string>back</string>
</property>
<property name="toolTip">
<string>后退</string>
</property>
</action>
<action name="actionForward">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/forward.png</normaloff>:/img/resource/forward.png</iconset>
</property>
<property name="text">
<string>forward</string>
</property>
<property name="toolTip">
<string>前进</string>
</property>
</action>
<action name="actionHome">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/home.png</normaloff>:/img/resource/home.png</iconset>
</property>
<property name="text">
<string>home</string>
</property>
<property name="toolTip">
<string>主页</string>
</property>
</action>
<action name="actionPause">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/pause.png</normaloff>:/img/resource/pause.png</iconset>
</property>
<property name="text">
<string>pause</string>
</property>
<property name="toolTip">
<string>暂停</string>
</property>
</action>
<action name="actionRefresh">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/refresh.png</normaloff>:/img/resource/refresh.png</iconset>
</property>
<property name="text">
<string>refresh</string>
</property>
<property name="toolTip">
<string>刷新</string>
</property>
</action>
<action name="actionGo">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/enter.jpg</normaloff>:/img/resource/enter.jpg</iconset>
</property>
<property name="text">
<string>go</string>
</property>
<property name="toolTip">
<string>确定前往</string>
</property>
</action>
<action name="actionNew_Windows">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/newwindows.gif</normaloff>:/img/resource/newwindows.gif</iconset>
</property>
<property name="text">
<string>New Windows</string>
</property>
</action>
<action name="actionResoures">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/cool.gif</normaloff>:/img/resource/cool.gif</iconset>
</property>
<property name="text">
<string>查看源码</string>
</property>
</action>
<action name="actionLLink">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/cry.gif</normaloff>:/img/resource/cry.gif</iconset>
</property>
<property name="text">
<string>高亮链接</string>
</property>
</action>
<action name="actionAboutUS">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/eat.gif</normaloff>:/img/resource/eat.gif</iconset>
</property>
<property name="text">
<string>关于我们</string>
</property>
</action>
<action name="actionshot">
<property name="icon">
<iconset resource="qrcc.qrc">
<normaloff>:/img/resource/sex.gif</normaloff>:/img/resource/sex.gif</iconset>
</property>
<property name="text">
<string>截图网页</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>QWebView</class>
<extends>QWidget</extends>
<header>QtWebKit/QWebView</header>
</customwidget>
</customwidgets>
<resources>
<include location="qrcc.qrc"/>
</resources>
<connections/>
</ui>

mainbrowser.py

 # -*- coding: UTF8 -*-

 from PyQt4 import QtGui, QtCore, QtWebKit, QtNetwork
from PyQt4.QtCore import QUrl
from mybrowserUI import Ui_MainWindow
import sys, os
import qrcc reload(sys)
sys.setdefaultencoding("utf-8") class MainMyBrowser(QtGui.QMainWindow):
def __init__(self,parent=None):
super(MainMyBrowser,self).__init__(parent)
self.Ui = Ui_MainWindow()
self.Ui.setupUi(self)
self.setWindowTitle('MyBrowser V2.1')
self.statusBar().showMessage('Ready')
self.initLayout()
self.initSimpleEvent()
url = QUrl('http://m.hao123.com')
self.Ui.webView.load(url) # 初始化Layout
def initLayout(self):
self.Ui.actionClose.setStatusTip(u'退出')
'''
添加地址栏,输入框 lineEdit
'''
self.lblAddress = QtGui.QLabel(u"地址:", self.Ui.toolBar)
self.Ui.toolBar.insertWidget(self.Ui.actionGo, self.lblAddress) #(self, QAction before #控件之前, QWidget widget # 改控件)
self.addressEdit = QtGui.QLineEdit(self.Ui.toolBar)
self.addressEdit.setFixedHeight(30) # lineEdit 框高度
self.addressEdit.setFont(QtGui.QFont('.SansSerif', 19)) # 设置框内字体
self.addressEdit.setStatusTip(u'请输入链接地址')
self.Ui.actionGo.setStatusTip(u'前往链接')
self.Ui.toolBar.insertWidget(self.Ui.actionGo, self.addressEdit) # 初始化效果事件
def initSimpleEvent(self):
self.progress = 0
self.Ui.actionClose.triggered.connect(QtGui.qApp.quit) # 退出
self.addressEdit.returnPressed.connect(self.changeLocation) #地址框回车触发GO效果
self.Ui.webView.loadFinished.connect(self.adjustLocation) # 加载完成改变输入框text()
self.Ui.webView.titleChanged.connect(self.adjustTitle) #标题修改触发
self.Ui.webView.loadProgress.connect(self.setProgress) # 显示加载进度
self.Ui.actionGo.triggered.connect(self.changeLocation)
self.Ui.actionBack.triggered.connect(self.Ui.webView.back) #返回
self.Ui.actionPause.triggered.connect(self.Ui.webView.stop)
self.Ui.actionRefresh.triggered.connect(self.Ui.webView.reload)
self.Ui.actionForward.triggered.connect(self.Ui.webView.forward)
self.Ui.actionHome.triggered.connect(self.GoHome) # 无法获取主页**=> self.Ui.webView.gohome
self.Ui.actionResoures.triggered.connect(self.viewSource) # 查看源码
self.Ui.actionNew_Windows.triggered.connect(self.newindows) # 新打开一个windows_tab
self.Ui.actionLLink.triggered.connect(self.highlightAllLinks) # 高亮
self.Ui.actionAboutUS.triggered.connect(self.aboutus) # 关于我们
self.Ui.actionshot.triggered.connect(self.shot) # 截图
'''
Webkit屏蔽右键菜单
'''
self.Ui.webView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.Ui.webView.customContextMenuRequested.connect(self.showContextMenu)
self.Ui.webView.contextMenu = QtGui.QMenu(self) #输入框改变时
def changeLocation(self):
url = QtCore.QUrl.fromUserInput(self.addressEdit.text())
self.Ui.webView.load(url)
self.Ui.webView.setFocus()
# 调整输入框的显示
def adjustLocation(self):
self.addressEdit.setText(self.Ui.webView.url().toString())
#调整windows标题显示
def adjustTitle(self):
if 0 < self.progress < 100:
self.setWindowTitle("%s (%s%%)" % (self.Ui.webView.title(), self.progress))
else:
self.setWindowTitle(self.Ui.webView.title())
#显示加载进度
def setProgress(self, p):
self.progress = p
self.adjustTitle() #模拟首页
def GoHome(self):
self.Ui.webView.load(QUrl('http://www.baidu.com'))
#查看源码
def viewSource(self):
accessManager = self.Ui.webView.page().networkAccessManager()
request = QtNetwork.QNetworkRequest(self.Ui.webView.url())
reply = accessManager.get(request)
reply.finished.connect(self.slotSourceDownloaded)
#查看源码
def slotSourceDownloaded(self):
reply = self.sender()
self.textEdit = QtGui.QTextEdit(None)
self.textEdit.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.textEdit.show()
self.textEdit.setPlainText(QtCore.QTextStream(reply).readAll())
self.textEdit.resize(600, 400)
reply.deleteLater() #新打开tab
# @QtCore.pyqtSlot()
def newindows(self):
window = MainMyBrowser(self)
window.show()
if self.addressEdit.text().isEmpty():
return; # 高亮
def highlightAllLinks(self):
code = """$('a').each(
function () {
$(this).css('background-color', 'yellow')
}
)"""
self.Ui.webView.page().mainFrame().evaluateJavaScript(code) # 关于我们
def aboutus(self):
QtGui.QMessageBox.about(self, "About WebBrowser",u"Pyqt 浏览器V2.1, power by dcb3688") #截图
def shot(self):
webView = self.Ui.webView
url = QtCore.QUrl.fromUserInput(self.addressEdit.text())
webView.load(QtCore.QUrl(url))
self.webPage = webView.page()
self.connect(webView, QtCore.SIGNAL("loadFinished(bool)"), self.savePage)
# 截图保存图片
def savePage(self,finished):
if finished:
self.statusBar().showMessage(u'开始截图')
size = self.webPage.mainFrame().contentsSize()
self.statusBar().showMessage(u"页面宽:%d,页面高:%d" % (size.width(), size.height()))
self.webPage.setViewportSize(QtCore.QSize(size.width()+16, size.height()))
img = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
painter = QtGui.QPainter(img)
self.webPage.mainFrame().render(painter)
painter.end()
fileName= "shot.png"
if img.save(fileName):
filePath = os.path.join(os.path.dirname(__file__), fileName)
QtGui.QMessageBox.information(self, "About WebBrowser", u'图片保存完成,\n'+'路径:'+filePath);
else:
self.statusBar().showMessage(u'截图失败')
else:
self.statusBar().showMessage(u'网页加载失败') # 显示右键内容
def showContextMenu(self, pos):
self.Ui.webView.contextMenu.move(self.pos() + pos)
self.Ui.webView.contextMenu.show() def keyPressEvent(self, event):
if event.key() ==QtCore.Qt.Key_Escape:
self.close()
if event.key() == QtCore.Qt.Key_F5:
self.changeLocation() class aboutDialog(QtGui.QWidget):
def __init__(self, parent=None):
super(aboutDialog, self).__init__(parent)
self.show() if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
appshow = MainMyBrowser()
appshow.show()
sys.exit(app.exec_())

效果:

网上一个截图: 给工具栏添加action:

Pyqt 一个简单的浏览器的更多相关文章

  1. 【Java】 实现一个简单文件浏览器(1)

    学习Java的Swing的时候写的一个超简单文件浏览器 效果如图: 项目结构: 这里面主要用了两个控件,JTree和JTable 下面先说下左侧的文件树如何实现: 首先是FileTree类,继承于JT ...

  2. Promise A 规范的一个简单的浏览器端实现

    简单的实现了一个promise 的规范,留着接下来模块使用.感觉还有很多能优化的地方,有时间看看源码,或者其他大神的代码 主要是Then 函数.回调有点绕人. !(function(win) { fu ...

  3. PYQT实现简单的浏览器功能

    主要的类 QMainWindow 提供一个有菜单条.锚接窗口(例如工具条)和一个状态条的主应用程序窗口. http://www.kuqin.com/qtdocument/qmainwindow.htm ...

  4. pyqt一个简单的动画

    import sys from PyQt4.QtGui import QApplication , QGraphicsEllipseItem , QGraphicsItemAnimationfrom ...

  5. 【Java】 实现一个简单文件浏览器(2)

    接着上篇文章 接下来说下程序右侧的文件内容表格如何实现 FileTable类: FileTable基础于JTable类,构造函数里用setDefaultRenderer设置每行默认的渲染器为FileT ...

  6. vue_cli下开发一个简单的模块权限系统之建立登录页面并且实现在浏览器输入地址出现内容

    新建一个Login.vue(登录页面,先把Hello.vue的内容复制过来即可) 然后我们打开router下面的index.js,第一个箭头:(引入vue路由)第二个箭头(引入我们新建的Login.v ...

  7. 一个简单有效的兼容IE7浏览器的办法

    最近发现了一个简单有效的兼容IE7浏览器的办法 直接将下面代码复制道页面 <meta http-equiv="X-UA-Compatible" content="I ...

  8. 制作一个简单的WPF图片浏览器

    原文:制作一个简单的WPF图片浏览器 注:本例选自MSDN样例,并略有改动.先看效果: 这里实现了以下几个功能:1.  对指定文件夹下所有JPG文件进行预览2.  对选定图片进行旋转3.  对选定图片 ...

  9. 如何开发一个简单的HTML5 Canvas 小游戏

    原文:How to make a simple HTML5 Canvas game 想要快速上手HTML5 Canvas小游戏开发?下面通过一个例子来进行手把手教学.(如果你怀疑我的资历, A Wiz ...

随机推荐

  1. django 的模板语言

    1.模版的执行 模版的创建过程,对于模版,其实就是读取模版(其中嵌套着模版标签),然后将 Model 中获取的数据插入到模版中,最后将信息返回给用户. def current_datetime(req ...

  2. idea让字体更圆滑

    个人用myeclipse习惯了, 转战idea 觉得自己看题来很方很死板的样子. 然后更换了其字体,如果喜欢你可以试试. 点击file --> setting.. --> 把编辑的字体改成 ...

  3. 2.5---链表来进行加法,链式A+B(CC150)

    这里是用了自己的方法,和书本不一样. import java.util.HashSet; import java.util.Set; class ListNode{ int val; ListNode ...

  4. svn co 与ssl

    默认情况下, yum安装的svn用的是GnuTLS, 而不是ssl, 导致checkout https协议打包的svn repo的时候会报错. 解决方法是用openssl重新编译安装svn.注意ssl ...

  5. Droid4x快照还原

    一.问题描述 1. Droid4x还原快照可以通过VirtualBox 先还原快照 2. virtualbox 还原快照之后 如果没有用virtualbox启动 并关闭     而是直接启动Droid ...

  6. ip netns相关命令

    1.增加虚拟网络命名空间   ip netns add net0   2.显示所有的虚拟网络命名空间 EULER:~ # ip netns list net0 也可通过查看/var/run/netns ...

  7. 【GoLang】golang 交叉编译 实现&工具

    apt-get install gcc-mingw-w64 env CGO_ENABLED= GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc g ...

  8. C# 复制(深拷贝、浅拷贝)

    Object.MemberwiseClone 方法 创建当前 Object 的浅表副本. protected Object MemberwiseClone() MemberwiseClone 方法创建 ...

  9. SQL合并多行查询到一行

    示例表 tb 数据如下 id value—————1 aa1 bb2 aaa2 bbb2 ccc 第一种 SELECT id, [val]=( SELECT [value] +',' FROM tb ...

  10. Zigzag Iterator

    Given two 1d vectors, implement an iterator to return their elements alternately. For example, given ...