PyGobject(二十九)布局容器之SearchBar

Gtk.SearchBar

Gtk.SearchBar带有Entry的容器,通常用于输入搜索内容,然后根据输入搜索或者过滤其它内容

继承关系

Gtk.SearchBar是Gtk.Bin的直接子类
这里写图片描述

Methods

方法修饰词方法名及参数
staticnew ()
connect_entry (entry)
get_search_mode ()
get_show_close_button ()
handle_event (event)
set_search_mode (search_mode)
set_show_close_button (visible)

Virtual Methods

Properties

NameTypeFlagsShort Description
search-mode-enabledboolr/w/en是否显示SearchBar,默认为False
show-close-buttonboolr/w/c/enWhether to show the close button in the toolbar

Signals

NameShort Description

例子

这里写图片描述
代码:

#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/7
# section 034
TITLE = "SearchBar"
DESCRIPTION = """
Gtk.SearchBar is a container made to have a search entry
(possibly with additional connex widgets, such as drop-down menus, or buttons) built-in.
The search bar would appear when a search is started through typing on the keyboard,
or the application’s search mode is toggled on
"""
import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Gio, GLib
import sys


class SearchBarApp(Gtk.Application):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, application_id="org.gtk.Example.GtkSearchBar",
                         flags=Gio.ApplicationFlags.FLAGS_NONE, **kwargs)
        # self.set_size_request(250, 200)

    @staticmethod
    def window_key_press_event_cb(window, event, search_bar):
        return search_bar.handle_event(event)

    def do_activate(self):
        window = Gtk.ApplicationWindow(application=self, title="SearchBar Example")
        search_bar = Gtk.SearchBar()
        search_bar.set_search_mode(True)
        window.add(search_bar)

        box = Gtk.Box(spacing=6)
        search_bar.add(box)

        entry = Gtk.SearchEntry()
        box.pack_start(entry, True, True, 0)

        menu_button = Gtk.MenuButton()
        box.pack_start(menu_button, False, False, 0)

        search_bar.connect_entry(entry)

        window.connect("key-press-event",
                       self.window_key_press_event_cb, search_bar)
        window.show_all()


def main():
    app = SearchBarApp()
    app.run(sys.argv)


if __name__ == "__main__":
    main()

代码解析

class SearchBarApp(Gtk.Application):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, 
        application_id="org.gtk.Example.GtkSearchBar",                    
        flags=Gio.ApplicationFlags.FLAGS_NONE, **kwargs)

自定义SearchBarApp类继承自Gtk.Application,在构造方法中指定application_id和flags

当Gtk.Application运行时执行虚方法do_activate

def do_activate(self):
        window = Gtk.ApplicationWindow(application=self, title="SearchBar Example")
        search_bar = Gtk.SearchBar()
        search_bar.set_search_mode(True)
        window.add(search_bar)

        box = Gtk.Box(spacing=6)
        search_bar.add(box)

        entry = Gtk.SearchEntry()
        box.pack_start(entry, True, True, 0)

        menu_button = Gtk.MenuButton()
        box.pack_start(menu_button, False, False, 0)

        search_bar.connect_entry(entry)

        window.connect("key-press-event",
                       self.window_key_press_event_cb, search_bar)
        window.show_all()

在该方法中创建一个Gtk.ApplicationWindow窗口
window = Gtk.ApplicationWindow(application=self, title="SearchBar Example")
然后生成一个SearchBar
search_bar = Gtk.SearchBar()
显示这个search_bar,默认是不显示的
search_bar.set_search_mode(True)
将search_bar添加到前面创建的window中
window.add(search_bar)

接着

box = Gtk.Box(spacing=6)
search_bar.add(box)

entry = Gtk.SearchEntry()
box.pack_start(entry, True, True, 0)

menu_button = Gtk.MenuButton()
box.pack_start(menu_button, False, False, 0)

创建一个Box,里面包含一个Gtk.SearchEntry和一个Gtk.MenuButton,然后将这个box添加到search_bar容器中。
将这个SearchEntry和search_bar联系起来
search_bar.connect_entry(entry)

最关键一点

window.connect("key-press-event",self.window_key_press_event_cb, search_bar)

@staticmethod
def window_key_press_event_cb(window, event, search_bar):
        return search_bar.handle_event(event)

使search_bar能够捕获到当前窗口的按键事件。这样当search_bar不可见时,按键盘上的任一字符,使search_bar重现

这里写图片描述
searchbar中输入内容时,下面的列表能够自动过滤掉不匹配的内容。还可以选择查找条件。
代码:

#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/7
# section 035
TITLE = "SearchBar(1)"
DESCRIPTION = ""
import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Gio, GLib

# list of tuples for each software, containing the software name, initial release, and main programming languages used
software_list = [("Firefox", 2002, "C++"),
                 ("Eclipse", 2004, "Java"),
                 ("Pitivi", 2004, "Python"),
                 ("Netbeans", 1996, "Java"),
                 ("Chrome", 2008, "C++"),
                 ("Filezilla", 2001, "C++"),
                 ("Bazaar", 2005, "Python"),
                 ("Git", 2005, "C"),
                 ("Linux Kernel", 1991, "C"),
                 ("GCC", 1987, "C"),
                 ("Frostwire", 2004, "Java")]

head_list = ["Software", "Release Year", "Programming Language"]


class SearchBarWindow(Gtk.Window):
    def __init__(self, *args, **kwargs):
        Gtk.Window.__init__(self, title="SearchBar Example")
        self.set_size_request(250, 200)
        self.selection = 0
        self.grid = Gtk.Grid()
        self.grid.set_column_homogeneous(True)
        self.grid.set_row_homogeneous(True)
        self.add(self.grid)

        self.create_searchbar()
        self.create_treeview()

    def create_searchbar(self):
        search_bar = Gtk.SearchBar()
        # search_bar.set_show_close_button(True)
        # show SearchBar
        search_bar.set_search_mode(True)
        self.grid.attach(search_bar, 0, 0, 5, 1)

        box = Gtk.Box(spacing=6)

        self.entry = Gtk.SearchEntry()
        self.entry.connect("search-changed", self.change)
        box.pack_start(self.entry, True, True, 0)

        cb = Gtk.ComboBoxText()
        cb.connect("changed", self.on_selection_changed)
        for value in head_list:
            cb.append_text(value)
        cb.set_active(0)

        box.pack_start(cb, False, False, 0)

        search_bar.add(box)
        search_bar.connect_entry(self.entry)
        self.connect("key-press-event",
                     self.window_key_press_event_cb, search_bar)

    def create_treeview(self):
        # Creating the ListStore model
        self.software_liststore = Gtk.ListStore(str, int, str)
        for software_ref in software_list:
            self.software_liststore.append(list(software_ref))
        self.current_filter_value = None

        # Creating the filter, feeding it with the liststore model
        self.language_filter = self.software_liststore.filter_new()
        # setting the filter function, note that we're not using the
        self.language_filter.set_visible_func(self.language_filter_func)

        # creating the treeview, making it use the filter as a model, and adding the columns
        self.treeview = Gtk.TreeView.new_with_model(self.language_filter)
        for i, column_title in enumerate(head_list):
            renderer = Gtk.CellRendererText()
            column = Gtk.TreeViewColumn(column_title, renderer, text=i)
            self.treeview.append_column(column)

        # setting up the layout, putting the treeview in a scrollwindow, and the buttons in a row
        self.scrollable_treelist = Gtk.ScrolledWindow()
        self.scrollable_treelist.set_vexpand(True)
        self.grid.attach(self.scrollable_treelist, 0, 1, 8, 10)
        self.scrollable_treelist.add(self.treeview)

    def language_filter_func(self, model, iter, data):
        """Tests if the language in the row is the one in the filter"""
        if self.current_filter_value is None or self.current_filter_value == "":
            return True
        else:
            rlt = str.lower(str(model[iter][self.selection])).find(str.lower(self.current_filter_value))
            return rlt != -1

    @staticmethod
    def window_key_press_event_cb(window, event, search_bar):
        return search_bar.handle_event(event)

    def change(self, search_entry):
        self.current_filter_value = search_entry.get_text()
        self.language_filter.refilter()

    def on_selection_changed(self, comboBox):
        # text = comboBox.get_active_text()
        self.selection = comboBox.get_active()
        self.language_filter.refilter()


def main():
    win = SearchBarWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

代码解析:这里面涉及到Gtk.TreeView。请参见Gtk.TreeView。其它内容比较好理解。





代码下载地址:http://download.youkuaiyun.com/detail/a87b01c14/9594728

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sanxiaochengyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值