python - 如何在 TreeView 中动态调整 pixbuf cellrenderer 的大小?

标签 python python-2.7 gtk gtk3

pic

我正在使用如上所示的 Gtk3 TreeView。该模型是一个 Gtk.TreeStore

  • Gtk.TreeStore(str, GdkPixbuf.Pixbuf)

对于图片,我可以通过以下方式将正确大小的图像添加到模型中:

  • pixbuf.scale_simple(48,48,GdkPixbuf.InterpType.BILINEAR)

不过,我也在别处使用该模型以不同方式显示 pixbuf,并且 pixbuf 也可以有多种大小。

我想做的是在运行时强制显示图片的大小。问题是 - 我该怎么做?

我尝试强制 GtkCellRendererPixbuf 为固定大小,但这只会显示正确大小的图像 - 但只有与固定大小对应的图像部分

pixbuf = Gtk.CellRendererPixbuf()
pixbuf.set_fixed_size(48,48)

我想到了使用 TreeViewColumn 的 set_cell_data_func:

col = Gtk.TreeViewColumn('', pixbuf, pixbuf=1)
col.set_cell_data_func(pixbuf, self._pixbuf_func, None)

def _pixbuf_func(self, col, cell, tree_model, tree_iter, data):
    cell.props.pixbuf = cell.props.pixbuf.scale_simple(48,48,GdkPixbuf.InterpType.BILINEAR)

这确实会在运行时动态调整图像大小 - 但在终端中我会收到数百个这样的错误:

sys:1: RuntimeWarning: Expecting to marshal a borrowed reference for <Pixbuf object at 0x80acbe0 (GdkPixbuf at 0x87926d0)>, but nothing in Python is holding a reference to this object. See: https://bugzilla.gnome.org/show_bug.cgi?id=687522

我还尝试通过调整树模型 pixbuf 的大小而不是 cell.props.pixbuf 来尝试替代方法,但这也会产生与上述相同的错误。

cell.props.pixbuf = tree_model.get_value(tree_iter,1).scale_simple(48,48,GdkPixbuf.InterpType.BILINEAR)

很明显这不是正确的方法 - 那么还有什么想法可以解决这个问题吗?欢迎任何指向基于 Gtk3 的 C++/Python 示例代码的链接。

我正在使用 Gtk+3.6/python 2.7

最佳答案

老问题,但遗憾的是仍然相关 - Gtk 中的这个错误仍然存​​在。幸运的是,有一个非常简单的解决方法。您需要做的就是保留对缩放后的 pixbuf 的引用。

我已经改变了_pixbuf_func 函数,这样它就可以接受一个字典,它在其中存储了小的pixbuf。这消除了烦人的警告消息,还防止每次调用 _pixbuf_func 时都缩小 pixbuf。

def pixbuf_func(col, cell, tree_model, tree_iter, data):
    pixbuf= tree_model[tree_iter][1] # get the original pixbuf from the TreeStore. [1] is
                                     # the index of the pixbuf in the TreeStore.
    try:
        new_pixbuf= data[pixbuf] # if a downscaled pixbuf already exists, use it
    except KeyError:
        new_pixbuf= pixbuf.scale_simple(48,48,GdkPixbuf.InterpType.BILINEAR)
        data[pixbuf]= new_pixbuf # keep a reference to this pixbuf to prevent Gtk warning
                                 # messages
    cell.set_property('pixbuf', new_pixbuf)

renderer = Gtk.CellRendererPixbuf()
col = Gtk.TreeViewColumn('', renderer)
col.set_cell_data_func(renderer, pixbuf_func, {}) # pass a dict to keep references in

这个解决方案的一个问题是,每当您的 TreeStore 的内容发生变化时,您必须从字典中删除存储的 Pixbuf,否则它们将永远存在并且您的程序将消耗比必要更多的内存。

关于python - 如何在 TreeView 中动态调整 pixbuf cellrenderer 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19778003/

相关文章:

python - 避免 Python 路径中的反斜杠

python - 我可以对当前正在写入的文件使用 fdpexpect 吗?

Python:循环遍历变量列表

Python:抽象实例变量?

python - 在 Pyomo/AMPL 中定义多个模型

python - 如何在Python中使用for循环从可用数据中创建一个函数

python - Keras LSTM 输入形状的输入形状错误

Python - 如何运行 gtk.main() 不会阻塞我的整个应用程序并允许我进行多任务处理?

css - 需要在gtk上制作透明textview

c - 如何在 GTK+ 中构建计算器?