Package Camelot :: Package camelot :: Package view :: Package controls :: Package delegates :: Module customdelegate |
[frames] | no frames]

# Source Code for Module Camelot.camelot.view.controls.delegates.customdelegate

      1  #  ===========================================================================

      2  #

      3  #  Copyright (C) 2007-2008 Conceptive Engineering bvba. All rights reserved.

      4  #  www.conceptive.be / project-camelot@conceptive.be

      5  #

      6  #  This file is part of the Camelot Library.

      7  #

      8  #  This file may be used under the terms of the GNU General Public

      9  #  License version 2.0 as published by the Free Software Foundation

     10  #  and appearing in the file LICENSE.GPL included in the packaging of

     11  #  this file.  Please review the following information to ensure GNU

     12  #  General Public Licensing requirements will be met:

     13  #  http://www.trolltech.com/products/qt/opensource.html

     14  #

     15  #  If you are unsure which license is appropriate for your use, please

     16  #  review the following information:

     17  #  http://www.trolltech.com/products/qt/licensing.html or contact

     18  #  project-camelot@conceptive.be.

     19  #

     20  #  This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE

     21  #  WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

     22  #

     23  #  For use of this library in commercial applications, please contact

     24  #  project-camelot@conceptive.be

     25  #

     26  #  ===========================================================================

     27

     28  from PyQt4 import QtGui, QtCore
     29  from PyQt4.QtCore import Qt, SIGNAL
     30  from PyQt4.QtGui import QItemDelegate
     31  from camelot.core.utils import variant_to_pyobject
     32

     33  from camelot.view.controls import editors
     34  from camelot.core.utils import create_constant_function
     35  from camelot.view.proxy import ValueLoading
     36

     37  # custom color

     38  not_editable_background = QtGui.QColor(235, 233, 237)
     39  # darkgray

     40  not_editable_foreground = QtGui.QColor(Qt.darkGray)
     41

     42

     43 -def DocumentationMetaclass(name, bases, dct):
     44      dct['__doc__'] = dct.get('__doc__','') + """

     45

     46  .. _delegate-%s:

     47

     48  .. image:: ../_static/delegates/%s_unselected_disabled.png

     49  .. image:: ../_static/delegates/%s_unselected_editable.png

     50

     51  .. image:: ../_static/delegates/%s_selected_disabled.png

     52  .. image:: ../_static/delegates/%s_selected_editable.png

     53

     54  """%(name, name, name, name, name,)
     55      import inspect
     56

     57      def add_field_attribute_item(name):
     58          dct['__doc__'] = dct['__doc__'] + "\n * :ref:`%s <field-attribute-%s>`"%(arg, arg)
     59

     60      if '__init__' in dct:
     61          dct['__doc__'] = dct['__doc__'] + 'Field attributes supported by the delegate : \n'
     62          args, _varargs, _varkw,  _defaults = inspect.getargspec(dct['__init__'])
     63          for arg in args:
     64              if arg not in ['self', 'parent']:
     65                  add_field_attribute_item(arg)
     66

     67      if 'editor' in dct:
     68          dct['__doc__'] = dct['__doc__'] + '\nBy default, creates a %s as its editor.\n'%dct['editor'].__name__
     69          dct['__doc__'] = dct['__doc__'] + '\n.. image:: ../_static/editors/%s_editable.png'%dct['editor'].__name__ + '\n'
     70          dct['__doc__'] = dct['__doc__'] + 'Field attributes supported by this editor : \n'
     71          args, _varargs, _varkw,  _defaults = inspect.getargspec(dct['editor'].__init__)
     72          for arg in args:
     73              if arg not in ['self', 'parent']:
     74                  add_field_attribute_item(arg)
     75

     76      return type(name, bases, dct)
     77

     78

     79 -class CustomDelegate(QItemDelegate):
     80      """Base class for implementing custom delegates.

     81

     82  .. attribute:: editor

     83

     84  class attribute specifies the editor class that should be used

     85  """
     86

     87      editor = None
     88

     89 -    def __init__(self, parent=None, editable=True, **kwargs):
     90          """:param parent: the parent object for the delegate

     91  :param editable: a boolean indicating if the field associated to the delegate

     92  is editable"""
     93          QItemDelegate.__init__(self, parent)
     94          self.editable = editable
     95          self.kwargs = kwargs
     96          self._font_metrics = QtGui.QFontMetrics(QtGui.QApplication.font())
     97          self._height = self._font_metrics.lineSpacing() + 10
     98          self._width = self._font_metrics.averageCharWidth() * 20
     99

    100 -    def createEditor(self, parent, option, index):
    101          """:param option: use an option with version 5 to indicate the widget

    102  will be put onto a form"""
    103          editor = self.editor(parent, editable=self.editable, **self.kwargs)
    104          assert editor
    105          assert isinstance(editor, (QtGui.QWidget,))
    106          if option.version != 5:
    107              editor.setAutoFillBackground(True)
    108          self.connect(editor,

    109                       editors.editingFinished,

    110                       self.commitAndCloseEditor)
    111          return editor
    112

    113 -    def sizeHint(self, option, index):
    114          return QtCore.QSize(self._width, self._height)
    115

    116 -    def commitAndCloseEditor(self):
    117          editor = self.sender()
    118          assert editor
    119          assert isinstance(editor, (QtGui.QWidget,))
    120          self.emit(SIGNAL('commitData(QWidget*)'), editor)
    121          sig = SIGNAL('closeEditor(QWidget*, \

    122                                    QAbstractItemDelegate::EndEditHint)')
    123          self.emit(sig, editor, QtGui.QAbstractItemDelegate.NoHint)
    124

    125 -    def setEditorData(self, editor, index):
    126          if not index.model():
    127              return
    128          value = variant_to_pyobject(index.model().data(index, Qt.EditRole))
    129          editor.set_value(value)
    130          index.model().data(index, Qt.ToolTipRole)
    131          tip = variant_to_pyobject(index.model().data(index, Qt.ToolTipRole))
    132          if tip not in (None, ValueLoading):
    133              editor.setToolTip(unicode(tip))
    134          else:
    135              editor.setToolTip('')
    136          background_color = variant_to_pyobject(index.model().data(index, Qt.BackgroundRole))
    137          if background_color not in (None, ValueLoading):
    138              editor.set_background_color(background_color)
    139

    140 -    def setModelData(self, editor, model, index):
    141          if isinstance(model, QtGui.QStandardItemModel):
    142              val = QtCore.QVariant(editor.get_value())
    143          else:
    144              val = create_constant_function(editor.get_value())
    145          model.setData(index, val)
    146

    147 -    def paint_text(self, painter, option, index, text, margin_left=0, margin_right=0):
    148          """Paint unicode text into the given rect defined by option, and fill the rect with

    149          the background color

    150          :arg margin_left: additional margin to the left, to be used for icons or others

    151          :arg margin_right: additional margin to the right, to be used for icons or others"""
    152

    153          background_color = QtGui.QColor(index.model().data(index, Qt.BackgroundRole))
    154          rect = option.rect
    155

    156          if( option.state & QtGui.QStyle.State_Selected ):
    157              painter.fillRect(option.rect, option.palette.highlight())
    158              fontColor = QtGui.QColor()
    159              if self.editable:
    160                  Color = option.palette.highlightedText().color()
    161                  fontColor.setRgb(Color.red(), Color.green(), Color.blue())
    162              else:
    163                  fontColor.setRgb(130,130,130)
    164          else:
    165              if self.editable:
    166                  painter.fillRect(rect, background_color)
    167                  fontColor = QtGui.QColor()
    168                  fontColor.setRgb(0,0,0)
    169              else:
    170                  painter.fillRect(rect, option.palette.window())
    171                  fontColor = QtGui.QColor()
    172                  fontColor.setRgb(130,130,130)
    173

    174

    175          painter.setPen(fontColor.toRgb())
    176          painter.drawText(rect.x() + 2 + margin_left,

    177                           rect.y(),

    178                           rect.width() - 4 - (margin_left + margin_right),

    179                           rect.height(),

    180                           Qt.AlignVCenter | Qt.AlignLeft,

    181                           text)
    182