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

1

9

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?

Unrivaled answered 22/11, 2015 at 19:59 Comment(0)
U
6

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)
Unrivaled answered 23/11, 2015 at 2:0 Comment(1)
The explanation for what you found: in the PyGObject bindings, objects' constructors only take keyword args representing the object's GObject properties. On the other hand, C constructors, which often have extra convenience parameters to set properties since properties can be cumbersome in C, are bound as static new() methods.This should work equally well: Gtk.ToolButton(icon_widget=openIcon, label="Open")Barman

© 2022 - 2024 — McMap. All rights reserved.