我正在使用Gtk (python3) + Glade创建一个应用程序。我在林中设置了一些加速器,比如:
<child>
<object class="GtkImageMenuItem" id="imagemenuitem5">
<property name="label">gtk-quit</property>
<accelerator key="q" signal="activate" modifiers="GDK_CONTROL_MASK"/>
</object>
</child>但是,在应用程序运行时,我不知道如何将这个事件的加速器更改为其他东西。有可能吗?我的实现对我的计划是错误的吗?
发布于 2015-10-13 05:57:42
<accelerator>元素在内部使用gtk_widget_add_accelerator()。根据这一职能的文件:
通过此函数添加的加速器在运行时不允许用户更改。如果您想支持用户可以更改的加速器,请使用
gtk_accel_map_add_entry()和gtk_widget_set_accel_path()或gtk_menu_item_set_accel_path()。
事实上,还有一种更现代的方法可以做到这一点:使用GAction、GApplication和GMenuModel,根本不创建任何菜单栏。下面是在运行时更改菜单项加速器的示例:
from gi.repository import Gio, Gtk
class App(Gtk.Application):
def __init__(self, **props):
super(App, self).__init__(application_id='org.gnome.example',
flags=Gio.ApplicationFlags.FLAGS_NONE, **props)
# Activating the LEP GEX VEN ZEA menu item will rotate through these
# accelerator keys
self.keys = ['L', 'G', 'V', 'Z']
def do_activate(self):
Gtk.Application.do_activate(self)
actions = self.create_actions()
self.add_action(actions['quit'])
self.win = Gtk.ApplicationWindow()
self.add_window(self.win)
self.win.add_action(actions['lep'])
self.set_accels_for_action('win.lep', ['<primary>' + self.keys[0]])
# Ctrl-Q is automatically assigned to an app action named quit
model = self.create_menus()
self.set_menubar(model)
actions['lep'].connect('activate', self.on_lep_activate)
actions['quit'].connect('activate', lambda *args: self.win.destroy())
self.win.show_all()
def create_actions(self):
return {name: Gio.SimpleAction(name=name) for name in ['lep', 'quit']}
def create_menus(self):
file_menu = Gio.Menu()
file_menu.append('LEP GEX VEN ZEA', 'win.lep')
file_menu.append('Quit', 'app.quit')
menu = Gio.Menu()
menu.append_submenu('File', file_menu)
return menu
def on_lep_activate(self, *args):
self.keys = self.keys[1:] + self.keys[:1]
self.set_accels_for_action('win.lep', ['<primary>' + self.keys[0]])
if __name__ == '__main__':
App().run([])您还可以通过创建一个menus.ui文件并在特定的GResource路径上将其提供给您的应用程序,使用Glade文件并自动将其连接起来:这是这里描述的。
https://stackoverflow.com/questions/32713207
复制相似问题