Qt/PyQt : How do I act on QWebView/QWebPage's "Open in New Window" action?

标签 qt pyqt pyqt4 qwebkit qwebpage

如果我有一个打开的 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。

最佳答案

您需要自己调用QWebViewcreateWindow 方法,例如重新实现QWebPage 的triggerAction ,像这样:

#!/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/

相关文章:

c++ - 将绑定(bind)到 FBO 的纹理复制到另一个 OpenGL 上下文

python - PySide:QWebView的Mouse move和Mouse press事件卡住html文档

python - easy_install 在 Windows 7 中不起作用

python-3.x - 将 pyqtgraph(绘图)添加到 QApplication

c++ - 如何自动链接到共享库的依赖项

Qt Translation 返回相同的字符串而不是翻译

linux - 在 Linux 中以编程方式请求提升权限

python - pyqt中的异步模式?或者更干净的后台调用模式?

python - 我应该如何在 PyQt5 的表格小部件中连接 CheckBox clicked 信号?

python - matplotlib 和 Qt : mouse scroll event key is always None