PyGobject(五十八)布局容器之IconView

Gtk.IconView

Gtk.IconView提供基于Gtk.TreeModel的另一种视图。它显示一个带文本和图标的网格视图。像Gtk.TreeView一样,允许单选和多选列表行。可以使用方向键选择,还支持使用鼠标进行拖放

继承关系

Gtk.IconView是Gtk.Container的直接子类
这里写图片描述

Methods

方法修饰词方法名及参数
staticnew ()
staticnew_with_area (area)
staticnew_with_model (model)
convert_widget_to_bin_window_coords (wx, wy)
create_drag_icon (path)
enable_model_drag_dest (targets, actions)
enable_model_drag_source (start_button_mask, targets, actions)
get_activate_on_single_click ()
get_cell_rect (path, cell)
get_column_spacing ()
get_columns ()
get_cursor ()
get_dest_item_at_pos (drag_x, drag_y)
get_drag_dest_item ()
get_item_at_pos (x, y)
get_item_column (path)
get_item_orientation ()
get_item_padding ()
get_item_row (path)
get_item_width ()
get_margin ()
get_markup_column ()
get_model ()
get_path_at_pos (x, y)
get_pixbuf_column ()
get_reorderable ()
get_row_spacing ()
get_selected_items ()
get_selection_mode ()
get_spacing ()
get_text_column ()
get_tooltip_column ()
get_tooltip_context (x, y, keyboard_tip)
get_visible_range ()
item_activated (path)
path_is_selected (path)
scroll_to_path (path, use_align, row_align, col_align)
select_all ()
select_path (path)
selected_foreach (func, *data)
set_activate_on_single_click (single)
set_column_spacing (column_spacing)
set_columns (columns)
set_cursor (path, cell, start_editing)
set_drag_dest_item (path, pos)
set_item_orientation (orientation)
set_item_padding (item_padding)
set_item_width (item_width)
set_margin (margin)
set_markup_column (column)
set_model (model)
set_pixbuf_column (column)
set_reorderable (reorderable)
set_row_spacing (row_spacing)
set_selection_mode (mode)
set_spacing (spacing)
set_text_column (column)
set_tooltip_cell (tooltip, path, cell)
set_tooltip_column (column)
set_tooltip_item (tooltip, path)
unselect_all ()
unselect_path (path)
unset_model_drag_dest ()
unset_model_drag_source ()

Virtual Methods

do_activate_cursor_item ()
do_item_activated (path)
do_move_cursor (step, count)
do_select_all ()
do_select_cursor_item ()
do_selection_changed ()
do_toggle_cursor_item ()
do_unselect_all ()

Properties

NameTypeFlagsShort Description
activate-on-single-clickboolr/w/enActivate row on a single click
cell-areaGtk.CellArear/w/co The Gtk.CellArea used to layout cells
column-spacingintr/w/enSpace which is inserted between grid columns
columnsintr/w/enNumber of columns to display
item-orientationGtk.Orientationr/w/enHow the text and icon of each item are positioned relative to each other
vitem-paddingintr/w/enPadding around icon view items
item-widthintr/w/enThe width used for each item
markup-columnintr/w/enModel column used to retrieve the text if using Pango markup
modelGtk.TreeModelr/wThe model for the icon view
pixbuf-columnintr/w/enModel column used to retrieve the icon pixbuf from
reorderableboolr/w/enView is reorderable
row-spacingintr/w/enSpace which is inserted between grid rows
selection-modeGtk.SelectionModer/w/enThe selection mode
spacingintr/w/enSpace which is inserted between cells of an item
text-columnintr/w/enModel column used to retrieve the text from
tooltip-columnintr/w/enThe column in the model containing the tooltip texts for the items

Signals

NameShort Description
activate-cursor-itemA keybinding signal which gets emitted when the user activates the currently focused item.
item-activatedThe ::item-activated signal is emitted when the method Gtk.IconView.item_activated() is called, when the user double clicks an item with the “activate-on-single-click” property set to False, or when the user single clicks an item when the “activate-on-single-click” property set to True.
move-cursorThe ::move-cursor signal is a keybinding signal which gets emitted when the user initiates a cursor movement.
select-allA keybinding signal which gets emitted when the user selects all items.
select-cursor-itemA keybinding signal which gets emitted when the user selects the item that is currently focused.
selection-changedThe ::selection-changed signal is emitted when the selection (i.e.
toggle-cursor-itemA keybinding signal which gets emitted when the user toggles whether the currently focused item is selected or not.
unselect-allA keybinding signal which gets emitted when the user unselects all items.

例子

这里写图片描述
代码:

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/16
# section 088
TITLE = "IconView"
DESCRIPTION = """
Gtk.IconView provides an alternative view on a Gtk.TreeModel.
It displays the model as a grid of icons with labels. Like Gtk.TreeView
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository.GdkPixbuf import Pixbuf

icons = ["edit-cut", "edit-paste", "edit-copy"]


class IconViewWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_default_size(200, 200)

        liststore = Gtk.ListStore(Pixbuf, str)
        iconview = Gtk.IconView.new()
        iconview.set_model(liststore)
        iconview.set_pixbuf_column(0)
        iconview.set_text_column(1)

        theme = Gtk.IconTheme.get_default()
        # print(theme.get_search_path())
        for icon in icons:
            if theme.has_icon(icon):
                pixbuf = theme.load_icon(icon, 48, 0)
            liststore.append([pixbuf, "Label"])

        self.add(iconview)


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


if __name__ == "__main__":
    main()

代码解析:

liststore = Gtk.ListStore(Pixbuf, str)

创建一个Gtk.ListStore,第一列为图片,第二列为文本

iconview = Gtk.IconView.new()
iconview.set_model(liststore)
iconview.set_pixbuf_column(0)
iconview.set_text_column(1)

创建Gtk.IconView,设置model为ListStore,设置图片列为第一列,文本列为第二列

theme = Gtk.IconTheme.get_default()
        # print(theme.get_search_path())
        for icon in icons:
            if theme.has_icon(icon):
                pixbuf = theme.load_icon(icon, 48, 0)
            liststore.append([pixbuf, "Label"])

填充liststore

这里写图片描述

代码

#!/usr/bin/env python3
# section 089
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri <johnp@redhat.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
# USA

TITLE = "Icon View Basics"
DESCRIPTION = """The GtkIconView widget is used to display and manipulate
icons. It uses a GtkTreeModel for data storage, so the list store example might
be helpful. We also use the Gio.File API to get the icons for each file type.
"""

import os

import gi

gi.require_version('GdkPixbuf', '2.0')
gi.require_version('Gtk', '3.0')

from gi.repository import GLib, Gio, GdkPixbuf, Gtk


class IconViewApp:
    (COL_PATH,
     COL_DISPLAY_NAME,
     COL_PIXBUF,
     COL_IS_DIRECTORY,
     NUM_COLS) = range(5)

    def __init__(self):
        self.pixbuf_lookup = {}

        self.window = Gtk.Window()
        self.window.set_title('Gtk.IconView demo')
        self.window.set_default_size(650, 400)
        self.window.connect('destroy', Gtk.main_quit)

        vbox = Gtk.VBox()
        self.window.add(vbox)

        tool_bar = Gtk.Toolbar()
        vbox.pack_start(tool_bar, False, False, 0)

        up_button = Gtk.ToolButton(stock_id=Gtk.STOCK_GO_UP)
        up_button.set_is_important(True)
        up_button.set_sensitive(False)
        tool_bar.insert(up_button, -1)

        home_button = Gtk.ToolButton(stock_id=Gtk.STOCK_HOME)
        home_button.set_is_important(True)
        tool_bar.insert(home_button, -1)

        sw = Gtk.ScrolledWindow()
        sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        sw.set_policy(Gtk.PolicyType.AUTOMATIC,
                      Gtk.PolicyType.AUTOMATIC)

        vbox.pack_start(sw, True, True, 0)

        # create the store and fill it with content
        self.parent_dir = '/'
        store = self.create_store()
        self.fill_store(store)

        icon_view = Gtk.IconView(model=store)
        icon_view.set_selection_mode(Gtk.SelectionMode.MULTIPLE)
        sw.add(icon_view)

        # connect to the 'clicked' signal of the "Up" tool button
        up_button.connect('clicked', self.up_clicked, store)

        # connect to the 'clicked' signal of the "home" tool button
        home_button.connect('clicked', self.home_clicked, store)

        self.up_button = up_button
        self.home_button = home_button

        # we now set which model columns that correspond to the text
        # and pixbuf of each item
        icon_view.set_text_column(self.COL_DISPLAY_NAME)
        icon_view.set_pixbuf_column(self.COL_PIXBUF)

        # connect to the "item-activated" signal
        icon_view.connect('item-activated', self.item_activated, store)
        icon_view.grab_focus()

        self.window.show_all()

    def sort_func(self, store, a_iter, b_iter, user_data):
        (a_name, a_is_dir) = store.get(a_iter,
                                       self.COL_DISPLAY_NAME,
                                       self.COL_IS_DIRECTORY)

        (b_name, b_is_dir) = store.get(b_iter,
                                       self.COL_DISPLAY_NAME,
                                       self.COL_IS_DIRECTORY)

        if a_name is None:
            a_name = ''

        if b_name is None:
            b_name = ''

        if (not a_is_dir) and b_is_dir:
            return 1
        elif a_is_dir and (not b_is_dir):
            return -1
        elif a_name > b_name:
            return 1
        elif a_name < b_name:
            return -1
        else:
            return 0

    def up_clicked(self, item, store):
        self.parent_dir = os.path.split(self.parent_dir)[0]
        self.fill_store(store)
        # de-sensitize the up button if we are at the root
        self.up_button.set_sensitive(self.parent_dir != '/')

    def home_clicked(self, item, store):
        self.parent_dir = GLib.get_home_dir()
        self.fill_store(store)

        # Sensitize the up button
        self.up_button.set_sensitive(True)

    def item_activated(self, icon_view, tree_path, store):
        iter_ = store.get_iter(tree_path)
        (path, is_dir) = store.get(iter_, self.COL_PATH, self.COL_IS_DIRECTORY)
        if not is_dir:
            return

        self.parent_dir = path
        self.fill_store(store)

        self.up_button.set_sensitive(True)

    def create_store(self):
        store = Gtk.ListStore(str, str, GdkPixbuf.Pixbuf, bool)

        # set sort column and function
        store.set_default_sort_func(self.sort_func)
        store.set_sort_column_id(-1, Gtk.SortType.ASCENDING)

        return store

    def file_to_icon_pixbuf(self, path):
        pixbuf = None

        # get the theme icon
        f = Gio.file_new_for_path(path)
        info = f.query_info(Gio.FILE_ATTRIBUTE_STANDARD_ICON,
                            Gio.FileQueryInfoFlags.NONE,
                            None)
        gicon = info.get_icon()

        # check to see if it is an image format we support
        for format in GdkPixbuf.Pixbuf.get_formats():
            for mime_type in format.get_mime_types():
                content_type = Gio.content_type_from_mime_type(mime_type)
                if content_type is not None:
                    break

            format_gicon = Gio.content_type_get_icon(content_type)
            if format_gicon.equal(gicon):
                #gicon = f.icon_new()
                break

        if gicon in self.pixbuf_lookup:
            return self.pixbuf_lookup[gicon]

        if isinstance(gicon, Gio.ThemedIcon):
            names = gicon.get_names()
            icon_theme = Gtk.IconTheme.get_default()
            for name in names:
                try:
                    pixbuf = icon_theme.load_icon(name, 64, 0)
                    break
                except GLib.GError:
                    pass

            self.pixbuf_lookup[gicon] = pixbuf

        elif isinstance(gicon, Gio.FileIcon):
            icon_file = gicon.get_file()
            path = icon_file.get_path()
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(path, 72, 72)
            self.pixbuf_lookup[gicon] = pixbuf

        return pixbuf

    def fill_store(self, store):
        store.clear()
        for name in os.listdir(self.parent_dir):
            path = os.path.join(self.parent_dir, name)
            is_dir = os.path.isdir(path)
            pixbuf = self.file_to_icon_pixbuf(path)
            store.append((path, name, pixbuf, is_dir))


def main():
    IconViewApp()
    Gtk.main()


if __name__ == '__main__':
    main()

这里写图片描述
代码

#!/usr/bin/env python3
# section 090
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri <johnp@redhat.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
# USA

TITLE = "Editing and Drag-and-Drop"
DESCRIPTION = """The GtkIconView widget supports Editing and Drag-and-Drop.
This example also demonstrates using the generic GtkCellLayout interface to set
up cell renderers in an icon view.
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GdkPixbuf


class IconviewEditApp:
    COL_TEXT = 0
    NUM_COLS = 1

    def __init__(self):
        self.window = Gtk.Window()
        self.window.set_title('Editing and Drag-and-Drop')
        self.window.set_border_width(8)
        self.window.connect('destroy', Gtk.main_quit)

        store = Gtk.ListStore(str)
        colors = ['Red', 'Green', 'Blue', 'Yellow']
        store.clear()
        for c in colors:
            store.append([c])

        icon_view = Gtk.IconView(model=store)
        icon_view.set_selection_mode(Gtk.SelectionMode.SINGLE)
        icon_view.set_item_orientation(Gtk.Orientation.HORIZONTAL)
        icon_view.set_columns(2)
        icon_view.set_reorderable(True)

        renderer = Gtk.CellRendererPixbuf()
        icon_view.pack_start(renderer, True)
        icon_view.set_cell_data_func(renderer,
                                     self.set_cell_color,
                                     None)

        renderer = Gtk.CellRendererText()
        icon_view.pack_start(renderer, True)
        renderer.props.editable = True
        renderer.connect('edited', self.edited, icon_view)
        icon_view.add_attribute(renderer, 'text', self.COL_TEXT)

        self.window.add(icon_view)

        self.window.show_all()

    def set_cell_color(self, cell_layout, cell, tree_model, iter_, icon_view):

        # FIXME return single element instead of tuple
        text = tree_model.get(iter_, self.COL_TEXT)[0]
        color = Gdk.color_parse(text)
        pixel = 0
        if color is not None:
            pixel = ((color.red >> 8) << 24 |
                     (color.green >> 8) << 16 |
                     (color.blue >> 8) << 8)

        pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 24, 24)
        pixbuf.fill(pixel)

        cell.props.pixbuf = pixbuf

    def edited(self, cell, path_string, text, icon_view):
        model = icon_view.get_model()
        path = Gtk.TreePath(path_string)

        iter_ = model.get_iter(path)
        model.set_row(iter_, [text])


def main():
    IconviewEditApp()
    Gtk.main()


if __name__ == '__main__':
    main()




代码下载地址:http://download.csdn.net/detail/a87b01c14/9594728

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

sanxiaochengyu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值