Пример #1
0
    def addLabelClass(self, label_config):
        # Check label configuration
        if 'attributes' not in label_config:
            raise ImproperlyConfigured("Label with no 'attributes' dict found")
        attrs = label_config['attributes']
        if 'class' not in attrs:
            raise ImproperlyConfigured("Labels must have an attribute 'class'")
        label_class = attrs['class']
        if label_class in self._class_config:
            raise ImproperlyConfigured(
                "Label with class '%s' defined more than once" % label_class)

        # Store config
        self._class_config[label_class] = label_config

        # Parse configuration and create handlers and item
        self.parseConfiguration(label_class, label_config)

        # Add label class button
        button_text = label_config['text']
        button = QPushButton(button_text, self)
        button.setCheckable(True)
        button.setFlat(True)
        button.clicked.connect(bind(self.onClassButtonPressed, label_class))
        self._class_buttons[label_class] = button
        self._classbox_layout.addWidget(button)

        # Add hotkey
        if 'hotkey' in label_config:
            hotkey = QShortcut(QKeySequence(label_config['hotkey']), self)
            hotkey.activated.connect(button.click)
            self._class_shortcuts[label_class] = hotkey
Пример #2
0
 def addComboClass(self, label_config):
     if 'text' not in label_config:
         raise ImproperlyConfigured("Combobox with no text found")
     attrs = label_config['text']
     if 'items' not in label_config:
         raise ImproperlyConfigured("Combobox with no items found")
     items = label_config['items']
     combobox = MaskComboItem(label_config)
     self._combo_items.append(combobox)
Пример #3
0
    def addLabelClass(self, label_config):
        """
        添加标签
        :param label_config: 标签的json
        """
        # Check label configuration
        if 'attributes' not in label_config:
            raise ImproperlyConfigured("Label with no 'attributes' dict found")
        attrs = label_config['attributes']
        if 'class' not in attrs:
            raise ImproperlyConfigured("Labels must have an attribute 'class'")
        label_class = attrs['class']
        if label_class in self._class_config:
            raise ImproperlyConfigured(
                "Label with class '%s' defined more than once" % label_class)

        # Store config
        self._class_config[label_class] = label_config

        # Parse configuration and create handlers and item
        self.parseConfiguration(label_class, label_config)

        # Add label class button
        button_text = label_config['text']
        button = QPushButton(button_text)
        button.setCheckable(True)
        button.setFlat(True)
        button.clicked.connect(bind(self.onClassButtonPressed, label_class))
        self._class_buttons[label_class] = button
        self._parea.setGeometry(0, 0, 200,
                                self._parea.geometry().height() + 40)
        self._classbox_layout.addWidget(button)

        # 添加右键菜单
        self.label_menu[label_class] = QtGui.QMenu(self)
        self.label_action[label_class] = self.label_menu[
            label_class].addAction('删除')
        self.label_action[label_class].triggered.connect(
            bind(self.remove_item, label_class))
        self._class_buttons[label_class].setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self._class_buttons[label_class].customContextMenuRequested.connect(
            bind(self.showContextMenu, label_class))

        # Add hotkey
        if 'hotkey' in label_config:
            # 快捷键
            hotkey = label_config['hotkey']
            # 快捷键已经存在,那就去掉原来的
            if hotkey in self.shortcut2button and self.shortcut2button[
                    hotkey] is not None:
                self.shortcut2button[hotkey].setShortcut(QKeySequence())
            # 设置快捷键
            button.setShortcut(QKeySequence(hotkey))
            self.shortcut2button[hotkey] = button
            self.label2shortcut[label_class] = hotkey
Пример #4
0
 def addShortcut(self, shortcut, widget, value):
     if widget is not None:
         if shortcut not in self._shortcuts:
             sc = QShortcut(QKeySequence(shortcut), self)
             self._shortcuts[shortcut] = sc
             if isinstance(widget, QPushButton):
                 sc.activated.connect(bind(lambda w: w.click() if not w.isChecked() else None, widget))
             elif isinstance(widget, QLineEdit):
                 sc.activated.connect(self.focusInputField)
         else:
             raise ImproperlyConfigured("Shortcut '%s' defined more than once" % shortcut)
     else:
         raise ImproperlyConfigured("Shortcut '%s' defined for value '%s' which is hidden" % (shortcut, value))
Пример #5
0
    def updateValues(self, values):
        if isinstance(values, type):
            self.addInputField(values)
        else:
            for val in values:
                v = val
                shortcut = None
                widget = None

                # Handle the case of the value being a 2-tuple consisting of (value, shortcut)
                if type(val) is tuple or type(val) is list:
                    if len(val) == 2:
                        v = val[0]
                        shortcut = val[1]
                    else:
                        raise ImproperlyConfigured(
                            "Values must be types, strings, numbers, or tuples of length 2: '%s'"
                            % str(val))

                # Handle the case where value is a Python type
                if isinstance(v, type):
                    if v is float or v is int or v is str:
                        self.addInputField(v)
                        widget = self._inputField
                    else:
                        raise ImproperlyConfigured(
                            "Input field with type '%s' not supported" % v)

                # * marks the position where buttons for new values will be insered
                elif val == "*" or val == "<*":
                    self._insertIndex = self._layout.count()
                elif val == "*>":
                    self._insertIndex = self._layout.count()
                    self._insertAtEnd = True

                # Add the value button
                else:
                    self.addValue(v)
                    widget = self._buttons[v]

                # If defined, add the specified shortcut
                if shortcut is not None:
                    self.addShortcut(shortcut, widget, v)
Пример #6
0
    def addInputField(self, _type):
        if self._inputField is None:
            self._inputFieldType = _type
            self._inputField = QLineEdit()
            if _type is float:
                self._inputField.setValidator(QDoubleValidator())
            elif _type is int:
                self._inputField.setValidator(QIntValidator())

            self._layout.addWidget(self._inputField)
            self._inputField.returnPressed.connect(self.onInputFieldReturnPressed)
        elif self._inputFieldType is not _type:
            raise ImproperlyConfigured("Input field for attribute '%s' configured twice with different types %s != %s"\
                    % (self._attribute, self._inputFieldType, _type))
Пример #7
0
    def create(self, filename, *args, **kwargs):
        """
        Create a container for the filename.

        Parameters
        ==========
        filename: str
            Filename for which a matching container should be created.
        *args, **kwargs:
            Arguments passed to constructor of the container.
        """
        for pattern, container in self._containers:
            if fnmatch.fnmatch(filename, pattern):
                return container(*args, **kwargs)
        raise ImproperlyConfigured("No container registered for filename %s" %
                                   filename)
Пример #8
0
    def addButton(self, buttonConfig):
        # LOG.info("addLabelClass with buttonConfig {} ...".format(buttonConfig))
        # Check label configuration
        if 'attributes' not in buttonConfig:
            raise ImproperlyConfigured("Label with no 'attributes' dict found")

        inserter_creator_method = buttonConfig['inserter']
        inserted_item_creator_method = buttonConfig['item']

        attrs = buttonConfig['attributes']
        # LOG.info("buttonConfig['attributes'] {} type {} ...".format(buttonConfig['attributes'], type(buttonConfig['attributes'])))
        if config.METADATA_LABELCLASS_TOKEN not in attrs:
            raise ImproperlyConfigured(
                "Labels must have an attribute config.METADATA_LABELCLASS_TOKEN"
            )
        label_class = attrs[config.METADATA_LABELCLASS_TOKEN]
        # LOG.info("buttonConfig['attributes'][config.METADATA_LABELCLASS_TOKEN] {} type {} ...".format(attrs[config.METADATA_LABELCLASS_TOKEN], type(attrs[config.METADATA_LABELCLASS_TOKEN])))
        if label_class in self._inserters_modelitems:
            raise ImproperlyConfigured(
                "Label with class '%s' defined more than once" % label_class)

        # Add INSERTER button
        displaytext = attrs['displaytext']
        buttonName = label_class
        button = QPushButton(displaytext, self)

        optionInfo = attrs.get('optioninfo', None)
        # print "button {}: option {}".format(buttonName, optionInfo)
        buttonOptionsWidget = None
        buttonDisplayColor = None
        tmp = [
            o.get(default_config.METADATA_DISPLAYCOLOR_TOKEN, None)
            for o in optionInfo['option']
            if o.get(config.METADATA_IS_DEFAULT_TOKEN, False)
        ][0] if optionInfo else None
        buttonDisplayColor = tmp if tmp else optionInfo['option'][0].get(
            default_config.METADATA_DISPLAYCOLOR_TOKEN,
            None) if optionInfo else attrs.get(
                default_config.METADATA_DISPLAYCOLOR_TOKEN, None)

        # LOG.info(u"buttonConfig['attributes'] = {}, displaytext = {}, displayColor = {}".format(attrs, displaytext, buttonDisplayColor))

        # ==== zx add @ 20161114 to display button with color configured by user ====
        txtColor = None
        if buttonDisplayColor is not None:
            qtColor, hexColor = utils.getColorDesc(buttonDisplayColor)
            rgba = utils.hexColorStrToRGBA(hexColor)
            distance = math.sqrt((rgba[0] - 255)**2 + (rgba[1] - 255)**2 +
                                 (rgba[2] - 255)**2)
            txtColor = '#000000' if distance > config.GUI_COLOR_TAG_TEXT_BLACKWHITE_TOGGLE_THRESHOLD else '#ffffff'
            buttonDisplayColor = hexColor[0:8]
            # LOG.info(u"buttonDisplayColor = {} txtColor = {}, qtColor = {} hexColor = {}".format(buttonDisplayColor, txtColor, qtColor, hexColor ))
            # print (u"buttonDisplayColor = {} txtColor = {}, qtColor = {} hexColor = {}".format(buttonDisplayColor, txtColor, qtColor, hexColor ))

        # print "button {} buttonDisplayColor {} ...".format(buttonName, buttonDisplayColor)
        utils.set_qobj_stylesheet(
            button,
            'QPushButton',
            widgetBackgroundColor=None,
            widgetTextColor=None,
            widgetBackgroundColorWhenChecked=buttonDisplayColor,
            widgetTextColorWhenChecked=txtColor)
        # ========================== zx add end ============================

        button.clicked.connect(bind(self.onClassButtonPressed, label_class))
        # Add hotkey
        if 'hotkey' in buttonConfig:
            hotkey = QShortcut(QKeySequence(buttonConfig['hotkey']), self)
            hotkey.activated.connect(button.click)
            self._class_shortcuts[label_class] = hotkey
            # print "{} is set hotkey {} {}".format(label_class, buttonConfig['hotkey'], hotkey)

        if optionInfo:
            optionListName = optionInfo['name']
            optionListText = optionInfo['displaytext']
            option = optionInfo['option']
            buttonOptionsWidget = AttachedCheckboxGroupWidget(
                buttonName,
                optionListName,
                optionListText,
                True,
                option,
                self._optionsCheckboxStateChangedSignal,
                parent=None)

            isDefaultOption = False
            for o in option:
                new_class = o.get('tag', None)
                if new_class:
                    # Add prototype mdoelItem for insertion
                    mi = {config.METADATA_LABELCLASS_TOKEN: new_class}
                    mi['displaytext'] = o.get('displaytext', new_class)

                    self._inserters_modelitems[
                        new_class] = AnnotationModelItem(mi)
                    self._inserters_guiitems[new_class] = (
                        inserter_creator_method, inserted_item_creator_method)
                    # print "addButton.....self._inserters_guiitems[{}] = {}".format(new_class, (inserter_creator_method, inserted_item_creator_method))
                    for key, val in o.iteritems():
                        if key != 'tag':
                            self._inserters_modelitems[new_class][key] = val

        else:
            attrs = buttonConfig['attributes']

            # Add prototype mdoelItem for insertion
            mi = {config.METADATA_LABELCLASS_TOKEN: label_class}
            mi['displaytext'] = attrs.get('displaytext', label_class)

            self._inserters_modelitems[label_class] = AnnotationModelItem(mi)
            self._inserters_guiitems[label_class] = (
                inserter_creator_method, inserted_item_creator_method)

            # update their values
            for key, val in attrs.iteritems():
                self._inserters_modelitems[label_class][key] = val
                # LOG.info("self._inserters_modelitems[{}][{}] = {}".format(label_class, key, val))

        self._widgets_dict[label_class] = [button, buttonOptionsWidget]
        # print "self._widgets_dict [ {} ] = {}".format(label_class, button)

        button.setCheckable(True)

        utils.set_qobj_stylesheet(
            self._widgets_dict[label_class][0],
            'QPushButton',
            widgetBackgroundColor=None,
            widgetTextColor=None,
            widgetBackgroundColorWhenChecked=buttonDisplayColor,
            widgetTextColorWhenChecked=txtColor)

        if buttonOptionsWidget:
            # self._layout.addWidget(button)
            self._inserterButtonGroup_layout.addWidget(button)
            self._layout.addWidget(buttonOptionsWidget)
        else:
            self._inserterButtonGroup_layout.addWidget(button)