QML WebEngineView简单用法和常用接口

前言

WebEngineView用于在 QML 界面中加载一个网页,该组件和QWebEngineView类对应,接口都是一样的,只是一个在 QML 中使用,一个是在 C++中使用,这里只根据在平常的使用中总结的简单的WebEngineView用法。

正文

简单用法

WebEngineView的使用非常简单,这里摘一段 Qt 帮助文档中的示例:

  import QtQuick 2.0
  import QtQuick.Window 2.0
  import QtWebEngine 1.0

  Window {
      width: 1024
      height: 750
      visible: true
      WebEngineView {
          id:webview
          anchors.fill: parent
          url: "http://www.www.baidu.com"
      }
  }

如上示例,只需要指定 url,即可自动加载网,但是如果仅仅就写成这样,会出现一个问题,就是只能加载当前这个网页,如果在网页里面还想再次点击其他链接,这样是不会相应的,那么该怎么实现这个功能呢,加上以下这句:

onNewViewRequested: request.openIn(webview)

这里的newViewRequested是一个信号,来看一下 Qt 帮助文档中对这个信号的介绍:
This signal is emitted when a page load is requested to happen in a separate web engine view. This can either be because the current page requested it explicitly through a JavaScript call to window.open, or because the user clicked on a link while holding Shift, Ctrl, or a built-in combination that triggers the page to open in a new window.

帮助文档写的很清楚,这里就不过多介绍了,实现方式就是绑定过该信号,然后加上一句:request.openIn(webview)

网页中的视频不能加载

通过以上方式加载网页后,如果网页中包含视频或音频之类的元素,是不能正常播放的,这是因为没有默认运行插件,如 flash player,设置方法如下:

webview.settings.pluginsEnabled:true

官网介绍如下:
*Enables support for Pepper plugins, such as the Flash player.
Disabled by default.*
除了以上设置,WebEngineSettings中还有很多其他属性可以设置,具体查看帮助文档。

缓存路径,清除缓存

加载网页会有缓存产生,那么缓存的路径如下:

webview.profile.cachePath

清理缓存

webview.profile.clearHttpCache()

注意,清理缓存的接口在QtWebEngine 1.3中才有。
还有一个接口有必要说一下,重新加载网页内容可以用 reload()函数,有一个和它类似的接口叫

reloadAndBypassCache()

官网的介绍如下:
*Reloads the current page, ignoring any cached content.
This QML method was introduced in QtWebEngine 1.1.*
这个接口的作用就是跳过缓存然后重新加载网页,如果网页有改动,又不想去清除缓存,那么可以通过该接口来重新加载网页。

OK,以上是最近在项目中遇到的关于 QML 加载网页相关的问题,做个简单的记录。

猜你喜欢

转载自blog.csdn.net/luoyayun361/article/details/78702906
QML