Exemple #1
0
    def createImage(self, transform):
        if self.type == DemoTextItem.DYNAMIC_TEXT:
            return None

        sx = min(transform.m11(), transform.m22())
        sy = max(transform.m22(), sx)

        textItem = QGraphicsTextItem()
        textItem.setHtml(self.text)
        textItem.setTextWidth(self.textWidth)
        textItem.setFont(self.font)
        textItem.setDefaultTextColor(self.textColor)
        textItem.document().setDocumentMargin(2)

        w = textItem.boundingRect().width()
        h = textItem.boundingRect().height()
        image = QImage(int(w * sx), int(h * sy),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(QColor(0, 0, 0, 0).rgba())
        painter = QPainter(image)
        painter.scale(sx, sy)
        style = QStyleOptionGraphicsItem()
        textItem.paint(painter, style, None)

        return image
    def texting(self):
        # image = self.image.copy()
        # cv2.putText(image,
        #             self.ui.textEdit_edit.toPlainText(),
        #             (10, 10),
        #             cv2.FONT_HERSHEY_SIMPLEX,
        #             0.6, (0, 0, 0), lineType=cv2.LINE_AA)
        # qpixmap = mat2qpixmap(image)
        # self.scene_edit.clear()
        # self.scene_edit.addPixmap(qpixmap)
        # self.scene_edit.update()

        text = self.ui.textEdit_edit.toPlainText()

        self.scene_edit.clear()
        self.scene_edit.addPixmap(self.qPixmap)
        qText = QGraphicsTextItem()
        qText.setDefaultTextColor(QColor(0, 0, 0))
        qText.setPlainText(text)
        qText.setFont(self.font)

        qPixmapWidth = self.qPixmap.width()
        qTextWidth = qText.boundingRect().width()
        qPixmapHeight = self.qPixmap.height()
        qTextHeigt = qText.boundingRect().height()

        posX = (qPixmapWidth - qTextWidth) / 2 + self.posX_default
        posY = (qPixmapHeight - qTextHeigt) / 2 + self.posY_default

        qText.setPos(posX, posY)

        self.scene_edit.addItem(qText)
        self.scene_edit.update()
Exemple #3
0
class GraphicItem(QGraphicsPixmapItem):
    def __init__(self, parent=None, text='', left=True):
        super().__init__(parent)
        self.pix = QPixmap("./res/Model.png")
        self.width = 55
        self.height = 55
        self.setPixmap(self.pix.scaled(self.width, self.height))
        self.setFlag(QGraphicsItem.ItemIsSelectable)
        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.left = left
        self.index = 0
        self.text = QGraphicsTextItem(self)
        self.text.setPlainText(text)
        if self.left:
            self.text.setDefaultTextColor(QColor(236, 190, 92))
        else:
            self.text.setDefaultTextColor(QColor(255, 59, 48))
        font = QFont()
        font.setBold(True)
        font.setPixelSize(16)
        self.text.setFont(font)

    def mouseMoveEvent(self, event):
        super().mouseMoveEvent(event)
        # update selected node and its edge
        if self.isSelected():
            for gr_edge in self.scene().edges:
                gr_edge.edge_wrap.update_positions()
Exemple #4
0
    def render_items(self, event=None):
        self.links = self.get_links_dict()
        self.render_preview()
        for item in self.settings['items']:
            text = QGraphicsTextItem()
            font_color = QColor('black')

            text.setPos(QPointF(item['x'], item['y']))

            font = QFont()
            font_name = item['params'].get(const.ITEM_DATA_KEY_FONT)
            if font_name:
                font.fromString(font_name)
                font_size = item['params'].get(const.ITEM_DATA_KEY_FONT_SIZE)
                if font_size:
                    font.setPointSize(font_size)
                else:
                    font.setPointSize(12)
                font_color_list = item['params'].get(
                    const.ITEM_DATA_KEY_FONT_COLOR)
                if font_color_list:
                    font_color.setRgb(*font_color_list)
                text.setFont(font)
            text_align = item['params'].get(const.ITEM_DATA_KEY_FONT_ALIGN)

            text.setFont(font)
            text.setTextWidth(item['w'])
            text.setDefaultTextColor(font_color)

            text.setHtml(
                f"<div align='{text_align}'>{self.test_row[self.links[item['name']]]}</div>"
            )

            self.scene.addItem(text)
Exemple #5
0
    def __showCircle(self):
        ratio = 3

        pen = QPen()
        pen.setBrush(Qt.red)
        pen.setWidth(0.01)

        font = QFont()
        font.setPointSize(200 * ratio)

        self.scene.clear()

        for i in range(len(self.pointsXYItem)):
            (x, y) = self.pointsXYItem[i]
            r = self.radius[i] * ratio

            circleItem = QGraphicsEllipseItem(x - r, y - r, 2 * r, 2 * r)
            circleItem.setPen(pen)

            self.scene.addItem(circleItem)

            strItem = QGraphicsTextItem()
            strItem.setDefaultTextColor(Qt.blue)
            strItem.setFont(font)

            strItem.setPlainText(self.pointsName[i])
            strItem.setPos(x, y)

            self.scene.addItem(strItem)
Exemple #6
0
    def createImage(self, transform):
        if self.type == DemoTextItem.DYNAMIC_TEXT:
            return None

        sx = min(transform.m11(), transform.m22())
        sy = max(transform.m22(), sx)

        textItem = QGraphicsTextItem()
        textItem.setHtml(self.text)
        textItem.setTextWidth(self.textWidth)
        textItem.setFont(self.font)
        textItem.setDefaultTextColor(self.textColor)
        textItem.document().setDocumentMargin(2)

        w = textItem.boundingRect().width()
        h = textItem.boundingRect().height()
        image = QImage(int(w * sx), int(h * sy),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(QColor(0, 0, 0, 0).rgba())
        painter = QPainter(image)
        painter.scale(sx, sy)
        style = QStyleOptionGraphicsItem()
        textItem.paint(painter, style, None)

        return image
Exemple #7
0
    def select_level(self):
        #set switches to the correct state
        self.set_switches_off('level')
        #self.cancel_button.clicked.connect(self.cancel_level_select)

        #initialize enter-key value and set correct state to selecting_level
        self.enter = 0
        self.selecting_level = True
        self.level_text = ''
        

        #initialize a scene where to put levels
        self.level_scene = QGraphicsScene()
        
        #view for scene
        self.level_scene_view = QGraphicsView(self.level_scene, self)
        
        self.level_scene_view.adjustSize()
        self.level_scene_view.show()
        self.layout.addWidget(self.level_scene_view)
        
        

        level = QGraphicsTextItem('Level')

        path = os.getcwd() #get the current working dir
        os.chdir(path) #change dir to the current working dir
        os.chdir('game_levels')
        
        position = 50
        levels = []
        data = os.listdir()
        for item in data:
            if os.path.isfile(item):
                levels.append(item)
                #add also item to level_scene to show user what levels there are to choose from
                level = QGraphicsTextItem(item)
                #change color, can be changed later
                level.setDefaultTextColor(QColor(225,100,25))
                self.level_scene.addItem(level)
                level.setPos(0,position)
                position +=20


        self.qline_edit = QLineEdit()
        
        #change text color
        
        palette = QPalette()
        palette.setColor(QPalette.Text,QColor(225,100,25)) #the color can be changed
        self.qline_edit.setPalette(palette)
        self.layout.addWidget(self.qline_edit)
        
        self.qline_edit.textEdited[str].connect(self.qline_edited)        
                
                
        
        

        os.chdir(path) #remember to change back to the working dir where all classes etc are
    def addWP(self, wp):
        if wp.command in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
                          mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
                          mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT,
                          mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS,
                          mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME,
                          mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM,
                          mavutil.mavlink.MAV_CMD_NAV_LAND]:
            

            #point
            rad = self.__wp_diameter * 0.5
            ellipse = QGraphicsEllipseItem(wp.y - rad, -wp.x - rad, 
                self.__wp_diameter, self.__wp_diameter, self.__mission_layer)
            ellipse.setBrush(QBrush(QColor(255, 255, 255)))
            e_pen = QPen(QColor(255, 255, 255))
            e_pen.setWidth(0)
            ellipse.setPen(e_pen)
            self.__mission_layer.addToGroup(ellipse)

            #label
            label = QGraphicsTextItem(str(wp.seq), self.__mission_layer)
            label.setZValue(2)
            label.setDefaultTextColor(Qt.white)
            label.setPos(wp.y + rad, -wp.x - rad)
            label.setScale(0.00002)  #bit hacky --  really should scale based on
                                 #current zoom, but I'm in a hurry.
            self.__mission_layer.addToGroup(label)
            label.show()
class fadingPic(QObject):
    """ Wrap a QGraphicsPixmapItem and impliment the fade in/out animation"""
    def __init__(self, pixmap, parent=None):
        super().__init__(parent)
        self.pixmap_item = QGraphicsPixmapItem(pixmap)
        self.text_item = QGraphicsTextItem(
            "Nerual Network based Channel Learning")
        font = QFont("Nokia Pure Text Light", 18)  # QFont.Bold
        self.text_item.setFont(font)
        self.text_item.setDefaultTextColor(QColor(18, 65, 145))

    def _set_opacity(self, opc):
        self.pixmap_item.setOpacity(opc)
        self.text_item.setOpacity(opc)

    def fadeIn(self):
        anim = QPropertyAnimation(self, b'opacity')
        anim.setDuration(800)
        anim.setStartValue(0)
        anim.setEndValue(1)
        #anim.setLoopCount(1)
        return anim

    def fadeOut(self):
        anim = QPropertyAnimation(self, b'opacity')
        anim.setDuration(800)
        anim.setStartValue(1)
        anim.setEndValue(0)
        #anim.setLoopCount(1)
        return anim

    opacity = pyqtProperty(float, fset=_set_opacity)
Exemple #10
0
class DSO_range(QGraphicsPolygonItem):
    def __init__(self, parent, text="", color=Qt.white, text_col=Qt.black):
        super().__init__(None)

        polygon = QPolygonF()

        self.width = 175
        self.height = 24

        polygon.append(QPointF(0, 0))
        polygon.append(QPointF(0, self.height))
        polygon.append(QPointF(self.width, self.height))
        polygon.append(QPointF(self.width, 0))

        self.setPolygon(polygon)

        # we want black background
        bg = QBrush()
        col = QColor(color)
        col.setAlpha(200)
        bg.setColor(col)
        bg.setStyle(Qt.SolidPattern)
        self.setBrush(bg)

        self.text = QGraphicsTextItem(self)
        self.text.setDefaultTextColor(QColor(text_col))
        self.text.setPlainText(text)

        self.show()

    def setText(self, text):
        self.text.setPlainText(text)
Exemple #11
0
    def _showLetter(self, i, j):
        """
        Graphical representation of a square to fill is created here.
        """

        x = j * self.SQUARE_SIZE
        y = i * self.SQUARE_SIZE
        self.scene.addRect(x, y, self.SQUARE_SIZE, self.SQUARE_SIZE,
                           QPen(Qt.black, 1, Qt.SolidLine), QBrush(Qt.NoBrush))

        square = self.model.grid[i][j]

        if len(square) == 1:
            numberTextItem = QGraphicsTextItem(str(square[0]))
            numberTextItem.setDefaultTextColor(Qt.darkGreen)
            numberTextItem.setPos(x + self.SQUARE_SIZE / 3,
                                  y + self.SQUARE_SIZE / 3)
            self.scene.addItem(numberTextItem)
        else:

            for number in square:
                numberTextItem = QGraphicsTextItem(str(number))
                xPos = x + ((number - 1) % 3) * self.SQUARE_SIZE / 3
                yPos = y + ((number - 1) / 3) * self.SQUARE_SIZE / 3
                numberTextItem.setPos(xPos, yPos)
                self.scene.addItem(numberTextItem)
Exemple #12
0
    def __drawPoint(self, x, y, index):
        #横线
        line1 = QGraphicsLineItem()
        line1.setPen(self.pen)
        line1.setLine(x - self.lineRadius, y, x + self.lineRadius, y)

        #竖线
        line2 = QGraphicsLineItem()
        line2.setPen(self.pen)
        line2.setLine(x, y - self.lineRadius, x, y + self.lineRadius)

        #文字说明
        text = QGraphicsTextItem()
        text.setDefaultTextColor(Qt.blue)
        text.setFont(self.font)

        text.setPlainText(self.pointsName[index])
        text.setPos(x, y)

        #放到组中
        pointGroup = QGraphicsItemGroup()
        pointGroup.addToGroup(line1)
        pointGroup.addToGroup(line2)
        pointGroup.addToGroup(text)

        #显示
        if self.pointsItem[index] is not None:
            self.scene.removeItem(self.pointsItem[index])

        #保存到字典
        self.pointsItem[index] = pointGroup
        #显示该点
        self.scene.addItem(self.pointsItem[index])
Exemple #13
0
class Node(QGraphicsEllipseItem):
    def __init__(self, name, rect=QRectF(0, 0, 20, 20), parent=None):
        QGraphicsEllipseItem.__init__(self, rect, parent)
        self.setX(random.randrange(0, 1000, 1))
        self.setY(random.randrange(0, 300, 1))
        self.edges = []
        self.setZValue(2)
        self.brush_color = QColor(153, 153, 153)
        self.setBrush(self.brush_color)
        self.setPen(QPen(Qt.NoPen))
        self.setFlags(QGraphicsItem.ItemIsMovable
                      | QGraphicsItem.ItemIsSelectable
                      | QGraphicsItem.ItemSendsGeometryChanges)
        self.text = QGraphicsTextItem(name)
        self.text.setDefaultTextColor(self.brush_color)
        self.text.setPos(-float(len(self.text.toPlainText())), -20.0)
        self.text.setParentItem(self)

        self.screen = ''

    def set_screen(self, screen):
        self.screen = screen

    def addEdge(self, edge):
        self.edges.append(edge)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemSelectedChange:
            self.setBrush(QColor("#1976D2") if value else self.brush_color)
            self.text.setDefaultTextColor(
                QColor("#1976D2") if value else self.brush_color)
            for i in range(len(self.edges)):
                self.edges[i].focus() if value else self.edges[i].defocus()

        if change == QGraphicsItem.ItemPositionHasChanged:
            for edge in self.edges:
                edge.adjust()

        return QGraphicsItem.itemChange(self, change, value)

    def mouseDoubleClickEvent(self, event):
        try:
            file = open(os.path.join(self.screen.project_folder,
                                     self.text.toPlainText()),
                        'r',
                        encoding='utf-8',
                        errors='ignore')

            with file:
                text = file.read()
                self.screen.new_document(title=self.text.toPlainText())
                self.screen.current_editor.setPlainText(text)
                self.screen.current_editor.set_change_name(
                    self.screen.tab_widget, False)
        except FileNotFoundError as error:
            QMessageBox.question(self.screen, 'Error',
                                 'Error occured : ' + str(error),
                                 QMessageBox.Close)
class AnimatedClock(QGraphicsView):
    def __init__(self, parent=None):
        QGraphicsView.__init__(self, parent)
        self.updateSecs = 0.5
        # Border
        self.setLineWidth(0)
        self.setFrameShape(QtWidgets.QFrame.NoFrame)
        # Size
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHeightForWidth(True)
        self.setSizePolicy(sizePolicy)
        # No scrollbars
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # Scene
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        self.setBackgroundBrush(QColor("black"))
        # Text of clock
        self.textItem = QGraphicsTextItem()
        self.textItem.color = QColor(QColor("black"))
        self.textItem.setFont(QFont("Segoe UI", 80))
        self.textItem.setDefaultTextColor(QColor("white"))
        self.textItem.setHtml("")
        self.textItem.setZValue(20)
        self.scene.addItem(self.textItem)
        # Start ticking
        self.start()

    def sizeHint(self):
        return QSize(300, 150)

    def start(self):
        self.updateTimer = QTimer()
        self.updateTimer.setInterval(self.updateSecs * 990)
        self.updateTimer.timeout.connect(self.updateClock)
        self.updateTimer.start()
        print("Animated clock - starting")

    def stop(self):
        if self.updateTimer != None:
            self.updateTimer.stop()
        print("Animated clock - stopping")

    def updateClock(self):
        localtime = time.localtime()
        timeString = time.strftime("%H:%M:%S", localtime)
        self.textItem.setHtml(timeString)
        width = self.frameGeometry().width()
        self.textItem.setFont(QFont("Segoe UI", width / 8))
        self.textItem.update()

    def heightForWidth(self, width):
        return width * .32

    def keyPressEvent(self, event): #QKeyEvent
        event.ignore()
 def create_winner_label(self):
     w = QGraphicsTextItem()
     w.setPlainText("%s" % self.mini_game_winner)
     game_board = self.parent()
     print(game_board)
     w.setFont(QFont('SansSerif', self.fonts[self.mini_game_winner]))
     w.setDefaultTextColor(Qt.black)
     w.setPos(self.x(), self.y())
     w.setVisible(False)
     return w
Exemple #16
0
    def printAttributes(self, background, border, text):
        """
        Prints the attributes of the node
        The attributes are a key, value pair

        :param background: background color of the node
        :param border: border color for the node
        :param text: text color for the node
        """
        y = self.y() + self.headerHeight
        x = self.x()

        self.attributesHeight = 0

        for k, v in self.node.attributes.items():
            key = QGraphicsTextItem()
            key.setFont(Configuration.font)
            key.setDefaultTextColor(QColor(text))
            key.setTextWidth(100)
            key.setPlainText(k)
            keyHeight = int(key.boundingRect().height() / 20 + 0.5) * 20

            value = QGraphicsTextItem()
            value.setFont(Configuration.font)
            value.setDefaultTextColor(QColor(text))
            value.setTextWidth(100)
            value.setPlainText(v)
            valueHeight = int(value.boundingRect().height() / 20 + 0.5) * 20

            height = valueHeight if valueHeight > keyHeight else keyHeight

            keyRect = QGraphicsRectItem()
            keyRect.setRect(x, y, 100, height)
            valueRect = QGraphicsRectItem()
            valueRect.setRect(x + 100, y, 100, height)

            keyRect.setBrush(QBrush(QColor(background)))
            valueRect.setBrush(QBrush(QColor(background)))

            keyRect.setPen(QPen(QColor(border), 2))
            valueRect.setPen(QPen(QColor(border), 2))

            key.setPos(x, y - 2)
            value.setPos(x + 100, y - 2)

            self.attributes.addToGroup(keyRect)
            self.attributes.addToGroup(valueRect)
            self.attributes.addToGroup(key)
            self.attributes.addToGroup(value)

            y = y + height
            self.attributesHeight += height

        self.addToGroup(self.attributes)
Exemple #17
0
 def on_actItem_Text_triggered(self):
    strText,OK=QInputDialog.getText(self,"输入","请输入文字")
    if (not OK):
       return
    item=QGraphicsTextItem(strText)
    font=self.font()
    font.setPointSize(20)
    font.setBold(True)
    item.setFont(font)   #设置字体
    item.setDefaultTextColor(Qt.black)  #设置颜色
    self.__setItemProperties(item,"文字")
    def showImage(self):
        (newImg, newImgInfo) = self.loadImage()
        # return PicItem(Pixmap(QPixmap(newImg)), -1, -1, xFactor, yFactor, newImgInfo)
        self.scene.clear()
        imgSz = newImgInfo.imgSize
        self.setSceneRect(QRectF(0,0,imgSz.width(), imgSz.height()))
        pixMap = QPixmap.fromImage(newImg)
        # # pixMap.setWidth(self.width())
        pixMapItem = self.scene.addPixmap(pixMap)
        # pixMapItem.setPos(50,50)
        # self.fitInView(QRectF(0, 0, self.width(), self.height()), Qt.KeepAspectRatio)
        # Add caption
        caption = QGraphicsTextItem()
        caption.setDefaultTextColor(QColor(255,255,255))
        caption.setPos(0, self.height()*0.94)
        caption.setFont(QFont("Segoe UI", 30))
        caption.setTextWidth(self.width())
        # caption.setPos(100, 100)
        # caption.setTextWidth(1500)
        # if newImgInfo.createDate is not None:
        #     caption.setPlainText(newImgInfo.createDate.format());
        # else:
        #     caption.setPlainText("Image is called bananas");
        # print("Tags", newImgInfo.tags)
        # tagStr = ""
        # for tag in newImgInfo.tags:
        #     if tag != "Duplicate":
        #         tagStr += (", " if len(tagStr) != 0 else "") + tag
        # if tagStr == "":
        #     tagStr = "NO TAGS"
        # captionStr = '<h1 style="text-align:center;width:100%">' + tagStr + '</h1>'
        # if newImgInfo.createDate is not None:
        #     print(newImgInfo.createDate.format())
        #     captionStr += '<BR><h2>' + newImgInfo.createDate.format() + '</h2>'

        captionStr = ""
        try:
            if newImgInfo.rating is not None:
                for i in range(newImgInfo.rating):
                    captionStr += "&#x2605;"
                for i in range(5-newImgInfo.rating):
                    captionStr += "&#x2606;"
            if newImgInfo.mainDate is not None:
                if len(captionStr) != 0:
                    captionStr += "  "
                captionStr += newImgInfo.mainDate.strftime("%d %b %Y")
        except Exception as excp:
            print("StaticPhotos: Cannot set caption")
        captionStr = '<div style="background-color:#000000;text-align: right;padding-right:10dp;">' + captionStr + "</div>"
        print(captionStr)
        caption.setHtml(captionStr)
        self.scene.addItem(caption)
        self.scene.update()
Exemple #19
0
class PickingStation(VisualizerGraphicItem):
    def __init__(self, ID=0, x=0, y=0):
        super(self.__class__, self).__init__(ID, x, y)
        self._kind_name = 'pickingStation'

        self._items = []
        self._graphics_item = QGraphicsRectItem(self)
        self._items.append(QGraphicsRectItem(self._graphics_item))
        self._items.append(QGraphicsRectItem(self._graphics_item))
        self._text = QGraphicsTextItem(self._graphics_item)

    def set_rect(self, rect):
        scale = config.get('display', 'id_font_scale')
        bold = config.get('display', 'id_font_bold')
        self._text.setFont(QFont('', rect.width() * 0.08 * scale))
        self._text.setPos(rect.x(), rect.y() + 0.6 * rect.height())
        self._text.setDefaultTextColor(
            QColor(config.get('display', 'id_font_color')))
        if self._display_mode == 0:
            if bold:
                self._text.setHtml('<b>P(' + str(self._id) + ')</b>')
            else:
                self._text.setHtml('P(' + str(self._id) + ')')
            self._graphics_item.setRect(rect.x(), rect.y(), rect.width(),
                                        rect.height())
            self._items[0].setRect(rect.x() + rect.width() / 5, rect.y(),
                                   rect.width() / 5, rect.height())
            self._items[1].setRect(rect.x() + rect.width() / 5 * 3, rect.y(),
                                   rect.width() / 5, rect.height())
        elif self._display_mode == 1:
            self._text.setPlainText('')
            self._graphics_item.setRect(rect.x(), rect.y(), rect.width(),
                                        rect.height())
            self._items[0].setRect(rect.x() + rect.width() / 5, rect.y(),
                                   rect.width() / 5, rect.height())
            self._items[1].setRect(rect.x() + rect.width() / 5 * 3, rect.y(),
                                   rect.width() / 5, rect.height())

    def determine_color(self, number, count, pattern=None):
        color = self._colors[0]
        color2 = self._colors[1]
        color.setAlpha(150)
        color2.setAlpha(150)
        brush = QBrush(color)
        brush2 = QBrush(color2)

        self._graphics_item.setBrush(brush)
        self._items[0].setBrush(brush2)
        self._items[1].setBrush(brush2)

    def get_rect(self):
        return self._graphics_item.rect()
Exemple #20
0
class ParticipantItem(QGraphicsItem):
    def __init__(self, model_item: Participant, parent=None):
        super().__init__(parent)

        self.model_item = model_item

        self.text = QGraphicsTextItem(self)

        self.line = QGraphicsLineItem(self)
        self.line.setPen(
            QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))

        self.refresh()

    def update_position(self, x_pos=-1, y_pos=-1):
        if x_pos == -1:
            x_pos = self.x_pos()

        if y_pos == -1:
            y_pos = self.line.line().y2()

        self.text.setPos(x_pos - (self.text.boundingRect().width() / 2), 0)
        self.line.setLine(x_pos, 30, x_pos, y_pos)

    def x_pos(self):
        return self.line.line().x1()

    def width(self):
        return self.boundingRect().width()

    def refresh(self):
        self.text.setPlainText(
            "?" if not self.model_item else self.model_item.shortname)
        if hasattr(self.model_item, "simulate") and self.model_item.simulate:
            font = QFont()
            font.setBold(True)
            self.text.setFont(font)
            self.text.setDefaultTextColor(Qt.darkGreen)
            self.line.setPen(
                QPen(Qt.darkGreen, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        else:
            self.text.setFont(QFont())
            self.text.setDefaultTextColor(constants.LINECOLOR)
            self.line.setPen(
                QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))

    def boundingRect(self):
        return self.childrenBoundingRect()

    def paint(self, painter, option, widget):
        pass
    def updateIcon(self, id, uav_state, image_num=0):
        if uav_state.get_lon() == 0.0:
            #haven't received a Pose message yet
            return

        if id not in self.__plane_icons:
            #make the plane's label first
            label = QGraphicsTextItem(str(id), self.__plane_layer)
            label.setZValue(2)
            label.setDefaultTextColor(Qt.red)
            self.__plane_layer.addToGroup(label) 
            label.show()
            self.__plane_labels[id] = label

            self.__plane_icons[id] = MapGraphicsIcon(id, label,
                                                    self.__plane_layer)
            self.__plane_icons[id].centerIconAt(uav_state.get_lon(),
                                               -uav_state.get_lat())
            self.__plane_icons[id].textureIcon(self.__plane_icon_pixmaps[image_num])

            #plane icons need to be drawn on top of map tiles:
            self.__plane_icons[id].setZValue(1)
            self.__plane_layer.addToGroup(self.__plane_icons[id])

            #key 0 = last update time
            self.__plane_icons[id].setData(0, 0)

            #refresh:
            #HACK: don't know why zooming works to refresh. Couldn't
            #get scene.invalidate() nor scene.update() to work
            self.onZoom(self.__current_detail_layer)
        #end if

        now = time.time()

        #if we don't have new pose data, then we don't update the plane icon
        if (self.__plane_icons[id].data(0) is None 
         or self.__plane_icons[id].data(0) >= uav_state.get_last_pose_update()):
            return

        #place icon
        self.__plane_icons[id].centerIconAt(uav_state.get_lon(), -uav_state.get_lat())
        #give correct heading:
        quat = uav_state.get_quat()
        heading = acs_math.yaw_from_quat(quat[0], quat[1], quat[2], quat[3])
        self.__plane_icons[id].setHeading(heading)
          
        #set last update time
        self.__plane_icons[id].setData(0, now)
Exemple #22
0
    def initUi(self):

        pos = QPointF(0, 0)

        for i in range(0, self.length):  #每一秒有1個刻度,總共 length 秒
            t1 = QGraphicsTextItem('|', self)
            t1.setDefaultTextColor(QColor(Qt.blue))
            t1.setPos(pos)

            t2 = QGraphicsTextItem('{}'.format(i + int(self.start)), self)
            t2.setDefaultTextColor(QColor(Qt.blue))
            t2.setPos(t1.boundingRect().bottomLeft() + pos)

            pos.setX(pos.x() + int(self.w / self.length))
        self.setRect(0, 0, self.w, self.h)
Exemple #23
0
class MyRect(QGraphicsRectItem):
    def __init__(self, parent=None):
        super(MyRect, self).__init__(parent)

        self.text_item = QGraphicsTextItem('My Text Here', self)
        self.value_item = QGraphicsTextItem('My Value Here', self)
        self.text_item.setDefaultTextColor(QColor(Qt.blue))
        self.value_item.setDefaultTextColor(QColor(Qt.red))

        self.value_item.setPos(self.text_item.boundingRect().bottomLeft())

        width = max(self.text_item.boundingRect().width(),
                    self.value_item.boundingRect().width())
        height = self.text_item.boundingRect().height(
        ) + self.value_item.boundingRect().height()
        self.setRect(50, 50, width, height)
Exemple #24
0
class ParticipantItem(QGraphicsItem):
    def __init__(self, model_item: Participant, parent=None):
        super().__init__(parent)

        self.model_item = model_item

        self.text = QGraphicsTextItem(self)

        self.line = QGraphicsLineItem(self)
        self.line.setPen(QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))

        self.refresh()

    def update_position(self, x_pos=-1, y_pos=-1):
        if x_pos == -1:
            x_pos = self.x_pos()

        if y_pos == -1:
            y_pos = self.line.line().y2()

        self.text.setPos(x_pos - (self.text.boundingRect().width() / 2), 0)
        self.line.setLine(x_pos, 30, x_pos, y_pos)

    def x_pos(self):
        return self.line.line().x1()

    def width(self):
        return self.boundingRect().width()

    def refresh(self):
        self.text.setPlainText("?" if not self.model_item else self.model_item.shortname)
        if hasattr(self.model_item, "simulate") and self.model_item.simulate:
            font = QFont()
            font.setBold(True)
            self.text.setFont(font)
            self.text.setDefaultTextColor(Qt.darkGreen)
            self.line.setPen(QPen(Qt.darkGreen, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        else:
            self.text.setFont(QFont())
            self.text.setDefaultTextColor(constants.LINECOLOR)
            self.line.setPen(QPen(Qt.darkGray, 1, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))

    def boundingRect(self):
        return self.childrenBoundingRect()

    def paint(self, painter, option, widget):
        pass
Exemple #25
0
class AnimatedClock():
    updateTimer = None
    calDataLock = threading.Lock()
    calDataUpdated = False
    curCalendars = None
    
    def __init__(self, scene, widthClkTextArea, heightClkTextArea, borders, updateSecs):
        self.masterScene = scene
        self.widthClkTextArea = widthClkTextArea
        self.heightClkTextArea = heightClkTextArea
        self.borders = borders
        self.updateSecs = updateSecs
        # Background
        self.textBkgd = QGraphicsRectItem(0, 0, self.widthClkTextArea, self.heightClkTextArea)
        self.textBkgd.setPos(self.borders[3], self.borders[0])
        self.textBkgd.setBrush(QColor("light green"))
        self.textBkgd.setZValue(10)
        scene.addItem(self.textBkgd)
        # Text Item
        self.textItem = QGraphicsTextItem()
        self.textItem.setFont(QFont("Segoe UI", 80))
        self.textItem.setDefaultTextColor(QColor("black"))
        self.textItem.setPos(QPointF(self.borders[3]+10,self.borders[0]+5))
        self.textItem.setHtml("<B>Clock</B>")
        self.textItem.setZValue(20)
        self.textItem.setTextWidth(self.widthClkTextArea-20)
        scene.addItem(self.textItem)
        
    def start(self):
        self.updateTimer = QTimer()
        self.updateTimer.setInterval(self.updateSecs * 1000)
        self.updateTimer.timeout.connect(self.updateClock)
        self.updateTimer.start()

    def stop (self):
        if self.updateTimer != None:
            self.updateTimer.stop()
    
    def updateClock(self):
        localtime = time.localtime()
#        dateString  = time.strftime("%a %d %b %Y", localtime)
        timeString  = time.strftime("%H:%M:%S", localtime)
        self.textItem.setHtml(timeString)
#        self.textItem.setTextWidth(self.widthCalTextArea-20)
        self.textItem.update()
Exemple #26
0
 def create_map_points(self):
     self.map_points_text_items = []
     self.map_points_items = []
     for map_point in self.map_data.map_points:
         color = QColor().fromRgb(map_point.r, map_point.g, map_point.b)
         rect = QGraphicsRectItem(
             QRectF(
                 QPointF(map_point.x, map_point.y),
                 QSizeF(5 / self.scale_ratio, 5 / self.scale_ratio)
             )
         )
         rect.setPen(QPen(Qt.black, 1 / self.scale_ratio))
         rect.setBrush(color)
         self.map_points_items.append(rect)
         text = QGraphicsTextItem(map_point.text)
         text.setDefaultTextColor(color)
         text.setPos(map_point.x, map_point.y)
         text.setFont(QFont('Times New Roman', 8 / self.scale_ratio, 2))
         self.map_points_text_items.append(text)
Exemple #27
0
class Bar(QGraphicsRectItem):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.max_val = 1
        self.current_val = 1

        self.WIDTH = parent.pixmap().width() if parent else 60
        self.setRect(parent.pos().x(), parent.pos().y(), self.WIDTH, 8)
        self.setBrush(Qt.red)

        self.text = QGraphicsTextItem(self)
        self.text.setDefaultTextColor(Qt.white)
        font = QFont('comic sans', 7)
        self.text.setFont(font)
        self.text.setPos(self.x(), self.y() - 7)

    def update_bar(self):
        # updates the bar graphics to the current amount of fullnes
        fill_fraction = float(self.current_val) / self.max_val
        self.text.setPlainText('{} / {}'.format(self.current_val,
                                                self.max_val))
        self.setRect(self.rect().x(),
                     self.rect().y(), fill_fraction * self.WIDTH, 8)

    def get_current_val(self):
        return self.current_val

    def set_current_val(self, value):
        self.current_val = value

    def set_max_val(self, value):
        self.max_val = value

    def increment(self, amount):
        # increase the amount the bar is filled and updates it
        self.current_val += amount
        self.update_bar()

    def decrement(self, amount):
        # decreases and updates
        self.current_val -= amount
        self.update_bar()
Exemple #28
0
	def actually_show_text(self, data):
		text_item = QGraphicsTextItem()
		text_item.setZValue(5)
		if len(data) >= 8 and data[7] != None:
			text_item.setDefaultTextColor(QColor(data[7]))
		else:
			text_item.setDefaultTextColor(QColor("#FFFFFF"))

		text_item.setX(data[2])
		text_item.setY(data[3])
		text_item.setTextWidth(data[4])
		text_item.setPlainText(data[5])

		temp_font = text_item.font()
		temp_font.setPointSize(data[6])
		text_item.setFont(temp_font)

		self.addItem(text_item)
		self.texts[data[1]] = text_item
		self.call_next_action()
class Video(QMainWindow):
    def __init__(self):
        super(Video, self).__init__()
        self.resize(1920, 1080)
        # ITEM
        self._item = QGraphicsVideoItem()
        self._textItem = QGraphicsTextItem()
        self._view = QGraphicsView()
        self._scene = QGraphicsScene()
        self._view.resize(1920, 1080)
        self._view.setScene(self._scene)
        self._scene.addItem(self._item)
        self._scene.addItem(self._textItem)
        self._textItem.setPlainText('SRT TEXT')
        self._textItem.setDefaultTextColor(Qt.red)
        font = self._textItem.font()
        font.setPixelSize(50)
        self._textItem.setFont(font)
        self._view.show()
        self._item.setSize(QSizeF(1920, 1080))
        self._player = QMediaPlayer(self)
        self._player.setMedia(
            QMediaContent(
                QUrl.fromLocalFile(
                    '/Users/huangkai/Documents/PycharmProjects/AllTest/Qt插入背景/AddVideos/Videos/yellow.mov'
                )))
        self._player.setVideoOutput(self._item)
        self._player.play()
        self.setCentralWidget(self._view)
        self._item.setPos(400, 500)
        # BUTTON
        self._btn = QPushButton(self)
        self._btn.resize(100, 50)
        self._btn.move(500, 500)
        self._btn.setText('test')
        self._btn.clicked.connect(self._change_text)

    def _change_text(self):
        self._textItem.setPlainText('Fighting')
    def update_view(self, steno_layout: StenoLayout, stroke: List[str]):
        ''' Updates the layout display for the provided layout and stroke '''

        scene = self.graphics_scene
        pen = self._scene_pen
        font = QFont(steno_layout.font) if steno_layout.font else QFont()
        # Clear all items from the scene. Could be more efficient...
        scene.clear()
        scene.setBackgroundBrush(QBrush(QColor(steno_layout.background_color)))

        for key in steno_layout.keys:
            path = LayoutDisplayView._create_key_path(steno_layout, key)
            brush = LayoutDisplayView._get_key_path_brush(key, (key.name in stroke))
            pen.setColor(QColor(key.stroke_color))

            # Add the key path before its label, then center the label
            scene.addPath(path, pen, brush)

            if key.label:
                label = QGraphicsTextItem(key.label)
                label.setFont(font)
                label.setDefaultTextColor(QColor(key.font_color))

                label_rect = label.boundingRect()
                label_rect.moveCenter(path.boundingRect().center())
                label.setPos(label_rect.x(), label_rect.y())
                scene.addItem(label)

        # Scene rects don't shrink when items are removed, so need to manually
        # set it to the current size needed by the contained items + margin
        margin = steno_layout.margin
        scene_rect = scene.itemsBoundingRect()
        scene_rect = scene_rect.marginsAdded(QMarginsF(margin, margin,
                                                       margin, margin))
        scene.setSceneRect(scene_rect)
        self.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)

        self.setScene(scene)
        self.show()
Exemple #31
0
    def addCircle(self, index, points, r):
        (x, y) = points

        circleItem = QGraphicsEllipseItem(x - r, y - r, 2 * r, 2 * r)
        circleItem.setPen(self.pen)

        # self.scene.addItem(circleItem)

        #横线
        line1 = QGraphicsLineItem()
        line1.setPen(self.pen)
        line1.setLine(x - self.lineRadius, y, x + self.lineRadius, y)

        #竖线
        line2 = QGraphicsLineItem()
        line2.setPen(self.pen)
        line2.setLine(x, y - self.lineRadius, x, y + self.lineRadius)

        #文字说明
        text = QGraphicsTextItem()
        text.setDefaultTextColor(Qt.blue)
        text.setFont(self.font)

        text.setPlainText(str(self.names[index]))
        text.setPos(x, y)

        #放到组中
        pointGroup = QGraphicsItemGroup()
        pointGroup.addToGroup(line1)
        pointGroup.addToGroup(line2)
        pointGroup.addToGroup(text)
        pointGroup.addToGroup(circleItem)

        #显示该点
        self.scene.addItem(pointGroup)

        self.pointsItem.append(pointGroup)
Exemple #32
0
class KeyWidget(QGraphicsRectItem):
    def __init__(self, rect: QRect, idx: int, note: str):
        super().__init__(rect.x(), rect.y(), rect.width(), rect.height())

        self.rect = rect
        self.idx = idx
        self.note = note
        self.label = None

        if note in WHITE_KEYS:
            self.setBrush(WHITE_KEY_COLOR)
            # set the label
            self.label = QGraphicsTextItem()
            self.label.setDefaultTextColor(Qt.black)
            # font = self.label.font()
            # font.setBold(True)
            # self.label.setFont(font)
            self.label.setZValue(100)
            self.label.setPlainText(note)
            self.label.setPos(
                self.rect.x() + self.rect.width() / 2 -
                self.label.boundingRect().width() / 2,
                self.rect.y() + self.rect.height() * 0.8)
        else:
            self.setBrush(Qt.black)

    def press(self, out_of_range=False):
        if out_of_range:
            self.setBrush(Qt.yellow)
        else:
            self.setBrush(Qt.gray)

    def release(self):
        if self.note in WHITE_KEYS:
            self.setBrush(WHITE_KEY_COLOR)
        else:
            self.setBrush(BLACK_KEY_COLOR)
class QGraphicsResizableRect(QGraphicsRectItem):
    hoverColor    = QColor(255, 0, 0) #_hovering and selection color

    def __init__(self,x,y,h,w, scene=None,parent=None, editor=None):
        """"
        This class implements the resizable rectangle item which is dispalied on the scene
         x y should be the original positions in scene coordinates
         h,w are the height and the width of the rectangle
        """
        
        self._editor = editor

        QGraphicsRectItem.__init__(self,0,0,w,h,parent=parent)
        self.Signaller=QGraphicsResizableRectSignaller(parent=parent)

        scene.addItem(self)

        #Default Appearence Properties
        self._fontColor=QColor(255, 255, 255)
        self._fontSize=10
        self._lineWidth=1

        ##Note: need to do like this because the x,y of the graphics item fix the position
        # of the zero relative to the scene
        self.moveBy(x,y)

        #Flags
        self.setFlag(QGraphicsItem.ItemIsMovable,True  )
        self.setFlag(QGraphicsItem.ItemIsSelectable,True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges ,True)

        self.setAcceptHoverEvents(True)
        self.setAcceptedMouseButtons(Qt.LeftButton | Qt.RightButton)


        self._resizeHandles=[]

        # A bit of flags
        self._hovering=False
        self._normalColor   = QColor(0, 0, 255)
        self.updateColor()
        self._has_moved=False
        self._selected=False
        self._dbg=False
        self._setupTextItem()
        self._isFixed = False

        self.initHandles()
        self.hideHandles()


        self.setToolTip("Hold CTRL to drag the box")

    @property
    def fontColor(self):
        return self._fontColor

    @pyqtSlot(int)
    def setFontColor(self,color):
        self._fontColor=color
        self.textItem.setDefaultTextColor(color)
        self.updateText(self.textItem.toPlainText())

    @property
    def fontSize(self):
        return self._fontSize

    @pyqtSlot(int)
    def setFontSize(self,s):
        self._fontSize=s
        font=QFont()
        font.setPointSize(self._fontSize)
        self.textItem.setFont(font)
        self.updateText(self.textItem.toPlainText())

    @property
    def lineWidth(self):
        return self._lineWidth

    @pyqtSlot(int)
    def setLineWidth(self,s):
        self._lineWidth=s
        self.updateColor()

    @property
    def color(self):
        return self._normalColor

    @pyqtSlot(int)
    def setColor(self,qcolor):
        self._normalColor=qcolor
        self.updateColor()


    @pyqtSlot()
    def _setupTextItem(self):
        #Set up the text
        self.textItem=QGraphicsTextItem("",parent=self)
        textItem=self.textItem
        font=QFont()
        font.setPointSize(self._fontSize)
        textItem.setFont(font)
        textItem.setPos(QPointF(0,0)) #upper left corner relative to the father

        textItem.setDefaultTextColor(self._fontColor)

        if self._dbg:
            #another text item only for debug
            self.textItemBottom=QGraphicsTextItem("",parent=self)
            self.textItemBottom.setPos(QPointF(self.width,self.height))
            self.textItemBottom.setDefaultTextColor(QColor(255, 255, 255))

            self._updateTextBottom("shape " +str(self.shape))

    @pyqtSlot(str)
    def _updateTextBottom(self,string):
        self.textItemBottom.setPlainText(string)

    def setNewSize(self, constrainAxis, size, flip=False):

        if constrainAxis == 0:
            h,w = size, self.rect().width()

        else:
            h,w = self.rect().height(), size


        if flip and constrainAxis ==0:
            w=-w
        if flip and constrainAxis ==1:
            h=-h
        newrect=QRectF(0, 0, w, h).normalized()
        self.setRect(newrect)
        self.width=self.rect().width()
        self.height=self.rect().height()
        self.shape=(self.height,self.width)

        #Ensures that the text is in the upper left corner
        a=0
        b=0
        if w<=0: a=w
        if h<=0: b=h
        self.textItem.setPos(QPointF(a,b))

        if self._dbg:
            self.textItemBottom.setPos(QPointF(self.width,self.height))

        for el in self._resizeHandles:
            #print "shape = %s , left = %s , right = %s , top = %s , bottm , %s "%(self.shape,self.rect().left(),self.rect().right(),self.rect().top(),self.rect().bottom())
            el.resetOffset(el._constrainAxis,rect=newrect)


        self.Signaller.signalHasResized.emit()


    def hoverEnterEvent(self, event):
        event.setAccepted(True)
        self._hovering = True
        #elf.setCursor(Qt.BlankCursor)
        #self.radius = self.radius # modified radius b/c _hovering
        self.updateColor()
        self.setSelected(True)
        self.showHandles()

        super(QGraphicsResizableRect,self).hoverEnterEvent( event)
        self._editor.imageViews[2].setFocus()

    def hoverLeaveEvent(self, event):
        event.setAccepted(True)
        self._hovering = False
        self.setSelected(False)
        #self.setCursor(CURSOR)
        #self.radius = self.radius # no longer _hovering
        self.hideHandles()
        super(QGraphicsResizableRect,self).hoverLeaveEvent( event)



    def initHandles(self):
        for constrAxes in range(2):
            h = ResizeHandle(self.rect(), constrAxes, self)
            self._resizeHandles.append( h )

    def moveHandles(self):
        for h, constrAxes in zip(self._resizeHandles, list(range(2))):
            h.resetOffset(constrAxes, self.rect())


    def hideHandles(self):
        for h in self._resizeHandles:
            h.hide()

    def showHandles(self):
        for h in self._resizeHandles:
            h.show()



    @pyqtSlot(int)
    def setSelected(self, selected):
        QGraphicsRectItem.setSelected(self, selected)
        if self.isSelected(): self.Signaller.signalSelected.emit()
        if not self.isSelected(): self._hovering=False
        self.updateColor()
        #self.resetHandles()

    @pyqtSlot()
    def updateColor(self):
        color = self.hoverColor if (self._hovering or self.isSelected())  else self._normalColor
        self.setPen(QPen(color,self._lineWidth))
        self.setBrush(QBrush(color, Qt.NoBrush))

    def dataPos(self):
        dataPos = self.scenePos()
        pos = [int(dataPos.x()), int(dataPos.y())]

        return pos

    def topLeftDataPos(self):
        dataPos = self.rect().topLeft()+self.scene().scene2data.map(self.scenePos())
        pos = [int(dataPos.x()), int(dataPos.y())]

        return pos

    def bottomRightDataPos(self):
        dataPos = self.rect().bottomRight()+self.scene().scene2data.map(self.scenePos())
        pos = [int(dataPos.x()), int(dataPos.y())]
        return pos

    def mousePressEvent(self,event):
        modifiers=QApplication.queryKeyboardModifiers()
        if modifiers == Qt.ControlModifier:
            QApplication.setOverrideCursor(Qt.ClosedHandCursor)

    def mouseMoveEvent(self,event):
        pos=self.dataPos()

        modifiers=QApplication.queryKeyboardModifiers()
        if modifiers == Qt.ControlModifier:

            self._has_moved=True
            super(QGraphicsResizableRect, self).mouseMoveEvent(event)
            string=str(self.pos()).split("(")[1][:-1]

            #self.QResizableRect.signalIsMoving.emit()
    #         dataPos = self.scene().scene2data.map(self.scenePos())
    #         pos = [dataPos.x(), dataPos.y()]

            #self.updateText("("+string+")"+" "+str(pos))

    def mouseDoubleClickEvent(self, event):
        logger.debug("DOUBLE CLICK ON ITEM")
        #FIXME: Implement me
        event.accept()

    @pyqtSlot(str)
    def updateText(self,string):

        self.textItem.setPlainText(string)


    def mouseReleaseEvent(self, event):

        if self._has_moved:
            self.Signaller.signalHasMoved.emit(self.pos())
            #self._has_moved=False

            self._has_moved=False
        QApplication.restoreOverrideCursor()
        return QGraphicsRectItem.mouseReleaseEvent(self, event)

    
    def itemChange(self, change,value):
        if change==QGraphicsRectItem.ItemPositionChange:
            newPos=value #new position in scene coordinates
            rect=self.scene().sceneRect()
            topLeftRectCoords=self.rect().topLeft()
            bottomRightRectCoords=self.rect().bottomRight()

            ntl=topLeftRectCoords+newPos
            nbr=bottomRightRectCoords+newPos



            if not rect.contains(ntl) or not rect.contains(nbr):
                ntl.setX(min(rect.right()-self.rect().width(), max(ntl.x(),rect.left())))
                ntl.setY(min(rect.bottom()-self.rect().height(), max(ntl.y(), rect.top())));
                return ntl-topLeftRectCoords




        return QGraphicsRectItem.itemChange(self, change,value)


    def setOpacity(self,float):
        logger.debug("Resetting Opacity {}".format(float))

        self._normalColor.setAlpha(float*255)

        self.updateColor()


    def fixSelf(self, isFixed):
        self._isFixed = isFixed
        self.setFlag(QGraphicsItem.ItemIsMovable,not isFixed)
Exemple #34
0
class OcrArea(QGraphicsRectItem):
    ## static data
    resizeBorder = .0

    def __init__(self, pos, size, type_, parent = None, scene = None,
                 areaBorder = 2, index = 0, textSize = 50):
        QGraphicsRectItem.__init__(self, 0, 0, size.width(), size.height(),
                                   parent)
        self.setPos(pos)
        self.newEvent = IsClicked()
        self.newEvent.area = self

        #self.setAcceptedMouseButtons(QtCore.Qt.NoButton)
        self.setFlags(QGraphicsItem.ItemIsMovable |
            QGraphicsItem.ItemIsFocusable |
            QGraphicsItem.ItemIsSelectable)

        ## set index label
        self.text = QGraphicsTextItem("%d" % index, self)
        self.setTextSize(textSize)

        ## TODO: How to create constants for the type?
        ## (such as constants in Qt) (enum?)
        self.kind = type_

        pen = QPen(self.color, areaBorder, Qt.SolidLine,
                   Qt.RoundCap, Qt.RoundJoin)
        self.setPen(pen)
        # self.setAcceptsHoverEvents(True)  # TODO

        # self.text.setFlag(QtGui.QGraphicsItem.ItemIgnoresTransformations)

    def setIndex(self, idx):
        self.text.setPlainText(str(idx))

    def setTextSize(self, size):
        font = QFont()
        font.setPointSizeF(size)
        self.text.setFont(font)

    def contextMenuEvent(self, event):
        menu = QMenu()
        removeAction = menu.addAction(QA.translate('QOcrWidget', "Remove"))
        #Action = menu.addAction(self.scene().tr("Remove"))
        menu.addSeparator()
        textAction = menu.addAction(QA.translate('QOcrWidget', "Text"))
        graphicsAction = menu.addAction(QA.translate('QOcrWidget', "Graphics"))

        ## verification of the type of the selection and
        ## setting a check box near the type that is in use
        textAction.setCheckable(True)
        graphicsAction.setCheckable(True)

        if self.kind == 1:
            textAction.setChecked(True)
        elif self.kind == 2:
            graphicsAction.setChecked(True)

        selectedAction = menu.exec_(event.screenPos())

        if selectedAction == removeAction:
            self.scene().removeArea(self)
        elif selectedAction == textAction:
            self.kind = 1
        elif selectedAction == graphicsAction:
            self.kind = 2

    # when the area is selected the signal "isClicked()" is raised
    def mousePressEvent(self, event):
        self.newEvent.isClicked.emit()
        QGraphicsRectItem.mousePressEvent(self, event)

    # type property
    def _setType(self, type_):
        self.__type = type_

        if self.__type == 1:
            self.color = Qt.darkGreen
        else:  ## TODO: else -> elif ... + else raise exception
            self.color = Qt.blue

        self.text.setDefaultTextColor(self.color)

        pen = self.pen()
        pen.setColor(self.color)
        self.setPen(pen)

    def _type(self):
        return self.__type

    kind = property(fget=_type, fset=_setType)
Exemple #35
0
class QGraphicsResizableRect(QGraphicsRectItem):
    hoverColor = QColor(255, 0, 0)  # _hovering and selection color

    def __init__(self, x, y, h, w, scene=None, parent=None, editor=None):
        """"
        This class implements the resizable rectangle item which is dispalied on the scene
         x y should be the original positions in scene coordinates
         h,w are the height and the width of the rectangle
        """

        self._editor = editor

        QGraphicsRectItem.__init__(self, 0, 0, w, h, parent=parent)
        self.Signaller = QGraphicsResizableRectSignaller(parent=parent)

        scene.addItem(self)

        # Default Appearence Properties
        self._fontColor = QColor(255, 255, 255)
        self._fontSize = 10
        self._lineWidth = 1

        ##Note: need to do like this because the x,y of the graphics item fix the position
        # of the zero relative to the scene
        self.moveBy(x, y)

        # Flags
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)

        self.setAcceptHoverEvents(True)
        self.setAcceptedMouseButtons(Qt.LeftButton | Qt.RightButton)

        self._resizeHandles = []

        # A bit of flags
        self._hovering = False
        self._normalColor = QColor(0, 0, 255)
        self.updateColor()
        self._has_moved = False
        self._selected = False
        self._dbg = False
        self._setupTextItem()
        self._isFixed = False

        self.initHandles()
        self.hideHandles()

        self.setToolTip("Hold CTRL to drag the box")

    @property
    def fontColor(self):
        return self._fontColor

    @pyqtSlot(int)
    def setFontColor(self, color):
        self._fontColor = color
        self.textItem.setDefaultTextColor(color)
        self.updateText(self.textItem.toPlainText())

    @property
    def fontSize(self):
        return self._fontSize

    @pyqtSlot(int)
    def setFontSize(self, s):
        self._fontSize = s
        font = QFont()
        font.setPointSize(self._fontSize)
        self.textItem.setFont(font)
        self.updateText(self.textItem.toPlainText())

    @property
    def lineWidth(self):
        return self._lineWidth

    @pyqtSlot(int)
    def setLineWidth(self, s):
        self._lineWidth = s
        self.updateColor()

    @property
    def color(self):
        return self._normalColor

    @pyqtSlot(int)
    def setColor(self, qcolor):
        self._normalColor = qcolor
        self.updateColor()

    @pyqtSlot()
    def _setupTextItem(self):
        # Set up the text
        self.textItem = QGraphicsTextItem("", parent=self)
        textItem = self.textItem
        font = QFont()
        font.setPointSize(self._fontSize)
        textItem.setFont(font)
        textItem.setPos(QPointF(0, 0))  # upper left corner relative to the father

        textItem.setDefaultTextColor(self._fontColor)

        if self._dbg:
            # another text item only for debug
            self.textItemBottom = QGraphicsTextItem("", parent=self)
            self.textItemBottom.setPos(QPointF(self.width, self.height))
            self.textItemBottom.setDefaultTextColor(QColor(255, 255, 255))

            self._updateTextBottom("shape " + str(self.shape))

    @pyqtSlot(str)
    def _updateTextBottom(self, string):
        self.textItemBottom.setPlainText(string)

    def setNewSize(self, constrainAxis, size, flip=False):

        if constrainAxis == 0:
            h, w = size, self.rect().width()

        else:
            h, w = self.rect().height(), size

        if flip and constrainAxis == 0:
            w = -w
        if flip and constrainAxis == 1:
            h = -h
        newrect = QRectF(0, 0, w, h).normalized()
        self.setRect(newrect)
        self.width = self.rect().width()
        self.height = self.rect().height()
        self.shape = (self.height, self.width)

        # Ensures that the text is in the upper left corner
        a = 0
        b = 0
        if w <= 0:
            a = w
        if h <= 0:
            b = h
        self.textItem.setPos(QPointF(a, b))

        if self._dbg:
            self.textItemBottom.setPos(QPointF(self.width, self.height))

        for el in self._resizeHandles:
            # print "shape = %s , left = %s , right = %s , top = %s , bottm , %s "%(self.shape,self.rect().left(),self.rect().right(),self.rect().top(),self.rect().bottom())
            el.resetOffset(el._constrainAxis, rect=newrect)

        self.Signaller.signalHasResized.emit()

    def hoverEnterEvent(self, event):
        event.setAccepted(True)
        self._hovering = True
        # elf.setCursor(Qt.BlankCursor)
        # self.radius = self.radius # modified radius b/c _hovering
        self.updateColor()
        self.setSelected(True)
        self.showHandles()

        super(QGraphicsResizableRect, self).hoverEnterEvent(event)
        self._editor.imageViews[2].setFocus()

    def hoverLeaveEvent(self, event):
        event.setAccepted(True)
        self._hovering = False
        self.setSelected(False)
        # self.setCursor(CURSOR)
        # self.radius = self.radius # no longer _hovering
        self.hideHandles()
        super(QGraphicsResizableRect, self).hoverLeaveEvent(event)

    def initHandles(self):
        for constrAxes in range(2):
            h = ResizeHandle(self.rect(), constrAxes, self)
            self._resizeHandles.append(h)

    def moveHandles(self):
        for h, constrAxes in zip(self._resizeHandles, list(range(2))):
            h.resetOffset(constrAxes, self.rect())

    def hideHandles(self):
        for h in self._resizeHandles:
            h.hide()

    def showHandles(self):
        for h in self._resizeHandles:
            h.show()

    @pyqtSlot(int)
    def setSelected(self, selected):
        QGraphicsRectItem.setSelected(self, selected)
        if self.isSelected():
            self.Signaller.signalSelected.emit()
        if not self.isSelected():
            self._hovering = False
        self.updateColor()
        # self.resetHandles()

    @pyqtSlot()
    def updateColor(self):
        color = self.hoverColor if (self._hovering or self.isSelected()) else self._normalColor
        self.setPen(QPen(color, self._lineWidth))
        self.setBrush(QBrush(color, Qt.NoBrush))

    def dataPos(self):
        dataPos = self.scenePos()
        pos = [int(dataPos.x()), int(dataPos.y())]

        return pos

    def topLeftDataPos(self):
        dataPos = self.rect().topLeft() + self.scene().scene2data.map(self.scenePos())
        pos = [int(dataPos.x()), int(dataPos.y())]

        return pos

    def bottomRightDataPos(self):
        dataPos = self.rect().bottomRight() + self.scene().scene2data.map(self.scenePos())
        pos = [int(dataPos.x()), int(dataPos.y())]
        return pos

    def mousePressEvent(self, event):
        modifiers = QApplication.queryKeyboardModifiers()
        if modifiers == Qt.ControlModifier:
            QApplication.setOverrideCursor(Qt.ClosedHandCursor)

    def mouseMoveEvent(self, event):
        pos = self.dataPos()

        modifiers = QApplication.queryKeyboardModifiers()
        if modifiers == Qt.ControlModifier:

            self._has_moved = True
            super(QGraphicsResizableRect, self).mouseMoveEvent(event)
            string = str(self.pos()).split("(")[1][:-1]

            # self.QResizableRect.signalIsMoving.emit()

    #         dataPos = self.scene().scene2data.map(self.scenePos())
    #         pos = [dataPos.x(), dataPos.y()]

    # self.updateText("("+string+")"+" "+str(pos))

    def mouseDoubleClickEvent(self, event):
        logger.debug("DOUBLE CLICK ON ITEM")
        # FIXME: Implement me
        event.accept()

    @pyqtSlot(str)
    def updateText(self, string):

        self.textItem.setPlainText(string)

    def mouseReleaseEvent(self, event):

        if self._has_moved:
            self.Signaller.signalHasMoved.emit(self.pos())
            # self._has_moved=False

            self._has_moved = False
        QApplication.restoreOverrideCursor()
        return QGraphicsRectItem.mouseReleaseEvent(self, event)

    def itemChange(self, change, value):
        if change == QGraphicsRectItem.ItemPositionChange:
            newPos = value  # new position in scene coordinates
            rect = self.scene().sceneRect()
            topLeftRectCoords = self.rect().topLeft()
            bottomRightRectCoords = self.rect().bottomRight()

            ntl = topLeftRectCoords + newPos
            nbr = bottomRightRectCoords + newPos

            if not rect.contains(ntl) or not rect.contains(nbr):
                ntl.setX(min(rect.right() - self.rect().width(), max(ntl.x(), rect.left())))
                ntl.setY(min(rect.bottom() - self.rect().height(), max(ntl.y(), rect.top())))
                return ntl - topLeftRectCoords

        return QGraphicsRectItem.itemChange(self, change, value)

    def setOpacity(self, float):
        logger.debug("Resetting Opacity {}".format(float))

        self._normalColor.setAlpha(float * 255)

        self.updateColor()

    def fixSelf(self, isFixed):
        self._isFixed = isFixed
        self.setFlag(QGraphicsItem.ItemIsMovable, not isFixed)
class TcamScreen(QtWidgets.QGraphicsView):

    new_pixmap = pyqtSignal(QtGui.QPixmap)
    new_pixel_under_mouse = pyqtSignal(bool, int, int, QtGui.QColor)
    destroy_widget = pyqtSignal()
    fit_in_view = pyqtSignal()

    def __init__(self, parent=None):
        super(TcamScreen, self).__init__(parent)
        self.setMouseTracking(True)
        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                           QtWidgets.QSizePolicy.Expanding)
        self.setDragMode(QGraphicsView.ScrollHandDrag)
        self.setFrameStyle(0)
        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)

        self.new_pixmap.connect(self.on_new_pixmap)
        self.fit_in_view.connect(self.fit_view)
        self.pix = ViewItem()
        self.scene.addItem(self.pix)
        self.scene.setSceneRect(self.pix.boundingRect())

        self.is_fullscreen = False

        # Flag to differentiate between actual images
        # and 'fake images' i.e. color background + text while
        # waiting for first trigger image
        self.display_real_image = True
        self.text_item = None

        self.fit_in_view_called = False

        self.mouse_position_x = -1
        self.mouse_position_y = -1

        self.zoom_factor = 1.0
        self.first_image = True
        self.image_counter = 0

        self.capture_roi = False
        self.roi_obj = None
        self.roi_origin = None
        self.roi_widgets = []

        self.selection_area = None
        self.capture_widget = None
        self.origin = None

    def fit_view(self):
        """

        """

        self.reset_zoom()
        self.scene.setSceneRect(self.pix.boundingRect())
        self.scene.update()
        self.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)

    def reset_zoom(self):

        self.zoom_factor = 1.0
        # this resets the view internal transformation matrix
        self.setTransform(QtGui.QTransform())

    def on_new_pixmap(self, pixmap):
        self.image_counter += 1
        self.pix.setPixmap(pixmap)

        if not self.display_real_image:
            self.text_item.hide()
            self.scene.removeItem(self.text_item)
            self.display_real_image = True

        if self.image_counter == 1:
            self.resize(self.size())
            self.scene.setSceneRect(self.pix.boundingRect())
            self.update()

            self.reset_zoom()
            self.first_image = False

        # wait for the second image
        # resizeEvents, etc appear before the scene has adjusted
        # to the actual image size. By waiting for the 2. image
        # we circumvent this by having the first image making all
        # adjustments for us. The only scenario where this will
        # cause problems is triggering.
        if self.is_fullscreen and self.image_counter == 2:
            self.fit_view()

        self.send_mouse_pixel()
        # don't call repaint here
        # it causes problems once the screen goes blank due to screensavers, etc
        # self.repaint()

    def wait_for_first_image(self):

        if not self.display_real_image:
            return

        self.reset_zoom()
        self.display_real_image = False

        self.text_item = QGraphicsTextItem()
        self.text_item.setDefaultTextColor(QColor("white"))

        self.text_item.setPos(100, 70)
        self.text_item.setPlainText("In Trigger Mode. Waiting for first image...")

        bg = QPixmap(1280, 720)
        bg.fill(QColor("grey"))
        self.pix.setPixmap(bg)
        self.image_counter += 1
        self.scene.addItem(self.text_item)

    def send_mouse_pixel(self):
        # mouse positions start at 0
        # we want the lower right corner to have the correct coordinates
        # e.g. an 1920x1080 image should have the coordinates
        # 1920x1080 for the last pixel

        self.new_pixel_under_mouse.emit(self.pix.legal_coordinates(self.mouse_position_x,
                                                                   self.mouse_position_y),
                                        self.mouse_position_x + 1,
                                        self.mouse_position_y + 1,
                                        self.pix.get_color_at_position(self.mouse_position_x,
                                                                       self.mouse_position_y))

    def mouseMoveEvent(self, event):
        mouse_position = self.mapToScene(event.pos())
        self.mouse_position_x = mouse_position.x()
        self.mouse_position_y = mouse_position.y()

        if self.selection_area:

            # adjust rect since we want to pull in all directions
            # origin can well be bottom left, thus recalc
            def calc_selection_rect():

                x = min(self.origin.x(), event.pos().x())
                y = min(self.origin.y(), event.pos().y())
                x2 = max(self.origin.x(), event.pos().x())
                y2 = max(self.origin.y(), event.pos().y())

                return QPoint(x, y), QPoint(x2, y2)

            p1, p2 = calc_selection_rect()
            self.selection_area.setGeometry(QRect(p1, p2))

        super().mouseMoveEvent(event)

    def mousePressEvent(self, event):
        """"""

        if self.capture_widget:

            self.selection_area = QRubberBand(QRubberBand.Rectangle, self)
            self.selection_area.setGeometry(QRect(event.pos(), QSize()))
            self.origin = event.pos()
            self.selection_area.show()

        super().mousePressEvent(event)

    def mouseReleaseEvent(self, event):

        if self.capture_widget:
            selectionBBox = self.selection_area.rect()
            rect = QRect(self.selection_area.pos(), selectionBBox.size())
            selectionBBox = self.mapToScene(rect).boundingRect().toRect()
            self.capture_widget.emit(selectionBBox)

            self.selection_area.hide()
            self.selection_area = None
            QApplication.restoreOverrideCursor()

        self.capture_widget = None
        self.selection_area = None

        super().mouseReleaseEvent(event)

    def is_scene_larger_than_image(self):
        """
        checks if the entire ViewItem is visible in the scene
        """
        port_rect = self.viewport().rect()
        scene_rect = self.mapToScene(port_rect).boundingRect()
        item_rect = self.pix.mapRectFromScene(scene_rect)

        isec = item_rect.intersected(self.pix.boundingRect())

        res = self.pix.get_resolution()
        if (isec.size().width() >= QSizeF(res).width() and
                isec.size().height() >= QSizeF(res).height()):
            return True
        return False

    def wheelEvent(self, event):

        if not self.display_real_image:
            return
        # Zoom Factor
        zoomInFactor = 1.25
        zoomOutFactor = 1 / zoomInFactor

        # Set Anchors
        self.setTransformationAnchor(QGraphicsView.NoAnchor)
        self.setResizeAnchor(QGraphicsView.NoAnchor)

        # Save the scene pos
        oldPos = self.mapToScene(event.pos())

        # Zoom
        if event.angleDelta().y() > 0:
            zoomFactor = zoomInFactor
        else:
            zoomFactor = zoomOutFactor

        if (self.is_scene_larger_than_image() and
                zoomFactor < 1.0):
            return

        self.zoom_factor *= zoomFactor

        # we scale the view itself to get infinite zoom
        # so that we can inspect a single pixel
        self.scale(zoomFactor, zoomFactor)

        # Get the new position
        newPos = self.mapToScene(event.pos())

        # Move scene to old position
        delta = newPos - oldPos
        self.translate(delta.x(), delta.y())

        self.scene.setSceneRect(self.pix.boundingRect())

    def set_scale_position(self, scale_factor, x, y):
        self.scale(scale_factor, scale_factor)
        self.translate(x, y)

    def keyPressEvent(self, event):
        if self.isFullScreen():
            if (event.key() == Qt.Key_F11 or
                    event.key() == Qt.Key_Escape or
                    event.key() == Qt.Key_F):
                self.destroy_widget.emit()
        elif self.capture_widget and event.key() == Qt.Key_Escape:
            self.abort_roi_capture()
        else:
            # Ignore event so that parent widgets can use it.
            # This is only called when we are not fullscreen.
            # Fullscreen causes us to have no parents.
            event.ignore()

    def start_roi_capture(self, finished_signal):
        """
        Capture a region of interest
        """

        self.capture_widget = finished_signal
        QApplication.setOverrideCursor(Qt.CrossCursor)

    def abort_roi_capture(self):
        """
        Abort the capture of a regoin of interest
        """
        self.capture_widget = None
        self.origin = None

        if self.selection_area:
            self.selection_area.hide()
            self.selection_area = None

        QApplication.restoreOverrideCursor()

    def add_roi(self, roi_widget):
        """
        Add roi_widget to the QGraphicsScene for display
        """
        if not roi_widget:
            return

        self.roi_widgets.append(roi_widget)
        self.scene.addItem(roi_widget)
        roi_widget.show()

    def remove_roi(self, roi_widget):
        """
        Remove given roi widget from the scene
        """
        if not roi_widget:
            return

        roi_widget.hide()
        try:
            self.roi_widgets.remove(roi_widget)
        except ValueError as e:
            # This means the widget is not in the list
            pass
Exemple #37
0
    def draw_fretboard(self, scene, posX, posY):
        # Real 22 frets Gibson guitar scale length
        SCALE_LENGTH = [
            0, 35.28, 68.59, 100.02, 129.69, 157.69, 184.13, 209.08, 232.63,
            254.85, 275.83, 295.63, 314.32, 331.98, 348.61, 364.34, 379.17,
            393.17, 406.39, 418.86, 430.64, 441.75, 452.24
        ]

        # Increase them for better representation
        self.scaleLength = [i * 3 for i in SCALE_LENGTH]

        # Distance between two strings
        DISTANCE = 34

        # Starting cooridnates
        x = posX
        y = posY

        # Note coordinates of the strings
        # Open position coordinates
        self.sNoteCoordinate1 = [QPoint(x, y)]
        self.sNoteCoordinate2 = [QPoint(x, y + DISTANCE)]
        self.sNoteCoordinate3 = [QPoint(x, y + DISTANCE * 2)]
        self.sNoteCoordinate4 = [QPoint(x, y + DISTANCE * 3)]
        self.sNoteCoordinate5 = [QPoint(x, y + DISTANCE * 4)]
        self.sNoteCoordinate6 = [QPoint(x, y + DISTANCE * 5)]

        # Offset from the open position
        OFFSET = 30

        # The remaining position coordinates
        for i in range(len(self.scaleLength) - 1):
            x = self.scaleLength[i] + (
                (self.scaleLength[i + 1] - self.scaleLength[i]) /
                2) + OFFSET - 14
            self.sNoteCoordinate1.append(QPoint(x, y))
            self.sNoteCoordinate2.append(QPoint(x, y + DISTANCE))
            self.sNoteCoordinate3.append(QPoint(x, y + DISTANCE * 2))
            self.sNoteCoordinate4.append(QPoint(x, y + DISTANCE * 3))
            self.sNoteCoordinate5.append(QPoint(x, y + DISTANCE * 4))
            self.sNoteCoordinate6.append(QPoint(x, y + DISTANCE * 5))

        # Store the strings in a list for better iteration
        self.sNoteCoordinates = []
        self.sNoteCoordinates.append(self.sNoteCoordinate6)
        self.sNoteCoordinates.append(self.sNoteCoordinate5)
        self.sNoteCoordinates.append(self.sNoteCoordinate4)
        self.sNoteCoordinates.append(self.sNoteCoordinate3)
        self.sNoteCoordinates.append(self.sNoteCoordinate2)
        self.sNoteCoordinates.append(self.sNoteCoordinate1)

        # Starting guitar string cooridnates
        x = posX
        y = posY

        # Draw outer fretboard box
        whitePen = QPen(Qt.white)
        whitePen.setWidth(5)
        whitePen.setJoinStyle(Qt.MiterJoin)
        brownBrush = QBrush(QColor(75, 30, 0))
        rect1 = QRectF(x, y, self.scaleLength[-1] + OFFSET, DISTANCE * 6)
        scene.addRect(rect1, whitePen, brownBrush)

        whiteBrush = QBrush(Qt.white)
        rect2 = QRectF(x, y, x + OFFSET, DISTANCE * 6)
        scene.addRect(rect2, whitePen, whiteBrush)

        # Starting inlay cooridnates
        x = posX
        y = posY

        # Trapezoid inlay color
        gradient = QLinearGradient(0, 0, 50, 50)
        gradient.setColorAt(0.0, QColor(200, 200, 200))
        gradient.setColorAt(0.5, Qt.white)
        gradient.setColorAt(1.0, QColor(200, 200, 200))
        gradient.setSpread(QGradient.ReflectSpread)
        grayPen = QPen(QColor(216, 216, 216))
        grayBrush = QBrush(gradient)

        # The 3rd, 5th, 7th and 9th inlay
        leftTrim = 5
        rightTrim = 40
        j = 2
        for i in range(4):
            x1 = x + self.scaleLength[j] + (
                (self.scaleLength[j + 1] - self.scaleLength[j]) / 2) + leftTrim
            x2 = x + self.scaleLength[j + 1] + (
                (self.scaleLength[i + 2] - self.scaleLength[i + 1]) /
                2) - rightTrim
            path = QPainterPath()
            path.moveTo(x1, y + DISTANCE)
            path.lineTo(x1, y + DISTANCE * 5)
            path.lineTo(x2, y + DISTANCE * 5 - 20)
            path.lineTo(x2, y + DISTANCE + 15)
            path.closeSubpath()
            scene.addPath(path, grayPen, grayBrush)
            leftTrim += 2
            rightTrim -= 5
            j += 2

        # The 12th inlay
        leftTrim = 15
        rightTrim = 8
        x1 = x + self.scaleLength[11] + (
            (self.scaleLength[12] - self.scaleLength[11]) / 2) + leftTrim
        x2 = x + self.scaleLength[12] + (
            (self.scaleLength[13] - self.scaleLength[12]) / 2) - rightTrim
        path = QPainterPath()
        path.moveTo(x1, y + DISTANCE)
        path.lineTo(x1, y + DISTANCE * 5)
        path.lineTo(x2, y + DISTANCE * 5 - 20)
        path.lineTo(x2, y + DISTANCE + 15)
        path.closeSubpath()
        scene.addPath(path, grayPen, grayBrush)

        # The 15th, 17th, 19th and 21th inlay
        leftTrim = 15
        rightTrim = 28
        j = 14
        for i in range(4):
            x1 = x + self.scaleLength[j] + (
                (self.scaleLength[j + 1] - self.scaleLength[j]) / 2) + leftTrim
            x2 = x + self.scaleLength[j + 1] + (
                (self.scaleLength[i + 2] - self.scaleLength[i + 1]) /
                2) - rightTrim
            path = QPainterPath()
            path.moveTo(x1, y + DISTANCE)
            path.lineTo(x1, y + DISTANCE * 5)
            path.lineTo(x2, y + DISTANCE * 5 - 20)
            path.lineTo(x2, y + DISTANCE + 15)
            path.closeSubpath()
            scene.addPath(path, grayPen, grayBrush)
            leftTrim += 2
            rightTrim -= 1 + (i + 1)
            j += 2

        # Starting guitar string cooridnates
        x = posX
        y = posY - 20

        # Draw the guitar strings
        s = QLineF(x, y, x + self.scaleLength[-1] + OFFSET, y)
        whitePen = QPen(Qt.white)
        whitePen.setWidth(1)
        startHPos = DISTANCE
        stringWidth = 1
        for i in range(6):
            whitePen.setWidth(stringWidth)
            guitarString = scene.addLine(s, whitePen)
            guitarString.setPos(0, startHPos)
            startHPos += DISTANCE
            stringWidth += 0.4

        # Starting fret cooridnates
        x = posX
        y = posY

        # Draw the frets
        fretPen = QPen(Qt.white)
        fretPen.setWidth(5)
        fret = QLineF(x + OFFSET, y, x + OFFSET, y + DISTANCE * 6 - 5)
        for i in range(len(self.scaleLength)):
            guitarFret = scene.addLine(fret, fretPen)
            guitarFret.setPos(self.scaleLength[i], 0)

        # Add fret numbers
        for i in range(22):
            fret_num = QGraphicsTextItem(str(i))
            fret_num.setFont(QFont("Verdana", 20))
            fret_num.setDefaultTextColor(QColor(Qt.red))
            fret_num.setPos(self.scaleLength[i], 220)
            scene.addItem(fret_num)
Exemple #38
0
class QNEPort(QGraphicsPathItem):
    (NamePort, TypePort) = (1, 2)
    (Type) = (QGraphicsItem.UserType + 1)

    def __init__(self, parent):
        super(QNEPort, self).__init__(parent)
        self.textColor = Qt.black

        self.label = QGraphicsTextItem(self)
        self.radius_ = 4
        self.margin = 3

        self.setPen(QPen(Qt.darkRed))
        self.setBrush(Qt.red)

        self.setFlag(QGraphicsItem.ItemSendsScenePositionChanges)

        self.m_portFlags = 0
        self.isOutput_ = False

        self.m_block = None
        self.m_connections = []

    def __del__(self):
        #print("Del QNEPort %s" % self.name)

        for connection in self.m_connections:
            if connection.port1():
                connection.port1().removeConnection(connection)
            if connection.port2():
                connection.port2().removeConnection(connection)
            if self.scene():
                self.scene().removeItem(connection)

    def setName(self, name):
        self.name = name
        self.label.setPlainText(name)
        self.label.setDefaultTextColor(self.textColor)
        self.setBrush(Qt.red)

    def setIsOutput(self, isOutput):
        self.isOutput_ = isOutput

        path = QPainterPath()
        if self.isOutput_:
            if self.name == '':
                path.addRect(-2 * self.radius_, -self.radius_,
                             2 * self.radius_, 2 * self.radius_)
                self.label.setPos(
                    -self.radius_ - self.margin -
                    self.label.boundingRect().width(),
                    -self.label.boundingRect().height() / 2)
            else:
                path.addEllipse(-2 * self.radius_, -self.radius_,
                                2 * self.radius_, 2 * self.radius_)
                self.label.setPos(
                    -self.radius_ - self.margin -
                    self.label.boundingRect().width(),
                    -self.label.boundingRect().height() / 2)
        else:
            if self.name == '':
                path.addRect(0, -self.radius_, 2 * self.radius_,
                             2 * self.radius_)
                self.label.setPos(self.radius_ + self.margin,
                                  -self.label.boundingRect().height() / 2)
            else:
                path.addEllipse(0, -self.radius_, 2 * self.radius_,
                                2 * self.radius_)
                self.label.setPos(self.radius_ + self.margin,
                                  -self.label.boundingRect().height() / 2)

        self.setPath(path)

    def setNEBlock(self, block):
        self.m_block = block

    def setPortFlags(self, flags):
        self.m_portFlags = flags

        if self.m_portFlags & self.TypePort:
            font = self.scene().font()
            font.setItalic(True)
            self.label.setFont(font)
            self.setPath(QPainterPath())
        elif self.m_portFlags & self.NamePort:
            font = self.scene().font()
            font.setBold(True)
            self.label.setFont(font)
            self.setPath(QPainterPath())

    def setPtr(self, ptr):
        self.m_ptr = ptr

    def type(self):
        return self.Type

    def radius(self):
        return self.radius_

    def portName(self):
        return self.name

    def isOutput(self):
        return self.isOutput_

    def block(self):
        return self.m_block

    def portFlags(self):
        return self.m_portFlags

    def ptr(self):
        return self.m_ptr

    def addConnection(self, connection):
        self.m_connections.append(connection)

    def removeConnection(self, connection):
        try:
            self.m_connections.remove(connection)
        except:
            pass

    def connections(self):
        return self.m_connections

    def isConnected(self, other):
        for connection in self.m_connections:
            if connection.port1() == other or connection.port2() == other:
                return True

        return False

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemScenePositionHasChanged:
            for connection in self.m_connections:
                connection.updatePosFromPorts()
                connection.updatePath()

        return value
Exemple #39
0
class MatchEnd(InfoScene):
    def __init__(self, parent):
        super().__init__()
        self.__parent__ = parent

        self.font = QFont()
        self.font.setPointSize(20)
        self.my_points = QGraphicsTextItem(str(self.__parent__.my_score))
        self.my_points.setDefaultTextColor(Qt.white)
        self.my_points.setFont(self.font)
        self.opponent_points = QGraphicsTextItem(
            str(self.__parent__.opponent_score))
        self.opponent_points.setDefaultTextColor(Qt.white)
        self.opponent_points.setFont(self.font)
        self.logo = QGraphicsPixmapItem()

        self.logo.setPos((SCENE_WIDTH - 600) / 2, 50)

        if self.__parent__.player == Player.PLAYER_1:
            self.my_points.setPos(50, 250)
            self.opponent_points.setPos(
                SCENE_WIDTH -
                (50 + self.opponent_points.boundingRect().width()), 250)
        else:
            self.opponent_points.setPos(50, 250)
            self.my_points.setPos(
                SCENE_WIDTH -
                (50 + self.opponent_points.boundingRect().width()), 250)

        self.buttons = [
            Button(self.__parent__.load_info_scene, InfoScenes.MAIN_MENU.value,
                   (SCENE_WIDTH - 300) / 2, SCENE_HEIGHT - 100,
                   IMAGES_DIR + "menu/continue_highlighted.png",
                   IMAGES_DIR + "menu/continue_highlighted.png",
                   ButtonState.HIGHLIGHTED)
        ]

        if self.__parent__.my_score == self.__parent__.opponent_score:
            self.logo.setPixmap(QPixmap(IMAGES_DIR + "menu/draw.png"))
        elif self.__parent__.my_score > self.__parent__.opponent_score:
            self.logo.setPixmap(QPixmap(IMAGES_DIR + "menu/you_won.png"))
        else:
            self.logo.setPixmap(QPixmap(IMAGES_DIR + "menu/you_lost.png"))

        self.__draw_menu_buttons()
        self.addItem(self.my_points)
        self.addItem(self.opponent_points)
        self.addItem(self.logo)

    """ Handles keyboard presses """

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_W:
            self.__change_button_focus(Direction.UP)
        elif event.key() == Qt.Key_S:
            self.__change_button_focus(Direction.DOWN)
        elif event.key() == Qt.Key_Return:
            self.__execute_button()

    """ Draws buttons in the scene """

    def __draw_menu_buttons(self):
        for button in self.buttons:
            self.addItem(button.graphics_item)

    """ Executes button logic """

    def __execute_button(self):
        for index in range(len(self.buttons)):
            self.buttons[index].execute()

    """ Changes button focus """

    def __change_button_focus(self, direction: Direction):
        if direction is None:
            return

        count = len(self.buttons)
        old_index = -1
        new_index = -1
        for index in range(count):
            if self.buttons[index].state is ButtonState.HIGHLIGHTED:
                old_index = index
                if direction is Direction.UP:
                    if index - 1 > 0:
                        new_index = index - 1
                    else:
                        new_index = 0
                elif direction is Direction.DOWN:
                    if index + 1 > count - 1:
                        new_index = count - 1
                    else:
                        new_index = index + 1

        self.buttons[old_index].set_state(ButtonState.NORMAL)
        self.buttons[new_index].set_state(ButtonState.HIGHLIGHTED)
Exemple #40
0
class Checkpoint(VisualizerGraphicItem):
    def __init__(self, ID=0, x=0, y=0):
        super(self.__class__, self).__init__(ID, x, y)
        self._kind_name = 'checkpoint'

        self._ids = {}

        self._graphics_item = QGraphicsRectItem(self)
        self._text = QGraphicsTextItem(self._graphics_item)
        self._shine = False

    def set_rect(self, rect):
        scale = config.get('display', 'id_font_scale')
        bold = config.get('display', 'id_font_bold')
        font = QFont('', rect.width() * 0.08 * scale)
        self._text.setFont(font)
        self._text.setPos(rect.x(), rect.y() + 0.6 * rect.height())
        self._text.setDefaultTextColor(
            QColor(config.get('display', 'id_font_color')))

        if self._display_mode == 0:
            ss = ''
            if bold:
                ss = '<b>'
            for key in self._ids:
                count = 0
                for ii in self._ids[key]:
                    if count == 0:
                        ss = ss + '(' + key + ': ' + ii[0]
                    else:
                        ss = ss + ', ' + ii[0]
                    count += 1
                ss = ss + ')\n'

            if bold:
                ss += '</b>'

            self._text.setHtml(ss)
            self._graphics_item.setRect(rect.x(), rect.y(), rect.width(),
                                        rect.height())

        elif self._display_mode == 1:
            self._text.setPlainText('')
            self._graphics_item.setRect(rect.x(), rect.y(), rect.width(),
                                        rect.height())

    def do_action(self, time_step):
        self._shine = False
        return

    def undo_action(self, time_step):
        self._shine = False
        return

    def visit(self):
        self._shine = True

    def determine_color(self, number, count, pattern=None):
        color = None
        if len(self._ids) == 1:
            for key in self._ids:
                color_id = self._ids[key][0][1] + 1
                if color_id < len(self._colors):
                    color = self._colors[color_id]

        if color is None:
            color = self._colors[0]

        if self._shine:
            color = calculate_color(color, QColor(255, 255, 255), 0.4)
        self._graphics_item.setBrush(QBrush(color))

    def parse_init_value(self, name, value):
        result = super(self.__class__, self).parse_init_value(name, value)
        if result != 1:
            return result

        if name == 'checkpoint' and len(value.arguments) == 3:
            if str(value.arguments[0]) not in self._ids:
                self._ids[str(value.arguments[0])] = []
            self._ids[str(value.arguments[0])].append(
                (str(value.arguments[1]), value.arguments[2].number))
            return 0
        return 1

    def get_rect(self):
        return self._graphics_item.rect()
Exemple #41
0
class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)  #调用父类构造函数,创建窗体
        self.ui = Ui_MainWindow()  #创建UI对象
        self.ui.setupUi(self)  #构造UI界面

        self.player = QMediaPlayer(self)  #创建视频播放器
        self.player.setNotifyInterval(1000)  #信息更新周期, ms

        scene = QGraphicsScene(self)
        self.ui.graphicsView.setScene(scene)

        self.videoItem = QGraphicsVideoItem()  #视频显示画面
        self.videoItem.setSize(QSizeF(320, 220))
        self.videoItem.setFlag(QGraphicsItem.ItemIsMovable)
        self.videoItem.setFlag(QGraphicsItem.ItemIsSelectable)
        self.videoItem.setFlag(QGraphicsItem.ItemIsFocusable)

        scene.addItem(self.videoItem)
        self.player.setVideoOutput(self.videoItem)  #设置视频显示图形项

        self.textItem = QGraphicsTextItem("面朝大海,春暖花开")  #弹幕文字
        font = self.textItem.font()
        font.setPointSize(20)
        self.textItem.setFont(font)
        self.textItem.setDefaultTextColor(Qt.red)
        self.textItem.setPos(100, 220)
        self.textItem.setFlag(QGraphicsItem.ItemIsMovable)
        self.textItem.setFlag(QGraphicsItem.ItemIsSelectable)
        self.textItem.setFlag(QGraphicsItem.ItemIsFocusable)
        scene.addItem(self.textItem)

        self.ui.btnText.setCheckable(True)  #弹幕文字按钮
        self.ui.btnText.setChecked(True)

        self.__duration = ""
        self.__curPos = ""
        self.player.stateChanged.connect(self.do_stateChanged)
        self.player.positionChanged.connect(self.do_positionChanged)
        self.player.durationChanged.connect(self.do_durationChanged)

##  ==============自定义功能函数========================

##  ==============event处理函数==========================

    def closeEvent(self, event):  #窗体关闭时
        # 窗口关闭时不能自动停止播放,需手动停止
        if (self.player.state() == QMediaPlayer.PlayingState):
            self.player.stop()

##  ==========由connectSlotsByName()自动连接的槽函数============

    @pyqtSlot()  ##打开文件
    def on_btnOpen_clicked(self):
        curPath = QDir.currentPath()  #获取系统当前目录
        ##      curPath=os.getcwd()
        title = "选择视频文件"
        filt = "视频文件(*.wmv *.avi);;所有文件(*.*)"
        fileName, flt = QFileDialog.getOpenFileName(self, title, curPath, filt)

        if (fileName == ""):
            return

        fileInfo = QFileInfo(fileName)
        baseName = fileInfo.fileName()
        ##      baseName=os.path.basename(fileName)
        self.ui.LabCurMedia.setText(baseName)
        curPath = fileInfo.absolutePath()
        QDir.setCurrent(curPath)  #重设当前目录

        media = QMediaContent(QUrl.fromLocalFile(fileName))

        self.player.setMedia(media)  #设置播放文件
        self.player.play()

    @pyqtSlot()  ##播放
    def on_btnPlay_clicked(self):
        self.player.play()

    @pyqtSlot()  ##暂停
    def on_btnPause_clicked(self):
        self.player.pause()

    @pyqtSlot()  ##停止
    def on_btnStop_clicked(self):
        self.player.stop()

    @pyqtSlot()  ##全屏
    def on_btnFullScreen_clicked(self):
        self.videoWidget.setFullScreen(True)

    @pyqtSlot()  ##静音按钮
    def on_btnSound_clicked(self):
        mute = self.player.isMuted()
        self.player.setMuted(not mute)
        if mute:
            self.ui.btnSound.setIcon(QIcon(":/icons/images/volumn.bmp"))
        else:
            self.ui.btnSound.setIcon(QIcon(":/icons/images/mute.bmp"))

    @pyqtSlot(int)  ##音量调节
    def on_sliderVolumn_valueChanged(self, value):
        self.player.setVolume(value)

    @pyqtSlot(int)  ##播放进度调节
    def on_sliderPosition_valueChanged(self, value):
        self.player.setPosition(value)

    @pyqtSlot()  ##放大
    def on_btnZoomIn_clicked(self):
        sc = self.videoItem.scale()
        self.videoItem.setScale(sc + 0.1)

    @pyqtSlot()  ##缩小
    def on_btnZoomOut_clicked(self):
        sc = self.videoItem.scale()
        self.videoItem.setScale(sc - 0.1)

    @pyqtSlot(bool)  ##弹幕
    def on_btnText_clicked(self, checked):
        self.textItem.setVisible(checked)

##  =============自定义槽函数===============================

    def do_stateChanged(self, state):
        isPlaying = (state == QMediaPlayer.PlayingState)

        self.ui.btnPlay.setEnabled(not isPlaying)
        self.ui.btnPause.setEnabled(isPlaying)
        self.ui.btnStop.setEnabled(isPlaying)

    def do_durationChanged(self, duration):
        self.ui.sliderPosition.setMaximum(duration)

        secs = duration / 1000  #秒
        mins = secs / 60  #分钟
        secs = secs % 60  #余数秒
        self.__duration = "%d:%d" % (mins, secs)
        self.ui.LabRatio.setText(self.__curPos + "/" + self.__duration)

    def do_positionChanged(self, position):
        if (self.ui.sliderPosition.isSliderDown()):
            return  #如果正在拖动滑条,退出

        self.ui.sliderPosition.setSliderPosition(position)

        secs = position / 1000  #秒
        mins = secs / 60  #分钟
        secs = secs % 60  #余数秒
        self.__curPos = "%d:%d" % (mins, secs)
        self.ui.LabRatio.setText(self.__curPos + "/" + self.__duration)
Exemple #42
0
class AnimatedCalendar():
    updatesRunning = False
    updateTimer = None
    listUpdateThread = None
    calDataLock = threading.Lock()
    calDataUpdated = False
    curCalendars = None
    
    def __init__(self, scene, widthCalTextArea, heightCalTextArea, borders, calFeeds, calUpdateSecs):
        self.masterScene = scene
        self.widthCalTextArea = widthCalTextArea
        self.heightCalTextArea = heightCalTextArea
        self.borders = borders
        self.calFeeds = calFeeds
        self.calendarUpdateSecs = calUpdateSecs
        # Background
        self.textBkgd = QGraphicsRectItem(0, 0, self.widthCalTextArea, self.heightCalTextArea)
        self.textBkgd.setPos(self.borders[3], self.borders[0])
        self.textBkgd.setBrush(QColor("light green"))
        self.textBkgd.setZValue(10)
        
        scene.addItem(self.textBkgd)
        # Text Item
        self.textItem = QGraphicsTextItem()
        self.textItem.setFont(QFont("Segoe UI", 24))
        self.textItem.setDefaultTextColor(QColor("black"))
        self.textItem.setPos(QPointF(self.borders[3]+10,self.borders[0]+10))
        self.textItem.setHtml("<B>Hello</B>Hello")
        self.textItem.setZValue(20)
        self.textItem.setTextWidth(self.widthCalTextArea-20)
        scene.addItem(self.textItem)
        
    def start(self):
        self.updatesRunning = True
        QTimer.singleShot(100, self.updateCalendar)
        self.listUpdateThread = CalendarUpdateThread(self, self.calFeeds, self.calendarUpdateSecs)
        self.listUpdateThread.start()
#        print("CalStarted")

    def stop (self):
        self.updatesRunning = False
        if self.updateTimer != None:
            self.updateTimer.stop()
        if self.listUpdateThread != None:
            self.listUpdateThread.stop()
    
    def setNewCalendarEntries(self, calendars):
        with self.calDataLock:
            self.curCalendars = calendars
            self.calDataUpdated = True
        
    def updateCalendar(self):
#        print("Update cal")
        
        with self.calDataLock:
            if self.calDataUpdated and self.curCalendars != None:
                for calEvents in self.curCalendars:
                    calStr = ""
                    lastDay = -1
                    for anEvent in calEvents:
                        # date, duration, summary, location, UID
                        eventDate = anEvent[0]
                        duration = anEvent[1]
                        summary = anEvent[2]
                        location = anEvent[3]
                        if lastDay != eventDate.day:
                            if lastDay != -1:
                                calStr += "<br/>"
                            calStr += "<b>" + anEvent[0].strftime("%a") + " (" + anEvent[0].strftime("%d %B)") + ")</b><br/>"
                            lastDay = eventDate.day
                        strDurTime = str(duration).rpartition(":")[0]
                        durStr = (str(duration.days) + "day" + ("s" if duration.days != 1 else "")) if duration.days > 0 else strDurTime
                        locStr = "<small>("+location+")</small>" if location != "" else ""
                        calStr += anEvent[0].strftime("%H:%M") + " <small>(" + durStr + ")</small> " + summary + " " + locStr + "<br/>"
#                        print (anEvent)
    #                    print(date)
                    self.textItem.setHtml(calStr)
                    self.textItem.setTextWidth(self.widthCalTextArea-20)
                    self.textItem.update()
            self.calDataUpdated = False
        
        if not self.updatesRunning:
            return 
        self.updateTimer = QTimer()
        self.updateTimer.setInterval(5000)
        self.updateTimer.setSingleShot(True)
        self.updateTimer.timeout.connect(self.updateCalendar)
        self.updateTimer.start()