How to dynamically add/remove widgets from Gtk 3 Window
Asked Answered
R

1

5

I am using python3 with Gtk3 and i need to basically remove some widgets from my Gtk.Window and replace them with other widgets when a Gtk.Button is clicked.I have tried using Gtk.ListBoxes with Gtk.ListBoxRows and so far i can remove all the Rows from the ListBox but when i try to add them back,essentially nothing happens.This is part of my code:

def left_view(self, box):
    listbox = box

    row0 = Gtk.ListBoxRow()
    row0.set_halign(Gtk.Align.START)
    listbox.add(row0)
    #Adding HorizontalBox to place widgets
    hbox = Gtk.Box(spacing=10,orientation=Gtk.Orientation.HORIZONTAL)
    row0.add(hbox)
    prod_name = Gtk.Label()
    stock_count = Gtk.Label()
    prod_name.set_text('Product Name')
    stock_count.set_text('Stock   ')
    self.prod_name_input = Gtk.Entry()
    self.stock_count_input = Gtk.Entry()

    #Packaging 101
    hbox.pack_start(prod_name, True, True, 0)
    hbox.pack_start(self.prod_name_input, True, True, 0)
    hbox.pack_start(stock_count, True, True, 0)
    hbox.pack_start(self.stock_count_input, True, True, 0)

the function will be given a Gtk.ListBox as the argument.And what i have so far when trying to remove() and add() things to the listbox is:

def remover(self,widget):
        vbox = widget.get_parent()
        base = vbox.get_parent()
        children = base.get_children()
        listbox = children[1]
        for row in listbox.get_children():
            listbox.remove(row)
        with open('product_info.json', 'r') as d:
            data = d.read()
            j = json.loads(data)
            d.close()
        self.keys = list(j.keys())
        row0 = Gtk.ListBoxRow()
        listbox.add_child(row0)
        scrollwindow = Gtk.ScrolledWindow()
        scrollwindow.set_hexpand(True)
        scrollwindow.set_vexpand(True)
        row0.add_child(scrollwindow)
        tview = Gtk.TextView()
        scrollwindow.add(tview)
        textbuffer = tview.get_buffer()
        for item in range(0, len(self.keys)):
            textbuffer.insert_at_cursor('   %s\t\t %s \n' %(item, self.keys[item]))

By the way,If there is a simpler way of just replacing widgets on the go in PyGObject,please do let me know coz most of the answers that i saw on the related questions where totally useless

Rauscher answered 31/10, 2017 at 8:18 Comment(1)
Remember, you have to show everything as you go, either with show() on every widget or show_all() on a toplevel like your main window.Unite
N
10

I was baffled by this, too. It turned out the created widgets must be explicitly shown with show() or show_all(). In your case:

    row0.show_all()

as the last statement.

Nolasco answered 29/6, 2018 at 12:19 Comment(1)
THANKS. THANKS. Sorry for the caps but I was going crazy for this super-simple thing.Jonme

© 2022 - 2024 — McMap. All rights reserved.