qwebpage中在新窗口打开连接失败

#coding=utf-8

__author__ = 'Administrator'

from PyQt5.QtWebKit import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebKitWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtNetwork import *
import sys

class Page(QWebPage):
    def __init__(self, parent = None):
        super(Page, self).__init__(parent)
        self._newPages = []

    #(虚函数)对于QWebPage的导航行为的处理,根据类型可以来处理导航行为
    def acceptNavigationRequest(self, QWebFrame, QNetworkRequest, QWebPage_NavigationType):
        if not QWebFrame:
            print('new frame is required')
            return True
        print('navtype=%d request=%s' % (QWebPage_NavigationType, QNetworkRequest.url()))
        return super(Page, self).acceptNavigationRequest(QWebFrame, QNetworkRequest, QWebPage_NavigationType)

    #(虚函数)对于点击一个链接,没有反应的原因是没有处理该链接所要触发并打开的窗口
    def createWindow(self, QWebPage_WebWindowType):
        p = Page()
        mv = QWebView()
        mv.setPage(p)
        mv.show()
        self._newPages.append((mv,p))
        return p

class PageReceiver(QObject):
    def __init__(self, parent = None):
        super(PageReceiver, self).__init__(parent)

    def showDialog(self):
        o = self.sender()
        o.dumpObjectInfo()
        print('openlink triggered')

def setAppProxy():
    proxy = QNetworkProxy()
    #Http访问代理
    proxy.setType(QNetworkProxy.HttpProxy)
    #proxy.setType(QtNetwork.QNetworkProxy.DefaultProxy)
    proxy.setHostName(u'proxy3.bj.petrochina')
    proxy.setPort(8080)
    QNetworkProxy.setApplicationProxy(proxy)

app = QApplication(sys.argv)
#setAppProxy()
#使用系统的设置,如果有代理,则自动使用代理
QNetworkProxyFactory.setUseSystemConfiguration(True)
wv = QWebView()
wv.setPage(Page())

'''
setting = wv.settings()
setting.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
setting.setAttribute(QWebSettings.JavascriptCanCloseWindows, True)
setting.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)
setting.setAttribute(QWebSettings.SpatialNavigationEnabled, True)
'''
wv.page().action(QWebPage.OpenLinkInNewWindow).setEnabled(True)
wv.page().action(QWebPage.OpenLink).setEnabled(True)
pr = PageReceiver()
#设置链接的代理默认,对所有的链接都处理,不设置则图片链接点击不起作用
wv.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
#wv.page().triggerAction(QWebPage.OpenLink).setEnabled(True)
#设置链接的处理方式,可以自定制例如处理本地的链接,不设置点击图片链接不起作用
#wv.linkClicked.connect(wv.load)
wv.page().linkClicked.connect(wv.load)
wv.page().action(QWebPage.OpenLink).triggered.connect(pr.showDialog)
#wv.page().setContentEditable(True)
wv.show()
wv.load(QUrl('https://www.baidu.com/'))
app.exec_()

你可能感兴趣的:(python,qt,PyQt,QtWebkit)