'''
pyqt5 简单浏览器 by 郑瑞国
'''
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow,QToolBar,QAction,QLineEdit,QTabWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QUrl,QSize
from PyQt5.QtWebEngineWidgets import QWebEngineView
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initUI()
def initUI(self):
self.setWindowTitle('My Browser')
self.setWindowIcon(QIcon('icons/penguin.png'))
self.resize(900,600)
self.showMaximized()
# 添加标签栏
#self.tabs = QTabWidget()
#self.add_new_tab(QUrl('http://www.baidu.com'), 'Homepage')
#self.setCentralWidget(self.tabs)
self.browser = WebEngineView()
self.browser.load(QUrl("https://www.bing.com"))
self.setCentralWidget(self.browser)
# 添加导航栏
navigation_bar = QToolBar('Navigation')
navigation_bar.setIconSize(QSize(16, 16))
self.addToolBar(navigation_bar)
# 添加前进、后退、停止加载和刷新的按钮
back_button = QAction(QIcon('icons/back.png'), 'Back', self)
next_button = QAction(QIcon('icons/next.png'), 'Forward', self)
stop_button = QAction(QIcon('icons/cross.png'), 'stop', self)
reload_button = QAction(QIcon('icons/renew.png'), 'reload', self)
back_button.triggered.connect(self.browser.back)
next_button.triggered.connect(self.browser.forward)
stop_button.triggered.connect(self.browser.stop)
reload_button.triggered.connect(self.browser.reload)
# 将按钮添加到导航栏上
navigation_bar.addAction(back_button)
navigation_bar.addAction(next_button)
navigation_bar.addAction(stop_button)
navigation_bar.addAction(reload_button)
#添加URL地址栏
self.urlbar = QLineEdit()
# 让地址栏能响应回车按键信号
self.urlbar.returnPressed.connect(self.navigate_to_url)
navigation_bar.addSeparator()
navigation_bar.addWidget(self.urlbar)
#让浏览器相应url地址的变化
self.browser.urlChanged.connect(self.renew_urlbar)
def navigate_to_url(self):
q = QUrl(self.urlbar.text())
if q.scheme() == '':
q.setScheme('http')
self.browser.setUrl(q)
def renew_urlbar(self, q):
# 将当前网页的链接更新到地址栏
self.urlbar.setText(q.toString())
self.urlbar.setCursorPosition(0)
def add_new_tab(self, qurl, label):
# 为标签创建新网页
browser = QWebEngineView()
browser.setUrl(qurl)
self.tabs.addTab(browser, label)
browser.urlChanged.connect(lambda qurl, browser=browser: self.renew_urlbar(qurl, browser))
class WebEngineView(QWebEngineView):
windowList = []
def createWindow(self, QWebEnginePage_WebWindowType):
new_webview = WebEngineView()
new_window = MainWindow()
new_window.setCentralWidget(new_webview)
self.windowList.append(new_window)
return new_webview
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())