WebKitGTK(Python)实现链接悬停显示URL或获取悬停事件方法
解决WebKitGTK Python绑定中悬停链接显示URL及获取悬停事件的问题
你的基础代码:
import gi gi.require_version("Gtk","3.0") gi.require_version("WebKit2","4.0") from gi.repository import Gtk, WebKit2 webv = WebKit2.WebView() window = Gtk.Window() window.add(webv) window.show_all() Gtk.main()
a) 悬停链接时在状态栏显示目标URL
WebKit2.WebView内置hovered-link属性,鼠标悬停链接时该属性会更新为目标URL,离开时自动清空。通过监听notify::hovered-link信号,就能实现状态栏显示功能:
- 用Gtk.Box布局WebView和状态栏(Gtk.Window默认只能容纳一个控件)
- 连接信号并更新状态栏文本
修改后的代码示例:
import gi gi.require_version("Gtk","3.0") gi.require_version("WebKit2","4.0") from gi.repository import Gtk, WebKit2 def on_hovered_link_changed(webview, param_spec, statusbar): hovered_url = webview.get_hovered_link() context_id = statusbar.get_context_id("link-hover") statusbar.remove_all(context_id) if hovered_url: statusbar.push(context_id, hovered_url) # 创建窗口与布局容器 window = Gtk.Window(title="Simple Browser") window.set_default_size(800, 600) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0) window.add(box) # 创建核心控件 webv = WebKit2.WebView() statusbar = Gtk.Statusbar() webv.load_uri("https://example.com") # 绑定信号 webv.connect("notify::hovered-link", on_hovered_link_changed, statusbar) # 组装布局 box.pack_start(webv, expand=True, fill=True, padding=0) box.pack_end(statusbar, expand=False, fill=True, padding=0) window.connect("destroy", Gtk.main_quit) window.show_all() Gtk.main()
该方案利用WebKit原生属性实现,无需手动处理DOM事件,是最简洁的实现方式。
b) 获取链接的鼠标悬停事件
如果需要更精细的控制(比如执行自定义逻辑),可以通过两种方式实现:
方式1:利用notify::hovered-link信号判断状态
notify::hovered-link信号本身就是悬停事件的通知:当hovered_url从None变为有效URL时,代表鼠标悬停到链接;从URL变回None时,代表鼠标离开链接。你可以在信号处理函数中添加自定义逻辑:
def on_hovered_link_changed(webview, param_spec, statusbar): hovered_url = webview.get_hovered_link() if hovered_url: print(f"鼠标悬停到链接:{hovered_url}") # 此处添加自定义业务逻辑 else: print("鼠标离开链接")
方式2:实时跟踪鼠标位置获取元素信息
如果需要实时监听鼠标移动,可使用Gtk.EventControllerMotion监听鼠标位置,再通过WebKit2.WebView.get_hit_test_result()获取鼠标下的元素详情:
def on_mouse_motion(controller, x, y, webview, statusbar): hit_result = webview.get_hit_test_result(x, y) if hit_result and hit_result.context_is_link(): link_url = hit_result.get_link_uri() context_id = statusbar.get_context_id("link-hover") statusbar.remove_all(context_id) statusbar.push(context_id, link_url) print(f"实时跟踪到链接:{link_url}") else: context_id = statusbar.get_context_id("link-hover") statusbar.remove_all(context_id) # 给WebView添加鼠标移动控制器 motion_controller = Gtk.EventControllerMotion.new() motion_controller.connect("motion", on_mouse_motion, webv, statusbar) webv.add_controller(motion_controller)
这种方式不仅能跟踪链接,还能判断鼠标下是否为图片、视频等元素,适合复杂交互场景。
内容的提问来源于stack exchange,提问作者Zh.
相关产品推荐
相关产品推荐

