Gtk.TextView是Gtk.Container的直接子类
方法修饰词 | 方法名及参数 |
---|---|
static | new () |
static | new_with_buffer (buffer) |
add_child_at_anchor (child, anchor) | |
add_child_in_window (child, which_window, xpos, ypos) | |
backward_display_line (iter) | |
backward_display_line_start (iter) | |
buffer_to_window_coords (win, buffer_x, buffer_y) | |
forward_display_line (iter) | |
forward_display_line_end (iter) | |
get_accepts_tab () | |
get_border_window_size (type) | |
get_bottom_margin () | |
get_buffer () | |
get_cursor_locations (iter) | |
get_cursor_visible () | |
get_default_attributes () | |
get_editable () | |
get_hadjustment () | |
get_indent () | |
get_input_hints () | |
get_input_purpose () | |
get_iter_at_location (x, y) | |
get_iter_at_position (x, y) | |
get_iter_location (iter) | |
get_justification () | |
get_left_margin () | |
get_line_at_y (y) | |
get_line_yrange (iter) | |
get_monospace () | |
get_overwrite () | |
get_pixels_above_lines () | |
get_pixels_below_lines () | |
get_pixels_inside_wrap () | |
get_right_margin () | |
get_tabs () | |
get_top_margin () | |
get_vadjustment () | |
get_visible_rect () | |
get_window (win) | |
get_window_type (window) | |
get_wrap_mode () | |
im_context_filter_keypress (event) | |
move_child (child, xpos, ypos) | |
move_mark_onscreen (mark) | |
move_visually (iter, count) | |
place_cursor_onscreen () | |
reset_cursor_blink () | |
reset_im_context () | |
scroll_mark_onscreen (mark) | |
scroll_to_iter (iter, within_margin, use_align, xalign, yalign) | |
scroll_to_mark (mark, within_margin, use_align, xalign, yalign) | |
set_accepts_tab (accepts_tab) | |
set_border_window_size (type, size) | |
set_bottom_margin (bottom_margin) | |
set_buffer (buffer) | |
set_cursor_visible (setting) | |
set_editable (setting) | |
set_indent (indent) | |
set_input_hints (hints) | |
set_input_purpose (purpose) | |
set_justification (justification) | |
set_left_margin (left_margin) | |
set_monospace (monospace) | |
set_overwrite (overwrite) | |
set_pixels_above_lines (pixels_above_lines) | |
set_pixels_below_lines (pixels_below_lines) | |
set_pixels_inside_wrap (pixels_inside_wrap) | |
set_right_margin (right_margin) | |
set_tabs (tabs) | |
set_top_margin (top_margin) | |
set_wrap_mode (wrap_mode) | |
starts_display_line (iter) | |
window_to_buffer_coords (win, window_x, window_y) |
do_backspace () |
do_copy_clipboard () |
do_cut_clipboard () |
do_delete_from_cursor (type, count) |
do_draw_layer (layer, cr) |
do_extend_selection (granularity, location, start, end) |
do_insert_at_cursor (str) |
do_move_cursor (step, count, extend_selection) |
do_paste_clipboard () |
do_populate_popup (popup) |
do_set_anchor () |
do_toggle_overwrite () |
Name | Type | Flags | Short Description |
---|---|---|---|
accepts-tab | bool | r/w/en | Whether Tab will result in a tab character being entered |
bottom-margin | int | r/w/en | Height of the bottom margin in pixels |
buffer | Gtk.TextBuffer | r/w | The buffer which is displayed |
cursor-visible | bool | r/w/en | If the insertion cursor is shown |
editable | bool | r/w/en | Whether the text can be modified by the user |
im-module | str | r/w | Which IM module should be used |
indent | int | r/w/en | Amount to indent the paragraph, in pixels |
input-hints | Gtk.InputHints | r/w/en | Hints for the text field behaviour |
input-purpose | Gtk.InputPurpose | r/w/en | Purpose of the text field |
justification | Gtk.Justification | r/w/en | Left, right, or center justification |
left-margin | int | r/w/en | Width of the left margin in pixels |
monospace | bool | r/w/en | Whether to use a monospace font |
overwrite | bool | r/w/en | Whether entered text overwrites existing contents |
pixels-above-lines | int | r/w/en | Pixels of blank space above paragraphs |
pixels-below-lines | int | r/w/en | Pixels of blank space below paragraphs |
pixels-inside-wrap | int | r/w/en | Pixels of blank space between wrapped lines in a paragraph |
populate-all | bool | r/w/en | Whether to emit ::populate-popup for touch popups |
right-margin | int | r/w/en | Width of the right margin in pixels |
tabs | Pango.TabArray | r/w | Custom tabs for this text |
top-margin | int | r/w/en | Height of the top margin in pixels |
wrap-mode | Gtk.WrapMode | r/w/en | Whether to wrap lines never, at word boundaries, or at character boundaries |
Name | Short Description |
---|---|
backspace | The ::backspace signal is a keybinding signal which gets emitted when the user asks for it. |
copy-clipboard | The ::copy-clipboard signal is a keybinding signal which gets emitted to copy the selection to the clipboard. |
cut-clipboard | The ::cut-clipboard signal is a keybinding signal which gets emitted to cut the selection to the clipboard. |
delete-from-cursor | The ::delete-from-cursor signal is a keybinding signal which gets emitted when the user initiates a text deletion. |
extend-selection | The ::extend-selection signal is emitted when the selection needs to be extended at location. |
insert-at-cursor | The ::insert-at-cursor signal is a keybinding signal which gets emitted when the user initiates the insertion of a fixed string at the cursor. |
move-cursor | The ::move-cursor signal is a keybinding signal which gets emitted when the user initiates a cursor movement. |
move-viewport | The ::move-viewport signal is a keybinding signal which can be bound to key combinations to allow the user to move the viewport, i.e. |
paste-clipboard | The ::paste-clipboard signal is a keybinding signal which gets emitted to paste the contents of the clipboard into the text view. |
populate-popup | The ::populate-popup signal gets emitted before showing the context menu of the text view. |
preedit-changed | If an input method is used, the typed text will not immediately be committed to the buffer. |
select-all | The ::select-all signal is a keybinding signal which gets emitted to select or unselect the complete contents of the text view. |
set-anchor | The ::set-anchor signal is a keybinding signal which gets emitted when the user initiates setting the “anchor” mark. |
toggle-cursor-visible | The ::toggle-cursor-visible signal is a keybinding signal which gets emitted to toggle the Gtk.TextView :cursor-visible property. |
toggle-overwrite | The ::toggle-overwrite signal is a keybinding signal which gets emitted to toggle the overwrite mode of the text view. |
#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/11
# section 095
#
# author: xiaosanyu
# website: yuxiaosan.tk \
# http://blog.csdn.net/a87b01c14
# created: 16/7/11
TITLE = "TextViewColor"
DESCRIPTION = """
change text color
"""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango, Gdk
class SimpletextWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="TextView Example")
self.set_size_request(100, 100)
view = Gtk.TextView()
buffer = view.get_buffer()
buffer.set_text("Hello, this is some text", -1)
# Change default font throughout the widget
font_desc = Pango.FontDescription("Serif 15")
view.modify_font(font_desc)
# Change default color throughout the widget
color = Gdk.color_parse("green")
rgba = Gdk.RGBA.from_color(color)
view.override_color(Gtk.StateFlags.NORMAL, rgba)
# Change left margin throughout the widget
view.set_left_margin(30)
# Use a tag to change the color for just one part of the widget
tag = buffer.create_tag("foreground", foreground="blue")
start = buffer.get_iter_at_offset(7)
end = buffer.get_iter_at_offset(12)
buffer.apply_tag(tag, start, end)
self.add(view)
def main():
win = SimpletextWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
if __name__ == "__main__":
main()
代码解析
代码
#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/20
# section 096
#
# author: xiaosanyu
# website: yuxiaosan.tk \
# http://blog.csdn.net/a87b01c14
# created: 16/7/20
TITLE = "AnimatedText"
DESCRIPTION = """
shows animated text on window
"""
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango, GLib
import math
text = "ZetCode"
LEN = len(text)
class PyApp(Gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.connect("destroy", Gtk.main_quit)
self.set_title("AnimatedText")
self.set_size_request(500, 300)
textview = Gtk.TextView()
textview.set_editable(False)
textview.set_cursor_visible(False)
textview.set_valign(Gtk.Align.BASELINE)
textview.set_size_request(-1, 200)
buffer = textview.get_buffer()
buffer.set_text(text)
self.count = 0
box = Gtk.Box()
box.set_valign(Gtk.Align.CENTER)
box.set_halign(Gtk.Align.CENTER)
box.add(textview)
self.add(box)
self.show_all()
GLib.timeout_add(500, self.on_timer, buffer)
def on_timer(self, buffer):
start = buffer.get_start_iter()
end = buffer.get_end_iter()
tabel = buffer.get_tag_table()
# buffer.remove_all_tags(start, end)
for i in range(tabel.get_size()):
tag = tabel.lookup("scale" + str(i))
if tag:
tabel.remove(tag)
for i in range(LEN):
value = math.ceil(abs(math.sin(self.count + (GLib.PI / LEN) * (i + 1))) * 10 + 1)
tag = buffer.create_tag(tag_name="scale" + str(i), scale=5,
rise=value * 10 * Pango.SCALE)
end = buffer.get_iter_at_offset(i + 1)
buffer.apply_tag_by_name(tag.props.name, start, end)
start = end
self.count += 0.1
return True
def main():
PyApp()
Gtk.main()
if __name__ == "__main__":
main()
#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/11
# section 097
#
# author: xiaosanyu
# website: yuxiaosan.tk \
# http://blog.csdn.net/a87b01c14
# created: 16/7/11
TITLE = "HyperTextView"
DESCRIPTION = """
Usually, tags modify the appearance of text in the view, e.g. making it
bold or colored or underlined. But tags are not restricted to appearance.
They can also affect the behavior of mouse and key presses, as this demo shows.
"""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango, Gdk
class HypertextWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="HyperTextView Example")
self.set_size_request(450, 150)
self.hovering_over_link = False
self.view = Gtk.TextView()
display = self.view.get_display()
self.hand_cursor = Gdk.Cursor.new_from_name(display, "pointer")
self.regular_cursor = Gdk.Cursor.new_from_name(display, "text")
self.view.set_wrap_mode(Gtk.WrapMode.WORD)
self.view.set_left_margin(20)
self.view.set_right_margin(20)
self.view.set_top_margin(20)
self.view.connect("key-press-event", self.key_press_event)
self.view.connect("event-after", self.event_after)
self.view.connect("motion-notify-event", self.motion_notify_event)
self.buffer = self.view.get_buffer()
self.buffer.set_text("Hello, this is some text", -1)
scrolledwindow = Gtk.ScrolledWindow()
scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
scrolledwindow.set_hexpand(True)
scrolledwindow.set_vexpand(True)
scrolledwindow.add(self.view)
self.add(scrolledwindow)
self.show_page(1)
def insert_link(self, iter, text, page):
tag = self.buffer.create_tag(tag_name=None, foreground="blue", underline=Pango.Underline.SINGLE)
# Gobject's method,RuntimeError: Data access methods are unsupported. Use normal Python attributes instead
# tag.set_data("page", page)
tag.page = page
self.buffer.insert_with_tags(iter, text, tag)
def show_page(self, page):
self.buffer.set_text("", 0)
iter = self.buffer.get_iter_at_offset(0)
if page == 1:
self.buffer.insert(iter, "Some text to show that simple ", -1)
self.insert_link(iter, "hyper text", 3)
self.buffer.insert(iter, " can easily be realized with ", -1)
self.insert_link(iter, "tags", 2)
self.buffer.insert(iter, ".", -1)
elif page == 2:
self.buffer.insert(iter,
"A tag is an attribute that can be applied to some range of text. "
"For example, a tag might be called \"bold\" and make the text inside "
"the tag bold. However, the tag concept is more general than that "
"tags don't have to affect appearance. They can instead affect the "
"behavior of mouse and key presses, \"lock\" a range of text so the "
"user can't edit it, or countless other things.\n", -1)
self.insert_link(iter, "Go back", 1)
elif page == 3:
tag = self.buffer.create_tag("weight", weight=Pango.Weight.BOLD)
self.buffer.insert_with_tags(iter, "hypertext:\n", tag)
self.buffer.insert(iter,
"machine-readable text that is not sequential but is organized "
"so that related items of information are connected.\n", -1)
self.insert_link(iter, "Go back", 1)
def follow_if_link(self, iter):
tags = iter.get_tags()
for tagp in tags:
page = tagp.page
if page:
self.show_page(page)
break
def key_press_event(self, widget, event):
if event.keyval == Gdk.KEY_Return or event.keyval == Gdk.KEY_KP_Enter:
iter = self.buffer.get_iter_at_mark(self.buffer.get_insert())
self.follow_if_link(iter)
return False
def event_after(self, widget, ev):
if ev.type == Gdk.EventType.BUTTON_RELEASE:
if ev.button.button != Gdk.BUTTON_PRIMARY:
return False
ex = ev.x
ey = ev.y
elif ev.type == Gdk.EventType.TOUCH_END:
ex = ev.x
ey = ev.y
else:
return False
# we shouldn't follow a link if the user has selected something #
mark = self.buffer.get_selection_bounds()
if mark:
return False
x, y = self.view.window_to_buffer_coords(Gtk.TextWindowType.WIDGET, ex, ey)
isok, iter = self.view.get_iter_at_location(x, y)
if isok:
self.follow_if_link(iter)
return True
def set_cursor_if_appropriate(self, x, y):
isok, iter = self.view.get_iter_at_location(x, y)
hovering = False
if isok:
tags = iter.get_tags()
for tagp in tags:
page = tagp.page
if page:
hovering = True
break
if hovering != self.hovering_over_link:
self.hovering_over_link = hovering
if hovering:
self.view.get_window(Gtk.TextWindowType.TEXT).set_cursor(self.hand_cursor)
else:
self.view.get_window(Gtk.TextWindowType.TEXT).set_cursor(self.regular_cursor)
def motion_notify_event(self, widget, event):
x, y = self.view.window_to_buffer_coords(Gtk.TextWindowType.WIDGET, event.x, event.y)
self.set_cursor_if_appropriate(x, y)
return False
def main():
win = HypertextWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
if __name__ == "__main__":
main()
代码:
#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/11
# section 098
#
# author: xiaosanyu
# website: yuxiaosan.tk \
# http://blog.csdn.net/a87b01c14
# created: 16/7/11
TITLE = "Markup"
DESCRIPTION = """
GtkTextBuffer lets you define your own tags that can influence
text formatting in a variety of ways. In this example, we show
that GtkTextBuffer can load Pango markup and automatically generate
suitable tags.
"""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio
import os
class MarkuptextWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Markup Example")
self.set_size_request(200, 200)
view = Gtk.TextView()
view.set_wrap_mode(Gtk.WrapMode.WORD)
view.set_left_margin(10)
view.set_right_margin(10)
buffer = view.get_buffer()
bytes = Gio.resources_lookup_data("/textview/markup.txt", 0)
start_iter = buffer.get_start_iter()
buffer.insert_markup(start_iter, bytes.get_data().decode(), -1)
scrolledwindow = Gtk.ScrolledWindow()
scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
scrolledwindow.set_hexpand(True)
scrolledwindow.set_vexpand(True)
scrolledwindow.add(view)
self.add(scrolledwindow)
def main():
win = MarkuptextWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
if __name__ == "__main__":
base_path = os.path.abspath(os.path.dirname(__file__))
resource_path = os.path.join(base_path, '../../Data/demo.gresource')
resource = Gio.Resource.load(resource_path)
Gio.resources_register(resource)
main()
markup.txt
Text sizes: <span size="xx-small">tinyspan> <span size="x-small">very smallspan> <span size="small">smallspan> <span size="medium">normalspan> <span size="large">largespan> <span size="x-large">very largespan> <span size="xx-large">hugespan>
Text <span color="gray">c<span color="green">ospan>l<span color="tomato">ospan>rsspan> and <span background="pink">backgroundsspan>
Colorful <span underline="low" underline-color="blue"><span underline="double" underline-color="red">underspan>linesspan> and <span background="pink"><span underline="error">mospan><span underline="error" underline-color="green">respan>span>
Colorful <span strikethrough="true" strikethrough-color="magenta">strikethroughsspan>
Superscripts and subscripts:ε<span rise="-6000" size="x-small" font_desc="italic">0span> = ω<span rise="8000" size="smaller">ω<span rise="14000" size="small">ω<span rise="20000">.<span rise="23000">.<span rise="26000">.span>span>span>span>span>
<span letter_spacing="3000">Letterspacingspan>
OpenType font features: <span font_desc="sans regular" font_features="dlig=0">feastspan> versus <span font_desc="sans regular" font_features="dlig=1">feastspan>
Shortcuts: <tt>Monospacett> – <b>Boldb> – <i>Italici> – <big>Bigbig> – <small>Smallsmall> – <u>Underlinedu> – <s>Strikethroughs> – Super<sup>scriptsup> – Sub<sub>scriptsub>
关于资源文件的生成
定义demo.gresource.xml,跟markup.txt在同一目录下
内容
<gresources>
<gresource prefix="/textview">
<file>markup.txtfile>
gresource>
gresources>
使用glib-compile-resources命令生成资源文件
cd 到demo.gresource.xml文件所在路径,执行一下命令
$/Users/xiaosanyu/gtk/inst/bin/glib-compile-resources
demo.gresource.xml
在当前目录下会生成demo.gresource文件
#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/20
# section 099
#
# author: xiaosanyu
# website: yuxiaosan.tk \
# http://blog.csdn.net/a87b01c14
# created: 16/7/20
TITLE = "TextTag"
DESCRIPTION = ""
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango
text = "Valour fate kinship darkness"
class PyApp(Gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.connect("destroy", Gtk.main_quit)
self.set_title("TextTag")
textview = Gtk.TextView()
textview.set_editable(False)
buffer = textview.get_buffer()
buffer.set_text(text)
self.add_fg_color(buffer)
self.add_underline(buffer)
self.add_bg_color(buffer)
self.add_strike(buffer)
self.set_size(buffer)
fix = Gtk.Fixed()
fix.put(textview, 5, 5)
self.add(fix)
self.show_all()
@staticmethod
def add_fg_color(buffer):
fg_color = buffer.create_tag(tag_name="fg_color", foreground="red")
start = buffer.get_start_iter()
end = buffer.get_iter_at_offset(6)
buffer.apply_tag_by_name(fg_color.props.name, start, end)
@staticmethod
def add_underline(buffer):
underline = buffer.create_tag(tag_name="underline", underline=Pango.Underline.DOUBLE)
start = buffer.get_iter_at_offset(7)
end = buffer.get_iter_at_offset(11)
buffer.apply_tag_by_name(underline.props.name, start, end)
@staticmethod
def add_bg_color(buffer):
bg_color = buffer.create_tag(tag_name="bg_color", background_gdk=Gdk.Color(40000, 40000, 40000))
start = buffer.get_iter_at_offset(12)
end = buffer.get_iter_at_offset(19)
buffer.apply_tag_by_name(bg_color.props.name, start, end)
@staticmethod
def add_strike(buffer):
strike = buffer.create_tag(tag_name="strike", strikethrough=True)
start = buffer.get_iter_at_offset(20)
end = buffer.get_iter_at_offset(29)
buffer.apply_tag_by_name(strike.props.name, start, end)
@staticmethod
def set_size(buffer):
size = buffer.create_tag(tag_name="size", size=30000)
start = buffer.get_iter_at_offset(0)
end = buffer.get_iter_at_offset(-1)
buffer.apply_tag_by_name(size.props.name, start, end)
def main():
PyApp()
Gtk.main()
if __name__ == "__main__":
main()
代码:
#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/16
# section 100
TITLE = "TextView"
DESCRIPTION = ""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango
class SearchDialog(Gtk.Dialog):
def __init__(self, parent):
Gtk.Dialog.__init__(self, "Search", parent,
Gtk.DialogFlags.MODAL, buttons=(
Gtk.STOCK_FIND, Gtk.ResponseType.OK,
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))
box = self.get_content_area()
label = Gtk.Label("Insert text you want to search for:")
box.add(label)
self.entry = Gtk.Entry()
box.add(self.entry)
self.show_all()
class TextViewWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="TextView Example")
self.set_default_size(-1, 350)
self.grid = Gtk.Grid()
self.add(self.grid)
self.create_textview()
self.create_toolbar()
self.create_buttons()
def create_toolbar(self):
toolbar = Gtk.Toolbar()
self.grid.attach(toolbar, 0, 0, 3, 1)
button_bold = Gtk.ToolButton()
button_bold.set_icon_name("format-text-bold-symbolic")
toolbar.insert(button_bold, 0)
button_italic = Gtk.ToolButton()
button_italic.set_icon_name("format-text-italic-symbolic")
toolbar.insert(button_italic, 1)
button_underline = Gtk.ToolButton()
button_underline.set_icon_name("format-text-underline-symbolic")
toolbar.insert(button_underline, 2)
button_bold.connect("clicked", self.on_button_clicked, self.tag_bold)
button_italic.connect("clicked", self.on_button_clicked,
self.tag_italic)
button_underline.connect("clicked", self.on_button_clicked,
self.tag_underline)
toolbar.insert(Gtk.SeparatorToolItem(), 3)
radio_justifyleft = Gtk.RadioToolButton()
radio_justifyleft.set_icon_name("format-justify-left-symbolic")
toolbar.insert(radio_justifyleft, 4)
radio_justifycenter = Gtk.RadioToolButton.new_from_widget(radio_justifyleft)
radio_justifycenter.set_icon_name("format-justify-center-symbolic")
toolbar.insert(radio_justifycenter, 5)
radio_justifyright = Gtk.RadioToolButton.new_from_widget(radio_justifyleft)
radio_justifyright.set_icon_name("format-justify-right-symbolic")
toolbar.insert(radio_justifyright, 6)
radio_justifyfill = Gtk.RadioToolButton.new_from_widget(radio_justifyleft)
radio_justifyfill.set_icon_name("format-justify-fill-symbolic")
toolbar.insert(radio_justifyfill, 7)
radio_justifyleft.connect("toggled", self.on_justify_toggled,
Gtk.Justification.LEFT)
radio_justifycenter.connect("toggled", self.on_justify_toggled,
Gtk.Justification.CENTER)
radio_justifyright.connect("toggled", self.on_justify_toggled,
Gtk.Justification.RIGHT)
radio_justifyfill.connect("toggled", self.on_justify_toggled,
Gtk.Justification.FILL)
toolbar.insert(Gtk.SeparatorToolItem(), 8)
button_clear = Gtk.ToolButton()
button_clear.set_icon_name("edit-clear-symbolic")
button_clear.connect("clicked", self.on_clear_clicked)
toolbar.insert(button_clear, 9)
toolbar.insert(Gtk.SeparatorToolItem(), 10)
button_search = Gtk.ToolButton()
button_search.set_icon_name("system-search-symbolic")
button_search.connect("clicked", self.on_search_clicked)
toolbar.insert(button_search, 11)
def create_textview(self):
scrolledwindow = Gtk.ScrolledWindow()
scrolledwindow.set_hexpand(True)
scrolledwindow.set_vexpand(True)
self.grid.attach(scrolledwindow, 0, 1, 3, 1)
self.textview = Gtk.TextView()
self.textbuffer = self.textview.get_buffer()
self.textbuffer.set_text("This is some text inside of a Gtk.TextView. "
+ "Select text and click one of the buttons 'bold', 'italic', "
+ "or 'underline' to modify the text accordingly.")
scrolledwindow.add(self.textview)
self.tag_bold = self.textbuffer.create_tag("bold",
weight=Pango.Weight.BOLD)
self.tag_italic = self.textbuffer.create_tag("italic",
style=Pango.Style.ITALIC)
self.tag_underline = self.textbuffer.create_tag("underline",
underline=Pango.Underline.SINGLE)
self.tag_found = self.textbuffer.create_tag("found",
background="yellow")
def create_buttons(self):
check_editable = Gtk.CheckButton("Editable")
check_editable.set_active(True)
check_editable.connect("toggled", self.on_editable_toggled)
self.grid.attach(check_editable, 0, 2, 1, 1)
check_cursor = Gtk.CheckButton("Cursor Visible")
check_cursor.set_active(True)
check_editable.connect("toggled", self.on_cursor_toggled)
self.grid.attach_next_to(check_cursor, check_editable,
Gtk.PositionType.RIGHT, 1, 1)
radio_wrapnone = Gtk.RadioButton.new_with_label_from_widget(None,
"No Wrapping")
self.grid.attach(radio_wrapnone, 0, 3, 1, 1)
radio_wrapchar = Gtk.RadioButton.new_with_label_from_widget(
radio_wrapnone, "Character Wrapping")
self.grid.attach_next_to(radio_wrapchar, radio_wrapnone,
Gtk.PositionType.RIGHT, 1, 1)
radio_wrapword = Gtk.RadioButton.new_with_label_from_widget(
radio_wrapnone, "Word Wrapping")
self.grid.attach_next_to(radio_wrapword, radio_wrapchar,
Gtk.PositionType.RIGHT, 1, 1)
radio_wrapnone.connect("toggled", self.on_wrap_toggled,
Gtk.WrapMode.NONE)
radio_wrapchar.connect("toggled", self.on_wrap_toggled,
Gtk.WrapMode.CHAR)
radio_wrapword.connect("toggled", self.on_wrap_toggled,
Gtk.WrapMode.WORD)
def on_button_clicked(self, widget, tag):
bounds = self.textbuffer.get_selection_bounds()
if len(bounds) != 0:
start, end = bounds
self.textbuffer.apply_tag(tag, start, end)
def on_clear_clicked(self, widget):
start = self.textbuffer.get_start_iter()
end = self.textbuffer.get_end_iter()
self.textbuffer.remove_all_tags(start, end)
def on_editable_toggled(self, widget):
self.textview.set_editable(widget.get_active())
def on_cursor_toggled(self, widget):
self.textview.set_cursor_visible(widget.get_active())
def on_wrap_toggled(self, widget, mode):
self.textview.set_wrap_mode(mode)
def on_justify_toggled(self, widget, justification):
self.textview.set_justification(justification)
def on_search_clicked(self, widget):
dialog = SearchDialog(self)
response = dialog.run()
if response == Gtk.ResponseType.OK:
cursor_mark = self.textbuffer.get_insert()
start = self.textbuffer.get_iter_at_mark(cursor_mark)
if start.get_offset() == self.textbuffer.get_char_count():
start = self.textbuffer.get_start_iter()
self.search_and_mark(dialog.entry.get_text(), start)
dialog.destroy()
def search_and_mark(self, text, start):
end = self.textbuffer.get_end_iter()
match = start.forward_search(text, 0, end)
if match != None:
match_start, match_end = match
self.textbuffer.apply_tag(self.tag_found, match_start, match_end)
self.search_and_mark(text, match_end)
def main(demoapp=None):
win = TextViewWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
if __name__ == "__main__":
main()
代码下载地址:http://download.csdn.net/detail/a87b01c14/9594728