2013-04-08 91 views
1

好吧,我想出了一個辦法。如果你有另一種方式,你仍然可以給你答案。你可能有一個更簡單的方法。在此期間,我將嘗試格式化答覆。我發現的方法有點混亂,所以我必須花時間。現在我會讓我的答案不被接受,看看別人是否有更好的方法。如何將菜單添加到工具欄? gtk3

我正在使用python與gtk3。

對於gtk3,有一個menutoolbutton,但它在文檔中的用法描述對我來說還不夠清楚。

除此之外,我還想要一個普通的按鈕,沒有用於此的工具按鈕的下拉箭頭。

如果有辦法用gtk uimanager做到這一點,我寧願這樣做。

回答

0

這是我的答案。

這是有點採取漫長的道路,但它的作品。

其中一個主要問題是我認爲我可以在網格中使用最近的按鈕,但gtk似乎只有最近的工具欄和菜單操作。所以如果我還想要另一個工具欄按鈕帶有彈出式菜單,這會變得複雜,因爲工具欄按鈕不易定製,因此沒有放置箭頭。

長話短說。我用常規的彈出式按鈕進行了很長一段路,並製作了一個網格來包含它和工具欄。

#the popup you see here will get used for the menu button 
TOOLBAR_UI = """ 
<ui> 
    <toolbar name="ToolBar"> 
     <toolitem action="FileOpen" /> 
     <toolitem action="FileSave" /> 
     <toolitem action="FileSaveAs" /> 
     <toolitem action="Undo" /> 
     <toolitem action="Redo" /> 
    </toolbar> 
    <popup name="Menu"> 
     <menuitem action="Bla" /> 
    </popup> 
</ui> 
""" 
class GroupView(Gtk.Grid): 

    def __init__(self): 
     Gtk.Grid.__init__(self, orientation=Gtk.Orientation.HORIZONTAL) 
     #the toolbar grid is placed in another grid to be 
     #placed in a gtk.window 
     group_toolbar = Toolbar() 
     self.add(group_toolbar) 


class Toolbar(Gtk.Grid): 
    def __init__(self): 
     Gtk.Grid.__init__(self, orientation=Gtk.Orientation.HORIZONTAL) 
     toolbar = Tools() 
     #toolbar is actually a grid with an actual toolbar 
     #and the menu button is in the grid 
     self.add(toolbar.display()) 
     self.add(toolbar.extra_menu) 

class Tools(Gtk.UIManager): 
    text_view = None 
    def __init__(self): 
     Gtk.UIManager.__init__(self) 
     self.add_ui_from_string(TOOLBAR_UI) 
     action_group = Gtk.ActionGroup("actions") 
     self.add_toolbar_actions(action_group) 

    def set_text_view(self, textview): 
     self.textview = textview 

    def add_toolbar_actions(self, action_group): 
     self.insert_action_group(action_group) 
     # 
     #..normal toolbar construction here 
     # 

     #its a menu button so only the menu actions 
     #need to be taken care of 
     action_bla = Gtk.Action("Bla", 'bla', None, None) 
     action_bla.connect("activate", self.action_bla_clicked) 
     action_group.add_action(action_bla) 
     #..the menu button is created here 
     self.extra_menu = ExtraMenu() 
     self.extra_menu.set_popup(self.get_widget("/Menu")) 

     #start action callbacks 
     #...placeholder for callbacks 
     #end action callbacks 
    #get ready to export the toolbar 
    def display(self): 
     toolbar = self.get_widget("/ToolBar") 
     toolbar.set_hexpand(True) 
     return toolbar 

class ExtraMenu(Gtk.MenuButton): 
    def __init__(self): 
     Gtk.MenuButton.__init__(self) 
     arrow = self.get_children()[0] 
     #the arrow is destroyed and a custom image is placed in the button 
     arrow.destroy() 
     self.add(Gtk.Image.new_from_stock(Gtk.STOCK_EXECUTE, Gtk.IconSize.BUTTON)) 

如果你嘗試上面的代碼,不要忘記添加一個窗口和一些動作回調。 如果你不能說我喜歡子類gtk很多。 :)