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

mybrowserUI.ui

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ui version="4.0">
  3. <class>MainWindow</class>
  4. <widget class="QMainWindow" name="MainWindow">
  5. <property name="geometry">
  6. <rect>
  7. <x>0</x>
  8. <y>0</y>
  9. <width>522</width>
  10. <height>336</height>
  11. </rect>
  12. </property>
  13. <property name="windowTitle">
  14. <string>MainWindow</string>
  15. </property>
  16. <widget class="QWidget" name="centralwidget">
  17. <layout class="QVBoxLayout" name="verticalLayout">
  18. <item>
  19. <widget class="QWebView" name="webView">
  20. <property name="url">
  21. <url>
  22. <string>about:blank</string>
  23. </url>
  24. </property>
  25. </widget>
  26. </item>
  27. </layout>
  28. </widget>
  29. <widget class="QMenuBar" name="menubar">
  30. <property name="geometry">
  31. <rect>
  32. <x>0</x>
  33. <y>0</y>
  34. <width>522</width>
  35. <height>23</height>
  36. </rect>
  37. </property>
  38. <widget class="QMenu" name="menu_F">
  39. <property name="title">
  40. <string>文件【&amp;F】</string>
  41. </property>
  42. <widget class="QMenu" name="menu">
  43. <property name="title">
  44. <string>新建</string>
  45. </property>
  46. <property name="icon">
  47. <iconset resource="qrcc.qrc">
  48. <normaloff>:/img/resource/worm.gif</normaloff>:/img/resource/worm.gif</iconset>
  49. </property>
  50. <addaction name="actionNew_Windows"/>
  51. </widget>
  52. <addaction name="menu"/>
  53. <addaction name="actionResoures"/>
  54. <addaction name="separator"/>
  55. <addaction name="actionClose"/>
  56. </widget>
  57. <widget class="QMenu" name="menuAbout">
  58. <property name="title">
  59. <string>关于【&amp;A】</string>
  60. </property>
  61. <addaction name="actionAboutUS"/>
  62. </widget>
  63. <widget class="QMenu" name="menu_2">
  64. <property name="title">
  65. <string>工具【&amp;T】</string>
  66. </property>
  67. <addaction name="actionLLink"/>
  68. <addaction name="separator"/>
  69. <addaction name="actionshot"/>
  70. </widget>
  71. <addaction name="menu_F"/>
  72. <addaction name="menu_2"/>
  73. <addaction name="menuAbout"/>
  74. </widget>
  75. <widget class="QToolBar" name="toolBar">
  76. <property name="windowTitle">
  77. <string>toolBar</string>
  78. </property>
  79. <attribute name="toolBarArea">
  80. <enum>TopToolBarArea</enum>
  81. </attribute>
  82. <attribute name="toolBarBreak">
  83. <bool>false</bool>
  84. </attribute>
  85. <addaction name="actionBack"/>
  86. <addaction name="actionForward"/>
  87. <addaction name="actionRefresh"/>
  88. <addaction name="actionPause"/>
  89. <addaction name="actionHome"/>
  90. <addaction name="separator"/>
  91. <addaction name="actionGo"/>
  92. </widget>
  93. <action name="actionClose">
  94. <property name="icon">
  95. <iconset resource="qrcc.qrc">
  96. <normaloff>:/img/resource/birthday.gif</normaloff>:/img/resource/birthday.gif</iconset>
  97. </property>
  98. <property name="text">
  99. <string>关闭</string>
  100. </property>
  101. </action>
  102. <action name="actionBack">
  103. <property name="icon">
  104. <iconset resource="qrcc.qrc">
  105. <normaloff>:/img/resource/back.png</normaloff>:/img/resource/back.png</iconset>
  106. </property>
  107. <property name="text">
  108. <string>back</string>
  109. </property>
  110. <property name="toolTip">
  111. <string>后退</string>
  112. </property>
  113. </action>
  114. <action name="actionForward">
  115. <property name="icon">
  116. <iconset resource="qrcc.qrc">
  117. <normaloff>:/img/resource/forward.png</normaloff>:/img/resource/forward.png</iconset>
  118. </property>
  119. <property name="text">
  120. <string>forward</string>
  121. </property>
  122. <property name="toolTip">
  123. <string>前进</string>
  124. </property>
  125. </action>
  126. <action name="actionHome">
  127. <property name="icon">
  128. <iconset resource="qrcc.qrc">
  129. <normaloff>:/img/resource/home.png</normaloff>:/img/resource/home.png</iconset>
  130. </property>
  131. <property name="text">
  132. <string>home</string>
  133. </property>
  134. <property name="toolTip">
  135. <string>主页</string>
  136. </property>
  137. </action>
  138. <action name="actionPause">
  139. <property name="icon">
  140. <iconset resource="qrcc.qrc">
  141. <normaloff>:/img/resource/pause.png</normaloff>:/img/resource/pause.png</iconset>
  142. </property>
  143. <property name="text">
  144. <string>pause</string>
  145. </property>
  146. <property name="toolTip">
  147. <string>暂停</string>
  148. </property>
  149. </action>
  150. <action name="actionRefresh">
  151. <property name="icon">
  152. <iconset resource="qrcc.qrc">
  153. <normaloff>:/img/resource/refresh.png</normaloff>:/img/resource/refresh.png</iconset>
  154. </property>
  155. <property name="text">
  156. <string>refresh</string>
  157. </property>
  158. <property name="toolTip">
  159. <string>刷新</string>
  160. </property>
  161. </action>
  162. <action name="actionGo">
  163. <property name="icon">
  164. <iconset resource="qrcc.qrc">
  165. <normaloff>:/img/resource/enter.jpg</normaloff>:/img/resource/enter.jpg</iconset>
  166. </property>
  167. <property name="text">
  168. <string>go</string>
  169. </property>
  170. <property name="toolTip">
  171. <string>确定前往</string>
  172. </property>
  173. </action>
  174. <action name="actionNew_Windows">
  175. <property name="icon">
  176. <iconset resource="qrcc.qrc">
  177. <normaloff>:/img/resource/newwindows.gif</normaloff>:/img/resource/newwindows.gif</iconset>
  178. </property>
  179. <property name="text">
  180. <string>New Windows</string>
  181. </property>
  182. </action>
  183. <action name="actionResoures">
  184. <property name="icon">
  185. <iconset resource="qrcc.qrc">
  186. <normaloff>:/img/resource/cool.gif</normaloff>:/img/resource/cool.gif</iconset>
  187. </property>
  188. <property name="text">
  189. <string>查看源码</string>
  190. </property>
  191. </action>
  192. <action name="actionLLink">
  193. <property name="icon">
  194. <iconset resource="qrcc.qrc">
  195. <normaloff>:/img/resource/cry.gif</normaloff>:/img/resource/cry.gif</iconset>
  196. </property>
  197. <property name="text">
  198. <string>高亮链接</string>
  199. </property>
  200. </action>
  201. <action name="actionAboutUS">
  202. <property name="icon">
  203. <iconset resource="qrcc.qrc">
  204. <normaloff>:/img/resource/eat.gif</normaloff>:/img/resource/eat.gif</iconset>
  205. </property>
  206. <property name="text">
  207. <string>关于我们</string>
  208. </property>
  209. </action>
  210. <action name="actionshot">
  211. <property name="icon">
  212. <iconset resource="qrcc.qrc">
  213. <normaloff>:/img/resource/sex.gif</normaloff>:/img/resource/sex.gif</iconset>
  214. </property>
  215. <property name="text">
  216. <string>截图网页</string>
  217. </property>
  218. </action>
  219. </widget>
  220. <customwidgets>
  221. <customwidget>
  222. <class>QWebView</class>
  223. <extends>QWidget</extends>
  224. <header>QtWebKit/QWebView</header>
  225. </customwidget>
  226. </customwidgets>
  227. <resources>
  228. <include location="qrcc.qrc"/>
  229. </resources>
  230. <connections/>
  231. </ui>

mainbrowser.py

  1. # -*- coding: UTF8 -*-
  2.  
  3. from PyQt4 import QtGui, QtCore, QtWebKit, QtNetwork
  4. from PyQt4.QtCore import QUrl
  5. from mybrowserUI import Ui_MainWindow
  6. import sys, os
  7. import qrcc
  8.  
  9. reload(sys)
  10. sys.setdefaultencoding("utf-8")
  11.  
  12. class MainMyBrowser(QtGui.QMainWindow):
  13. def __init__(self,parent=None):
  14. super(MainMyBrowser,self).__init__(parent)
  15. self.Ui = Ui_MainWindow()
  16. self.Ui.setupUi(self)
  17. self.setWindowTitle('MyBrowser V2.1')
  18. self.statusBar().showMessage('Ready')
  19. self.initLayout()
  20. self.initSimpleEvent()
  21. url = QUrl('http://m.hao123.com')
  22. self.Ui.webView.load(url)
  23.  
  24. # 初始化Layout
  25. def initLayout(self):
  26. self.Ui.actionClose.setStatusTip(u'退出')
  27. '''
  28. 添加地址栏,输入框 lineEdit
  29. '''
  30. self.lblAddress = QtGui.QLabel(u"地址:", self.Ui.toolBar)
  31. self.Ui.toolBar.insertWidget(self.Ui.actionGo, self.lblAddress) #(self, QAction before #控件之前, QWidget widget # 改控件)
  32. self.addressEdit = QtGui.QLineEdit(self.Ui.toolBar)
  33. self.addressEdit.setFixedHeight(30) # lineEdit 框高度
  34. self.addressEdit.setFont(QtGui.QFont('.SansSerif', 19)) # 设置框内字体
  35. self.addressEdit.setStatusTip(u'请输入链接地址')
  36. self.Ui.actionGo.setStatusTip(u'前往链接')
  37. self.Ui.toolBar.insertWidget(self.Ui.actionGo, self.addressEdit)
  38.  
  39. # 初始化效果事件
  40. def initSimpleEvent(self):
  41. self.progress = 0
  42. self.Ui.actionClose.triggered.connect(QtGui.qApp.quit) # 退出
  43. self.addressEdit.returnPressed.connect(self.changeLocation) #地址框回车触发GO效果
  44. self.Ui.webView.loadFinished.connect(self.adjustLocation) # 加载完成改变输入框text()
  45. self.Ui.webView.titleChanged.connect(self.adjustTitle) #标题修改触发
  46. self.Ui.webView.loadProgress.connect(self.setProgress) # 显示加载进度
  47. self.Ui.actionGo.triggered.connect(self.changeLocation)
  48. self.Ui.actionBack.triggered.connect(self.Ui.webView.back) #返回
  49. self.Ui.actionPause.triggered.connect(self.Ui.webView.stop)
  50. self.Ui.actionRefresh.triggered.connect(self.Ui.webView.reload)
  51. self.Ui.actionForward.triggered.connect(self.Ui.webView.forward)
  52. self.Ui.actionHome.triggered.connect(self.GoHome) # 无法获取主页**=> self.Ui.webView.gohome
  53. self.Ui.actionResoures.triggered.connect(self.viewSource) # 查看源码
  54. self.Ui.actionNew_Windows.triggered.connect(self.newindows) # 新打开一个windows_tab
  55. self.Ui.actionLLink.triggered.connect(self.highlightAllLinks) # 高亮
  56. self.Ui.actionAboutUS.triggered.connect(self.aboutus) # 关于我们
  57. self.Ui.actionshot.triggered.connect(self.shot) # 截图
  58. '''
  59. Webkit屏蔽右键菜单
  60. '''
  61. self.Ui.webView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
  62. self.Ui.webView.customContextMenuRequested.connect(self.showContextMenu)
  63. self.Ui.webView.contextMenu = QtGui.QMenu(self)
  64.  
  65. #输入框改变时
  66. def changeLocation(self):
  67. url = QtCore.QUrl.fromUserInput(self.addressEdit.text())
  68. self.Ui.webView.load(url)
  69. self.Ui.webView.setFocus()
  70. # 调整输入框的显示
  71. def adjustLocation(self):
  72. self.addressEdit.setText(self.Ui.webView.url().toString())
  73. #调整windows标题显示
  74. def adjustTitle(self):
  75. if 0 < self.progress < 100:
  76. self.setWindowTitle("%s (%s%%)" % (self.Ui.webView.title(), self.progress))
  77. else:
  78. self.setWindowTitle(self.Ui.webView.title())
  79. #显示加载进度
  80. def setProgress(self, p):
  81. self.progress = p
  82. self.adjustTitle()
  83.  
  84. #模拟首页
  85. def GoHome(self):
  86. self.Ui.webView.load(QUrl('http://www.baidu.com'))
  87. #查看源码
  88. def viewSource(self):
  89. accessManager = self.Ui.webView.page().networkAccessManager()
  90. request = QtNetwork.QNetworkRequest(self.Ui.webView.url())
  91. reply = accessManager.get(request)
  92. reply.finished.connect(self.slotSourceDownloaded)
  93. #查看源码
  94. def slotSourceDownloaded(self):
  95. reply = self.sender()
  96. self.textEdit = QtGui.QTextEdit(None)
  97. self.textEdit.setAttribute(QtCore.Qt.WA_DeleteOnClose)
  98. self.textEdit.show()
  99. self.textEdit.setPlainText(QtCore.QTextStream(reply).readAll())
  100. self.textEdit.resize(600, 400)
  101. reply.deleteLater()
  102.  
  103. #新打开tab
  104. # @QtCore.pyqtSlot()
  105. def newindows(self):
  106. window = MainMyBrowser(self)
  107. window.show()
  108. if self.addressEdit.text().isEmpty():
  109. return;
  110.  
  111. # 高亮
  112. def highlightAllLinks(self):
  113. code = """$('a').each(
  114. function () {
  115. $(this).css('background-color', 'yellow')
  116. }
  117. )"""
  118. self.Ui.webView.page().mainFrame().evaluateJavaScript(code)
  119.  
  120. # 关于我们
  121. def aboutus(self):
  122. QtGui.QMessageBox.about(self, "About WebBrowser",u"Pyqt 浏览器V2.1, power by dcb3688")
  123.  
  124. #截图
  125. def shot(self):
  126. webView = self.Ui.webView
  127. url = QtCore.QUrl.fromUserInput(self.addressEdit.text())
  128. webView.load(QtCore.QUrl(url))
  129. self.webPage = webView.page()
  130. self.connect(webView, QtCore.SIGNAL("loadFinished(bool)"), self.savePage)
  131. # 截图保存图片
  132. def savePage(self,finished):
  133. if finished:
  134. self.statusBar().showMessage(u'开始截图')
  135. size = self.webPage.mainFrame().contentsSize()
  136. self.statusBar().showMessage(u"页面宽:%d,页面高:%d" % (size.width(), size.height()))
  137. self.webPage.setViewportSize(QtCore.QSize(size.width()+16, size.height()))
  138. img = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
  139. painter = QtGui.QPainter(img)
  140. self.webPage.mainFrame().render(painter)
  141. painter.end()
  142. fileName= "shot.png"
  143. if img.save(fileName):
  144. filePath = os.path.join(os.path.dirname(__file__), fileName)
  145. QtGui.QMessageBox.information(self, "About WebBrowser", u'图片保存完成,\n'+'路径:'+filePath);
  146. else:
  147. self.statusBar().showMessage(u'截图失败')
  148. else:
  149. self.statusBar().showMessage(u'网页加载失败')
  150.  
  151. # 显示右键内容
  152. def showContextMenu(self, pos):
  153. self.Ui.webView.contextMenu.move(self.pos() + pos)
  154. self.Ui.webView.contextMenu.show()
  155.  
  156. def keyPressEvent(self, event):
  157. if event.key() ==QtCore.Qt.Key_Escape:
  158. self.close()
  159. if event.key() == QtCore.Qt.Key_F5:
  160. self.changeLocation()
  161.  
  162. class aboutDialog(QtGui.QWidget):
  163. def __init__(self, parent=None):
  164. super(aboutDialog, self).__init__(parent)
  165. self.show()
  166.  
  167. if __name__ == '__main__':
  168. app = QtGui.QApplication(sys.argv)
  169. appshow = MainMyBrowser()
  170. appshow.show()
  171. 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. thinkphp的各种内部函数 D()、F()、S()、C()、L()、A()、I()

    D() 加载Model类 M() 加载Model类 A() 加载Action类 L() 获取语言定义 C() 获取配置值    用法就是   C("这里填写在配置文件里数组的下标" ...

  2. Binary Tree Longest Consecutive Sequence

    Given a binary tree, find the length of the longest consecutive sequence path (连续的路径,不是从小到大). The pa ...

  3. 【leetcode】Wildcard Matching

    Wildcard Matching Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any ...

  4. pl/sql中having的用法

    HAVING的作用: 因为where关键字无法与聚集函数一起使用,HAVING可以和聚集函数一起使用 HAVING的语法: SELECT column_name, aggregate_function ...

  5. ios block 导致的循环引用

    [[NSNotificationCenter defaultCenter] addObserverForName:@"UIWindowDidRotateNotification" ...

  6. linux学习之lvm-逻辑卷管理器

    一.简介 lvm即逻辑卷管理器(logical volume manager),它是linux环境下对磁盘分区进行管理的一种机制.lvm是建立在硬盘和分区之上的一个逻辑层,来提高分区管理的灵活性.它是 ...

  7. c++ template

    在类中其中一个函数使用模板,函数定义和实现必须放在头文件里. ca.h template<typename T> void swap2(T &a,T &b) { T c=a ...

  8. XE 的程序升级 XE5 问题处理记录

    XE 的程序升级 XE5 问题处理记录 1.  [dcc32 Fatal Error] frxClass.pas(3556): F1026 File not found: 'xxxxx\Registr ...

  9. 7.js模式-装饰者模式

    1. 装饰者模式 给对象动态增加职责的方式称为装饰者模式. Function.prototype.before = function(beforefn){ var _self = this; retu ...

  10. 6.js模式-中介者模式

    1. 中介者模式 所有对象通过中介者进行通信 var playDirector = (function(){ var players = []; var options = {}; options.a ...