How do I set Gtk.TextView "width"

Hello! I am using Gtk4 in python3 and would like to have a scrollable text view with line wrapping of, say, 1000 pixels wide.

I can set the wrap mode Gtk.WrapMode.WORD_CHAR to get the text wrapped.

To set the width I subclass Gtk.TextView and override the three methods:

class _FixedWidthText(Gtk.TextView):
	def do_size_allocate(self, width, height, baseline):
		width = 1000
		Gtk.TextView.do_size_allocate(self, width, height, baseline)

	def do_measure(self, orientation, for_size):
		width = 1000

		if orientation == Gtk.Orientation.HORIZONTAL:
			return width, width, -1, -1
		elif orientation == Gtk.Orientation.VERTICAL:
			m = Gtk.TextView.do_measure(self, Gtk.Orientation.VERTICAL, width)
			return m.minimum, m.natural, -1, -1
		else:
			raise NotImplemented(f'Unexpected orientation value {orientation}.')

	def do_get_request_mode(self):
		return Gtk.SizeRequestMode.CONSTANT_SIZE

However, with this approach the text view is not scrollable horizontally :frowning: - the scroll bar does not appear with the AUTOMATIC scrolling policy and is unscrollable with the ALWAYS policy.

By trial and error it looks like commenting out do_size_allocate override may be the problem but the gtk4 documentation is not very clear about what goes wrong (or, maybe, I just missed it)…

There is the GtkTextView:right-margin property. Depending on the width of the scrolled window, you can adjust the right-margin I think.

Thank you, @swilmet , for your reply! If I use the right margin then would I need to update it every time the main window size change? I.e.
right_margin = window_width - 1000

This would be done in a size change signal, right?

Yes, something along these lines. But I don’t know more.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.