调整网格后,GTK3不会重绘

时间:2016-10-05 13:24:08

标签: python gtk3

我有一个直截了当的例子我正在尝试使用GTK3,我想要一个简单的网格,可以在调整大小时重新调整:

#!/usr/bin/python3

from gi.repository import Gtk, Gdk

class Window(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title='Grid Test')

        self.scroll = Gtk.ScrolledWindow()
        self.scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        self.add(self.scroll)

        self.grid = Gtk.Grid()
        self.scroll.add(self.grid)

        self.create_items()

        # quit on ctrl-w
        accel = Gtk.AccelGroup()
        accel.connect(Gdk.keyval_from_name('W'), Gdk.ModifierType.CONTROL_MASK, 0, self.exit)
        self.add_accel_group(accel)

        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(bytes('''
        .button {
            background: none;
            border: none;
        }
        '''.encode()))
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

        self.width = self.scroll.get_allocated_width()
        self.scroll.connect("size-allocate", self.on_resize, self.scroll, self.grid)

    def create_items(self):
        # remove existing
        for wid in self.grid.get_children():
            self.grid.remove(wid)

        col, row = 0, 0
        cols = self.scroll.get_allocated_width() / (40 + self.grid.get_column_spacing())
        for i in range(10):
            button = Gtk.Button(label='foo{}'.format(i))
            button.connect('clicked', self.on_click)
            self.grid.attach(button, col, row, 1, 1)

            if col >= cols:
                col = 0
                row += 1
            else:
                col += 1

    def on_click(self, widget):
        print('clicked')

    def exit(self, *args):
        Gtk.main_quit()

    def on_resize(self, a, b, c, grid):
        new_width = self.scroll.get_allocated_width()
        if new_width != self.width:
            self.create_items()
            self.width = new_width

if __name__ == '__main__':
    win = Window()
    win.connect('delete-event', Gtk.main_quit)
    win.show_all()
    Gtk.main()

这总是会导致一个空窗口。如果我删除了size-allocate处理程序,那么这些项目会进行渲染,但当然不会在窗口大小发生变化时进行调整。

我尝试在窗口和滚动视图上使用self.queue_draw()强制重绘,但这些似乎没有帮助。

1 个答案:

答案 0 :(得分:0)

create_items()运行后,按钮仍然隐藏;您应该将visible=True添加到其中的Gtk.Button构造函数中,或者在win.show_all()的末尾重新运行create_items()