Max
Max

Reputation: 877

GTK4 ApplicationWindow that is also a ScrolledWindow?

Here is a minimal GTK 4 app written using the Python bindings, based on this tutorial. It displays a window with a very long block of text:

import sys
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw


class MainWindow(Gtk.ApplicationWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        long_label = Gtk.Label.new("Here is a very long chunk of text.\n" * 100)
        self.set_child(long_label)

class MyApp(Adw.Application):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.connect('activate', self.on_activate)

    def on_activate(self, app):
        self.win = MainWindow(application=app)
        self.win.present()

if __name__ == "__main__":
    app = MyApp(application_id="com.example.GtkApplication")
    app.run(sys.argv)

The tutorial uses the class Gtk.ApplicationWindow for the MainWindow, which lets you set the application_id in the main function and other convenient features.

However, the default Gtk.ApplicationWindow does not include a scrollbar. Rather than build one manually, it seems the best way to do this is to make my main window an instance of Gtk.ScrolledWindow, documented here, which lets you specify the scroll behavior etc. at a high level.

Unfortunately, dropping Gtk.ScrolledWindow in place of Gtk.ApplicationWindow causes an error:

TypeError: gobject `__main__+MainWindow' doesn't support property `application'

(I have added the pygobject tag because it is the language of my MWE, but I think that my question is agnostic with respect to the binding language.)

Upvotes: 0

Views: 571

Answers (1)

nielsdg
nielsdg

Reputation: 2743

A Gtk.ScrolledWindow isn't really a "window" per se as most people know it (it used to map to the very specific concept of a X11 Window). It's a widget that allows you to scroll through its child widget.

In other words, if you want an application window where you can scroll through the content, you would wrap your Gtk.Label with a Gtk.ScrolledWindow and you would then set that as the Gtk.ApplicationWindow's child.

In other words, your MainWindow would become:

class MainWindow(Gtk.ApplicationWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        long_label = Gtk.Label(label=("Here is a very long chunk of text.\n" * 100))

        # Wrap a scrolled window around it
        scrolled = Gtk.ScrolledWindow()
        scrolled.set_child(long_label)

        # Set it as the main child of the window
        self.set_child(scrolled)

Upvotes: 1

Related Questions