oglops

How to show html in QComboBox lineEdit ?

Jul 22nd, 2013
700
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.65 KB | None | 0 0
  1. #! /usr/bin/env python
  2. """
  3.    Autor : Barish Chandran B
  4.    Description : PyQt4 custom combobox for selecting multiple options.
  5.    Created : Aug 10, 2012
  6.    Email : [email protected]
  7. """
  8. from PyQt4 import QtGui, QtCore
  9.  
  10. class MultiCheckComboBox(QtGui.QComboBox):
  11.     """ Class definition for the custom QComboBox that can select multiple
  12.        options using check-box.
  13.    """
  14.     def __init__(self, parent=None):
  15.         """ Initialization for MultiCheckComboBox class.
  16.  
  17.            Args:
  18.                parent (QWidget): parent widget to which the table is attached.
  19.        """
  20.         super(MultiCheckComboBox, self).__init__(parent)
  21.  
  22.         self._model = MultiCheckComboModel(self)
  23.         self._lineEdit = QtGui.QLineEdit()
  24.         self._listView = self.view()
  25.         self._separator = ', '
  26.         self._defaultText = 'all'
  27.         self._maxTextLength = 42
  28.         self._checkedItems = []
  29.  
  30.         self.setModel(self._model)
  31.         self._lineEdit.setReadOnly(True)
  32.         self.setLineEdit(self._lineEdit)
  33.         self.setInsertPolicy(QtGui.QComboBox.NoInsert)
  34.  
  35.         self._lineEdit.installEventFilter(self)
  36.         self._listView.installEventFilter(self)
  37.         self._listView.window().installEventFilter(self)
  38.         self._listView.viewport().installEventFilter(self)
  39.         self.installEventFilter(self)
  40.  
  41.         self.connect(self,
  42.                     QtCore.SIGNAL('activated(int)'),
  43.                     self.toggleCheckState)
  44.         self.connect(self._model,
  45.                     QtCore.SIGNAL('checkStateChanged()'),
  46.                     self.updateCheckedItems)
  47.         self.connect(self._model,
  48.                     QtCore.SIGNAL('rowsInserted(const QModelIndex&,int,int)'),
  49.                     self.updateCheckedItems)
  50.         self.connect(self._model,
  51.                     QtCore.SIGNAL('rowsRemoved(const QModelIndex&,int,int)'),
  52.                     self.updateCheckedItems)
  53.         self.connect(self,
  54.                     QtCore.SIGNAL('clearAll()'),
  55.                     self.clearAllEvent)
  56.         self.connect(self,
  57.                     QtCore.SIGNAL('checkAll()'),
  58.                     self.checkAllEvent)
  59.  
  60.     def defaultText(self):
  61.         """ Function to get the default text of ComboBox.
  62.  
  63.            Returns:
  64.                (str) return the default text.
  65.        """
  66.         return self._defaultText
  67.  
  68.     def setDefaultText(self, text):
  69.         """ Function to set the default text of ComboBox.
  70.  
  71.            Args:
  72.                text (str): string for default text
  73.        """
  74.         self._defaultText = text
  75.         self.updateCheckedItems()
  76.  
  77.     def itemCheckState(self, index):
  78.         """ Function to get the check state of the given item.
  79.  
  80.            Args:
  81.                index (QModelIndex):    model index of the item.
  82.        """
  83.         if self._model.itemData(index, QtCore.Qt.CheckStateRole).toInt():
  84.             return QtCore.Qt.Checked
  85.             QtCore.Qt.UnChecked
  86.  
  87.     def setItemCheckState(self, index, state):
  88.         """ Function to set the check state of the given item.
  89.  
  90.            Args:
  91.                index (QModelIndex):    model index of the item.
  92.                state (QCheckState):    check state of the item.
  93.        """
  94.         checkState = QtCore.Qt.Checked if state else QtCore.Qt.Unchecked
  95.         self._model.setItemData(index,
  96.                                 checkState,
  97.                                 QtCore.Qt.CheckStateRole)
  98.  
  99.     def separator(self):
  100.         """ Function to get the separator text for the ComboBox.
  101.  
  102.            Returns:
  103.                (str) return combobox's separator
  104.        """
  105.         return self._separator
  106.  
  107.     def setSeparator(self, separator):
  108.         """ Function to get the separator text for the ComboBox.
  109.  
  110.            Args:
  111.                separator (str):    separator as string.
  112.        """
  113.         self._separator = separator
  114.         self.updateCheckedItems()
  115.  
  116.     def maxTextLength(self):
  117.         """ Function to get the maximum length that display on the ComboBox.
  118.  
  119.            Returns:
  120.                (int) return combobox's maximum display length
  121.        """
  122.         return self._maxTextLength
  123.  
  124.     def setMaxTextLength(self, length):
  125.         """ Function to set the maximum length that display on the ComboBox.
  126.  
  127.            Args:
  128.                length (int):   combobox's maximum display length.
  129.        """
  130.         self._maxTextLength = length
  131.         self.updateCheckedItems()
  132.  
  133.     def checkedItems(self):
  134.         """ Function to get the checked items label as list.
  135.  
  136.            Returns:
  137.                (QStringList) list of item labels.
  138.        """
  139.         itemList = QtCore.QStringList()
  140.         if self._model:
  141.             modelIndex = self._model.index(0,
  142.                                             self.modelColumn(),
  143.                                             self.rootModelIndex())
  144.             modelIndexList = self._model.match(modelIndex,
  145.                                                 QtCore.Qt.CheckStateRole,
  146.                                                 QtCore.Qt.Checked,
  147.                                                 -1,
  148.                                                 QtCore.Qt.MatchExactly)
  149.             for mIndex in modelIndexList:
  150.                 itemList << mIndex.data().toString()      return itemList     def setCheckedItems(self, items):       """ Function to set the checked state for the given items.          Args:               items (QStringList):    list of item labels.        """         for item in items:          index = self.Findtext(item)             state = QtCore.Qt.Unchecked if index == -1 else QtCore.Qt.Checked           self.setItemCheckState(index, state)    def checkAll(self, check=False):        """ Function to set all the items as checked or unchecked based on          the argument.           Args:               check(bool):        check state.            Returns:                (list) : list of items Checked or UnChecked based                       on the status.      """         itemList = QtCore.QStringList()         searchState = QtCore.Qt.Checked         assignState = QtCore.Qt.Unchecked       if check:           searchState = QtCore.Qt.Unchecked           assignState = QtCore.Qt.Checked         if self._model:             modelIndex = self._model.index(0,                                           self.modelColumn(),                                             self.rootModelIndex())          modelIndexList = self._model.match(modelIndex,                                          QtCore.Qt.CheckStateRole,                                           searchState,                                            -1,                                             QtCore.Qt.MatchExactly)             for mIndex in modelIndexList:               self.setItemData(mIndex.row(),                              assignState,                                QtCore.Qt.CheckStateRole)       return itemList     def trimDisplayText(self, text):        """ Function to trim the display text base on the max length property.          Args:               text (str):     text to be trimmed.             Returns:                (str) : trimmed text.       """         textLength = self._maxTextLength - 3        if (self._maxTextLength and             self._maxTextLength > 3 and
  151.             len(text) > textLength):
  152.             text = '%s...' % text[:textLength]
  153.         return text
  154.  
  155.     def setEditText(self, text):
  156.         """ Override the setEditText function.
  157.  
  158.            Args:
  159.                text (str): default text for the ComboBox.
  160.        """
  161.         super(MultiCheckComboBox, self).setEditText(self.trimDisplayText(text))
  162.  
  163.     def reloadPopup(self):
  164.         """ Function to reload the popup of the Combobox.
  165.        """
  166.         currentIndex = self._listView.currentIndex()
  167.         scrollValue = self._listView.verticalScrollBar().value()
  168.         self.showPopup()
  169.         self._listView.setCurrentIndex(currentIndex)
  170.         self._listView.verticalScrollBar().setValue(scrollValue)
  171.  
  172.     def keyPressEvent(self, event):
  173.         """ Function to override key press event.
  174.  
  175.            Args:
  176.                event (QEvent):     event to overwrite.
  177.        """
  178.         if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
  179.             pass
  180.  
  181.     def eventFilter(self, obj, event):
  182.         """ Function to filter out the unwanted events and add new
  183.            functionalities for it.
  184.  
  185.            Args:
  186.                obj (QWidget):  list of strings that shows in QCompleter
  187.                event (QEvent):     event to be filtered
  188.  
  189.            Returns:
  190.                (bool) return the status in boolean.
  191.        """
  192.         eventType = event.type()
  193.         if eventType == QtCore.QEvent.KeyPress:
  194.             return False
  195.         if eventType == QtCore.QEvent.KeyRelease:
  196.             eventKey = event.key()
  197.             if (obj in (self, self._listView, self._lineEdit)
  198.                 and eventKey in (QtCore.Qt.Key_Up, QtCore.Qt.Key_Down)):
  199.                 self.reloadPopup()
  200.                 return False
  201.             elif obj == self._listView and eventKey == QtCore.Qt.Key_Space:
  202.                 self.reloadPopup()
  203.                 return True
  204.             elif obj == self._listView and eventKey in (QtCore.Qt.Key_Enter,
  205.                                                         QtCore.Qt.Key_Return,
  206.                                                         QtCore.Qt.Key_Escape,
  207.                                                         QtCore.Qt.Key_Tab):
  208.                 self.hidePopup()
  209.                 return True
  210.         if eventType == QtCore.QEvent.MouseButtonPress:
  211.             return False
  212.         if eventType == QtCore.QEvent.MouseButtonRelease:
  213.             eventButton = event.button()
  214.             if eventButton == QtCore.Qt.RightButton:
  215.                 return False
  216.             if obj == self._listView.viewport():
  217.                 self.emit(QtCore.SIGNAL('activated(int)'),
  218.                             self._listView.currentIndex().row())
  219.                 self.reloadPopup()
  220.                 return True
  221.             if obj == self._lineEdit:
  222.                 self.showPopup()
  223.             elif obj not in (self._listView, self._listView.window()):
  224.                 self.hidePopup()
  225.         return False
  226.  
  227.     def updateCheckedItems(self, index=None, start=None, end=None):
  228.         """ Slot to update the checkedItems when he dataChanged or
  229.            checkStateChanged Signal emits.
  230.  
  231.            Args:
  232.                index (int):    row index of the item.
  233.                start (int):    start index of the change
  234.                end (int):  end index of the change
  235.        """
  236.         itemList = self.checkedItems()
  237.         if not itemList or len(list(itemList)) == self._model.rowCount():
  238.             self.setEditText(self._defaultText)
  239.         else:
  240.             self.setEditText(itemList.join(self._separator))
  241.         self.emit(QtCore.SIGNAL('checkedItemsChanged(PyQt_PyObject)'), itemList)
  242.  
  243.     def toggleCheckState(self, index):
  244.         """ Slot to update the check state of the item in the given index,
  245.            Calls when the activated signal emits.
  246.  
  247.            Args:
  248.                index (QModelIndex):    index of the item that has to change.
  249.        """
  250.         value = self.itemData(index, QtCore.Qt.CheckStateRole)
  251.         if value.toInt()[0]:
  252.             state = QtCore.Qt.Unchecked
  253.         else:
  254.             state = QtCore.Qt.Checked
  255.         self.setItemData(index, state, QtCore.Qt.CheckStateRole)
  256.  
  257.     def clearAllEvent(self):
  258.         """ Event for clear all check from the list view.
  259.        """
  260.         self.checkAll(False)
  261.  
  262.     def checkAllEvent(self):
  263.         """ Event for check all from the list view.
  264.        """
  265.         self.checkAll(True)
  266.  
  267.     def contextMenuEvent(self, event):
  268.         """ Event for create context menu.
  269.            Args:
  270.                event (QEvent):     mouse right click event.
  271.        """
  272.         signalMap = {}
  273.         contextMenu = QtGui.QMenu(self)
  274.  
  275.         clearAllAction = contextMenu.addAction("Clear All")
  276.         signalMap[clearAllAction] = "clearAll()"
  277.         checkAllAction = contextMenu.addAction("Check All")
  278.         signalMap[checkAllAction] = "checkAll()"
  279.  
  280.         contextMenuAction = contextMenu.exec_(QtGui.QCursor.pos())
  281.         if contextMenuAction and contextMenuAction in signalMap:
  282.             self.emit(QtCore.SIGNAL(signalMap[contextMenuAction]))
  283.  
  284. class MultiCheckComboModel(QtGui.QStandardItemModel):
  285.     """ Class definition for the custom QComboBox that can select multiple
  286.        options using check-box.
  287.    """
  288.     def __init__(self, parent=None):
  289.         """ Initialization for MultiCheckComboModel class.
  290.  
  291.            Args:
  292.                parent(QWidget): parent widget to which the table is attached.
  293.        """
  294.         super(MultiCheckComboModel, self).__init__(parent)
  295.  
  296.     def flags(self, index):
  297.         """ Overwritten function to return the wanted roles for the
  298.            given index.
  299.  
  300.            Args:
  301.                index (QModelIndex):    index of the item.
  302.        """
  303.         return QtCore.Qt.ItemIsUserCheckable | \
  304.                 QtCore.Qt.ItemIsSelectable | \
  305.                 QtCore.Qt.ItemIsEnabled | \
  306.                 QtCore.Qt.ItemIsEditable
  307.  
  308.     def data(self, index, role):
  309.         """ Overwritten function to return value based on the role and index.
  310.  
  311.            Args:
  312.                index (QModelIndex):    index of the item that has to change.
  313.                role (UserRole):    Qt.UserRole
  314.  
  315.            Return:
  316.                (QVariant)  return the value for specific role.
  317.        """
  318.         value = super(MultiCheckComboModel, self).data(index, role)
  319.         if index.isValid() and role == QtCore.Qt.CheckStateRole:
  320.             if not value.isValid():
  321.                 return QtCore.Qt.Unchecked
  322.             else:
  323.                 return value
  324.         return value
  325.  
  326.     def setData(self, index, value, role):
  327.         """ Overwritten function to return set value based on the
  328.            role and index.
  329.  
  330.            Args:
  331.                index (QModelIndex):    index of the item that has to change.
  332.                value (QVariant):   value for the specific role.
  333.                role (UserRole):    Qt.UserRole
  334.  
  335.            Return:
  336.                (bool) return the status in boolean.
  337.        """
  338.         result = super(MultiCheckComboModel, self).setData(index, value, role)
  339.  
  340.         if result and role == QtCore.Qt.CheckStateRole:
  341.             self.emit(QtCore.SIGNAL('dataChanged(PyQt_PyObject, PyQt_PyObject)'),
  342.                                     index,
  343.                                     index)
  344.             self.emit(QtCore.SIGNAL('checkStateChanged()'))
  345.         return True
Advertisement
Add Comment
Please, Sign In to add comment