Esempio n. 1
0
    def __init__(self,
                 values,
                 errors=None,
                 colors=None,
                 header='',
                 fsize=9,
                 height=0,
                 hlines=None,
                 kind='bar',
                 hlines_col=None,
                 extras=None,
                 col_width=11,
                 ylim=None,
                 xlabel='',
                 ylabel=''):

        self.col_w = float(col_width)
        self.height = height
        #        self.values = [float(v) for v in values]
        self.values = [int(v) for v in values]
        self.width = self.col_w * len(self.values)
        self.errors = errors if errors else []
        self.colors = colors if colors else ['gray'] * len(self.values)
        self.header = header
        self.fsize = fsize
        if ylim:
            self.ylim = tuple((float(y) for y in ylim))
        else:
            self.ylim = (int(min(self.values) - 0.5),
                         int(max(self.values) + 0.5))
        self.xlabel = xlabel
        self.ylabel = ylabel

        if self.errors:
            if type(self.errors[0]) is list or type(self.errors[0]) is tuple:
                self._up_err = [float(e[1]) for e in self.errors]
                self._dw_err = [float(-e[0]) for e in self.errors]
            else:
                self._up_err = [float(e) for e in self.errors]
                self._dw_err = [float(-e) for e in self.errors]
        if kind == 'bar':
            self.draw_fun = self.draw_bar
        elif kind == 'stick':
            self.draw_fun = self.draw_stick
        elif kind == 'curve':
            self.draw_fun = self.draw_curve
        else:
            raise 'kind %s not yet implemented... ;)'

        self.hlines = [float(h) for h in hlines] if hlines else [1.0]
        self.hlines_col = hlines_col if hlines_col else ['black'] * len(
            self.hlines)

        self.extras = extras if extras else ['']
        if len(self.extras) != len(self.values):
            self.extras = ['']

        super(RulerFace, self).__init__(
            QGraphicsRectItem(-40, 0, self.width + 40, self.height + 50))
        self.item.setPen(QPen(QColor('white')))
Esempio n. 2
0
    def update_items(self):
        self.item = QGraphicsRectItem(-30, 0, self.width + 40,
                                      self.height + 70)
        #self.item.setPen(QPen(QColor('gray')))
        self.item.setPen(QPen(QColor('white')))

        try:
            put_colored_boxes = self.put_colored_boxes
        except AttributeError:
            put_colored_boxes = (False, 0)

        if put_colored_boxes[0]:
            (_, tree_h) = put_colored_boxes
            self.draw_colored_boxes(tree_h)

        # draw lines
        for line, col in zip(self.hlines, self.hlines_col):
            self.draw_hlines(line, col)
        # draw plot
        width = self.col_w
        for i, val in enumerate(self.values):
            self.draw_fun(width * i + self.col_w / 2, val, i)
        # draw error bars
        if self.errors:
            for i in range(len(self.errors)):
                self.draw_errors(width * i + self.col_w / 2, i)
        # draw x axis
        self.draw_x_axis()
        # draw y axis
        self.draw_y_axis()
        # put header
        self.write_header()
Esempio n. 3
0
 def showMoveHelper(self, visible=True):
     """show help text In empty HandBoards"""
     if visible:
         if not self.__moveHelper:
             splitter = QGraphicsRectItem(self)
             hbCenter = self.rect().center()
             splitter.setRect(hbCenter.x() * 0.5, hbCenter.y(), hbCenter.x() * 1, 1)
             helpItems = [splitter]
             for name, yFactor in [(m18n('Move Exposed Tiles Here'), 0.5),
                                     (m18n('Move Concealed Tiles Here'), 1.5)]:
                 helper = QGraphicsSimpleTextItem(name, self)
                 helper.setScale(3)
                 nameRect = QRectF()
                 nameRect.setSize(helper.mapToParent(helper.boundingRect()).boundingRect().size())
                 center = QPointF(hbCenter)
                 center.setY(center.y() * yFactor)
                 helper.setPos(center - nameRect.center())
                 if self.sceneRotation() == 180:
                     rotateCenter(helper, 180)
                 helpItems.append(helper)
             self.__moveHelper = self.scene().createItemGroup(helpItems)
         self.__moveHelper.setVisible(True)
     else:
         if self.__moveHelper:
             self.__moveHelper.setVisible(False)
Esempio n. 4
0
    def mousePressEvent(self, event):
        pos = event.scenePos()
        any_item = self.scene.item_at(pos)
        if not any_item and event.button() & Qt.LeftButton:
            self.modifiers = event.modifiers()
            self.selection_rect = QRectF(pos, QSizeF(0, 0))
            self.rect_item = QGraphicsRectItem(
                self.selection_rect.normalized())

            self.rect_item.setPen(
                QPen(QBrush(QColor(51, 153, 255, 192)), 0.4, Qt.SolidLine,
                     Qt.RoundCap))

            self.rect_item.setBrush(QBrush(QColor(168, 202, 236, 192)))

            self.rect_item.setZValue(-100)

            # Clear the focus if necessary.
            if not self.scene.stickyFocus():
                self.scene.clearFocus()

            if not self.modifiers & Qt.ControlModifier:
                self.scene.clearSelection()

            event.accept()
            return True
        else:
            self.cancel(self.ErrorReason)
            return False
def scientific_name_face(node, *args, **kwargs):
    scientific_name_text = QGraphicsTextItem()
    #underscore = node.name.replace("_", " ")
    words = node.name.split("_")
    text = []
    if len(words) < 2:
        # some sort of acronym or bin name, leave it alone
        text = words
    elif len(words) > 2:
        if len(words) >= 5:
            text.extend(
                ['<b>' + words[0] + ' <i> ' + words[1], words[2] + ' </i> '])
            text.extend(words[3:] + ['</b>'])

        elif len(words) == 3:
            text.extend([
                ' <span style="color:grey"><i> ' + words[0],
                words[1] + words[2] + '  </i></span>'
            ])

        else:
            # assume that everything after the
            # second word is strain name
            # which should not get italicized
            text.extend([
                ' <span style="color:grey"><i> ' + words[0],
                words[1] + '  </i></span>'
            ])
            text.extend(words[2:])
    else:
        text.extend([
            ' <span style="color:grey"><i> ' + words[0],
            words[1] + ' </i></span> '
        ])

    scientific_name_text.setHtml(' '.join(text))

    # below is a bit of a hack - I've found that the height of the bounding
    # box gives a bit too much padding around the name, so I just minus 10
    # from the height and recenter it. Don't know whether this is a generally
    # applicable number to use
    #myFont = QFont()
    masterItem = QGraphicsRectItem(
        0, 0,
        scientific_name_text.boundingRect().width(),
        scientific_name_text.boundingRect().height() - 10)

    scientific_name_text.setParentItem(masterItem)
    center = masterItem.boundingRect().center()
    scientific_name_text.setPos(
        masterItem.boundingRect().x(),
        center.y() - scientific_name_text.boundingRect().height() / 2)

    # I don't want a border around the masterItem
    masterItem.setPen(QPen(QtCore.Qt.NoPen))

    return masterItem
Esempio n. 6
0
 def __init__(self, text, parent):
     QGraphicsObject.__init__(self, parent)
     self.text_item = QGraphicsTextItem(text + ':', self)
     f = self.text_item.font()
     f.setBold(True)
     self.text_item.setFont(f)
     self.rect_item = QGraphicsRectItem(self.text_item.boundingRect(), self)
     self.rect_item.setPen(QPen(Qt.NoPen))
     self.rect_item.stackBefore(self.text_item)
Esempio n. 7
0
 def __init__(self,
              pen=QPen(Qt.black),
              brush=QBrush(Qt.white),
              xData=None,
              yData=None,
              tooltip=None):
     OWCurve.__init__(self, xData, yData, tooltip=tooltip)
     self.set_pen(pen)
     self.set_brush(brush)
     self._item = QGraphicsRectItem(self)
Esempio n. 8
0
 def __init__(self):
     QGraphicsScene.__init__(self)
     self.__disableFocusRect = False
     self._focusBoard = None
     self.focusRect = QGraphicsRectItem()
     pen = QPen(QColor(Qt.blue))
     pen.setWidth(6)
     self.focusRect.setPen(pen)
     self.addItem(self.focusRect)
     self.focusRect.setZValue(ZValues.marker)
     self.focusRect.hide()
Esempio n. 9
0
    def _setSceneRect(self):
        w, h = self.dataShape
        rect = self.data2scene.mapRect(QRect(0, 0, w, h))
        sw, sh = rect.width(), rect.height()
        self.setSceneRect(0, 0, sw, sh)

        #this property represent a parent to QGraphicsItems which should
        #be clipped to the data, such as temporary capped lines for brushing.
        #This works around ilastik issue #516.
        self.dataRect = QGraphicsRectItem(0, 0, sw, sh)
        self.dataRect.setPen(QPen(QColor(0, 0, 0, 0)))
        self.dataRect.setFlag(QGraphicsItem.ItemClipsChildrenToShape)
        self.addItem(self.dataRect)
Esempio n. 10
0
        def hoverEnterEvent(self, e):
            """ when mouse is over"""
            if not self.label:
                self.label = QGraphicsRectItem(parent=self)
                #self.label.setY(-18)
                self.label.setX(11)
                self.label.setBrush(QBrush(QColor("white")))
                self.label.text = QGraphicsSimpleTextItem(parent=self.label)

            self.setZValue(1)
            self.label.text.setText(self.codon)
            self.label.setRect(self.label.text.boundingRect())
            self.label.setVisible(True)
Esempio n. 11
0
    def setTiles(self):
        #background
        brush = QBrush()
        pix = QPixmap(os.getcwd() + "/robotImages/tile.png")
        brush.setTexture(pix)
        brush.setStyle(24)
        self.setBackgroundBrush(brush)

        #wall
        #left
        left = QGraphicsRectItem()
        pix = QPixmap(os.getcwd() + "/robotImages/tileVert.png")
        left.setRect(QtCore.QRectF(0, 0, pix.width(), self.height))
        brush.setTexture(pix)
        brush.setStyle(24)
        left.setBrush(brush)
        left.name = 'left'
        self.addItem(left)
        #right
        right = QGraphicsRectItem()
        right.setRect(self.width - pix.width(), 0, pix.width(), self.height)
        right.setBrush(brush)
        right.name = 'right'
        self.addItem(right)
        #top
        top = QGraphicsRectItem()
        pix = QPixmap(os.getcwd() + "/robotImages/tileHori.png")
        top.setRect(QtCore.QRectF(0, 0, self.width, pix.height()))
        brush.setTexture(pix)
        brush.setStyle(24)
        top.setBrush(brush)
        top.name = 'top'
        self.addItem(top)
        #bottom
        bottom = QGraphicsRectItem()
        bottom.setRect(0, self.height - pix.height(), self.width, pix.height())
        bottom.setBrush(brush)
        bottom.name = 'bottom'
        self.addItem(bottom)
Esempio n. 12
0
def scientific_name_face(node, *args, **kwargs):
    scientific_name_text = QGraphicsTextItem()
    words = node.visual_label.split()
    text = []
    if hasattr(node, 'bg_col'):
        container_div = '<div style="background-color:{};">'.format(node.bgcolor)
        text.append(container_div)
    if len(words) < 2:
        # some sort of acronym or bin name, leave it alone
        text.extend(words)

    elif len(words) > 2:
        if words[0] == 'Candidatus':
            # for candidatus names, only the Candidatus part is italicised
            # name shortening it for brevity
            text.append('<i>Ca.</i>')
            text.extend(words[1:])
        elif re.match('^[A-Z]+$', words[0]):
            # If the first word is in all caps then it is an abreviation
            # so we don't want to italicize that at all
            text.extend(words)
        else:
            # assume that everything after the second word is strain name
            # which should not get italicised
            text.extend(['<i>'+words[0],words[1]+'</i>'])
            text.extend(words[2:])
    else:
        text.extend(['<i>'+words[0],words[1]+'</i>'])

    if hasattr(node, 'bg_col'):
        text.append('</div>')
    scientific_name_text.setHtml(' '.join(text))
    #print(scientific_name_text.boundingRect().width(), scientific_name_text.boundingRect().height())

    # below is a bit of a hack - I've found that the height of the bounding
    # box gives a bit too much padding around the name, so I just minus 10
    # from the height and recenter it. Don't know whether this is a generally
    # applicable number to use
    masterItem = QGraphicsRectItem(0, 0, scientific_name_text.boundingRect().width(), scientific_name_text.boundingRect().height() - 10)


    scientific_name_text.setParentItem(masterItem)
    center = masterItem.boundingRect().center()
    scientific_name_text.setPos(masterItem.boundingRect().x(), center.y() - scientific_name_text.boundingRect().height()/2)
    # I dont want a border around the masterItem
    masterItem.setPen(QPen(QtCore.Qt.NoPen))


    return masterItem
Esempio n. 13
0
    def hoverEnterEvent(self, event):
        """ Stuff related to hover enter events.

        For now we just show a rectangular outline.

        """

        if not self._outline:
            self._outline = QGraphicsRectItem(self.boundingRect(), self)
            highlightColor = QColor(Qt.blue)
            highlightColor.setAlpha(30)
            self._outline.setBrush(highlightColor)
            highlightPen = QPen(Qt.blue)
            highlightPen.setWidth(2)
            self._outline.setPen(highlightPen)
        else:
            self._outline.show()
Esempio n. 14
0
    def hoverEnterEvent(self, e):
        # There are many ways of adding interactive elements. With the
        # following code, I show/hide a text item over my custom
        # DynamicItemFace
        if not self.label:
            self.label = QGraphicsRectItem()
            self.label.setParentItem(self)
            # This is to ensure that the label is rendered over the
            # rest of item children (default ZValue for items is 0)
            self.label.setZValue(1)
            self.label.setBrush(QBrush(QColor("white")))
            self.label.text = QGraphicsSimpleTextItem()
            self.label.text.setParentItem(self.label)

        self.label.text.setText(self.node.name)
        self.label.setRect(self.label.text.boundingRect())
        self.label.setVisible(True)
Esempio n. 15
0
    def update_items(self):
        rect_h = self.height
        if self.x_axis:
            rect_h += 30
        self.item = QGraphicsRectItem(0, 0, self.width + 40, rect_h)
        self.item.setPen(QPen(QColor('white')))

        #X axis

        if self.x_axis:
            self.draw_x_axis()

        # Legend

        self.draw_legend()

        # Y axes and colo rect
        yi = -1
        for model in ["PCOC", "PC", "OC", "Topological", "Identical"]:
            if self.dict_values_pcoc.has_key(model):
                yi += 1
                y = yi * self.col_w

                # Y axes
                ## Stick
                yaxis = (yi + 0.5) * self.col_w
                lineItem = QGraphicsLineItem(self.width,
                                             yaxis,
                                             self.width + 5,
                                             yaxis,
                                             parent=self.item)
                lineItem.setPen(QPen(QColor('black')))
                ## Text
                text = QGraphicsSimpleTextItem(model)
                text.setFont(QFont("Arial", self.fsize - 2))
                text.setParentItem(self.item)
                tw = text.boundingRect().width()
                th = text.boundingRect().height()
                ## Center text according to masterItem size
                text.setPos(self.width + 5, yaxis - th / 2)

                # Color rect for each model
                values = self.dict_values_pcoc[model]
                for i, val in enumerate(values):
                    self.draw_fun(i * self.col_w, y, val, col_width=self.col_w)
Esempio n. 16
0
def ugly_name_face(node, *args, **kargs):
    """ This is my item generator. It must receive a node object, and
    returns a Qt4 graphics item that can be used as a node face.
    """
    width = node.dist * 2.5
    height = 12
    masterItem = InteractiveItem(0, 0, width, height)
    masterItem.node = node
    masterItem.setPen(QPen(QtCore.Qt.NoPen))

    color_rect = QGraphicsRectItem(masterItem.rect())
    color_rect.setParentItem(masterItem)
    color_rect.setBrush(QBrush(QColor(100, 100, 200, 100)))
    color_rect.setPen(QPen(QtCore.Qt.NoPen))

    masterItem.color_rect = color_rect

    return masterItem
Esempio n. 17
0
    def __init__(self, palette, values, parent):
        QGraphicsObject.__init__(self, parent)
        self.parent = parent
        self.palette = palette
        self.values = values
        self.legend = parent
        self.label_items = [QGraphicsTextItem(text, self) for text in values]
        for i in self.label_items:
            i.setTextWidth(50)

        self.rect = QRectF()

        self.gradient_item = QGraphicsRectItem(self)
        self.gradient = QLinearGradient()
        self.gradient.setStops([(v * 0.1, self.palette[v * 0.1])
                                for v in range(11)])
        self.orientation = Qt.Horizontal
        self.set_orientation(Qt.Vertical)
Esempio n. 18
0
 def updateSelectionRect(self, event):
     pos = event.scenePos()
     buttonDownPos = event.buttonDownScenePos(Qt.LeftButton)
     rect = QRectF(pos, buttonDownPos).normalized()
     rect = rect.intersected(self.sceneRect())
     if not self.selectionRect:
         self.selectionRect = QGraphicsRectItem()
         self.selectionRect.setBrush(QColor(10, 10, 10, 20))
         self.selectionRect.setPen(QPen(QColor(200, 200, 200, 200)))
         self.addItem(self.selectionRect)
     self.selectionRect.setRect(rect)
     if event.modifiers() & Qt.ControlModifier or \
             event.modifiers() & Qt.ShiftModifier:
         path = self.selectionArea()
     else:
         path = QPainterPath()
     path.addRect(rect)
     self.setSelectionArea(path)
     self.selectionRectPointChanged.emit(pos)
Esempio n. 19
0
def render_drop_shadow_frame(pixmap, shadow_rect, shadow_color,
                             offset, radius, rect_fill_color):
    pixmap.fill(QColor(0, 0, 0, 0))
    scene = QGraphicsScene()
    rect = QGraphicsRectItem(shadow_rect)
    rect.setBrush(QColor(rect_fill_color))
    rect.setPen(QPen(Qt.NoPen))
    scene.addItem(rect)
    effect = QGraphicsDropShadowEffect(color=shadow_color,
                                       blurRadius=radius,
                                       offset=offset)

    rect.setGraphicsEffect(effect)
    scene.setSceneRect(QRectF(QPointF(0, 0), QSizeF(pixmap.size())))
    painter = QPainter(pixmap)
    scene.render(painter)
    painter.end()
    scene.clear()
    scene.deleteLater()
    return pixmap
Esempio n. 20
0
    def __init__(self,
                 seq,
                 seqtype="aa",
                 fsize=10,
                 fg_colors=None,
                 bg_colors=None,
                 codon=None,
                 col_w=11,
                 alt_col_w=3,
                 special_col=None,
                 interactive=False):
        self.seq = seq
        self.codon = codon
        self.fsize = fsize
        self.style = seqtype
        self.col_w = float(col_w)
        self.alt_col_w = float(alt_col_w)
        self.special_col = special_col if special_col else []
        self.width = 0  # will store the width of the whole sequence
        self.interact = interactive

        if self.style == "aa":
            if not fg_colors:
                fg_colors = _aafgcolors
            if not bg_colors:
                bg_colors = _aabgcolors
        else:
            if not fg_colors:
                fg_colors = _ntfgcolors
            if not bg_colors:
                bg_colors = _ntbgcolors

        self.fg_col = self.__init_col(fg_colors)
        self.bg_col = self.__init_col(bg_colors)

        # for future?
        self.row_h = 13.0

        super(MySequenceFace,
              self).__init__(QGraphicsRectItem(0, 0, self.width, self.row_h))
Esempio n. 21
0
    def test_controlpointrect(self):
        control = ControlPointRect()
        rect = QGraphicsRectItem(QRectF(10, 10, 100, 200))
        self.scene.addItem(rect)
        self.scene.addItem(control)

        control.setRect(rect.rect())
        control.setFocus()
        control.rectChanged.connect(rect.setRect)

        control.setRect(QRectF(20, 20, 100, 200))
        self.assertEqual(control.rect(), rect.rect())
        self.assertEqual(control.rect(), QRectF(20, 20, 100, 200))

        control.setControlMargins(5)
        self.assertEqual(control.controlMargins(), QMargins(5, 5, 5, 5))
        control.rectEdited.connect(rect.setRect)

        self.view.show()
        self.app.exec_()

        self.assertEqual(rect.rect(), control.rect())
Esempio n. 22
0
 def __init__(self, name, point, parent):
     QGraphicsObject.__init__(self, parent)
     self.text_item = QGraphicsTextItem(name, self)
     if point:
         s = point.size()
         height = max(2 * s, self.text_item.boundingRect().height())
     else:
         height = self.text_item.boundingRect().height()
     p = 0.5 * height
     self.text_item.setPos(height, 0)
     self.point_item = point
     if point:
         self.point_item.setParentItem(self)
         self.point_item.setPos(p, p)
     self._rect = QRectF(0, 0,
                         height + self.text_item.boundingRect().width(),
                         height)
     self.rect_item = QGraphicsRectItem(self._rect, self)
     self.rect_item.setPen(QPen(Qt.NoPen))
     self.rect_item.stackBefore(self.text_item)
     if self.point_item:
         self.rect_item.stackBefore(self.point_item)
Esempio n. 23
0
def trinomial_face(binom,
                   spp,
                   ftype="Verdana",
                   fsize=10,
                   fgcolor="black",
                   fstyle="normal",
                   bold=False):
    """
    Stolen from:
    https://connorskennerton.wordpress.com/2016/11/16/python-ete3-formatting-organism-names-the-way-i-want/
    """

    font = QFont(ftype, fsize)
    font.setBold(bold)
    if fstyle == "italic":
        font.setStyle(QFont.StyleItalic)
    elif fstyle == "oblique":
        font.setStyle(QFont.StyleOblique)

    text = QGraphicsTextItem()
    text.setFont(font)
    if spp is None:
        text.setHtml("<i>{}</i>".format(binom))
    else:
        text.setHtml("<i>{}</i> {}".format(binom, spp))

    rect = QGraphicsRectItem(0, 0,
                             text.boundingRect().width(),
                             text.boundingRect().height() - 10)
    text.setParentItem(rect)
    center = rect.boundingRect().center()
    text.setPos(rect.boundingRect().x(),
                center.y() - text.boundingRect().height() / 2)

    # no border
    rect.setPen(QPen(QtCore.Qt.NoPen))

    return ete3.faces.StaticItemFace(rect)
Esempio n. 24
0
    def draw_legend(self):
        legend_h = self.height * ((self.nb_models - 1) / float(self.nb_models))
        if legend_h < 35:
            legend_h = 35
        legend_rect = QGraphicsRectItem(-20, 0, 10, legend_h, parent=self.item)
        x0 = -20
        n_cat = 6.
        for y, str_y in [(1, 1), (1 / n_cat * 5, 0.99), (1 / n_cat * 4, 0.9),
                         (1 / n_cat * 3, 0.8), (1 / n_cat * 2, 0.7),
                         (1 / n_cat * 1, 0.5), (1 / n_cat * 0, 0)]:
            y_stick = legend_h - y * legend_h
            lineItem = QGraphicsLineItem(x0 - 5,
                                         y_stick,
                                         x0,
                                         y_stick,
                                         parent=self.item)
            lineItem.setPen(QPen(QColor('black')))
            text = QGraphicsSimpleTextItem(str(str_y))
            text.setFont(QFont("Arial", self.fsize - 4))
            text.setParentItem(self.item)
            tw = text.boundingRect().width()
            th = text.boundingRect().height()
            # Center text according to masterItem size
            text.setPos(x0 - tw - 7, y_stick - th / 2)

        for (y1, y2, c) in [(1, 1 / n_cat * 5, 0.99),
                            (1 / n_cat * 5, 1 / n_cat * 4, 0.9),
                            (1 / n_cat * 4, 1 / n_cat * 3, 0.8),
                            (1 / n_cat * 3, 1 / n_cat * 2, 0.7),
                            (1 / n_cat * 2, 1 / n_cat * 1, 0.5),
                            (1 / n_cat * 1, 1 / n_cat * 0, 0)]:
            y1_stick = legend_h - y1 * legend_h
            y2_stick = legend_h - y2 * legend_h
            self.draw_fun(x0,
                          y1_stick,
                          c,
                          col_width=10,
                          col_height=y2_stick - y1_stick)
Esempio n. 25
0
    def __init__(o, parent, puzzle_client, mainwindow, *args):
        QGraphicsScene.__init__(o, parent, *args)
        o._input_tracker = InputTracker(o, accepts=sum(KEYS.values(), []))

        o.setBackgroundBrush(QBrush(QColor("darkGray")))
        o.client = puzzle_client
        o.mainwindow = mainwindow
        o.cluster_map = {}

        # connect my events
        o.client.puzzle.connect(o._display_puzzle)
        o.client.piece_pixmaps.connect(o._set_piece_pixmaps)
        o.client.clusters.connect(o.OnClustersChanged)
        o.client.grabbed.connect(o.onClustersGrabbed)
        o.client.moved.connect(o.onClustersMoved)
        o.client.dropped.connect(o.onClustersDropped)
        o.client.joined.connect(o.onClustersJoined)
        # request puzzle data from server
        o.client.get_puzzle()

        # init piece movement
        o.rotations = 1  # number of rotations that the puzzle allows
        # List of cluster (widgets) that have been grabbed locally. dict clusterid -> ClusterWidget
        o.grabbed_widgets = {}
        # number of rotations (relative to initial rotation) having been applied to the grabbed widgets.
        o._move_rotation = 0
        # time of last position update (for rate limit)
        o._last_move_send_time = 0

        # init selection
        o._drag_start = None
        o._rubberband = QGraphicsRectItem(QRectF(0., 0., 100., 100.))
        p = QPen(QColor(255, 255, 255))
        o._rubberband.setPen(p)
        o._rubberband.hide()
        o.addItem(o._rubberband)
Esempio n. 26
0
def polygon_name_face(node, *args, **kwargs):
    """create a wedge shaped face in the style of ARB

    Args:
    width (int): size in pixels for the width of the wedge
    height (int): size in pixels for the height of the wedge
    width_percent (float): change the angle of the point of the wedge.
    This must be a number between 0 and 1

    Returns:
    QGraphicsRectItem: The Qt graphics item of the polygon
    """

    n_leaves = len(node.get_leaves())
    closest_leaf_dist = node.get_closest_leaf()[1]
    farthest_leaf_dist = node.get_farthest_leaf()[1]

    base_height = 30
    width = 60
    height = math.log(n_leaves, 2) + base_height

    width_percent = closest_leaf_dist / farthest_leaf_dist

    #print(width, height, width_percent)

    points = [
    (0.0, 0.0), # top left point
    (width, 0.0), # top right point
    (width * width_percent, height), # bottom right point
    (0.0, height), # bottom left point
    (0.0, 0.0) # back to the beginning
    ]
    shape = QPolygonF()
    for i in points:
        shape << QtCore.QPointF(*i)

    ## Creates a main master Item that will contain all other elements
    ## Items can be standard QGraphicsItem
    masterItem = QGraphicsRectItem(0, 0, width, height)

    # Keep a link within the item to access node info
    masterItem.node = node

    # I dont want a border around the masterItem
    masterItem.setPen(QPen(QtCore.Qt.NoPen))

    polygon = QGraphicsPolygonItem(shape, masterItem)
    # Make the wedge grey in color
    polygon.setBrush(QBrush(QColor( '#D3D3D3')))

    # Print the name of the node
    # Center text according to masterItem size
    center = masterItem.boundingRect().center()

    text = QGraphicsSimpleTextItem(node.name)
    text.setParentItem(polygon)

    tw = text.boundingRect().width()
    th = text.boundingRect().height()
    text.setPos(center.x() + tw/2, center.y() - th/2)

    # this is a hack to prevent the name being printed twice
    # we set the node name to blank after we write it with the QGraphicsSimpleTextItem
    # it must be set to a blank string for it not to be printed later
    node.name = ''


    # print the number of collapsed leaves in the polygon
    leaves_count_text = QGraphicsSimpleTextItem('('+str(n_leaves)+')')
    leaves_count_text.setParentItem(polygon)
    leaves_count_text.setFont(QFont('Veranda', 6))
    leaves_count_text.setPos(masterItem.boundingRect().x() + 5, center.y() - leaves_count_text.boundingRect().height()/2)

    polygon.setPos(0, masterItem.boundingRect().y()/1.5)

    return masterItem
Esempio n. 27
0
    def draw_colored_boxes(self, h):

        stick_colors = self.colors

        num_col_red = stick_colors.count("red")
        num_col_orange = stick_colors.count("orange")
        num_col_yellow = stick_colors.count("#EFDB00")
        num_col_gray = stick_colors.count("gray")

        colored_box_h = self.height + h - 5

        if num_col_red:
            rect_red = QGraphicsRectItem(self.col_w * 0 - 1,
                                         self.coordY(self.ylim[1]) - 5,
                                         self.col_w * num_col_red,
                                         colored_box_h)
            qpen = QPen(QColor('red'))
            qpen.setWidth(1)
            qpen.setStyle(
                5)  # dash line : http://doc.qt.io/qt-4.8/qt.html#PenStyle-enum
            rect_red.setPen(qpen)
            rect_red.setBrush(QColor("#FFD1D1"))
            rect_red.setZValue(-1)
            rect_red.setParentItem(self.item)
            #rect_red.setOpacity(0.5)

        if num_col_orange:
            rect_orange = QGraphicsRectItem(self.col_w * num_col_red + 1,
                                            self.coordY(self.ylim[1]) - 5,
                                            self.col_w * num_col_orange - 2,
                                            colored_box_h)
            qpen = QPen(QColor('orange'))
            qpen.setWidth(1)
            qpen.setStyle(
                5)  # dash line : http://doc.qt.io/qt-4.8/qt.html#PenStyle-enum
            rect_orange.setPen(qpen)
            rect_orange.setBrush(QColor("#FFE3B0"))
            rect_orange.setZValue(-1)
            rect_orange.setParentItem(self.item)
            #rect_orange.setOpacity(0.5)

        if num_col_yellow:
            rect_yellow = QGraphicsRectItem(
                self.col_w * (num_col_orange + num_col_red) + 1,
                self.coordY(self.ylim[1]) - 5, self.col_w * num_col_yellow - 2,
                colored_box_h)
            qpen = QPen(QColor('#EFDB00'))
            qpen.setWidth(1)
            qpen.setStyle(
                5)  # dash line : http://doc.qt.io/qt-4.8/qt.html#PenStyle-enum
            rect_yellow.setPen(qpen)
            rect_yellow.setBrush(QColor("#FBFFA5"))
            rect_yellow.setZValue(-1)
            rect_yellow.setParentItem(self.item)
            #rect_yellow.setOpacity(0.5)

        if num_col_gray:
            rect_gray = QGraphicsRectItem(
                self.col_w * (num_col_orange + num_col_red + num_col_yellow) +
                1,
                self.coordY(self.ylim[1]) - 5, self.col_w * num_col_gray,
                colored_box_h)
            qpen = QPen(QColor('gray'))
            qpen.setWidth(1)
            qpen.setStyle(
                5)  # dash line : http://doc.qt.io/qt-4.8/qt.html#PenStyle-enum
            rect_gray.setPen(qpen)
            rect_gray.setBrush(QColor("#E2E2E2"))
            rect_gray.setZValue(-1)
            rect_gray.setParentItem(self.item)
Esempio n. 28
0
    def setAxisIntersect(self, intersect):
        self._axisIntersect = intersect
        #print "SkeletonsLayer(axis=%d) is updating intersect=%d" % (self._axis, self._axisIntersect)

        nodes, eIntersected, ePlane = self._3d._skeletons.intersect(
            self._axis, self._axisIntersect)

        #update existing items
        toRemove = []
        for node, item in self._node2view.iteritems():
            if node.pos[self._axis] != self._axisIntersect:
                self._scene.removeItem(item)
                toRemove.append(node)
            elif node.pointF(self._axis) != item.pos():
                item.setPos(self._scene.data2scene.map(node.pointF(
                    self._axis)))
            if node.isSelected() != item.isSelected():
                item.setSelected(node.isSelected())
                assert item.isSelected() == node.isSelected()
            i = 0
            newSize = [0, 0]
            for j in range(3):
                if j == self._axis:
                    continue
                newSize[i] = node.shape[j]
                i += 1
            newRectF = QRectF(0, 0, *newSize)
            newRectF = self._scene.data2scene.mapRect(newRectF)

            item.setRect(
                QRectF(-newRectF.width() / 2.0, -newRectF.height() / 2.0,
                       newRectF.width(), newRectF.height()))

        for r in toRemove:
            del self._node2view[r]

        #add new views for nodes
        for n in nodes:
            if n in self._node2view:
                continue

            pos2D = list(n.pos)
            del pos2D[self._axis]

            shape2D = n.shape2D(self._axis)
            itm = QGraphicsSkeletonNode(shape2D,
                                        skeletons=self._3d._skeletons,
                                        node=n)
            itm.setPos(self._scene.data2scene.map(QPointF(*pos2D)))
            itm.setSelected(n.isSelected())

            self._scene.addItem(itm)
            self._node2view[n] = itm

        for itm in self._edge2view.values():
            self._scene.removeItem(itm)
        self._edge2view = dict()

        for e in ePlane:
            l = QLineF(e[0].pointF(), e[1].pointF())

            c1 = e[0].color()
            c2 = e[1].color()
            mixColor = QColor((c1.red() + c2.red()) / 2,
                              (c1.green() + c2.green()) / 2,
                              (c1.blue() + c2.blue()) / 2)

            line = QGraphicsLineItem(self._scene.data2scene.map(l))
            line.setPen(QPen(mixColor))
            self._scene.addItem(line)
            self._edge2view[e] = line

        for theEdge, e in eIntersected:
            c1 = theEdge[0].color()
            c2 = theEdge[1].color()
            mixColor = QColor((c1.red() + c2.red()) / 2,
                              (c1.green() + c2.green()) / 2,
                              (c1.blue() + c2.blue()) / 2)

            nodeSize = 6
            p = QGraphicsRectItem(-nodeSize / 2, -nodeSize / 2, nodeSize,
                                  nodeSize)
            pos2D = list(e)
            del pos2D[self._axis]
            p.setPos(self._scene.data2scene.map(QPointF(*pos2D)))
            p.setPen(QPen(mixColor))
            self._scene.addItem(p)
            self._edge2view[e] = p
Esempio n. 29
0
 def draw_fun(self, x, y, val, col_width=10, col_height=10, color="gray"):
     color = get_corr_color(val)
     rect = QGraphicsRectItem(x, y, col_width, col_height, parent=self.item)
     rect.setPen(QPen(QColor('black')))
     rect.setBrush(QColor(color))