Rimas
Rimas

Reputation: 6024

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.

Upvotes: 3

Views: 3155

Answers (3)

Rimas
Rimas

Reputation: 6024

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

Upvotes: 7

aatwo
aatwo

Reputation: 1008

Thanks to all the others who provided answers for this. After encountering this bug I was somewhat stumped, but after learning of the way setEnabled(false) affects the focus stealing from the other answers I discovered that simply disabling the webview, setting the html or reloading it, then re-enabling it circumvents the issue (at least in Qt 5.7):

I.E.

myWebView->setEnabled( false );
myWebView->setHtml( html );
myWebView->setEnabled( true );

or

myWebView->setEnabled( false );
myWebView->reload();
myWebView->setEnabled( true );

This allows you to fix the problem without needing to subclass anything as one of the other answers suggests.

Upvotes: 1

Netrix
Netrix

Reputation: 342

I encountered the same problem in my app in PyQt5. What I managed to do is to disable the whole widget like this (in Python):

view = PyQt5.QtWebEngineWidgets.QWebEngineView()
view.setEnabled(False)

This resulted in view being operational with mouse (it accepts mouse clicks and things can be changed on web page) but i won't take focus from different widget.

I would definitely call it a bug instead of feature in QtWebEngineWidgets.

Upvotes: 2

Related Questions