Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the non-deprecated way to display a stock icon in GTK3?

I'm assembling a GUI using PyGObject. This Python code works in context. I get a toolbar button with the stock "Open" icon.

from gi.repository import Gtk

# ...

toolbar = Gtk.Toolbar()
toolbar.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR)

# ...

self.fileOpen = Gtk.ToolButton.new_from_stock(Gtk.STOCK_OPEN)
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)

Image shows icon appearing on the toolbar.

But according to this resource, new_from_stock() is deprecated:

Deprecated since version 3.10: Use Gtk.ToolButton.new () together with Gtk.Image.new_from_icon_name () instead.

Okay then. So after digging further, this is what I came up with for a replacement:

self.fileOpen = Gtk.ToolButton(
        Gtk.Image.new_from_icon_name("document-open",
                                     Gtk.IconSize.LARGE_TOOLBAR),
        "Open")
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)

But this is the result:

Image shows icon not appearing on the toolbar.

What is the correct way to do this that is still supported by the current GTK library?

like image 544
aaaantoine Avatar asked Nov 22 '15 19:11

aaaantoine


1 Answers

Looking at this C++ GitHub example, I'm surprised to discover a direct call to the static new() function rather than the constructor.

So I decided to try it. Look carefully at the difference. It's subtle.

                              #vvv
self.fileOpen = Gtk.ToolButton.new(
        Gtk.Image.new_from_icon_name("document-open",
                                     Gtk.IconSize.LARGE_TOOLBAR),
        "Open")
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)

To my surprise, this displays the icon where the other approach does not.

Bonus: Cleaner version of the above:

# iconSize to be reused
iconSize = Gtk.IconSize.LARGE_TOOLBAR

# ...

openIcon = Gtk.Image.new_from_icon_name("document-open", iconSize)
self.fileOpen = Gtk.ToolButton.new(openIcon, "Open")
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)
like image 169
aaaantoine Avatar answered Nov 07 '22 07:11

aaaantoine