How do I set a maximum text width for a GtkTextView?

322 Views Asked by At

I have a GtkTextView, and I would like to be able to set a maximum line width for the text. If the width of the TextView exceeds the maximum text width, the extra space should be filled with padding on the left and right on the text. Although Gtk supports a min-width CSS property, there appears to be no max-width property. Instead I tried to dynamically set the margins whenever the TextView is resized by connecting size-allocate to

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)

This produces the desired text line width for any given TextView width, but leads to strange behavior when resizing the window. Resizing the window to a smaller width happens with a slow delay. Attempting to maximize the window makes the window jump to a width much larger than the screen. size-allocate may not be the correct signal to connect to, but I have not been able to find any other way to dynamically set margins when the TextView is resized.

What is the correct way to achieve a maximum text line width?

1

There are 1 best solutions below

0
On BEST ANSWER

I came up with a solution. I created a custom container by inheriting from GtkBin, overrode do_size_allocate, and added my GtkTextView to that container:

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)