Exemplo n.º 1
0
 def get_sections(self):
     from camelot.model.memento import Memento
     from model import AnnualEmploymentControlTotal
     from model import AnnualHouseholdControlTotal
     from model import Building
     from model import BuildingType
     from model import EmploymentSector
     from model import Household
     from model import HouseholdCharacteristicsForHT
     from model import Job
     from model import TravelData
     from model import Zone
     from camelot.model.i18n import Translation
     return [
         Section('Scenario Tables',
                 Icon('tango/24x24/apps/system-users.png'),
                 items=[
                     AnnualEmploymentControlTotal,
                     AnnualHouseholdControlTotal
                 ]),
         Section('Base Year Data Core Tables',
                 Icon('tango/24x24/categories/preferences-system.png'),
                 items=[Building, Household, Job, TravelData, Zone]),
         Section('Base Year Data Lookup Tables',
                 Icon('tango/24x24/categories/preferences-system.png'),
                 items=[
                     BuildingType,
                     EmploymentSector,
                     HouseholdCharacteristicsForHT,
                 ])
     ]
Exemplo n.º 2
0
    def get_sections(self):

        from camelot.model.memento import Memento
        from camelot.model.party import (Person, Organization, PartyCategory)
        from camelot.model.i18n import Translation

        from camelot_example.model import Movie, Tag, VisitorReport
        from camelot_example.view import VisitorsPerDirector
        # begin import action
        from camelot_example.importer import ImportCovers
        # end import action

        return [
            # begin section with action
            Section(_('Movies'),
                    self,
                    Icon('tango/22x22/mimetypes/x-office-presentation.png'),
                    items=[
                        Movie, Tag, VisitorReport, VisitorsPerDirector,
                        ImportCovers()
                    ]),
            # end section with action
            Section(_('Relation'),
                    self,
                    Icon('tango/22x22/apps/system-users.png'),
                    items=[Person, Organization, PartyCategory]),
            Section(_('Configuration'),
                    self,
                    Icon('tango/22x22/categories/preferences-system.png'),
                    items=[Memento, Translation])
        ]
Exemplo n.º 3
0
 def __init__( self, objects, admin ):
     self.objects = objects
     self.admin = admin
     self.window_title = admin.get_verbose_name_plural()
     self.title = _('Data Preview')
     self.subtitle = _('Please review the data below.')
     self.icon = Icon('tango/32x32/mimetypes/x-office-spreadsheet.png')
Exemplo n.º 4
0
    def set_instance_represenation(self, representation_and_propagate):
        """Update the gui"""
        ((desc, pk), propagate) = representation_and_propagate
        self._entity_representation = desc
        self.search_input.set_user_input(desc)

        if pk != False:
            self.open_button.setIcon(
                Icon('tango/16x16/places/folder.png').getQIcon())
            self.open_button.setToolTip(unicode(_('open')))
            self.open_button.setEnabled(True)

            self.search_button.setIcon(
                Icon('tango/16x16/actions/edit-clear.png').getQIcon())
            self.search_button.setToolTip(unicode(_('clear')))
            self.entity_set = True
        else:
            self.open_button.setIcon(self.new_icon.getQIcon())
            self.open_button.setToolTip(unicode(_('new')))
            self.open_button.setEnabled(self._editable)

            self.search_button.setIcon(self.search_icon.getQIcon())
            self.search_button.setToolTip(_('Search'))
            self.entity_set = False

        if propagate:
            self.editingFinished.emit()
Exemplo n.º 5
0
    def __init__(self, parent=None, width=50, height=40, dpi=50, **kwargs):
        from matplotlib.figure import Figure
        from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
        super(ChartEditor, self).__init__(parent)

        chart_frame = QtGui.QFrame(self)
        chart_frame.setFrameShape(self.Box)
        chart_frame.setContentsMargins(1, 1, 1, 1)
        chart_frame_layout = QtGui.QHBoxLayout()
        chart_frame_layout.setMargin(0)
        chart_frame.setLayout(chart_frame_layout)

        # find out background color, because using a transparent
        # figure fails when the window is resized: the background
        # is not redrawn
        # need to do str() else matplotlib gets confused by the qstring
        # bgcolorrgb = str(self.palette().background().color().name())
        self.fig = Figure(
            figsize=(width, height),
            dpi=dpi,
            facecolor='#ffffff',
        )
        layout = QtGui.QHBoxLayout()
        self.canvas = FigureCanvas(self.fig)
        chart_frame_layout.addWidget(self.canvas)
        layout.addWidget(chart_frame)
        button_layout = QtGui.QVBoxLayout()
        button_layout.setSpacing(0)

        icon = Icon(
            'tango/16x16/actions/document-print-preview.png').getQIcon()
        button_layout.addStretch()

        print_button = QtGui.QToolButton()
        print_button.setIcon(icon)
        print_button.setAutoRaise(True)
        print_button.setToolTip(_('Print Preview'))
        print_button.clicked.connect(self.print_preview)
        button_layout.addWidget(print_button)

        icon = Icon('tango/16x16/actions/edit-copy.png').getQIcon()
        copy_button = QtGui.QToolButton()
        copy_button.setIcon(icon)
        copy_button.setAutoRaise(True)
        copy_button.setToolTip(_('Copy to clipboard'))
        copy_button.clicked.connect(self.copy_to_clipboard)
        button_layout.addWidget(copy_button)

        layout.addLayout(button_layout)
        layout.setMargin(0)
        self.setLayout(layout)
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                  QtGui.QSizePolicy.Expanding)
        self.canvas.installEventFilter(self)
        self.show_fullscreen_signal.connect(self.show_fullscreen)
        self.canvas.updateGeometry()
        self._litebox = None
Exemplo n.º 6
0
    def __init__(self, parent):
        QtGui.QWidget.__init__(self, parent)
        layout = QtGui.QHBoxLayout()
        layout.setSpacing(0)
        layout.setContentsMargins(3, 3, 3, 3)

        #
        # The search timer reduced the number of search signals that are
        # emitted, by waiting for the next keystroke before emitting the
        # search signal
        #
        timer = QtCore.QTimer(self)
        timer.setInterval(300)
        timer.setSingleShot(True)
        timer.setObjectName('timer')
        timer.timeout.connect(self.emit_search)

        # Search button
        self.search_button = QtGui.QToolButton()
        icon = Icon('tango/16x16/actions/system-search.png').getQIcon()
        self.search_button.setIcon(icon)
        self.search_button.setIconSize(QtCore.QSize(14, 14))
        self.search_button.setAutoRaise(True)
        self.search_button.setToolTip(_('Expand or collapse search options'))
        self.search_button.clicked.connect(self.emit_expand_search_options)

        # Search input
        from camelot.view.controls.decorated_line_edit import DecoratedLineEdit
        self.search_input = DecoratedLineEdit(self)
        self.search_input.set_background_text(_('Search...'))
        #self.search_input.setStyleSheet('QLineEdit{ border-radius: 0.25em;}')
        self.search_input.returnPressed.connect(self.emit_search)
        self.search_input.textEdited.connect(self._start_search_timer)
        self.search_input.arrow_down_key_pressed.connect(
            self.on_arrow_down_key_pressed)

        self.setFocusProxy(self.search_input)

        # Cancel button
        self.cancel_button = QtGui.QToolButton()
        icon = Icon('tango/16x16/actions/edit-clear.png').getQIcon()
        self.cancel_button.setIcon(icon)
        self.cancel_button.setIconSize(QtCore.QSize(14, 14))
        self.cancel_button.setAutoRaise(True)
        self.cancel_button.clicked.connect(self.emit_cancel)

        # Setup layout
        layout.addWidget(self.search_button)
        layout.addWidget(self.search_input)
        layout.addWidget(self.cancel_button)
        self.setLayout(layout)
Exemplo n.º 7
0
    def __init__(self, parent, img='face-plain', editable=True, **kwargs):
        CustomEditor.__init__(self, parent)
        self.box = QtGui.QComboBox()
        self.box.setFrame(True)
        self.box.setEditable(False)
        self.allSmileys = []

        self.allSmileys.append('face-angel')
        self.allSmileys.append('face-crying')
        self.allSmileys.append('face-devilish')
        self.allSmileys.append('face-glasses')
        self.allSmileys.append('face-grin')
        self.allSmileys.append('face-kiss')
        self.allSmileys.append('face-monkey')
        self.allSmileys.append('face-plain')
        self.allSmileys.append('face-sad')
        self.allSmileys.append('face-smile')
        self.allSmileys.append('face-smile-big')
        self.allSmileys.append('face-surprise')
        self.allSmileys.append('face-wink')

        for i, value in enumerate(self.allSmileys):
            imgPath = 'tango/16x16/emotes/' + value + '.png'
            icon = Icon(imgPath).getQIcon()

            self.box.addItem(icon, '')
            self.box.setFixedHeight(self.get_height())

            if value == 'face-plain':
                self.box.setCurrentIndex(i)

        self.setFocusPolicy(Qt.StrongFocus)
        layout = QtGui.QHBoxLayout(self)
        layout.setMargin(0)
        layout.setSpacing(0)
        self.img = img
        self.imgPath = 'tango/16x16/emotes/' + img + '.png'
        self.Icon = Icon(self.imgPath).getQIcon()
        self.setAutoFillBackground(True)
        #self.starCount = maximum
        if not editable:
            self.box.setEnabled(False)
        else:
            self.box.setEnabled(True)
        self.box.currentIndexChanged.connect(self.smiley_changed)

        layout.addWidget(self.box)
        layout.addStretch()
        self.setLayout(layout)
Exemplo n.º 8
0
class TranslateLabelAction(QtWidgets.QAction):
    
    translate_icon = Icon( 'tango/16x16/apps/preferences-desktop-locale.png' )
    
    def __init__(self, parent):
        super(TranslateLabelAction, self).__init__(_('Change translation'), parent)
        self.setIcon(self.translate_icon.getQIcon())
Exemplo n.º 9
0
    def paint(self, painter, option, index):
        painter.save()
        img = index.model().data(index, Qt.DisplayRole).toString()

        background_color = QtGui.QColor(index.model().data(
            index, Qt.BackgroundRole))

        imgPath = 'tango/16x16/emotes/' + img + '.png'
        self.drawBackground(painter, option, index)
        rect = option.rect
        rect = QtCore.QRect(rect.left() + 3,
                            rect.top() + 6,
                            rect.width() - 5, rect.height())

        if (option.state & QtGui.QStyle.State_Selected):
            painter.fillRect(option.rect, option.palette.highlight())
        else:
            if not self.editable:
                painter.fillRect(option.rect, option.palette.window())
            else:
                painter.fillRect(option.rect, background_color)

        icon = Icon(imgPath).getQPixmap()
        QtGui.QApplication.style().drawItemPixmap(painter, rect, 1, icon)
        rect = QtCore.QRect(rect.left() + 20, rect.top(), rect.width(),
                            rect.height())
        painter.restore()
Exemplo n.º 10
0
    def paint(self, painter, option, index):
        painter.save()
        self.drawBackground(painter, option, index)
        stars = index.model().data(index, Qt.EditRole).toInt()[0]

        background_color = QtGui.QColor(index.model().data(
            index, Qt.BackgroundRole))

        rect = option.rect
        rect = QtCore.QRect(rect.left() + 3,
                            rect.top() + 6,
                            rect.width() - 5, rect.height())

        if (option.state & QtGui.QStyle.State_Selected):
            painter.fillRect(option.rect, option.palette.highlight())
        else:
            if not self.editable:
                painter.fillRect(option.rect, option.palette.window())
            else:
                painter.fillRect(option.rect, background_color)

        for i in range(5):
            if i + 1 <= stars:
                icon = Icon(
                    'tango/16x16/status/weather-clear.png').getQPixmap()
                QtGui.QApplication.style().drawItemPixmap(
                    painter, rect, 1, icon)
                rect = QtCore.QRect(rect.left() + 20, rect.top(), rect.width(),
                                    rect.height())
        painter.restore()
Exemplo n.º 11
0
class Restore(Refresh):
    """
Restore the database to disk

.. attribute:: backup_mechanism

    A subclass of :class:`camelot.core.backup.BackupMechanism` that enables 
    the application to perform backups an restores.
"""

    verbose_name = _('&Restore')
    tooltip = _('Restore the database from a backup')
    icon = Icon('tango/16x16/devices/drive-harddisk.png')
    backup_mechanism = BackupMechanism
    shortcut = None

    def model_run(self, model_context):
        from camelot.view.action_steps import UpdateProgress, SelectRestore
        label, storage = yield SelectRestore(self.backup_mechanism)
        yield UpdateProgress(text=_('Restore in progress'))
        backup_mechanism = self.backup_mechanism(label, storage)
        restore_iterator = backup_mechanism.restore(settings.ENGINE())
        for completed, total, description in restore_iterator:
            yield UpdateProgress(completed, total, text=description)
        for step in super(Restore, self).model_run(model_context):
            yield step
Exemplo n.º 12
0
class ConfirmSelection(Action):

    verbose_name = _('OK')
    icon = Icon('tango/16x16/emblems/emblem-symbolic-link.png')

    def model_run(self, model_context):
        yield SetSelectedObjects(list(model_context.get_selection()))
Exemplo n.º 13
0
class ReporteRecaudacionRealTotalPorBarrio(Action):
    verbose_name = ''
    icon = Icon('tango/16x16/actions/document-print.png')

    def _build_context(self, model_context):
        Linea = namedtuple('Linea', ['semana',
                                     'barrio',
                                     'recaudacion',
                                     ])
        iterator = model_context.get_collection()
        detalle = []
        total_recaudacion = 0
        for row in iterator:
            linea = Linea(row.semana,
                          row.barrio,
                          money_fmt(row.recaudacion))
            total_recaudacion += row.recaudacion
            detalle.append(linea)

        context = {
            'header_image_filename': header_image_filename(),
            'fecha_desde': fecha_desde(),
            'fecha_hasta': fecha_hasta(),
            'detalle': detalle,
            'total_recaudacion': money_fmt(total_recaudacion),
            }
        return context

    def model_run(self, model_context):
        context = self._build_context(model_context)
        # mostrar el reporte
        fileloader = PackageLoader('m2000', 'templates')
        env = Environment(loader=fileloader)
        t = env.get_template('recaudacion_real_total_x_barrio.html')
        yield PrintHtml(t.render(context))
Exemplo n.º 14
0
class ToNextRow(ListContextAction):
    """Move to the next row in a table"""

    shortcut = QtGui.QKeySequence.MoveToNextPage
    icon = Icon('tango/16x16/actions/go-next.png')
    tooltip = _('Next')
    verbose_name = _('Next')

    def gui_run(self, gui_context):
        item_view = gui_context.item_view
        selection = item_view.selectedIndexes()
        rows = item_view.model().rowCount()
        if rows <= 0:
            return
        if selection:
            current_row = selection[0].row()
            next_row = (current_row + 1) % rows
        else:
            next_row = 0
        item_view.selectRow(next_row)

    def get_state(self, model_context):
        state = super(ToNextRow, self).get_state(model_context)
        #if state.enabled:
        #    max_row = model_context.collection_count - 1
        #    state.enabled = ( model_context.current_row < max_row )
        return state
Exemplo n.º 15
0
class ChangeLogging(Action):
    """Allow the user to change the logging configuration"""

    verbose_name = _('Change logging')
    icon = Icon('tango/16x16/emblems/emblem-photos.png')
    tooltip = _('Change the logging configuration of the application')

    def model_run(self, model_context):
        from camelot.view.controls import delegates
        from camelot.view import action_steps
        from camelot.admin.object_admin import ObjectAdmin

        class Options(object):
            def __init__(self):
                self.level = logging.INFO

            class Admin(ObjectAdmin):
                list_display = ['level']
                field_attributes = {
                    'level': {
                        'delegate':
                        delegates.ComboBoxDelegate,
                        'editable':
                        True,
                        'choices': [(l, logging.getLevelName(l)) for l in [
                            logging.DEBUG, logging.INFO, logging.WARNING,
                            logging.ERROR, logging.CRITICAL
                        ]]
                    }
                }

        options = Options()
        yield action_steps.ChangeObject(options)
        logging.getLogger().setLevel(options.level)
Exemplo n.º 16
0
class OpenNewView(EntityAction):
    """An application action that opens a new view of an Entity
    
    :param entity_admin: an instance of 
        :class:`camelot.admin.entity_admin.EntityAdmin` to be used to
        visualize the entities
    
    """

    verbose_name = _('New')
    shortcut = QtGui.QKeySequence.New
    icon = Icon('tango/16x16/actions/document-new.png')
    tooltip = _('New')

    def get_state(self, model_context):
        state = super(OpenNewView, self).get_state(model_context)
        state.verbose_name = self.verbose_name or ugettext('New %s') % (
            self._entity_admin.get_verbose_name())
        state.tooltip = ugettext('Create a new %s') % (
            self._entity_admin.get_verbose_name())
        return state

    def gui_run(self, gui_context):
        """:return: a new view"""
        from camelot.view.workspace import show_top_level
        form = self._entity_admin.create_new_view(parent=None)
        show_top_level(form, gui_context.workspace)
Exemplo n.º 17
0
class ProgressDialog(QtGui.QProgressDialog):
    """A Progress Dialog to be used in combination with a post to the model thread::
    
    to display a progress dialog until my_function has finished :
    
    d = ProgressDialog()
    post(my_function, p.finished, p.exception)
    d.exec_()
    
    """

    progress_icon = Icon('tango/32x32/actions/appointment-new.png')

    def __init__(self, name, icon=progress_icon):
        QtGui.QProgressDialog.__init__(self, QtCore.QString(),
                                       QtCore.QString(), 0, 0)
        label = QtGui.QLabel(unicode(name))
        #label.setPixmap(icon.getQPixmap())
        self.setLabel(label)
        self.setWindowTitle(_('Please wait'))

    @QtCore.pyqtSlot(bool)
    @QtCore.pyqtSlot()
    def finished(self, success=True):
        self.close()

    @QtCore.pyqtSlot(object)
    def exception(self, exception_info):
        from camelot.view.controls.exception import model_thread_exception_message_box
        model_thread_exception_message_box(exception_info)
        self.finished(False)
Exemplo n.º 18
0
class PrintPreview(ListContextAction):
    """Print all rows in a table"""

    icon = Icon('tango/16x16/actions/document-print-preview.png')
    tooltip = _('Print Preview')
    verbose_name = _('Print Preview')

    def model_run(self, model_context):
        from camelot.view import action_steps
        columns = model_context.admin.get_columns()

        table = []
        getters = [
            field_attributes['getter'] for _field, field_attributes in columns
        ]
        to_strings = [
            field_attributes['to_string']
            for _field, field_attributes in columns
        ]
        column_range = range(len(columns))
        for obj in model_context.get_collection():
            table.append(
                [to_strings[i](getters[i](obj)) for i in column_range])
        context = {
            'title':
            model_context.admin.get_verbose_name_plural(),
            'table':
            table,
            'columns':
            [field_attributes['name'] for _field, field_attributes in columns],
        }
        yield action_steps.PrintJinjaTemplate(template='list.html',
                                              context=context)
Exemplo n.º 19
0
 def __init__(self,
              name,
              icon=Icon('tango/32x32/actions/appointment-new.png')):
     super(FormActionProgressDialog, self).__init__(name=name, icon=icon)
     self.html_document = None
     self.page_size = None
     self.page_orientation = None
Exemplo n.º 20
0
class ReportePagos(Action):
    verbose_name = ''
    icon = Icon('tango/16x16/actions/document-print.png')

    def _build_context(self, model_context):
        Linea = namedtuple('Linea', ['credito',
                                     'fecha',
                                     'monto',
                                     'asistencia',
                                     ])
        iterator = model_context.get_collection()
        detalle = []
        total_monto = 0
        for row in iterator:
            linea = Linea(row.credito,
                          row.fecha,
                          money_fmt(row.monto),
                          row.asistencia)
            total_monto += row.monto
            detalle.append(linea)

        context = {
            'header_image_filename': header_image_filename(),
            'detalle': detalle,
            'total_monto': money_fmt(total_monto),
            }
        return context

    def model_run(self, model_context):
        context = self._build_context(model_context)
        # mostrar el reporte
        fileloader = PackageLoader('m2000', 'templates')
        env = Environment(loader=fileloader)
        t = env.get_template('pagos.html')
        yield PrintHtml(t.render(context))
Exemplo n.º 21
0
class OpenNewView(EntityAction):
    """An application action that opens a new view of an Entity
    
    :param entity_admin: an instance of 
        :class:`camelot.admin.entity_admin.EntityAdmin` to be used to
        visualize the entities
    
    """

    verbose_name = _('New')
    shortcut = QtGui.QKeySequence.New
    icon = Icon('tango/16x16/actions/document-new.png')
    tooltip = _('New')

    def get_state(self, model_context):
        state = super(OpenNewView, self).get_state(model_context)
        state.verbose_name = self.verbose_name or ugettext('New %s') % (
            self._entity_admin.get_verbose_name())
        state.tooltip = ugettext('Create a new %s') % (
            self._entity_admin.get_verbose_name())
        return state

    def model_run(self, model_context):
        from camelot.view import action_steps
        admin = yield action_steps.SelectSubclass(self._entity_admin)
        new_object = admin.entity()
        # Give the default fields their value
        admin.add(new_object)
        admin.set_defaults(new_object)
        yield action_steps.OpenFormView([new_object], admin)
Exemplo n.º 22
0
 def __init__(self, objects, admin):
     self.objects = objects
     self.admin = admin
     self.window_title = admin.get_verbose_name_plural()
     self.title = _("Data Preview")
     self.subtitle = _("Please review the data below.")
     self.icon = Icon("tango/32x32/mimetypes/x-office-spreadsheet.png")
Exemplo n.º 23
0
class ToPreviousRow(ListContextAction):
    """Move to the previous row in a table"""

    shortcut = QtGui.QKeySequence.MoveToPreviousPage
    icon = Icon('tango/16x16/actions/go-previous.png')
    tooltip = _('Previous')
    verbose_name = _('Previous')

    def gui_run(self, gui_context):
        item_view = gui_context.item_view
        selection = item_view.selectedIndexes()
        rows = item_view.model().rowCount()
        if rows <= 0:
            return
        if selection:
            current_row = selection[0].row()
            previous_row = (current_row - 1) % rows
        else:
            previous_row = 0
        item_view.selectRow(previous_row)

    def get_state(self, model_context):
        state = super(ToPreviousRow, self).get_state(model_context)
        #if state.enabled:
        #    state.enabled = ( model_context.current_row > 0 )
        return state
Exemplo n.º 24
0
    def paint(self, painter, option, index):
        painter.save()
        self.drawBackground(painter, option, index)
        value = variant_to_pyobject(index.model().data(index, Qt.EditRole))
        field_attributes = variant_to_pyobject(index.data(Qt.UserRole))
        fontColor = QtGui.QColor()
        editable, prefix, suffix, background_color, arrow = True, '', '', None, None

        if field_attributes != ValueLoading:
            editable = field_attributes.get('editable', True)
            prefix = field_attributes.get('prefix', '')
            suffix = field_attributes.get('suffix', '')
            background_color = field_attributes.get('background_color', None)
            arrow = field_attributes.get('arrow', None)

        fontColor = QtGui.QColor()
        if (option.state & QtGui.QStyle.State_Selected):
            painter.fillRect(option.rect, option.palette.highlight())
        else:
            if editable:
                painter.fillRect(option.rect, background_color
                                 or option.palette.base())
                fontColor.setRgb(0, 0, 0)
            else:
                painter.fillRect(option.rect, background_color
                                 or option.palette.window())
                fontColor.setRgb(130, 130, 130)

        if arrow:
            comparator = arrow.y
        else:
            comparator = value
        #self.icons[cmp(comparator,0)].paint(painter, option.rect.left(), option.rect.top()+1, option.rect.height(), option.rect.height(), Qt.AlignVCenter)
        iconpath = self.icons[cmp(comparator, 0)]
        icon = QtGui.QIcon(Icon(iconpath).getQPixmap())
        icon.paint(painter, option.rect.left(),
                   option.rect.top() + 1, option.rect.height(),
                   option.rect.height(), Qt.AlignVCenter)

        value_str = u''
        if value != None and value != ValueLoading:
            if self.unicode_format != None:
                value_str = self.unicode_format(value)
            else:
                value_str = unicode(
                    self._locale.toString(float(value), 'f', self.precision))
        value_str = unicode(prefix) + u' ' + unicode(
            value_str) + u' ' + unicode(suffix)

        fontColor = fontColor.darker()
        painter.setPen(fontColor.toRgb())
        rect = QtCore.QRect(option.rect.left() + 23, option.rect.top(),
                            option.rect.width() - 23, option.rect.height())

        painter.drawText(rect.x() + 2, rect.y(),
                         rect.width() - 4, rect.height(),
                         Qt.AlignVCenter | Qt.AlignRight, value_str)

        painter.restore()
Exemplo n.º 25
0
class ManyToManyEditor(One2ManyEditor, AbstractManyToOneEditor):

    remove_icon = Icon('tango/16x16/actions/list-remove.png')
    add_icon = Icon('tango/16x16/actions/list-add.png')

    def setupButtons(self, layout, _table):
        button_layout = QtGui.QVBoxLayout()
        button_layout.setSpacing(0)
        self.remove_button = QtGui.QToolButton()
        self.remove_button.setIcon(self.remove_icon.getQIcon())
        self.remove_button.setAutoRaise(True)
        self.remove_button.setFixedHeight(self.get_height())
        self.remove_button.clicked.connect(self.removeSelectedRows)
        self.add_button = QtGui.QToolButton()
        self.add_button.setIcon(self.add_icon.getQIcon())
        self.add_button.setAutoRaise(True)
        self.add_button.setFixedHeight(self.get_height())
        self.add_button.clicked.connect(self.createSelectView)
        button_layout.addStretch()
        button_layout.addWidget(self.add_button)
        button_layout.addWidget(self.remove_button)
        layout.addLayout(button_layout)

    def set_field_attributes(self, editable=True, **kwargs):
        self.add_button.setEnabled(editable)
        self.remove_button.setEnabled(editable)

    def selectEntity(self, entity_instance_getter):
        @model_function
        def insert():
            o = entity_instance_getter()
            self.model.append_object(o)

        post(insert, self.emit_editing_finished)

    def emit_editing_finished(self, *args):
        self.editingFinished.emit()

    def removeSelectedRows(self):
        """Remove the selected rows in this tableview, but don't delete them"""
        table = self.findChild(QtGui.QWidget, 'table')
        if table:
            self.model.remove_rows(set(
                map(lambda x: x.row(), table.selectedIndexes())),
                                   delete=False)
            self.editingFinished.emit()
Exemplo n.º 26
0
class SelectBackupDialog(SelectDialog):

    icon = Icon('tango/32x32/actions/document-save.png')

    def __init__(self, default_storage, default_label, parent=None):
        super(SelectBackupDialog,
              self).__init__(ugettext('Select backup file'), default_storage,
                             default_label, parent)

        self.set_banner_logo_pixmap(self.icon.getQPixmap())
        self.set_banner_title(ugettext('Select file'))
        self.set_banner_subtitle(
            ugettext(
                'Please select a backup file. All data in this file will be overwritten.'
            ))
        self.banner_widget().setStyleSheet('background-color: white;')

    def setup_widgets(self):
        super(SelectBackupDialog, self).setup_widgets()
        self._default_label = QtWidgets.QLabel(ugettext('Label:'))
        self._default_edit = LabelLineEdit(self.default_storage)
        self._default_label.setBuddy(self._default_edit)
        self._hlayout.addWidget(self._default_label)
        self._hlayout.addWidget(self._default_edit)
        self._default_edit.textChanged.connect(self._onDefaultEditChanged)
        self._default_edit.textChanged.connect(self.complete_changed)
        self._default_edit.setText(self.default_label)

    def _onDefaultEditChanged(self, text):
        if self._default_radio.isChecked():
            self.label = self._default_edit.filename()

    def show_widgets(self, selection):
        default_selected = self._isDefaultSelected(selection)
        self._default_label.setVisible(default_selected)
        self._default_edit.setVisible(default_selected)
        super(SelectBackupDialog, self).show_widgets(selection)

    def complete_changed(self):
        default_selected = self._default_radio.isChecked()
        if default_selected:
            self.storage = self.default_storage
            self.label = self._default_edit.filename()
        else:
            self.storage = None
            self.label = self._custom_edit.text()
        ok_button = self.findChild(QtWidgets.QPushButton, 'ok')
        if ok_button:
            ok_button.setEnabled(self.label != '')

    def _setPath(self, start_dir):
        path = QtGui.QFileDialog.getSaveFileName(
            self,
            six.text_type(self.caption),
            start_dir or u'',
            ugettext('Database files (*%s);;All files (*.*)' % self.extension),
        )
        return path
Exemplo n.º 27
0
 def paste(cls, parent, slot, **kwargs):
     default = dict(text=_('Paste'),
                    slot=slot,
                    parent=parent,
                    shortcut=QtGui.QKeySequence.Paste,
                    actionicon=Icon('tango/16x16/actions/edit-paste.png'),
                    tip=_('Paste content from clipboard'))
     default.update(kwargs)
     return cls.create_action(**default)
Exemplo n.º 28
0
 def copy(cls, parent, slot, **kwargs):
     default = dict(text=_('Copy'),
                    slot=slot,
                    parent=parent,
                    shortcut=QtGui.QKeySequence.Copy,
                    actionicon=Icon('tango/16x16/actions/edit-copy.png'),
                    tip=_('Copy to clipboard'))
     default.update(kwargs)
     return cls.create_action(**default)
Exemplo n.º 29
0
 def remote_support(cls, parent, slot, **kwargs):
     default = dict(
         parent=parent,
         text=_('Remote support'),
         slot=slot,
         actionicon=Icon('tango/16x16/devices/video-display.png'),
         tip=_('Let the support agent take over your desktop'))
     default.update(kwargs)
     return cls.create_action(**default)
Exemplo n.º 30
0
 def affiliated_website(cls, parent, slot, **kwargs):
     default = dict(
         parent=parent,
         text=_('Affiliated website'),
         slot=slot,
         actionicon=Icon('tango/16x16/apps/internet-web-browser.png'),
         tip=_('Go to the affiliated website'))
     default.update(kwargs)
     return cls.create_action(**default)
Exemplo n.º 31
0
 def whats_new(cls, parent, slot, **kwargs):
     default = dict(parent=parent,
                    text=_('&What\'s new'),
                    slot=slot,
                    actionicon=Icon(
                        'tango/16x16/status/software-update-available.png'),
                    tip=_("Show the What's New box"))
     default.update(kwargs)
     return cls.create_action(**default)
Exemplo n.º 32
0
class ChangeObjects(ActionStep):
    """
    Pop up a list for the user to change objects
    
    :param objects: a list of objects to change
    :param admin: an instance of an admin class to use to edit the objects.
    
    .. image:: /_static/listactions/import_from_file_preview.png
    
    This action step can be customised using these attributes :    
        
    .. attribute:: window_title
    
        the window title of the dialog shown
        
    .. attribute:: title
    
        the title of the dialog shown
        
    .. attribute:: subtitle
    
        the subtitle of the dialog shown
        
    .. attribute:: icon
    
        the :class:`camelot.view.art.Icon` in the top right corner of
        the dialog
    
    """

    def __init__(self, objects, admin):
        self.objects = objects
        self.admin = admin
        self.window_title = admin.get_verbose_name_plural()
        self.title = _("Data Preview")
        self.subtitle = _("Please review the data below.")
        self.icon = Icon("tango/32x32/mimetypes/x-office-spreadsheet.png")

    def get_objects(self):
        """Use this method to get access to the objects to change in unit tests
        
        :return: the object to change
        """
        return self.objects

    def render(self):
        """create the dialog. this method is used to unit test
        the action step."""
        dialog = ChangeObjectsDialog(self.objects, self.admin)
        dialog.setWindowTitle(unicode(self.window_title))
        dialog.set_banner_title(unicode(self.title))
        dialog.set_banner_subtitle(unicode(self.subtitle))
        dialog.set_banner_logo_pixmap(self.icon.getQPixmap())
        #
        # the dialog cannot estimate its size, so use 75% of screen estate
        #
        desktop = QtGui.QApplication.desktop()
        available_geometry = desktop.availableGeometry(dialog)
        dialog.resize(available_geometry.width() * 0.75, available_geometry.height() * 0.75)
        return dialog

    def gui_run(self, gui_context):
        dialog = self.render()
        result = dialog.exec_()
        if result == QtGui.QDialog.Rejected:
            raise CancelRequest()
        return self.objects
Exemplo n.º 33
0
 def clear_image(self):
     dummy_image = Icon('tango/32x32/mimetypes/image-x-generic.png')
     self.set_pixmap(dummy_image.getQPixmap())