Reputation: 579
I have a simple widget that is a QWebView. I load it with setHtml(). Most of the time this is just so the user can read the styled text, however there are a few links, and if one is clicked, the QWebView properly displays the linked page, but now there is no way to get back to the original page. I want to implement a Back key shortcut (or maybe a Back button, but the problem is the same). And I can't figure out how to tell my QWebView or its QWebPage to do that. Some code trying everything I could think of:
class helpDisplay(QWebView):
def __init__(self, parent=None ):
super(helpDisplay, self).__init__(parent)
self.backAction = self.page().action(QWebPage.Back)
self.backAction.setEnabled(True) # initially was False
self.backAction.setShortcut(QKeySequence.Back) # was empty, now ctl-[
...
self.setHtml(...) # big string input from a file
...
def keyPressEvent(self, event): # trap keys
if event.key() == Qt.Key_B: # temporary for testing
self.page().triggerAction(QWebPage.Back)
self.backAction.activate(QAction.Trigger)
None of this causes navigation backward from a link. Hitting ctl-[ does nothing. Hitting "b" enters the keyPressEvent trap and calls triggerAction and activate, but nothing visible happens.
Edit: found WebPage.history(), and added the following to the key-b trap:
self.page().history().back()
This kinda works: if I click a link start->A, self.page().history().canGoBack()
is False and self.page().history().back()
does nothing. However if I click another link start->A->B, now it canGoBack() and does, back to page A. But I can't go back to the original page loaded with setHtml().
Conclusion: WebView.setHtml() does not create an entry in WebPage.history. This could explain why backAction doesn't seem to work...
Further edit: Following up in the Qt Assistant I find that under QWebFrame.setHtml() it admits, "Note: This method will not affect session or global history..." Unfortunately they didn't carry that note back to QWebPage or QWebView. In fact it makes sense: a history item would normally be just a URL, so it isn't too odd they wouldn't want to store 20K or 50K of html text as a history item.
Upvotes: 4
Views: 3277
Reputation: 92569
Just to reduce some of your code, QWebView does have a back() slot: http://doc.qt.io/archives/qt-4.7/qwebview.html#back.
That aside, since you have discovered that the use of setHtml() apparently doesn't create a history entry, you could try one of these suggestions:
Use your history check to see if it can go back. If it can, go back. If it can't run setHtml again with your original source since you know it was the first page displayed.
Or, write your pages out to a temp html file and use the load() method instead for a file:/// url. That might make a history entry.
Upvotes: 1