GTK3可调整大小的图像阻止窗口还原大小

2024-10-03 09:15:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个扩展Gtk图像根据PyGTK: How do I make an image automatically scale to fit it's parent widget?自动调整父级大小,但需要进行一些改进和更正。你知道吗

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GdkPixbuf, GLib

class ImageEx(Gtk.Image):
    pixbuf = None

    def __init__(self, *args, **kwargs):
        super(ImageEx, self).__init__(*args, **kwargs)
        self.connect("size-allocate", self.on_size_allocate)
        self.props = super(ImageEx, self).props
        self.props.width_request  = 100
        self.props.height_request = -1
        self.props.hexpand = True
        self.tempHeight = 0
        self.tempWidth  = 0
        self.origHeight = 0
        self.origWidth  = 0


    def set_from_pixbuf(self, pixbuf):
        self.pixbuf = pixbuf
        self.origHeight = pixbuf.get_height()
        self.origWidth  = pixbuf.get_width()
        self.tempHeight = 0
        self.tempWidth  = 0
        self.on_size_allocate(None, self.get_allocation())

    def calculateHeight(self, desiredWidth):
        return desiredWidth * self.origHeight / self.origWidth

    def on_size_allocate(self, obj, rect):
        if self.pixbuf is not None:
            desiredWidth = min(rect.width-10, self.origWidth)
            if self.tempWidth != desiredWidth:
                self.tempWidth = desiredWidth
                self.tempHeight = self.calculateHeight(desiredWidth)
                pixbuf = self.pixbuf.scale_simple(self.tempWidth,
                                                  self.tempHeight,
                                                  GdkPixbuf.InterpType.BILINEAR)
                GLib.idle_add(super(ImageEx, self).set_from_pixbuf,
                              pixbuf)

我把它用在Gtk.窗格,它工作正常,我可以调整面板和窗口的大小,但是如果我展开窗口,我不能用窗口按钮还原它,但是如果我移动窗口,它会正确还原。你知道吗

如此不一致的状态怎么可能存在? 我怎样才能纠正它?你知道吗

谢谢


Tags: fromselfnonegtksizedefpropsgi