问题
I have a code that suppose to open/create new window if the link is target _blank but, it doesn't do as intended and gives no action in return.
Here is the code:
class MyPage(QWebEnginePage):
def __init__(self, parent=None):
super(MyPage, self).__init__(parent)
def triggerAction(self, action, checked=False):
if action == QWebEnginePage.OpenLinkInNewWindow:
self.createWindow(QWebEnginePage.WebBrowserWindow)
return super(MyPage, self).triggerAction(action, checked)
class MyWindow(QtWebEngineWidgets.QWebEngineView):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.myPage = MyPage(self)
self.setPage(self.myPage)
def createWindow(self, windowType):
if windowType == QWebEnginePage.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 = QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
main.load(QUrl("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_a_target"))
sys.exit(app.exec_())
Would like to know why it's not working, if possible.
Thanks, Max
回答1:
If you directly test the link in any browser you will see that the action is to create a new tab, so windowType
is for that case the type QWebEnginePage::WebBrowserTab
, at that time we create the new window and show it as shown below:
class MyWindow(QWebEngineView):
[...]
def createWindow(self, windowType):
if windowType == QWebEnginePage.WebBrowserTab:
self.webView = MyWindow()
self.webView.setAttribute(Qt.WA_DeleteOnClose, True)
self.webView.show()
return self.webView
return super(MyWindow, self).createWindow(windowType)
来源:https://stackoverflow.com/questions/47897467/qwebengine-open-createwindow-if-target-blank