Search code examples
qtfocusqtwebengine

How to prevent QWebEngineView to grab focus on setHtml(...) and load(...) calls?


I have created simple Qt Window Layout with QTreeView and QWebEngineView: after selecting some item in the tree view, the Web engine view shows some content. The problem is what when QWebEngineView::setHtml(...) or load(...) is called the tree view loses keyboard focus and Web engine view gets it. This causes difficulties when selecting items with keyboard in the tree view. So, how to prevent the tree view focus lost?

I tried to use QTextBrowser instead of QWebEngineView. It doesn't have this problem, but it is not suitable for complex HTML pages.


Solution

  • Suppose we have:

    QWebEngineView *webView = new QWebEngineView;
    

    For Qt 5.8 and newer

    The problem can be solved by tweaking settings:

    webView->settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, false);
    

    The sample code: https://github.com/rmisev/FocusWidget/tree/if-qt-5.8

    References:

    For Qt 5.7 and earlier

    The simplest solution (also pointed by @Netrix) is to call:

    webView->setEnabled(false);
    

    But this disables keyboard input to the webView.

    To solve this problem I created the simple FocusWidget class as parent widget for webView, which works as follows:

    1. Initially it disables webView (webView->setEnabled(false)), so prevents to take focus on load(...), setHtml(...) calls.
    2. When FocusWidget gets focus, it enables and forwards focus to webView, so enables keyboard input.
    3. When webView and its children loses focus, FocusWidget disables webView again

    The source code and sample application: https://github.com/rmisev/FocusWidget