两个带共享滚动条的Gtk TextView小部件

时间:2011-07-07 22:20:12

标签: c# gtk gtk#

我希望并排放置两个TextView小部件,这些小部件与一个滚动条一起滚动。

我可以将两个TextView小部件放在Hbox中,然后将它们添加到Viewport,然后添加到ScrolledWindow。然而,这不符合我的要求。从滚动条滚动将起作用。但是TextView中发生的操作不会改变滚动位置。 (箭头键,向上翻页,向下翻页等)我也无法使用TextView.ScrollToMark和其他TextView滚动方法以编程方式更改滚动。

如何让两个TextView小部件共享滚动条并在TextView中更新滚动操作?

1 个答案:

答案 0 :(得分:0)

关键是使用ScrolledWindow而不是Viewport,并在ScrolledWindows之间共享调整。视口将只滚动一个太大而不适合容器的小部件。另一方面,ScrolledWindow将其调整链接到TextView调整,这些调整受光标移动的影响。

我设法通过链接ScrolledWindows之间的调整,隐藏它们的滚动条,然后将它们放在一个只控制所有子窗口滚动条(未显示)的大型ScrolledWindow中来实现此功能。

以下是Python中的完整代码解决方案。您应该能够轻松地将其调整为C#。

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk

if __name__ == "__main__":
    window = gtk.Window()

    box = gtk.HBox()

    textview1 = gtk.TextView()
    textview2 = gtk.TextView()

    hadjustment = None
    vadjustment = None

    for textview in (textview1, textview2):
        sw = gtk.ScrolledWindow()
        # don't show the scrollbars on these sub-scrolledwindows
        sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_NEVER)
        sw.add(textview)

        # use the first scrolledwindow's adjustments
        if hadjustment is None:
            hadjustment = sw.get_hadjustment()
        else:
            sw.set_hadjustment(hadjustment)
        if vadjustment is None:
            vadjustment = sw.get_vadjustment()
        else:
            sw.set_vadjustment(vadjustment)

        box.pack_start(sw, padding=5)

        buffer = textview.get_buffer()
        buffer.set_text("If a widget has native scrolling abilities,\n"
                        " it can be added to the gtk.ScrolledWindow\n"
                        "with the gtk.Container.add() method. If a\n"
                        "widget does not, you must first add the\n"
                        "widget to a gtk.Viewport, then add the\n"
                        "gtk.Viewport to the scrolled window. The\n"
                        "convenience method add_with_viewport() does\n"
                        "exactly this, so you can ignore the presence\n"
                        "of the viewport.")

    # this scrolled window will encompass the rest and have scrollbars
    main_sw = gtk.ScrolledWindow(hadjustment, vadjustment)
    main_sw.set_policy(gtk.POLICY_ALWAYS, gtk.POLICY_ALWAYS)
    main_sw.add(box)
    window.add(main_sw)

    window.show_all()
    gtk.main()