class StatisticsSelectionWidget(GroupBoxWidget):
    #this value is set up in __createModel__ method
    VALUE_COLUMN = 0

    """
    widget which gives ability to select statistics
    """
    @temporarySettingsDecorator()
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Statistics')
        super(StatisticsSelectionWidget, self).__init__(parent, **params)

        self.params = Params(**params)
        if self.params.statistics_base_classes == None:
            self.params.statistics_base_classes = [Asymmetry]

        if self.params.data_accessor:
            self.params.data_accessor.addListener(self,
                                __StatisticsSelectionVectorListener__(self))

        self.__createButtons__()
        self.__createTable__()
        self.__createModel__()
        self.__fillStatistics__(self.params.statistics_base_classes)

    def __createTable__(self):
        self.__table__ = TableViewWidget(self,
            change_check_count_handler=self.params.change_selection_count_handler,  # @IgnorePep8
            check_handler=self.__check_handler__)
        self.__table__.setSelectionMode(QAbstractItemView.MultiSelection)
        self.__table__.setSelectionBehavior(QAbstractItemView.SelectRows)

    def __createModel__(self):
        model = __StatisticsSelectionModel__(self)
        labels = QStringList(["Statistic", "Description", "Value"])
        StatisticsSelectionWidget.VALUE_COLUMN = labels.indexOf("Value")
        model.setNumValueColumn(StatisticsSelectionWidget.VALUE_COLUMN)
        model.setHorizontalHeaderLabels(labels)
        self.__table__.setModel(model)
        self.__table__.setColumnHidden(StatisticsSelectionWidget.VALUE_COLUMN,
                                       True)

    def __createButtons__(self):
        buttons_composite = CompositeWidget(self, layout=QHBoxLayout())
        PushButtonWidget(buttons_composite, i18n_def="Select all",
                    clicked_handler=self.__select_all_handler__)

        PushButtonWidget(buttons_composite, i18n_def="Unselect all",
                    clicked_handler=self.__unselect_all_handler__)

    def __select_all_handler__(self):
        self.__table__.changeCheckStatForAll(True)

    def __unselect_all_handler__(self):
        self.__table__.changeCheckStatForAll(False)

    def __fillStatistics__(self, _statistics_base_classes):
        model = self.__table__.model()
        model.removeRows(0, model.rowCount())

        self.__statistics_classes__ = []

        for base_class in _statistics_base_classes:
            for subclass in get_subclasses(base_class):
                self.__statistics_classes__.append(subclass)

        #sort alphabetically
        cmp_stat = lambda x, y: cmp(x.__name__, y.__name__)
        self.__statistics_classes__ = sorted(self.__statistics_classes__,
                                             cmp_stat)

        for statistic_class in self.__statistics_classes__:
            check_column = QStandardItem('%s' % statistic_class.__name__)
            check_column.setCheckState(Qt.Unchecked)
            check_column.setCheckable(True)

            description_column = QStandardItem(str(statistic_class().description)) # @IgnorePep8

            value_column = QStandardItem('')

            model.appendRow([check_column, description_column, value_column])

    @property
    def statistics_classes(self):
        return self.__statistics_classes__

    def getSelectedStatisticsClasses(self):
        selected_classes = []
        model = self.__table__.model()
        for idx in range(model.rowCount()):
            item = model.item(idx)
            if item.isCheckable() and item.checkState() == Qt.Checked:
                selected_classes.append(self.__statistics_classes__[idx])
        return selected_classes

    def setStatisticsValues(self, values_map):
        """
        method to set up statistics values
        """
        if values_map == None:
            return
        #show value column
        self.__table__.setColumnHidden(StatisticsSelectionWidget.VALUE_COLUMN,
                                       False)
        for statistic_class in values_map:
            row = self.__statistics_classes__.index(statistic_class)
            self.__table__.model().setItem(row,
                            StatisticsSelectionWidget.VALUE_COLUMN,
                            QStandardItem(str(values_map[statistic_class])))

    def __check_handler__(self, item):
        """
        handler invoked when a user check selected row in statistics
        table view, the parameter is an model's item
        """
        if self.params.check_handler:
            if item.isCheckable():
                statistic_class = self.__statistics_classes__[item.row()]
                #parameters of outer handler check_handler are
                #statistics object and whether is checked or unchecked
                self.params.check_handler(statistic_class(),
                                          item.checkState() == Qt.Checked)

    def checkStatistic(self, _statistic):
        """
        method checks statistic identified by a parameter - statistic class
        """
        row = self.__statistics_classes__.index(_statistic)
        if row >= 0:
            item = self.__table__.model().item(row)
            if item.isCheckable():
                item.setCheckState(Qt.Checked)

    def __getSelectedStatisticsClassesNames__(self):
        return [statistic_class.__name__
                for statistic_class in self.getSelectedStatisticsClasses()]

    @temporarySetterDecorator(name='selected_statistics',
                    _conv=QVariant.toPyObject,
                    _getter_handler=__getSelectedStatisticsClassesNames__)
    def __setSelectedStatistics__(self, _statistics_class_names):
        if not _statistics_class_names == None:
            model = self.__table__.model()
            for idx in range(model.rowCount()):
                item = model.item(idx)
                if item.isCheckable() and item.checkState() == Qt.Unchecked \
                    and self.__statistics_classes__[idx].__name__ in _statistics_class_names: # @IgnorePep8
                    item.setCheckState(Qt.Checked)
Example #2
0
class TableViewWidget(QTableView, Common):
    def __init__(self, parent, **params):
        super(TableViewWidget, self).__init__(parent)
        prepareWidget(parent=parent, widget=self, **params)
        self.params = Params(**params)
        self.__checked_count__ = 0
        self.__scroll_contents_by_handler__ = None

    @property
    def checked_count(self):
        """
        return number of rows at check state (if any)
        if return -1 than mean table view is not checkable
        """
        return self.__checked_count__ if self.is_checkable else -1

    @property
    def is_checkable(self):
        """
        return true if a table is checkable
        """
        model = self.model()
        if not model == None:
            for idx in range(model.rowCount()):
                if model.item(idx).isCheckable():
                    return True
        return False

    def changeCheckStatForAll(self, _check):
        """
        method changes check state (True/False) for the whole table view
        """
        if not self.is_checkable:
            return
        self.setEnabled(False)
        count = self.model().rowCount()
        progressManager = ProgressDialogManager(
            self,
            label_text=("Checking..." if _check else "Unchecking..."),
            max_value=count)
        with progressManager as progress:
            for idx in range(count):
                if (progress.wasCanceled()):
                    break
                progress.increaseCounter()
                self.model().item(idx).setCheckState(
                    Qt.Checked if _check else Qt.Unchecked)
        self.setEnabled(True)

    def setModel(self, model):
        super(TableViewWidget, self).setModel(model)
        #signal used when selected row check state is changed
        self.connect(self.model(), ITEM_CHANGED_SIGNAL, self.__itemChanged__)
        if self.params.rows_inserted_handler:
            self.connect(self.model(), ROWS_INSERTED_SIGNAL,
                         self.params.rows_inserted_handler)

    def __itemChanged__(self, item):
        if item.isCheckable():
            if item.checkState() == Qt.Checked:
                self.__checked_count__ = self.__checked_count__ + 1
            else:
                self.__checked_count__ = self.__checked_count__ - 1
            if self.params.change_check_count_handler:
                self.params.change_check_count_handler(self.__checked_count__)
            if self.params.check_handler:
                self.params.check_handler(item)

    def clearRows(self):
        """
        method deletes all rows
        """
        model = self.model()
        if model:
            if hasattr(model, 'removeRows'):
                self.__checked_count__ = 0
                model.removeRows(0, model.rowCount())

    def setScrollContentsByHandler(self, _handler):
        """
        set up a handler which will be invoked when scrolling happens
        """
        self.__scroll_contents_by_handler__ = _handler

    def scrollContentsBy(self, dx, dy):
        """
        overriding a method invoked when scrolling happens
        """
        super(TableViewWidget, self).scrollContentsBy(dx, dy)
        if (dx != 0 or dy != 0) and \
            not self.__scroll_contents_by_handler__ == None:
            self.__scroll_contents_by_handler__()
class StatisticsSelectionWidget(GroupBoxWidget):
    #this value is set up in __createModel__ method
    VALUE_COLUMN = 0
    """
    widget which gives ability to select statistics
    """
    @temporarySettingsDecorator()
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Statistics')
        super(StatisticsSelectionWidget, self).__init__(parent, **params)

        self.params = Params(**params)
        if self.params.statistics_base_classes == None:
            self.params.statistics_base_classes = [Asymmetry]

        if self.params.data_accessor:
            self.params.data_accessor.addListener(
                self, __StatisticsSelectionVectorListener__(self))

        self.__createButtons__()
        self.__createTable__()
        self.__createModel__()
        self.__fillStatistics__(self.params.statistics_base_classes)

    def __createTable__(self):
        self.__table__ = TableViewWidget(
            self,
            change_check_count_handler=self.params.
            change_selection_count_handler,  # @IgnorePep8
            check_handler=self.__check_handler__)
        self.__table__.setSelectionMode(QAbstractItemView.MultiSelection)
        self.__table__.setSelectionBehavior(QAbstractItemView.SelectRows)

    def __createModel__(self):
        model = __StatisticsSelectionModel__(self)
        labels = QStringList(["Statistic", "Description", "Value"])
        StatisticsSelectionWidget.VALUE_COLUMN = labels.indexOf("Value")
        model.setNumValueColumn(StatisticsSelectionWidget.VALUE_COLUMN)
        model.setHorizontalHeaderLabels(labels)
        self.__table__.setModel(model)
        self.__table__.setColumnHidden(StatisticsSelectionWidget.VALUE_COLUMN,
                                       True)

    def __createButtons__(self):
        buttons_composite = CompositeWidget(self, layout=QHBoxLayout())
        PushButtonWidget(buttons_composite,
                         i18n_def="Select all",
                         clicked_handler=self.__select_all_handler__)

        PushButtonWidget(buttons_composite,
                         i18n_def="Unselect all",
                         clicked_handler=self.__unselect_all_handler__)

    def __select_all_handler__(self):
        self.__table__.changeCheckStatForAll(True)

    def __unselect_all_handler__(self):
        self.__table__.changeCheckStatForAll(False)

    def __fillStatistics__(self, _statistics_base_classes):
        model = self.__table__.model()
        model.removeRows(0, model.rowCount())

        self.__statistics_classes__ = []

        for base_class in _statistics_base_classes:
            for subclass in get_subclasses(base_class):
                self.__statistics_classes__.append(subclass)

        #sort alphabetically
        cmp_stat = lambda x, y: cmp(x.__name__, y.__name__)
        self.__statistics_classes__ = sorted(self.__statistics_classes__,
                                             cmp_stat)

        for statistic_class in self.__statistics_classes__:
            check_column = QStandardItem('%s' % statistic_class.__name__)
            check_column.setCheckState(Qt.Unchecked)
            check_column.setCheckable(True)

            description_column = QStandardItem(
                str(statistic_class().description))  # @IgnorePep8

            value_column = QStandardItem('')

            model.appendRow([check_column, description_column, value_column])

    @property
    def statistics_classes(self):
        return self.__statistics_classes__

    def getSelectedStatisticsClasses(self):
        selected_classes = []
        model = self.__table__.model()
        for idx in range(model.rowCount()):
            item = model.item(idx)
            if item.isCheckable() and item.checkState() == Qt.Checked:
                selected_classes.append(self.__statistics_classes__[idx])
        return selected_classes

    def setStatisticsValues(self, values_map):
        """
        method to set up statistics values
        """
        if values_map == None:
            return
        #show value column
        self.__table__.setColumnHidden(StatisticsSelectionWidget.VALUE_COLUMN,
                                       False)
        for statistic_class in values_map:
            row = self.__statistics_classes__.index(statistic_class)
            self.__table__.model().setItem(
                row, StatisticsSelectionWidget.VALUE_COLUMN,
                QStandardItem(str(values_map[statistic_class])))

    def __check_handler__(self, item):
        """
        handler invoked when a user check selected row in statistics
        table view, the parameter is an model's item
        """
        if self.params.check_handler:
            if item.isCheckable():
                statistic_class = self.__statistics_classes__[item.row()]
                #parameters of outer handler check_handler are
                #statistics object and whether is checked or unchecked
                self.params.check_handler(statistic_class(),
                                          item.checkState() == Qt.Checked)

    def checkStatistic(self, _statistic):
        """
        method checks statistic identified by a parameter - statistic class
        """
        row = self.__statistics_classes__.index(_statistic)
        if row >= 0:
            item = self.__table__.model().item(row)
            if item.isCheckable():
                item.setCheckState(Qt.Checked)

    def __getSelectedStatisticsClassesNames__(self):
        return [
            statistic_class.__name__
            for statistic_class in self.getSelectedStatisticsClasses()
        ]

    @temporarySetterDecorator(
        name='selected_statistics',
        _conv=QVariant.toPyObject,
        _getter_handler=__getSelectedStatisticsClassesNames__)
    def __setSelectedStatistics__(self, _statistics_class_names):
        if not _statistics_class_names == None:
            model = self.__table__.model()
            for idx in range(model.rowCount()):
                item = model.item(idx)
                if item.isCheckable() and item.checkState() == Qt.Unchecked \
                    and self.__statistics_classes__[idx].__name__ in _statistics_class_names: # @IgnorePep8
                    item.setCheckState(Qt.Checked)
Example #4
0
class TableViewWidget(QTableView, Common):
    def __init__(self, parent, **params):
        super(TableViewWidget, self).__init__(parent)
        prepareWidget(parent=parent, widget=self, **params)
        self.params = Params(**params)
        self.__checked_count__ = 0
        self.__scroll_contents_by_handler__ = None

    @property
    def checked_count(self):
        """
        return number of rows at check state (if any)
        if return -1 than mean table view is not checkable
        """
        return self.__checked_count__ if self.is_checkable else -1

    @property
    def is_checkable(self):
        """
        return true if a table is checkable
        """
        model = self.model()
        if not model == None:
            for idx in range(model.rowCount()):
                if model.item(idx).isCheckable():
                    return True
        return False

    def changeCheckStatForAll(self, _check):
        """
        method changes check state (True/False) for the whole table view
        """
        if not self.is_checkable:
            return
        self.setEnabled(False)
        count = self.model().rowCount()
        progressManager = ProgressDialogManager(self,
                label_text=("Checking..." if _check else "Unchecking..."),
                max_value=count)
        with progressManager as progress:
            for idx in range(count):
                if (progress.wasCanceled()):
                    break
                progress.increaseCounter()
                self.model().item(idx).setCheckState(Qt.Checked
                                                if _check else Qt.Unchecked)
        self.setEnabled(True)

    def setModel(self, model):
        super(TableViewWidget, self).setModel(model)
        #signal used when selected row check state is changed
        self.connect(self.model(), ITEM_CHANGED_SIGNAL, self.__itemChanged__)
        if self.params.rows_inserted_handler:
            self.connect(self.model(), ROWS_INSERTED_SIGNAL,
                         self.params.rows_inserted_handler)

    def __itemChanged__(self, item):
        if item.isCheckable():
            if item.checkState() == Qt.Checked:
                self.__checked_count__ = self.__checked_count__ + 1
            else:
                self.__checked_count__ = self.__checked_count__ - 1
            if self.params.change_check_count_handler:
                self.params.change_check_count_handler(self.__checked_count__)
            if self.params.check_handler:
                self.params.check_handler(item)

    def clearRows(self):
        """
        method deletes all rows
        """
        model = self.model()
        if model:
            if hasattr(model, 'removeRows'):
                self.__checked_count__ = 0
                model.removeRows(0, model.rowCount())

    def setScrollContentsByHandler(self, _handler):
        """
        set up a handler which will be invoked when scrolling happens
        """
        self.__scroll_contents_by_handler__ = _handler

    def scrollContentsBy(self, dx, dy):
        """
        overriding a method invoked when scrolling happens
        """
        super(TableViewWidget, self).scrollContentsBy(dx, dy)
        if (dx != 0 or dy != 0) and \
            not self.__scroll_contents_by_handler__ == None:
            self.__scroll_contents_by_handler__()