【问题标题】:How do I set a maximum text width for a GtkTextView?如何为 GtkTextView 设置最大文本宽度?
【发布时间】:2020-10-06 03:13:33
【问题描述】:

我有一个 GtkTextView,我希望能够为文本设置最大线宽。如果 TextView 的宽度超过了最大文本宽度,多余的空间应该在文本的左右两边用 padding 填充。尽管 Gtk 支持 min-width CSS 属性,但似乎没有 max-width 属性。相反,我尝试通过将 size-allocate 连接到调整 TextView 的大小来动态设置边距

def on_textview_size_allocate(textview, allocation):
    width = allocation.width
        if width > max_width:                       
            textview.set_left_margin((width - max_width) / 2)            
            textview.set_right_margin((width - max_width) / 2)            
        else:                                       
            textview.set_left_margin(0)
            textview.set_right_margin(0)

这会为任何给定的 TextView 宽度生成所需的文本行宽,但在调整窗口大小时会导致奇怪的行为。将窗口调整为更小的宽度会发生缓慢的延迟。尝试最大化窗口会使窗口跳到比屏幕大得多的宽度。 size-allocate 可能不是要连接的正确信号,但我无法找到任何其他方法来在调整 TextView 大小时动态设置边距。

实现最大文本行宽的正确方法是什么?

【问题讨论】:

    标签: gtk max width line gtktextview


    【解决方案1】:

    我想出了一个解决方案。我通过继承GtkBin 创建了一个自定义容器,覆盖了do_size_allocate,并将我的GtkTextView 添加到该容器中:

    class MyContainer(Gtk.Bin):
        max_width = 500
    
        def do_size_allocate(self, allocation):
            # if container width exceeds max width
            if allocation.width > self.max_width:
                # calculate extra space
                extra_space = allocation.width - self.max_width
                # subtract extra space from allocation width
                allocation.width -= extra_space
                # move allocation to the right so that it is centered
                allocation.x += extra_space / 2
            # run GtkBin's normal do_size_allocate
            Gtk.Bin.do_size_allocate(self, allocation)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 2011-04-11
      • 1970-01-01
      • 2018-11-11
      • 2021-01-27
      相关资源
      最近更新 更多