Ejemplo n.º 1
0
class TestSignals(unittest.TestCase):
    def setUp(self):
        self.klist = ObjectList()
        self.klist.connect('has-rows', self._on_klist__has_rows)
        self.klist.connect('selection-changed',
                           self._on_klist__selection_changed)
        self.rows = None
        self.selected = None

    def _on_klist__has_rows(self, klist, rows):
        self.rows = rows

    def _on_klist__selection_changed(self, klist, selected):
        self.selected = selected

    def testHasRows(self):
        self.assertEqual(self.rows, None)
        self.assertEqual(len(self.klist), 0)

        # Add one
        self.klist.append(0)
        self.assertEqual(len(self.klist), 1)
        self.assertEqual(self.rows, True)
        self.klist.remove(0)
        self.assertEqual(self.rows, False)
        self.assertEqual(len(self.klist), 0)

        # Add several
        self.klist.extend((1, 2))
        self.assertEqual(len(self.klist), 2)
        self.assertEqual(self.rows, True)
        self.klist.remove(1)
        self.assertEqual(self.rows, True)
        self.klist.remove(2)
        self.assertEqual(self.rows, False)
        self.assertEqual(len(self.klist), 0)

    def testSelectionChanged(self):
        self.assertEqual(self.selected, None)
        self.assertEqual(len(self.klist), 0)
        self.klist.extend((0, 1))
        self.klist.select(0)
        self.assertEqual(self.selected, 0)
        self.klist.unselect_all()
        self.assertEqual(self.selected, None)
        self.assertRaises(ValueError, self.klist.select, 2)
Ejemplo n.º 2
0
class TestSignals(unittest.TestCase):
    def setUp(self):
        self.klist = ObjectList()
        self.klist.connect('has-rows', self._on_klist__has_rows)
        self.klist.connect('selection-changed',
                           self._on_klist__selection_changed)
        self.rows = None
        self.selected = None

    def _on_klist__has_rows(self, klist, rows):
        self.rows = rows

    def _on_klist__selection_changed(self, klist, selected):
        self.selected = selected

    def testHasRows(self):
        self.assertEqual(self.rows, None)
        self.assertEqual(len(self.klist), 0)

        # Add one
        self.klist.append(0)
        self.assertEqual(len(self.klist), 1)
        self.assertEqual(self.rows, True)
        self.klist.remove(0)
        self.assertEqual(self.rows, False)
        self.assertEqual(len(self.klist), 0)

        # Add several
        self.klist.extend((1, 2))
        self.assertEqual(len(self.klist), 2)
        self.assertEqual(self.rows, True)
        self.klist.remove(1)
        self.assertEqual(self.rows, True)
        self.klist.remove(2)
        self.assertEqual(self.rows, False)
        self.assertEqual(len(self.klist), 0)

    def testSelectionChanged(self):
        self.assertEqual(self.selected, None)
        self.assertEqual(len(self.klist), 0)
        self.klist.extend((0, 1))
        self.klist.select(0)
        self.assertEqual(self.selected, 0)
        self.klist.unselect_all()
        self.assertEqual(self.selected, None)
        self.assertRaises(ValueError, self.klist.select, 2)
Ejemplo n.º 3
0
class ListContainer(gtk.HBox):
    """A ListContainer is an L{ObjectList} with buttons to be able
    to modify the content of the list.
    Depending on the list_mode, @see L{set_list_mode} you will
    have add, remove and edit buttons.

    Signals
    =======
      - B{add-item} (returns item):
        - emitted when the add button is clicked, you're expected to
          return an object here
      - B{remove-item} (item, returns bool):
        - emitted when removing an item,
          you can block the removal from the list by returning False
      - B{edit-item} (item):
        - emitted when editing an item
          you can block the update afterwards by returning False

    @ivar add_button: add button
    @type add_button: L{gtk.Button}
    @ivar remove_button: remove button
    @type remove_button: L{gtk.Button}
    @ivar edit_button: edit button
    @type edit_button: L{gtk.Button}
    """

    gsignal('add-item', retval=object)
    gsignal('remove-item', object, retval=bool)
    gsignal('edit-item', object, retval=bool)
    gsignal('selection-changed', object)

    def __init__(self, columns, orientation=gtk.ORIENTATION_VERTICAL):
        """
        Create a new ListContainer object.
        @param columns: columns for the L{kiwi.ui.objectlist.ObjectList}
        @type columns: a list of L{kiwi.ui.objectlist.Columns}
        @param orientation: the position where the buttons will be
            placed: at the right (vertically) or at the bottom (horizontally)
            of the list. Defaults to the right of the list.
        @type: gtk.ORIENTATION_HORIZONTAL or gtk.ORIENTATION_VERTICAL
        """
        self._list_type = None

        gtk.HBox.__init__(self)

        self._orientation = orientation

        self._create_ui(columns)
        self.set_list_type(ListType.NORMAL)

    # Private API

    def _create_ui(self, columns):
        self.list = ObjectList(columns)
        self.list.connect('selection-changed',
                          self._on_list__selection_changed)
        self.list.connect('row-activated', self._on_list__row_activated)

        self.add_button = gtk.Button(stock=gtk.STOCK_ADD)
        self.add_button.connect('clicked', self._on_add_button__clicked)

        self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE)
        self.remove_button.set_sensitive(False)
        self.remove_button.connect('clicked', self._on_remove_button__clicked)

        self.edit_button = gtk.Button(stock=gtk.STOCK_EDIT)
        self.edit_button.set_sensitive(False)
        self.edit_button.connect('clicked', self._on_edit_button__clicked)

        self._vbox = gtk.VBox(spacing=6)

        if self._orientation == gtk.ORIENTATION_VERTICAL:
            self.pack_start(self.list)
            self.list.show()
            self._add_buttons_to_box(self._vbox)
            self._pack_vbox()
        elif self._orientation == gtk.ORIENTATION_HORIZONTAL:
            self._vbox.pack_start(self.list)
            self.list.show()
            hbox = gtk.HBox(spacing=6)
            self._add_buttons_to_box(hbox)
            self._vbox.pack_start(hbox, expand=False)
            hbox.show()
            self._pack_vbox()
        else:
            raise TypeError(
                "buttons_orientation must be gtk.ORIENTATION_VERTICAL "
                " or gtk.ORIENTATION_HORIZONTAL")

    def _add_buttons_to_box(self, box):
        box.pack_start(self.add_button, expand=False)
        box.pack_start(self.remove_button, expand=False)
        box.pack_start(self.edit_button, expand=False)

    def _pack_vbox(self):
        self.pack_start(self._vbox, expand=False, padding=6)
        self._vbox.show()

    def _set_child_packing(self, padding):
        expand = self._orientation == gtk.ORIENTATION_HORIZONTAL

        self.set_child_packing(self._vbox, expand, True, padding,
                               gtk.PACK_START)

    def _add_item(self):
        retval = self.emit('add-item')
        if retval is None:
            return
        elif isinstance(retval, NotImplementedError):
            raise retval

        self.list.append(retval)

    def _remove_item(self, item):
        retval = self.emit('remove-item', item)
        if retval:
            self.list.remove(item)

    def _edit_item(self, item):
        retval = self.emit('edit-item', item)
        if retval:
            self.list.update(item)

    # Public API

    def add_item(self, item):
        """Appends an item to the list
        @param item: item to append
        """
        self.list.append(item)

    def add_items(self, items):
        """Appends a list of items to the list
        @param items: items to add
        @type items: a sequence of items
        """
        self.list.extend(items)

    def remove_item(self, item):
        """Removes an item from the list
        @param item: item to remove
        """
        self.list.remove(item)

    def update_item(self, item):
        """Updates an item in the list.
        You should call this if you change the object
        @param item: item to update
        """
        self.list.update(item)

    def default_remove(self, item):
        """Asks the user confirmation for removal of an item.
        @param item: a description of the item that will be removed
        @returns: True if the user confirm the removal, False otherwise
        """
        response = yesno(_('Do you want to remove %s ?') %
                         (quote(str(item)), ),
                         parent=None,
                         default=gtk.RESPONSE_OK,
                         buttons=((gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
                                  (gtk.STOCK_REMOVE, gtk.RESPONSE_OK)))
        return response == gtk.RESPONSE_OK

    def set_list_type(self, list_type):
        """Sets the kind of list type.
        @param list_type:
        """
        if not isinstance(list_type, ListType):
            raise TypeError("list_type must be a ListType enum")

        self.add_button.set_property('visible',
                                     (list_type != ListType.READONLY
                                      and list_type != ListType.REMOVEONLY
                                      and list_type != ListType.UNADDABLE))
        self.remove_button.set_property(
            'visible', (list_type != ListType.READONLY
                        and list_type != ListType.UNREMOVABLE))
        self.edit_button.set_property('visible',
                                      (list_type != ListType.READONLY
                                       and list_type != ListType.UNEDITABLE
                                       and list_type != ListType.REMOVEONLY))
        if list_type in [ListType.READONLY, ListType.REMOVEONLY]:
            padding = 0
        else:
            padding = 6
        self._set_child_packing(padding)
        self._list_type = list_type

    def clear(self):
        """Removes all the items in the list"""
        self.list.clear()

    # Callbacks

    def _on_list__selection_changed(self, list, selection):
        object_selected = selection is not None
        self.remove_button.set_sensitive(object_selected)
        self.edit_button.set_sensitive(object_selected)
        self.emit('selection-changed', selection)

    def _on_list__row_activated(self, list, item):
        if (self._list_type != ListType.READONLY
                and self._list_type != ListType.UNEDITABLE):
            self._edit_item(item)

    def _on_add_button__clicked(self, button):
        self._add_item()

    def _on_remove_button__clicked(self, button):
        self._remove_item(self.list.get_selected())

    def _on_edit_button__clicked(self, button):
        self._edit_item(self.list.get_selected())
Ejemplo n.º 4
0
        Product('Bubble gum', '0.3'),
        Product('Tutti-frutti', '1.50')
        )

win = gtk.Window()
win.connect('destroy', gtk.main_quit)
win.set_border_width(6)
win.set_size_request(650, 300)

vbox = gtk.VBox()
win.add(vbox)


def entry_activate_cb(entry):
    text = entry.get_text()
    products = [product for product in data
                if text.lower() in product.name.lower()]
    l.add_list(products)

entry = gtk.Entry()
entry.connect('activate', entry_activate_cb)
vbox.pack_start(entry, False, False, 6)

l = ObjectList(columns)
l.extend(data)
vbox.pack_start(l)

win.show_all()

gtk.main()
Ejemplo n.º 5
0
class ListContainer(gtk.HBox):
    """A ListContainer is an L{ObjectList} with buttons to be able
    to modify the content of the list.
    Depending on the list_mode, @see L{set_list_mode} you will
    have add, remove and edit buttons.

    Signals
    =======
      - B{add-item} (returns item):
        - emitted when the add button is clicked, you're expected to
          return an object here
      - B{remove-item} (item, returns bool):
        - emitted when removing an item,
          you can block the removal from the list by returning False
      - B{edit-item} (item):
        - emitted when editing an item
          you can block the update afterwards by returning False

    @ivar add_button: add button
    @type add_button: L{gtk.Button}
    @ivar remove_button: remove button
    @type remove_button: L{gtk.Button}
    @ivar edit_button: edit button
    @type edit_button: L{gtk.Button}
    """

    gsignal('add-item', retval=object)
    gsignal('remove-item', object, retval=bool)
    gsignal('edit-item', object, retval=bool)
    gsignal('selection-changed', object)

    def __init__(self, columns, orientation=gtk.ORIENTATION_VERTICAL):
        """
        Create a new ListContainer object.
        @param columns: columns for the L{kiwi.ui.objectlist.ObjectList}
        @type columns: a list of L{kiwi.ui.objectlist.Columns}
        @param orientation: the position where the buttons will be
            placed: at the right (vertically) or at the bottom (horizontally)
            of the list. Defaults to the right of the list.
        @type: gtk.ORIENTATION_HORIZONTAL or gtk.ORIENTATION_VERTICAL
        """
        self._list_type = None

        gtk.HBox.__init__(self)

        self._orientation = orientation

        self._create_ui(columns)
        self.set_list_type(ListType.NORMAL)

    # Private API

    def _create_ui(self, columns):
        self.list = ObjectList(columns)
        self.list.connect('selection-changed',
                          self._on_list__selection_changed)
        self.list.connect('row-activated',
                          self._on_list__row_activated)

        self.add_button = gtk.Button(stock=gtk.STOCK_ADD)
        self.add_button.connect('clicked', self._on_add_button__clicked)

        self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE)
        self.remove_button.set_sensitive(False)
        self.remove_button.connect('clicked', self._on_remove_button__clicked)

        self.edit_button = gtk.Button(stock=gtk.STOCK_EDIT)
        self.edit_button.set_sensitive(False)
        self.edit_button.connect('clicked', self._on_edit_button__clicked)

        self._vbox = gtk.VBox(spacing=6)

        if self._orientation == gtk.ORIENTATION_VERTICAL:
            self.pack_start(self.list)
            self.list.show()
            self._add_buttons_to_box(self._vbox)
            self._pack_vbox()
        elif self._orientation == gtk.ORIENTATION_HORIZONTAL:
            self._vbox.pack_start(self.list)
            self.list.show()
            hbox = gtk.HBox(spacing=6)
            self._add_buttons_to_box(hbox)
            self._vbox.pack_start(hbox, expand=False)
            hbox.show()
            self._pack_vbox()
        else:
            raise TypeError(
                "buttons_orientation must be gtk.ORIENTATION_VERTICAL "
                " or gtk.ORIENTATION_HORIZONTAL")

    def _add_buttons_to_box(self, box):
        box.pack_start(self.add_button, expand=False)
        box.pack_start(self.remove_button, expand=False)
        box.pack_start(self.edit_button, expand=False)

    def _pack_vbox(self):
        self.pack_start(self._vbox, expand=False, padding=6)
        self._vbox.show()

    def _set_child_packing(self, padding):
        expand = self._orientation == gtk.ORIENTATION_HORIZONTAL

        self.set_child_packing(self._vbox, expand, True, padding,
                               gtk.PACK_START)

    def _add_item(self):
        retval = self.emit('add-item')
        if retval is None:
            return
        elif isinstance(retval, NotImplementedError):
            raise retval

        self.list.append(retval)

    def _remove_item(self, item):
        retval = self.emit('remove-item', item)
        if retval:
            self.list.remove(item)

    def _edit_item(self, item):
        retval = self.emit('edit-item', item)
        if retval:
            self.list.update(item)

    # Public API

    def add_item(self, item):
        """Appends an item to the list
        @param item: item to append
        """
        self.list.append(item)

    def add_items(self, items):
        """Appends a list of items to the list
        @param items: items to add
        @type items: a sequence of items
        """
        self.list.extend(items)

    def remove_item(self, item):
        """Removes an item from the list
        @param item: item to remove
        """
        self.list.remove(item)

    def update_item(self, item):
        """Updates an item in the list.
        You should call this if you change the object
        @param item: item to update
        """
        self.list.update(item)

    def default_remove(self, item):
        """Asks the user confirmation for removal of an item.
        @param item: a description of the item that will be removed
        @returns: True if the user confirm the removal, False otherwise
        """
        response = yesno(_('Do you want to remove %s ?') % (quote(str(item)),),
                         parent=None,
                         default=gtk.RESPONSE_OK,
                         buttons=((gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
                                  (gtk.STOCK_REMOVE, gtk.RESPONSE_OK)))
        return response == gtk.RESPONSE_OK

    def set_list_type(self, list_type):
        """Sets the kind of list type.
        @param list_type:
        """
        if not isinstance(list_type, ListType):
            raise TypeError("list_type must be a ListType enum")

        self.add_button.set_property(
            'visible',
            (list_type != ListType.READONLY and
             list_type != ListType.REMOVEONLY and
             list_type != ListType.UNADDABLE))
        self.remove_button.set_property(
            'visible',
            (list_type != ListType.READONLY and
             list_type != ListType.UNREMOVABLE))
        self.edit_button.set_property(
            'visible',
            (list_type != ListType.READONLY and
             list_type != ListType.UNEDITABLE and
             list_type != ListType.REMOVEONLY))
        if list_type in [ListType.READONLY, ListType.REMOVEONLY]:
            padding = 0
        else:
            padding = 6
        self._set_child_packing(padding)
        self._list_type = list_type

    def clear(self):
        """Removes all the items in the list"""
        self.list.clear()

    # Callbacks

    def _on_list__selection_changed(self, list, selection):
        object_selected = selection is not None
        self.remove_button.set_sensitive(object_selected)
        self.edit_button.set_sensitive(object_selected)
        self.emit('selection-changed', selection)

    def _on_list__row_activated(self, list, item):
        if (self._list_type != ListType.READONLY and
            self._list_type != ListType.UNEDITABLE):
            self._edit_item(item)

    def _on_add_button__clicked(self, button):
        self._add_item()

    def _on_remove_button__clicked(self, button):
        self._remove_item(self.list.get_selected())

    def _on_edit_button__clicked(self, button):
        self._edit_item(self.list.get_selected())
Ejemplo n.º 6
0
        Product('Bubble gum', '0.3'), Product('Tutti-frutti', '1.50'))

win = Gtk.Window()
win.connect('destroy', Gtk.main_quit)
win.set_border_width(6)
win.set_size_request(650, 300)

vbox = Gtk.VBox()
win.add(vbox)


def entry_activate_cb(entry):
    text = entry.get_text()
    products = [
        product for product in data if text.lower() in product.name.lower()
    ]
    l.add_list(products)


entry = Gtk.Entry()
entry.connect('activate', entry_activate_cb)
vbox.pack_start(entry, False, False, 6)

l = ObjectList(columns)
l.extend(data)
vbox.pack_start(l, True, True, 0)

win.show_all()

Gtk.main()
Ejemplo n.º 7
0
class ListDialog:
    """ Diálogo de edição de uma tabela com botões padrão e uma lista de campos. """
    def __init__(self, controle, tabela, titulo):
        """ controle é um objeto da classe Controle.
            tabela é o nome de uma instancia de Classe no Controle que referencia um tabela no Modelo.
            titulo é nome de leitura da tabela sendo editada (ex. 'Categorias') """
        self.controle = controle
        self.tabela = tabela
        self.data = []
        self.buttons = []
        self.new_method = self.create_new_record
        self.save_method = self.salvar
        self.populate_method = self.populate
        self.titulo = titulo or self.tabela.nome_tabela
        self.edit_mode = False
        self.editing_new = False
        self.editing = False
        self.selection = None
        self.do_nothing = False

    def make_widget(self, fields, custom_buttons = []):
        """ Cria e retorna o widget que contém o toolbar, a lista e os campos para edição.
            fields é uma lista de FieldType.
            custom_buttons é uma lista de ListToolButton que substitui os botões padrão. """
#-------Campos
        self.fields = []
        
        for field in fields:
            if field.show_field:
                field.label = gtk.Label(field.titulo + ":")
                if field.tabelacombo:
                    field.entry = ComboEntry()
                    tabelacombo = getattr(self.controle, field.tabelacombo)
                    itens = tabelacombo.combo()
                    field.entry.prefill(itens)
                else:
                    field.entry = ProxyEntry(field.tipo)
                    field.entry.set_mask(field.mask)
            self.fields.append(field)
        
        vbox_main = gtk.VBox()
        hbox_topo = gtk.HBox()
        
        self.widget = gtk.EventBox()
#-------Toolbar
        toolbar = gtk.Toolbar()
        toolbar.set_orientation(gtk.ORIENTATION_VERTICAL)
        toolbar.set_style(gtk.TOOLBAR_BOTH)
        
        if not custom_buttons:
            self.tb_novo = ListToolButton(self.default_new, gtk.STOCK_NEW)
            self.tb_edit = ListToolButton(self.default_edit, gtk.STOCK_EDIT)
            self.custom_buttons = [self.tb_novo, self.tb_edit]
        else:
            self.custom_buttons = custom_buttons 

        for tool_button in self.custom_buttons:
            toolbar.insert(tool_button.button, -1)
        
#-------Lista
        vbox_lista = gtk.VBox()
        hbox_entry = gtk.HBox()
        
        self.entry_localizar = gtk.Entry()
        self.entry_localizar.connect('activate', self.localizar)
        label = gtk.Label('Localizar')
        
        frame_lista = gtk.Frame(self.titulo)
        self.listview = self.create_list()
        self.listview.connect("row_activated", self.on_row_activated)
        self.listview.connect('selection-changed',self.on_selection_changed)
        
#-------Frame
        frame_dados = gtk.Frame("Informações")
        hbox_dados = gtk.HBox(False, 6)
        vbox_label = gtk.VBox(True, 4)
        vbox_entry = gtk.VBox(True, 4)
         
        for field in self.fields:
            if field.show_field:
                vbox_label.pack_start(field.label, False, True, 8)
                vbox_entry.pack_start(field.entry, False, True, 8)
        
        #Botões
        self.button_save = gtk.Button(stock=gtk.STOCK_SAVE)
        self.button_save.connect("clicked", self.save_method)
        self.button_cancel = gtk.Button(stock=gtk.STOCK_CANCEL)
        self.button_cancel.connect("clicked", self.cancel)
        
        vbox_dados_buttons = gtk.VButtonBox()
        vbox_dados_buttons.set_layout(gtk.BUTTONBOX_SPREAD)
        vbox_dados_buttons.add(self.button_save)
        vbox_dados_buttons.add(self.button_cancel)
        
#-------Notify
        self.notify = self.controle.notify()
        self.notify_box = self.notify.get_widget()
        self.notify.show_notify('info','Clique em NOVO para adicionar um novo item')
        self.tabela.set_notify(self.notify)

#-------Posicionar todos
        frame_lista.add(self.listview)
        vbox_lista.pack_start(hbox_entry, False, False, 2)
        vbox_lista.pack_start(frame_lista, True, True, 2)
        hbox_entry.pack_end(self.entry_localizar, False, False, 2)
        hbox_entry.pack_end(label, False, False, 2)
        hbox_topo.pack_start(toolbar, False, False, 5)
        hbox_topo.pack_start(vbox_lista, True, True, 2)
        hbox_dados.pack_start(vbox_label, False, False, 2)
        hbox_dados.pack_start(vbox_entry, True, True, 2)
        hbox_dados.pack_start(vbox_dados_buttons, False, False, 2)
        frame_dados.add(hbox_dados)
        vbox_main.pack_start(hbox_topo, True, True, 2)
        vbox_main.pack_start(frame_dados, False, False, 2)
        vbox_main.pack_start(self.notify_box, False, True, 2)
        self.widget.add(vbox_main)
        
        self.set_edit_mode(False)
        return self.widget

    def create_list(self):
        columns = []
        for field in self.fields:
            if field.show_in_list:
                columns.append(Column(field.field_name, data_type = field.tipo, title = field.titulo))
        self.lista = ObjectList(columns)
        self.data = self.populate_method()
        self.lista.extend(self.data)
        return self.lista

    def localizar(self, entry):
        text = self.entry_localizar.get_text().lower()
        searches = text.split(" ")
        if not searches: #lista vazia
            lista = self.data
        else:
            lista = []
            for item in self.data:
                itemtext = ""
                #reúne o texto inteiro do item (separado por espaço):
                for field in self.fields:
                    if field.searchable:
                        itemtext += str(getattr(item, field.field_name)).lower() + " "
                contain_all = True
                for searchtext in searches:
                    if searchtext not in itemtext:
                        contain_all = False
                if contain_all:
                    lista.append(item)
        self.lista.add_list(lista)

    def set_edit_mode(self, edit_mode):
        """ Coloca ou tira os campos em modo de edição. """
        for field in self.fields:
            if field.entry:
                field.entry.set_sensitive(edit_mode)
        
        for tool_button in self.custom_buttons:
            tool_button.button.set_sensitive(not edit_mode)
        
        self.entry_localizar.set_sensitive(not edit_mode)
        self.button_save.set_sensitive(edit_mode)
        self.button_cancel.set_sensitive(edit_mode)
        self.editing = edit_mode
        
    def cancel(self, widget):
        """Cancela a edição de um item"""
        self.set_edit_mode(False)
        self.clear_entry()
        self.lista.refresh()
        if self.editing_new:
            self.lista.remove(self.newobj)
            self.editing_new = False
            
        self.notify.show_notify('info','Clique em NOVO para adicionar um novo item')
            
    def create_new_record(self):
        """Adiciona um item padrão a lista para depois ser editado"""
        self.notify.hide()
        obj = ListItem()
        for field in self.fields:
            if field.tipo == str or field.tabelacombo:
                setattr(obj, field.field_name, '')
            else:
                setattr(obj, field.field_name, converter.from_string(field.tipo, '0'))
        return obj

    def populate(self):
        """Popula a lista com os itens"""
        itens = self.tabela.listar()
        objetos = []
        for item in itens:
            obj = ListItem()
            for field in self.fields:
                if not field.tabelacombo:
                    setattr(obj, field.field_name, item[field.field_name])
                else:
                    tabelacombo = getattr(self.controle, field.tabelacombo)
                    descricao = tabelacombo.item_descricao(item[field.field_name])
                    try:
                        setattr(obj, field.field_name, descricao[0][0])
                    except:
                        setattr(obj, field.field_name, descricao)
            objetos.append(obj)
        return objetos
        
    def default_new(self, sender):
        self.newobj = self.new_method() #Chama new_method para criar um novo item
        self.data.append(self.newobj)
        self.listview.append(self.newobj)
        self.listview.refresh()
        self.listview.select(self.newobj)
        self.set_edit_mode(True)
        self.editing_new = True
        self.item = self.selection
        
    def default_edit(self, sender):
        if self.selection:
            self.populate_entry(self.selection)
            self.set_edit_mode(True)
            self.item = self.selection
        
    def on_row_activated(self, list, item):
        """Preenche os campos com os valores da coluna clicada e coloca em modo de edição"""
        self.item = item
        self.populate_entry(item)
        
    def populate_entry(self, item):
        """Preenche os campos com os itens"""
        self.notify.hide()
        for field in self.fields:
            if field.entry:
                if field.tabelacombo:
                    field.entry.select_item_by_label(str(getattr(item, field.field_name)))
                else:
                    field.entry.set_text(str(getattr(item, field.field_name)))
        self.set_edit_mode(True)
        
    def clear_entry(self):
        """Limpa os campos apos edicao ou cancelar"""
        for field in self.fields:
            if field.entry:
                field.entry.set_text('')
        self.set_edit_mode(False)
        
    def on_selection_changed(self, list, selection):
        """Verifica se o usuario editou os campos e não salvou"""
        if self.do_nothing:
            self.do_nothing = False
            return
            
        self.selection = selection
        response = False
        if self.editing == True:
            for field in self.fields:
                if field.entry:
                    if not field.identificador:
                        user_edited = field.entry.get_text()
                        
                        #Se for um novo item
                        if self.editing_new == True:
                            if user_edited:
                                response = self.ask_to_save(field)
                                if response == True:
                                    self.salvar(None)
                                else:
                                    self.cancel(None)
                            else:
                                if response:
                                        self.do_nothing = True
                                        self.listview.select(self.item)
                                else:
                                    self.cancel(None)

                        #Se editando item da lista
                        elif self.editing == True:
                            field_in_list = (str(getattr(self.item, field.field_name)))
                            if user_edited != field_in_list:
                                response = self.ask_to_save(field)
                                if response == True:
                                    self.salvar(None)
                                else:
                                    self.cancel(None)
                            else:
                                if response:
                                        self.do_nothing = True
                                        self.listview.select(self.item)
        
    def ask_to_save(self, field):
        """Pergunta ao usuario sobre a edicao de campos"""
        #Criando um novo
        if self.editing_new : 
            question =str('Deseja salvar %s ?')
            for field in self.fields:
                if field.searchable:
                    registro = quote(str(field.entry.get_text()))
        #Editando
        else:
            question =str('Deseja salvar alterações em %s ?')
            registro = quote(str(getattr(self.item, field.field_name)))
            
        response = yesno((question) % (registro,),
                         parent=None,
                         default=gtk.RESPONSE_OK,
                         buttons=((gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
                                  (gtk.STOCK_SAVE, gtk.RESPONSE_OK)))
        return response == gtk.RESPONSE_OK
        
    def salvar(self, widget):
        """Insere ou edita um registro na tabela"""
        record = {}
        #Insere novo
        if self.editing_new :
            record = self.tabela.insert(self.fields)
            if record :
                for field in self.fields:
                    if field.identificador:
                        setattr(self.newobj, field.field_name, record['last_id'])
                    elif field.tabelacombo:
                        tabelacombo = getattr(self.controle, field.tabelacombo)
                        descricao = tabelacombo.item_descricao(record[field.field_name])
                        setattr(self.newobj, field.field_name, descricao[0][0])
                    else:
                        setattr(self.newobj, field.field_name, record[field.field_name])
                self.editing_new = False
                self.lista.refresh()
                self.clear_entry()
                self.hide_notify()
         #Edita
        else:
            record = self.tabela.update(self.fields, self.item)
            if record:
                for field in self.fields:
                    if field.identificador:
                        pass
                    elif field.tabelacombo:
                        tabelacombo = getattr(self.controle, field.tabelacombo)
                        descricao = tabelacombo.item_descricao(record[field.field_name])
                        try:
                            setattr(self.item, field.field_name, descricao[0][0])
                        except:
                            setattr(self.item, field.field_name, descricao)
                    else:
                        setattr(self.item, field.field_name, record[field.field_name])
                self.lista.refresh()
                self.clear_entry()
                self.hide_notify()
        
    def hide_notify(self):
        self.notify.hide()
Ejemplo n.º 8
0
class ListContainer(Gtk.Box):
    """A ListContainer is an :class:`ObjectList` with buttons to be able
    to modify the content of the list.
    Depending on the list_mode, @see :class:`set_list_mode` you will
    have add, remove and edit buttons.

    Signals
    =======
      - B{add-item} (returns item):
        - emitted when the add button is clicked, you're expected to
          return an object here
      - B{remove-item} (item, returns bool):
        - emitted when removing an item,
          you can block the removal from the list by returning False
      - B{edit-item} (item):
        - emitted when editing an item
          you can block the update afterwards by returning False

    :ivar add_button: add button
    :type add_button: :class:`Gtk.Button`
    :ivar remove_button: remove button
    :type remove_button: :class:`Gtk.Button`
    :ivar edit_button: edit button
    :type edit_button: :class:`Gtk.Button`
    """

    __gtype_name__ = 'ListContainer'
    gsignal('add-item', retval=object)
    gsignal('remove-item', object, retval=bool)
    gsignal('edit-item', object, retval=bool)
    gsignal('selection-changed', object)

    def __init__(self, columns, orientation=Gtk.Orientation.VERTICAL):
        """
        Create a new ListContainer object.
        :param columns: columns for the :class:`kiwi.ui.objectlist.ObjectList`
        :type columns: a list of :class:`kiwi.ui.objectlist.Columns`
        :param orientation: the position where the buttons will be
            placed: at the right (vertically) or at the bottom (horizontally)
            of the list. Defaults to the right of the list.
        :type: Gtk.Orientation.HORIZONTAL or Gtk.Orientation.VERTICAL
        """
        self._list_type = None

        super(ListContainer, self).__init__(orientation=Gtk.Orientation.HORIZONTAL)

        self._orientation = orientation

        self._create_ui(columns)
        self.set_list_type(ListType.NORMAL)

    # Private API

    def _create_ui(self, columns):
        self.list = ObjectList(columns)
        self.list.connect('selection-changed',
                          self._on_list__selection_changed)
        self.list.connect('row-activated',
                          self._on_list__row_activated)

        self.add_button = Gtk.Button(stock=Gtk.STOCK_ADD)
        self.add_button.connect('clicked', self._on_add_button__clicked)

        self.remove_button = Gtk.Button(stock=Gtk.STOCK_REMOVE)
        self.remove_button.set_sensitive(False)
        self.remove_button.connect('clicked', self._on_remove_button__clicked)

        self.edit_button = Gtk.Button(stock=Gtk.STOCK_EDIT)
        self.edit_button.set_sensitive(False)
        self.edit_button.connect('clicked', self._on_edit_button__clicked)

        self._vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        if self._orientation == Gtk.Orientation.VERTICAL:
            self.pack_start(self.list, True, True, 0)
            self.list.show()
            self._add_buttons_to_box(self._vbox)
            self._pack_vbox()
        elif self._orientation == Gtk.Orientation.HORIZONTAL:
            self._vbox.pack_start(self.list, True, True, 0)
            self.list.show()
            hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
            self._add_buttons_to_box(hbox)
            self._vbox.pack_start(hbox, False, True, 0)
            hbox.show()
            self._pack_vbox()
        else:
            raise TypeError(
                "buttons_orientation must be Gtk.Orientation.VERTICAL "
                " or Gtk.Orientation.HORIZONTAL")

    def _add_buttons_to_box(self, box):
        box.pack_start(self.add_button, False, True, 0)
        box.pack_start(self.remove_button, False, True, 0)
        box.pack_start(self.edit_button, False, True, 0)

    def _pack_vbox(self):
        self.pack_start(self._vbox, False, True, 6)
        self._vbox.show()

    def _set_child_packing(self, padding):
        expand = self._orientation == Gtk.Orientation.HORIZONTAL

        self.set_child_packing(self._vbox, expand, True, padding,
                               Gtk.PackType.START)

    def _add_item(self):
        retval = self.emit('add-item')
        if retval is None:
            return
        elif isinstance(retval, NotImplementedError):
            raise retval

        self.list.append(retval)
        self.list.refresh()

    def _remove_item(self, item):
        retval = self.emit('remove-item', item)
        if retval:
            self.list.remove(item)

    def _edit_item(self, item):
        retval = self.emit('edit-item', item)
        if retval:
            self.list.update(item)

    # Public API

    def add_item(self, item):
        """Appends an item to the list
        :param item: item to append
        """
        self.list.append(item)

    def add_items(self, items):
        """Appends a list of items to the list
        :param items: items to add
        :type items: a sequence of items
        """
        self.list.extend(items)

    def remove_item(self, item):
        """Removes an item from the list
        :param item: item to remove
        """
        self.list.remove(item)

    def update_item(self, item):
        """Updates an item in the list.
        You should call this if you change the object
        :param item: item to update
        """
        self.list.update(item)

    def default_remove(self, item):
        """Asks the user confirmation for removal of an item.
        :param item: a description of the item that will be removed
        :returns: True if the user confirm the removal, False otherwise
        """
        response = yesno(_('Do you want to remove %s ?') %
                        (GLib.markup_escape_text(str(item)),),
                         parent=None,
                         default=Gtk.ResponseType.OK,
                         buttons=((Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL),
                                  (Gtk.STOCK_REMOVE, Gtk.ResponseType.OK)))
        return response == Gtk.ResponseType.OK

    def set_list_type(self, list_type):
        """Sets the kind of list type.
        :param list_type:
        """
        if not isinstance(list_type, ListType):
            raise TypeError("list_type must be a ListType enum")

        self.add_button.set_property(
            'visible',
            list_type not in [ListType.READONLY, ListType.REMOVEONLY,
                              ListType.UNADDABLE])
        self.remove_button.set_property(
            'visible',
            list_type not in [ListType.READONLY, ListType.ADDONLY,
                              ListType.UNREMOVABLE])
        self.edit_button.set_property(
            'visible',
            list_type not in [ListType.READONLY, ListType.ADDONLY,
                              ListType.UNEDITABLE, ListType.REMOVEONLY])
        if list_type in [ListType.READONLY, ListType.REMOVEONLY]:
            padding = 0
        else:
            padding = 6
        self._set_child_packing(padding)
        self._list_type = list_type

    def clear(self):
        """Removes all the items in the list"""
        self.list.clear()

    # Callbacks

    def _on_list__selection_changed(self, list, selection):
        object_selected = selection is not None
        self.remove_button.set_sensitive(object_selected)
        self.edit_button.set_sensitive(object_selected)
        self.emit('selection-changed', selection)

    def _on_list__row_activated(self, list, item):
        if self._list_type not in [ListType.READONLY, ListType.ADDONLY,
                                   ListType.UNEDITABLE]:
            self._edit_item(item)

    def _on_add_button__clicked(self, button):
        self._add_item()

    def _on_remove_button__clicked(self, button):
        self._remove_item(self.list.get_selected())

    def _on_edit_button__clicked(self, button):
        self._edit_item(self.list.get_selected())
Ejemplo n.º 9
0
class Devolver:
    class Dvd:
        def __init__(self, cod, title, valor, check=False):
            self.check = check
            self.cod = cod
            self.title = title
            self.valor = currency(valor)

        def __repr__(self):
            return "<Titulo %s>" % self.title

    def popular_lista_dvds_devolucao(self, widget):
        cod = self.entry_cod_dvd.get_text()
        try:
            dvds = self.controle.listar_dvds_locados(cod, self.data)
        except:
            pass
        status = self.controle.notify()
        if status == True:
            listado = self.controle.dvd_listado_check()
            if listado == False:
                cod_cliente = self.controle.cliente_devolucao()
                cliente = self.controle.listar_cliente(cod_cliente)
                self.entry_cod_cliente.set_text(str(cod_cliente))
                self.entry_nome_cliente.set_text(cliente[0][1])

                for dvd in dvds:
                    codigo = dvd[0]
                    titulo = dvd[1]
                    valor = dvd[2]
                    if codigo == int(cod):
                        self.data.append(Devolver.Dvd(codigo, titulo, valor, True))
                    else:
                        self.data.append(Devolver.Dvd(codigo, titulo, valor))
                self.lista.extend(self.data)
                atributo = "check"
                self.lista.emit("cell-edited", self.lista, atributo)
            else:
                self.lista.refresh(False)
            # self.notify_box.hide()
        else:
            pass
            # self.notify_box.show()
        self.entry_cod_dvd.set_text("")
        self.entry_cod_dvd.grab_focus()

    def set_controle(self, controle):
        self.controle = controle

    def close(self, w):
        self.controle.main_status = False
        self.w_devolver.destroy()

    def receber(self, widget):
        itens = self.controle.receber_devolucao(self.lista)
        Receber(self.controle, self.w_devolver, itens)

    def cadastra(self, widget, focus):
        recebido = self.controle.get_receber_status()
        if recebido == True:
            self.controle.set_receber_status(False)
            for dvd in self.data:
                if dvd.check == True:
                    self.controle.devolucao(dvd.cod)

            status = self.controle.notify()
            if status == False:
                self.notify_box.show()
            else:
                self.w_devolver.hide()
                self.controle.main_status = True

    def __init__(self, controle):
        self.w_devolver = gtk.Dialog()
        self.w_devolver.set_position(gtk.WIN_POS_CENTER)
        self.w_devolver.connect("destroy", self.close)
        self.w_devolver.connect("focus_in_event", self.cadastra)
        self.w_devolver.set_title("CEF SHOP - Devolução")
        self.w_devolver.set_size_request(650, 400)
        self.w_devolver.set_border_width(8)
        self.controle = controle
        self.quant_itens = 0

        # -------Elementos
        label_dvd = gtk.Label("Codigo do DvD :")
        self.entry_dvd = gtk.Entry(0)

        self.data = []
        columns = [
            Column("check", data_type=bool, editable=True, title="Conferido"),
            Column("cod", data_type=int, sorted=True, title="Código"),
            Column("title", data_type=str, title="Titulo"),
            Column("valor", data_type=currency, title="Valor"),
        ]
        self.lista = ObjectList(columns, mode=gtk.SELECTION_NONE)
        self.lista.extend(self.data)

        # ------Divisao v principal
        vbox_main = gtk.VBox(False, 2)
        self.w_devolver.vbox.add(vbox_main)

        # ------Frame Clientes
        frame_cliente = gtk.Frame("Cliente")
        vbox_main.pack_start(frame_cliente, False, True, 2)

        hbox_cliente = gtk.HBox(False, 2)
        hbox_cliente.set_border_width(2)
        frame_cliente.add(hbox_cliente)

        f_cliente = gtk.Fixed()

        label_cod_cliente = gtk.Label("Codigo :")
        f_cliente.put(label_cod_cliente, 2, 8)

        self.entry_cod_cliente = gtk.Entry(0)
        self.entry_cod_cliente.set_size_request(60, 28)
        self.entry_cod_cliente.set_editable(False)
        self.entry_cod_cliente.set_sensitive(False)
        f_cliente.put(self.entry_cod_cliente, 60, 4)

        self.entry_nome_cliente = gtk.Entry(0)
        self.entry_nome_cliente.set_size_request(500, 28)
        self.entry_nome_cliente.set_editable(False)
        self.entry_nome_cliente.set_sensitive(False)
        f_cliente.put(self.entry_nome_cliente, 122, 4)

        hbox_cliente.pack_start(f_cliente, False, True, 4)

        # ---divisao h
        hbox_body = gtk.HBox(False, 2)
        vbox_main.pack_start(hbox_body, True, True, 2)

        # ------framecod dvds

        f_dvd = gtk.Fixed()
        frame_dvds = gtk.Frame("DvDs")
        hbox_body.pack_start(frame_dvds, False, True, 2)

        vbox_dvd = gtk.VBox(False, 2)
        vbox_dvd.set_border_width(2)
        frame_dvds.add(vbox_dvd)

        button_adicionar = gtk.Button(stock=gtk.STOCK_ADD)

        label_cod_dvd = gtk.Label("Codigo :")
        f_dvd.put(label_cod_dvd, 2, 8)
        self.entry_cod_dvd = gtk.Entry(0)
        self.entry_cod_dvd.set_size_request(60, 28)
        self.entry_cod_dvd.connect("activate", self.popular_lista_dvds_devolucao)
        f_dvd.put(self.entry_cod_dvd, 60, 4)

        vbox_dvd.pack_start(f_dvd, False, True, 4)

        button_adicionar.connect("clicked", self.popular_lista_dvds_devolucao)

        bbox = gtk.VButtonBox()
        bbox.set_layout(gtk.BUTTONBOX_START)
        vbox_dvd.pack_start(bbox, False, True, 4)
        bbox.add(button_adicionar)

        # ------lista de filmes
        frame_filmes = gtk.Frame("Lista de Locações")
        hbox_body.pack_start(frame_filmes, True, True, 2)
        vbox_lista = gtk.VBox(False, 2)

        frame_filmes.add(vbox_lista)
        vbox_lista.pack_start(self.lista, True, True, 2)

        label = SummaryLabel(klist=self.lista, column="valor", label="<b>Saldo Devedor:</b>", value_format="<b>%s</b>")
        vbox_lista.pack_start(label, False, False, 4)

        # -------area de notificacao

        # -------Botoes
        button_cancel = gtk.Button(stock=gtk.STOCK_CANCEL)
        button_cancel.connect("clicked", self.close)
        button_ok = gtk.Button(stock=gtk.STOCK_OK)
        button_ok.connect("clicked", self.receber)

        bbox = gtk.HButtonBox()
        bbox.set_layout(gtk.BUTTONBOX_END)
        self.w_devolver.action_area.pack_start(bbox, False, True, 0)

        bbox.add(button_cancel)
        button_cancel.set_flags(gtk.CAN_DEFAULT)

        bbox.add(button_ok)
        button_cancel.grab_default()

        self.w_devolver.show_all()
        self.w_devolver.show()
Ejemplo n.º 10
0
class Locar:
    class Dvd:
        def __init__(self, cod, title, valor):
            self.cod = cod
            self.title = title
            self.valor = currency(valor)

        def __repr__(self):
            return "<Titulo %s>" % self.title

    def set_controle(self, controle):
        self.controle = controle

    def close(self, w):
        self.controle.main_status = False
        self.w_locar.destroy()

    def sensitive(self, is_sensitive=False):
        pass
        # self.entry_nome_cliente.set_sensitive(is_sensitive)
        # self.entry_cod_dvd.set_sensitive(is_sensitive)

    def localizado(self, widget, focus):
        pass

    #    dadoscliente = self.controle.cliente_localizado()
    #  if dadoscliente[0] == True:
    #    self.entry_cod_cliente.set_text(str(dadoscliente[1][0][0]))
    #  self.entry_nome_cliente.set_text(dadoscliente[1][0][1])
    # self.sensitive(True)
    # self.entry_cod_dvd.grab_focus()

    def receber(self, widget):
        pass
        # itens = self.controle.receber_locacao(self.lista)
        # Receber(self.controle, self.w_locar, itens)

    def cadastra(self, widget, focus):
        recebido = self.controle.get_receber_status()
        if recebido == True:
            self.controle.set_receber_status(False)
            cod_cliente = self.entry_cod_cliente.get_text()
            for iten in self.lista:
                cod_dvd = int(iten.cod)
                self.controle.alugar(cod_cliente, cod_dvd)

            status = self.controle.notify()
            if status == True:
                self.notify_box.show()
            else:
                self.w_locar.hide()
                self.controle.main_status = True

    def remover_item(self, w):
        item = self.lista.get_selected_row_number()
        for itens in self.lista:
            if itens == self.lista[item]:
                self.lista.remove(itens)
        atributo = "cod"
        self.lista.emit("cell-edited", self.lista, atributo)

    def popular_lista_dvds(self, w):
        cod = self.entry_cod_dvd.get_text()
        try:
            dvd = self.controle.listar_dvd(cod, self.quant_itens, self.lista)
        except:
            pass
        status = self.controle.notify()
        if status == True:
            codigo = dvd[0][0]
            titulo = dvd[0][1]
            valor = dvd[0][2]
            self.lista.append(Locar.Dvd(codigo, titulo, valor))
            atributo = "cod"
            self.lista.emit("cell-edited", self.lista, atributo)
            self.notify_box.hide()
        else:
            self.notify_box.show()
        self.entry_cod_dvd.set_text("")

    def localizar_cliente_cod(self, widget):
        cod = self.entry_cod_cliente.get_text()
        if cod is not "":
            try:
                cliente = self.controle.listar_cliente(cod)
            except:
                pass
            status = self.controle.notify()
            if status == True:
                self.entry_nome_cliente.set_text(cliente[0][1])
                self.sensitive(True)
                self.notify_box.hide()
                self.entry_cod_dvd.grab_focus()
            else:
                self.entry_nome_cliente.set_text("")
                self.sensitive(False)
                self.notify_box.show()

    def __init__(self, controle):
        self.w_locar = gtk.Dialog()
        self.w_locar.set_position(gtk.WIN_POS_CENTER)
        self.w_locar.connect("destroy", self.close)
        self.w_locar.connect("focus_in_event", self.cadastra)
        self.w_locar.connect("focus_in_event", self.localizado)
        self.w_locar.set_title("CEF SHOP - Locar")
        self.w_locar.set_size_request(650, 400)
        self.w_locar.set_border_width(8)
        self.controle = controle
        self.quant_itens = 0

        # ------Divisao v principal
        vbox_main = gtk.VBox(False, 2)
        self.w_locar.vbox.add(vbox_main)

        # ------Elementos
        self.data = []
        columns = [
            Column("cod", data_type=int, sorted=True, title="Código"),
            Column("title", data_type=str, title="Titulo"),
            Column("valor", data_type=currency, title="Valor"),
        ]
        self.lista = ObjectList(columns, mode=gtk.SELECTION_MULTIPLE)
        self.lista.extend(self.data)

        # ------Frame Clientes
        frame_cliente = gtk.Frame("Cliente")
        vbox_main.pack_start(frame_cliente, False, True, 2)

        hbox_cliente = gtk.HBox(False, 2)
        hbox_cliente.set_border_width(2)
        frame_cliente.add(hbox_cliente)

        f_cliente = gtk.Fixed()

        label_cod_cliente = gtk.Label("Codigo :")
        f_cliente.put(label_cod_cliente, 2, 8)

        self.entry_cod_cliente = gtk.Entry(0)
        self.entry_cod_cliente.set_size_request(60, 28)
        self.entry_cod_cliente.connect("activate", self.localizar_cliente_cod)
        f_cliente.put(self.entry_cod_cliente, 60, 4)

        # self.entry_nome_cliente = gtk.Entry(0)
        self.entry_nome_cliente = ComboEntry()
        self.entry_nome_cliente.set_size_request(500, 26)

        tabelacombo = self.controle.clientes
        itens = tabelacombo.combo()
        self.entry_nome_cliente.prefill(itens)

        # self.entry_nome_cliente.set_editable(False)
        f_cliente.put(self.entry_nome_cliente, 122, 4)

        # button_localizar_cliente = gtk.Button(stock=gtk.STOCK_FIND)
        # button_localizar_cliente.connect("clicked", localizar_cliente, self.w_locar, self.controle)
        # f_cliente.put(button_localizar_cliente,524, 0)

        hbox_cliente.pack_start(f_cliente, False, True, 4)

        # ---divisao h
        hbox_body = gtk.HBox(False, 2)
        vbox_main.pack_start(hbox_body, True, True, 2)

        # ------framecod dvds

        f_dvd = gtk.Fixed()
        frame_dvds = gtk.Frame("DvDs")
        hbox_body.pack_start(frame_dvds, False, True, 2)

        vbox_dvd = gtk.VBox(False, 2)
        vbox_dvd.set_border_width(2)
        frame_dvds.add(vbox_dvd)

        label_cod_dvd = gtk.Label("Codigo :")
        f_dvd.put(label_cod_dvd, 2, 8)
        self.entry_cod_dvd = gtk.Entry(0)
        self.entry_cod_dvd.set_size_request(60, 28)
        self.entry_cod_dvd.connect("activate", self.popular_lista_dvds)
        f_dvd.put(self.entry_cod_dvd, 60, 4)

        vbox_dvd.pack_start(f_dvd, False, True, 4)

        button_remover = gtk.Button(stock=gtk.STOCK_REMOVE)
        button_remover.connect("clicked", self.remover_item)
        button_adicionar = gtk.Button(stock=gtk.STOCK_ADD)
        button_adicionar.connect("clicked", self.popular_lista_dvds)

        bbox = gtk.VButtonBox()
        bbox.set_layout(gtk.BUTTONBOX_START)
        vbox_dvd.pack_start(bbox, False, True, 4)

        bbox.add(button_adicionar)
        bbox.add(button_remover)

        # ------lista de filmes
        frame_filmes = gtk.Frame("Lista de Locações")
        hbox_body.pack_start(frame_filmes, True, True, 2)
        vbox_lista = gtk.VBox(False, 2)

        frame_filmes.add(vbox_lista)
        vbox_lista.pack_start(self.lista, True, True, 2)

        label = SummaryLabel(klist=self.lista, column="valor", label="<b>Total:</b>", value_format="<b>%s</b>")
        vbox_lista.pack_start(label, False, False, 4)

        # -------area de notificacao

        # -------Botoes
        button_cancel = gtk.Button(stock=gtk.STOCK_CANCEL)
        button_cancel.connect("clicked", self.close)
        button_ok = gtk.Button(stock=gtk.STOCK_OK)
        button_ok.connect("clicked", self.receber)

        bbox = gtk.HButtonBox()
        bbox.set_layout(gtk.BUTTONBOX_END)
        self.w_locar.action_area.pack_start(bbox, False, True, 0)

        bbox.add(button_cancel)
        button_cancel.set_flags(gtk.CAN_DEFAULT)

        bbox.add(button_ok)
        button_cancel.grab_default()

        self.sensitive()
        self.w_locar.show_all()
        self.w_locar.show()
Ejemplo n.º 11
0
class ListContainer(Gtk.Box):
    """A ListContainer is an :class:`ObjectList` with buttons to be able
    to modify the content of the list.
    Depending on the list_mode, @see :class:`set_list_mode` you will
    have add, remove and edit buttons.

    Signals
    =======
      - B{add-item} (returns item):
        - emitted when the add button is clicked, you're expected to
          return an object here
      - B{remove-item} (item, returns bool):
        - emitted when removing an item,
          you can block the removal from the list by returning False
      - B{edit-item} (item):
        - emitted when editing an item
          you can block the update afterwards by returning False

    :ivar add_button: add button
    :type add_button: :class:`Gtk.Button`
    :ivar remove_button: remove button
    :type remove_button: :class:`Gtk.Button`
    :ivar edit_button: edit button
    :type edit_button: :class:`Gtk.Button`
    """

    __gtype_name__ = 'ListContainer'
    gsignal('add-item', retval=object)
    gsignal('remove-item', object, retval=bool)
    gsignal('edit-item', object, retval=bool)
    gsignal('selection-changed', object)

    def __init__(self, columns, orientation=Gtk.Orientation.VERTICAL):
        """
        Create a new ListContainer object.
        :param columns: columns for the :class:`kiwi.ui.objectlist.ObjectList`
        :type columns: a list of :class:`kiwi.ui.objectlist.Columns`
        :param orientation: the position where the buttons will be
            placed: at the right (vertically) or at the bottom (horizontally)
            of the list. Defaults to the right of the list.
        :type: Gtk.Orientation.HORIZONTAL or Gtk.Orientation.VERTICAL
        """
        self._list_type = None

        super(ListContainer,
              self).__init__(orientation=Gtk.Orientation.HORIZONTAL)

        self._orientation = orientation

        self._create_ui(columns)
        self.set_list_type(ListType.NORMAL)

    # Private API

    def _create_ui(self, columns):
        self.list = ObjectList(columns)
        self.list.connect('selection-changed',
                          self._on_list__selection_changed)
        self.list.connect('row-activated', self._on_list__row_activated)

        self.add_button = Gtk.Button(stock=Gtk.STOCK_ADD)
        self.add_button.connect('clicked', self._on_add_button__clicked)

        self.remove_button = Gtk.Button(stock=Gtk.STOCK_REMOVE)
        self.remove_button.set_sensitive(False)
        self.remove_button.connect('clicked', self._on_remove_button__clicked)

        self.edit_button = Gtk.Button(stock=Gtk.STOCK_EDIT)
        self.edit_button.set_sensitive(False)
        self.edit_button.connect('clicked', self._on_edit_button__clicked)

        self._vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        if self._orientation == Gtk.Orientation.VERTICAL:
            self.pack_start(self.list, True, True, 0)
            self.list.show()
            self._add_buttons_to_box(self._vbox)
            self._pack_vbox()
        elif self._orientation == Gtk.Orientation.HORIZONTAL:
            self._vbox.pack_start(self.list, True, True, 0)
            self.list.show()
            hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
            self._add_buttons_to_box(hbox)
            self._vbox.pack_start(hbox, False, True, 0)
            hbox.show()
            self._pack_vbox()
        else:
            raise TypeError(
                "buttons_orientation must be Gtk.Orientation.VERTICAL "
                " or Gtk.Orientation.HORIZONTAL")

    def _add_buttons_to_box(self, box):
        box.pack_start(self.add_button, False, True, 0)
        box.pack_start(self.remove_button, False, True, 0)
        box.pack_start(self.edit_button, False, True, 0)

    def _pack_vbox(self):
        self.pack_start(self._vbox, False, True, 6)
        self._vbox.show()

    def _set_child_packing(self, padding):
        expand = self._orientation == Gtk.Orientation.HORIZONTAL

        self.set_child_packing(self._vbox, expand, True, padding,
                               Gtk.PackType.START)

    def _add_item(self):
        retval = self.emit('add-item')
        if retval is None:
            return
        elif isinstance(retval, NotImplementedError):
            raise retval

        self.list.append(retval)
        self.list.refresh()

    def _remove_item(self, item):
        retval = self.emit('remove-item', item)
        if retval:
            self.list.remove(item)

    def _edit_item(self, item):
        retval = self.emit('edit-item', item)
        if retval:
            self.list.update(item)

    # Public API

    def add_item(self, item):
        """Appends an item to the list
        :param item: item to append
        """
        self.list.append(item)

    def add_items(self, items):
        """Appends a list of items to the list
        :param items: items to add
        :type items: a sequence of items
        """
        self.list.extend(items)

    def remove_item(self, item):
        """Removes an item from the list
        :param item: item to remove
        """
        self.list.remove(item)

    def update_item(self, item):
        """Updates an item in the list.
        You should call this if you change the object
        :param item: item to update
        """
        self.list.update(item)

    def default_remove(self, item):
        """Asks the user confirmation for removal of an item.
        :param item: a description of the item that will be removed
        :returns: True if the user confirm the removal, False otherwise
        """
        response = yesno(_('Do you want to remove %s ?') %
                         (GLib.markup_escape_text(str(item)), ),
                         parent=None,
                         default=Gtk.ResponseType.OK,
                         buttons=((Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL),
                                  (Gtk.STOCK_REMOVE, Gtk.ResponseType.OK)))
        return response == Gtk.ResponseType.OK

    def set_list_type(self, list_type):
        """Sets the kind of list type.
        :param list_type:
        """
        if not isinstance(list_type, ListType):
            raise TypeError("list_type must be a ListType enum")

        self.add_button.set_property(
            'visible', list_type not in [
                ListType.READONLY, ListType.REMOVEONLY, ListType.UNADDABLE
            ])
        self.remove_button.set_property(
            'visible', list_type
            not in [ListType.READONLY, ListType.ADDONLY, ListType.UNREMOVABLE])
        self.edit_button.set_property(
            'visible', list_type not in [
                ListType.READONLY, ListType.ADDONLY, ListType.UNEDITABLE,
                ListType.REMOVEONLY
            ])
        if list_type in [ListType.READONLY, ListType.REMOVEONLY]:
            padding = 0
        else:
            padding = 6
        self._set_child_packing(padding)
        self._list_type = list_type

    def clear(self):
        """Removes all the items in the list"""
        self.list.clear()

    # Callbacks

    def _on_list__selection_changed(self, list, selection):
        object_selected = selection is not None
        self.remove_button.set_sensitive(object_selected)
        self.edit_button.set_sensitive(object_selected)
        self.emit('selection-changed', selection)

    def _on_list__row_activated(self, list, item):
        if self._list_type not in [
                ListType.READONLY, ListType.ADDONLY, ListType.UNEDITABLE
        ]:
            self._edit_item(item)

    def _on_add_button__clicked(self, button):
        self._add_item()

    def _on_remove_button__clicked(self, button):
        self._remove_item(self.list.get_selected())

    def _on_edit_button__clicked(self, button):
        self._edit_item(self.list.get_selected())
Ejemplo n.º 12
0
class Receber():
    """Classe contendo a janela e o metodos de recebimento"""
    class Item:
        def __init__(self,item, valor):
            """item é a descrição do item alugado ou comprado
                valor o preço do item"""
            self.item = item
            self.valor = currency(valor)
        def __repr__(self):
            return '<Titulo %s>' % self.item
    
    def close(self,w):
        self.w_receber.destroy()
        
    def recebido(self, widget):
        """Envia o sinal para o controle que o recebimento foi realizado com sucesso"""
        self.controle.set_receber_status(True)   
        self.w_receber.destroy()
    
    def __init__(self, controle, window, itens):
        """window é a janela que está chamando o recebimento
            itens a lista de itens adquiridos com descrição e preço"""
        self.w_receber = gtk.Dialog("CEF SHOP - Recebimento", window, gtk.DIALOG_MODAL)
        self.w_receber.set_position(gtk.WIN_POS_CENTER)
        self.w_receber.set_size_request(550,450)
        self.w_receber.connect("destroy", self.close)
        self.controle = controle

#------Divisao v principal
        vbox_main = gtk.VBox(False, 2)
        self.w_receber.vbox.add(vbox_main)   

#------Lista
        self.data = []
        columns = [
            Column('item', data_type = str, title="Item"),
            Column('valor', data_type = currency, title="Valor") 
        ]
        self.lista = ObjectList(columns)
        for iten in itens:
            item = iten[0]
            valor = iten[1]
            self.data.append(Receber.Item(item, valor))
        self.lista.extend(self.data)

#------lista de itens    
        frame_itens = gtk.Frame("Lista de Produtos")
        vbox_main.pack_start(frame_itens, True, True, 2)
        vbox_lista = gtk.VBox(False, 2)

        frame_itens.add(vbox_lista)
        vbox_lista.pack_start(self.lista, True, True, 2)
        
        label = SummaryLabel(klist=self.lista, column='valor', label='<b>Total:</b>',
                     value_format='<b>%s</b>')
        vbox_lista.pack_start(label, False, False, 4)
        
#-----entrada valor
        hbox_valor = gtk.HBox() 

        label_troco = ProxyLabel('Troco ')
        label_troco.set_bold(True)
        label_valor_troco = ProxyLabel(data_type = currency)
        label_valor_troco.set_bold(True)
        label_valor_troco.update(currency('0.00'))
        
        label_dinheiro = ProxyLabel('Dinheiro ')
        label_dinheiro.set_bold(True)
        entry_dinheiro = ProxyEntry(data_type = currency)
        
        hbox_valor.pack_start(label_troco, False, False, 2)
        hbox_valor.pack_start(label_valor_troco, False, False, 2)
        
        hbox_valor.pack_end(entry_dinheiro, False, False, 2)
        hbox_valor.pack_end(label_dinheiro, False, False, 2)
        self.w_receber.vbox.pack_start(hbox_valor,False, True, 4)
        
#-------area de notificacao
        self.notify_box = notify_area(self.controle)
        self.w_receber.vbox.pack_start(self.notify_box,False, True, 4)

#-------Botoes
        button_cancel = gtk.Button(stock=gtk.STOCK_CANCEL)
        button_cancel.connect("clicked", self.close)
        button_ok = gtk.Button(stock=gtk.STOCK_OK)
        button_ok.connect("clicked", self.recebido)

        bbox = gtk.HButtonBox ()
        bbox.set_layout(gtk.BUTTONBOX_END)
        bbox.add(button_cancel)
        button_cancel.set_flags(gtk.CAN_DEFAULT)
        bbox.add(button_ok)
        self.w_receber.action_area.pack_start(bbox, False, True, 0)
    
#------Mostra tudo
        self.w_receber.show_all()
        self.notify_box.hide()
        self.w_receber.show()