我正在开发一个小型应用程序。我想修改WebKit Webview的默认上下文菜单。具体来说,我想
我正在寻找解决方案
有效方法:
什么不起作用:
代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from gi.repository import Gtk, WebKit
class MyWindow(Gtk.Window):
def __init__(self, *args):
Gtk.Window.__init__(self, title="test")
self.wv = WebKit.WebView()
self.add(self.wv)
# add item
def append_item(webview, context_menu, hit_result_event, event):
option = Gtk.ImageMenuItem('Extra')
context_menu.append(option)
option.show()
# select case, change this to "1", "2" etc.
x = 0
# block/hide context menu
if x == 1:
settings = self.wv.get_settings()
settings.set_property('enable-default-context-menu', False)
# add item
elif x == 2:
self.wv.connect('context-menu', append_item)
# remove item
# ???
# remove all items
# ???
win = MyWindow()
win.show_all()
Gtk.main()
有效方法:
什么不起作用:
代码:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk, Gdk, WebKit2
class MyWindow(Gtk.Window):
def __init__(self, *args):
Gtk.Window.__init__(self, title="test")
self.wv = WebKit2.WebView()
self.add(self.wv)
# block/hide context menu
def context_menu_block(self, event, case):
# right-click
if case == "button":
if event.button == 3:
return True
# keyboard
elif case == "key":
state = event.state
shift = (state & Gdk.ModifierType.SHIFT_MASK)
# menu key
if event.keyval == 65383:
return True
# shift & F10
elif shift and event.keyval == 65479:
return True
# add item
def append_item(webview, context_menu, hit_result_event, event):
action = Gtk.Action("FileNewStandard", "_New", "Create a new file", Gtk.STOCK_NEW)
option = WebKit2.ContextMenuItem().new(action)
context_menu.append(option)
# remove all items
def remove_all_items(webview, context_menu, hit_result_event, event):
context_menu.remove_all()
# select case, change this to "1", "2" etc.
x = 0
# block/hide context menu
if x == 1:
self.wv.connect('button-press-event', context_menu_block, "button")
self.wv.connect('key-press-event', context_menu_block, "key")
# add item
elif x == 2:
self.wv.connect('context-menu', append_item)
# remove item
# ???
# remove all items
elif x == 3:
self.wv.connect('context-menu', remove_all_items)
win = MyWindow()
win.show_all()
Gtk.main()