How to filter out «back» events in a [Qt] web view?

361 views Asked by At

I develop an application with WebKit-based forms and it’s important that, when on a form, a user can press Backspace without returning to previous page. How do I do this in QtWebKit?

I found out that one can inherit a class from QWebPage and overload QWebPage::triggerAction() to selectively filter out events, e.g. QWebPage::Back. Nevertheless, it works only on the first page, and if you open another page in the same webview child the triggerAction() overload will not be called.

2

There are 2 answers

0
Andrey Rogozhnikov On BEST ANSWER

For now, answer is «there is no simple way to do it». I've got and answer on Qt's bug tracker, see https://bugreports.qt-project.org/browse/QTBUG-35555

Hope this will be fixed.

0
Korvo On

You could try one of these alternatives:

1. eventFilter:

bool CWebView:eventFilter( QObject *pObj, QEvent *event )
{
 QKeyEvent* pkeyEvent = (QKeyEvent*)event;

 if (Qt::ControlModifier == pKeyEvent->state())
 {
  switch (pKeyEvent->key())
  {
   case Qt::Key_Backspace:
     //something (eg. return false)
   break;
  }
 }
 return true;
}

2. clear history:

#include <QWebHistory>

...

QWebView* CWebView;
...
CWebView->history()->clear();

3. Javascript (I consider the best alternative):

window.location.replace(url);

after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

source: https://stackoverflow.com/a/8969975/1518921