如果我有一个打开的 QWebView,我喜欢它的默认上下文菜单,其中包含“在新窗口中打开”作为链接选项。但是,当用户请求在新窗口中打开链接时,我似乎找不到采取行动的方法。覆盖 QWebPage.createWindow 方法似乎不起作用,因为当用户选择在新窗口中打开链接时不会调用该方法。

有什么建议吗?我正在使用 PyQt。

示例代码:

class LocalWebPage(QWebPage):
    def acceptNavigationRequest(self, webFrame, networkRequest, navigationType):
        print '*acceptNavigationRequest**',webFrame, networkRequest, navigationType
        return QWebPage.acceptNavigationRequest(self, webFrame, networkRequest, navigationType)

    def createWindow(self, windowType):
        print '--createWindow', windowType
        return QWebPage.createWindow(self, windowType)


class Browser(Ui_MainWindow, QMainWindow):
    def __init__(self, base, name):

        ...
        self.page = LocalWebPage()
        self.webViewMain = QWebView(self.centralwidget)
        self.webViewMain.setPage(self.page)
        ...

我在那里有调试打印来验证 createWindow 没有被调用。

最佳答案

您需要自己调用 createWindowQWebView 方法,例如通过重新实现 triggerActionQWebPage ,如下所示:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtGui, QtCore, QtWebKit

class MyPage(QtWebKit.QWebPage):
    def __init__(self, parent=None):
        super(MyPage, self).__init__(parent)

    def triggerAction(self, action, checked=False):
        if action == QtWebKit.QWebPage.OpenLinkInNewWindow:
            self.createWindow(QtWebKit.QWebPage.WebBrowserWindow)

        return super(MyPage, self).triggerAction(action, checked)


class MyWindow(QtWebKit.QWebView):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.myPage = MyPage(self)

        self.setPage(self.myPage)

    def createWindow(self, windowType):
        if windowType == QtWebKit.QWebPage.WebBrowserWindow:
            self.webView = MyWindow()
            self.webView.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)

            return self.webView

        return super(MyWindow, self).createWindow(windowType)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()
    main.load(QtCore.QUrl("http://www.example.com"))

    sys.exit(app.exec_())

关于Qt/PyQt : How do I act on QWebView/QWebPage's "Open in New Window" action?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14804326/

10-13 07:00