Пример #1
0
class QMarkablePicture(QLabel):
    def __init__(self, parent=None):
        QLabel.__init__(self, parent)
        self.initBrush()
        self.marks = []
        self.is_marks_count_limited = False
        self.marks_count_limit = 0

    def initBrush(self):
        self.brush = QBrush(Qt.SolidPattern)
        self.brush.setColor(QColor(constants.defaultBrushColor))

    def paintEvent(self, e):
        QLabel.paintEvent(self, e)
        painter = QPainter()
        painter.begin(self)
        painter.setBrush(self.brush)
        for mark in self.marks:
            painter.drawEllipse(mark, constants.ellipsWidth, constants.ellipsHeight)
        painter.end()

    def setBrushColor(self, color):
        self.brush.setColor(color)

    def drawMark(self, mark):
        if self.__isAbleDrawMark():
            self.marks.append(mark)
            self.update()

    def removeMark(self, mark):
        for painted_mark in self.marks:
            if self.__isApproximatelyEqual(mark, painted_mark, constants.epsilon):
                self.marks.remove(painted_mark)
                break
        self.update()

    def getMarks(self):
        return self.marks.copy()

    def setMarksCountLimit(self, limit):
        self.is_marks_count_limited = True
        self.marks_count_limit = limit

    def __isAbleDrawMark(self):
        limit_enabled_condition = self.is_marks_count_limited and (len(self.marks) < self.marks_count_limit)
        limit_disabled_condition = not self.is_marks_count_limited
        return limit_enabled_condition or limit_disabled_condition

    def __isApproximatelyEqual(self, firstMark, secondMark, epsilon):
        full_equality = firstMark == secondMark

        x_top_limit = (firstMark.x() + epsilon) >= secondMark.x()
        x_bottom_limit = (firstMark.x() - epsilon) <= secondMark.x()
        x_equality = x_top_limit and x_bottom_limit

        y_top_limit = (firstMark.y() + epsilon) >= secondMark.y()
        y_bottom_limit = (firstMark.y() - epsilon) <= secondMark.y()
        y_equality = y_top_limit and y_bottom_limit

        return full_equality or (x_equality and y_equality)
Пример #2
0
    def createArrow(self):
        # add an arrow to destination line
        myLine = self.destinationLine.line()
        myLine.setLength(myLine.length() - TransitionGraphicsItem.ARROW_SIZE)
        rotatePoint = myLine.p2() - self.destinationLine.line().p2()

        rightPointX = rotatePoint.x() * math.cos(math.pi / 6) - rotatePoint.y() * math.sin(math.pi / 6)
        rightPointY = rotatePoint.x() * math.sin(math.pi / 6) + rotatePoint.y() * math.cos(math.pi / 6)
        rightPoint = QPointF(rightPointX + self.destinationLine.line().x2(),
                             rightPointY + self.destinationLine.line().y2())

        leftPointX = rotatePoint.x() * math.cos(-math.pi / 6) - rotatePoint.y() * math.sin(-math.pi / 6)
        leftPointY = rotatePoint.x() * math.sin(-math.pi / 6) + rotatePoint.y() * math.cos(-math.pi / 6)
        leftPoint = QPointF(leftPointX + self.destinationLine.line().x2(),
                            leftPointY + self.destinationLine.line().y2())

        polygon = QPolygonF()
        polygon << rightPoint << leftPoint << self.destinationLine.line().p2() << rightPoint

        if self.arrow == None:
            self.arrow = QGraphicsPolygonItem(polygon, self)
        else:
            self.arrow.setPolygon(polygon)

        brush = QBrush(Qt.SolidPattern)
        brush.setColor(Qt.black)
        self.arrow.setBrush(brush)
Пример #3
0
 def drawCircle(self, painter, centerX, centerY, color, size):
     pen = QPen(color, size)
     painter.setPen(pen)
     brush = QBrush(Qt.SolidPattern)
     brush.setColor(QColor(Qt.blue))
     painter.setBrush(brush)
     painter.drawEllipse(centerX, centerY, 5, 5)
Пример #4
0
class RoundedPushButton1(QPushButton):
    def __init__(self,parent, default_wide, default_high,text=''):
        QPushButton.__init__(self, parent)
        #self.resize(100,80)
        self.default_high=default_high
        self.default_wide=default_wide
        self.xrd=self.default_wide/10
        #self.yrd=self.default_high/10
        self.yrd=self.xrd
        #self.resize(self.default_wide,self.default_high)

        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(0)
        self.brush=QBrush(Qt.SolidPattern)

        self.textlabel=textQLabel(self,text)

    def paintEvent(self,event):
        #brush.setStyle(Qt.Dense1Pattern)
        self.brush.setColor(self.backgroundColor)
        self.painter=QPainter(self)
        self.painter.setRenderHint(QPainter.Antialiasing)
        
        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush)
        self.painter.drawRoundedRect(QRect(0,0,self.default_wide,self.default_high), self.xrd, self.yrd)
        #self.painter.drawPixmap(self.imgx, self.imgy, self.piximg)
        self.painter.end()
Пример #5
0
class ModCrossButton(QPushButton):
    def __init__(self,parent,path=None):
        QPushButton.__init__(self,parent)

        self.parent=parent


        #self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(100)
        self.brush=QBrush(Qt.SolidPattern)


    def paintEvent(self,event):
        self.wide=self.width()
        self.high=self.height()
        self.xdis=self.wide/7
        self.ydis=self.xdis

        self.path=QPainterPath()
        self.path.setFillRule(Qt.OddEvenFill)

        self.path.moveTo(self.wide/2, self.high/2-self.xdis)
        self.path.arcTo(0,0, self.wide, self.high,0,360)
        #self.path.closeSubpath()

        self.path.moveTo(self.wide/2-self.xdis/2, self.ydis)
        self.path.lineTo(self.wide/2-self.xdis/2, self.high/2-self.xdis/2)
        self.path.lineTo(self.ydis, self.high/2-self.xdis/2)
        self.path.lineTo(self.ydis, self.high/2+self.xdis/2)
        self.path.lineTo(self.wide/2-self.xdis/2, self.high/2+self.xdis/2)
        self.path.lineTo(self.wide/2-self.xdis/2, self.high-self.ydis)
        self.path.lineTo(self.wide/2+self.xdis/2, self.high-self.ydis)
        self.path.lineTo(self.wide/2+self.xdis/2, self.high/2+self.xdis/2)
        self.path.lineTo(self.wide-self.ydis, self.high/2+self.xdis/2)
        self.path.lineTo(self.wide-self.ydis, self.high/2-self.xdis/2)
        self.path.lineTo(self.wide/2+self.xdis/2, self.high/2-self.xdis/2)
        self.path.lineTo(self.wide/2+self.xdis/2, self.ydis)
        self.path.closeSubpath()

        self.brush.setColor(self.backgroundColor)
        self.painter=QPainter(self)
        self.painter.setRenderHint(QPainter.Antialiasing)

        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush)
        self.painter.drawPath(self.path)
        self.painter.end()

    #def mousePressEvent(self,ev):
    #    self.parent.close()

    def enterEvent(self,ev):
        self.backgroundColor.setRgb(242,146,52) 
        self.update()
        
    def leaveEvent(self,ev):
        self.backgroundColor.setRgb(157,157,157)
        self.update()
Пример #6
0
	def __init__(self, parent = None, message = None, itemType = "log"):
		QListWidgetItem.__init__(self)
		self.itemType = itemType

		if (itemType == "log"):
			self.setText("--- " + str(message))
		elif (itemType == "in"):
			self.setText("<<< " + str(message))
		elif (itemType == "out"):
			self.setText(">>> " + str(message))
		else:
			self.setText(str(message))

		font = QFont()
		font.setFamily("Monospace")
		if (itemType == "in") or (itemType == "out"):
			font.setBold(True)
			font.setWeight(75)
		else:
			font.setBold(False)
			font.setWeight(50)
		self.setFont(font)

		brush = QBrush(QColor(0, 0, 0))
		if (itemType == "in"):
			brush = QBrush(QColor(0, 0, 85))
		elif (itemType == "out"):
			brush = QBrush(QColor(0, 85, 0))
		brush.setStyle(Qt.NoBrush)
		self.setForeground(brush)
 def setStyle(self, painter, fillColor, penColor, stroke):
     brush = QBrush()
     pen = QPen(penColor, stroke)
     brush.setColor(fillColor)
     brush.setStyle(Qt.SolidPattern)
     painter.setBrush(brush)
     painter.setPen(pen)
     painter.setRenderHint(QPainter.Antialiasing)
Пример #8
0
 def setRequired(self, required):
     self.required = required
     brush = QBrush()
     if required:
         brush.setColor(QColor(255, 0, 0))
     else:
         brush.setColor(QColor(0, 0, 0))
     self.setForeground(0, brush)
Пример #9
0
 def __set_brushAlpha(self, alpha: int):
     """
     Args:
         alpha: Description
     """
     brush = QBrush(self.item.brush())
     color = QColor(brush.color())
     color.setAlpha(alpha)
     self.item.setBrush(QBrush(color))
Пример #10
0
class ModCloseButton(QPushButton):
    def __init__(self,parent,wide,high,ppath=None):
        QPushButton.__init__(self,parent)

        self.parent=parent
        self.wide=wide
        self.high=high
        self.resize(self.wide,self.high)
        self.xdis=self.wide/10

        #self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(100)
        self.brush=QBrush(Qt.SolidPattern)

        if ppath :
            self.path=ppath
        else :
            self.path=QPainterPath()

            self.path.moveTo(self.wide/2, self.high/2-self.xdis)
            self.path.arcTo(0,0, self.wide-2*self.xdis, self.high-2*self.xdis,45,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2-self.xdis, self.high/2)
            self.path.arcTo(0,0,self.wide-2*self.xdis,self.high-2*self.xdis,135,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2, self.high/2+self.xdis)
            self.path.arcTo(0,0,self.wide-2*self.xdis, self.high-2*self.xdis,225,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2+self.xdis, self.high/2)
            self.path.arcTo(0,0,self.wide-2*self.xdis, self.high-2*self.xdis,315,90)
            self.path.closeSubpath()

    def paintEvent(self,event):
        self.brush.setColor(self.backgroundColor)
        self.painter=QPainter(self)
        self.painter.setRenderHint(QPainter.Antialiasing)

        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush)
        self.painter.drawPath(self.path)
        self.painter.end()

    def mousePressEvent(self,ev):
        self.parent.close()

    def enterEvent(self,ev):
        self.backgroundColor.setRgb(234,39,13) 
        self.update()
        
    def leaveEvent(self,ev):
        self.backgroundColor.setRgb(157,157,157)
        self.update()
    def valueChanged(self, property, value):
        if (not self.propertyToId.contains(property)):
            return

        if (not self.currentItem or self.currentItem.isNone()):
            return
        tp = type(value)
        id = self.propertyToId[property]
        if tp == float:
            if (id == "xpos"):
                self.currentItem.setX(value)
            elif (id == "ypos"):
                self.currentItem.setY(value)
            elif (id == "zpos"):
                self.currentItem.setZ(value)
        elif tp == str:
            if (id == "text"):
                if (self.currentItem.rtti() == RttiValues.Rtti_Text):
                    i = self.currentItem
                    i.setText(value)
        elif tp == QColor:
            if (id == "color"):
                if (self.currentItem.rtti() == RttiValues.Rtti_Text):
                    i = self.currentItem
                    i.setColor(value)
            elif (id == "brush"):
                if (self.currentItem.rtti() == RttiValues.Rtti_Rectangle or self.currentItem.rtti() == RttiValues.Rtti_Ellipse):
                    i = self.currentItem
                    b = QBrush(i.brush())
                    b.setColor(value)
                    i.setBrush(b)
            elif (id == "pen"):
                if (self.currentItem.rtti() == RttiValues.Rtti_Rectangle or self.currentItem.rtti() == RttiValues.Rtti_Line):
                    i = self.currentItem
                    p = QPen(i.pen())
                    p.setColor(value)
                    i.setPen(p)
        elif tp == QFont:
            if (id == "font"):
                if (self.currentItem.rtti() == RttiValues.Rtti_Text):
                    i = self.currentItem
                    i.setFont(value)
        elif tp == QPoint:
            if (self.currentItem.rtti() == RttiValues.Rtti_Line):
                i = self.currentItem
                if (id == "endpoint"):
                    i.setPoints(i.startPoint().x(), i.startPoint().y(), value.x(), value.y())
        elif tp == QSize:
            if (id == "size"):
                if (self.currentItem.rtti() == RttiValues.Rtti_Rectangle):
                    i = self.currentItem
                    i.setSize(value.width(), value.height())
                elif (self.currentItem.rtti() == RttiValues.Rtti_Ellipse):
                    i = self.currentItem
                    i.setSize(value.width(), value.height())
        self.canvas.update()
Пример #12
0
 def paintEvent(self, ev):
     pen = QPen()
     pen.setStyle(Qt.DotLine)
     pen.setWidth(2)
     pen.setColor(QColor(Qt.white))
     brush = QBrush()
     brush.setStyle(Qt.SolidPattern)
     brush.setColor(QColor(0, 0, 0))
     painter = QPainter(self)
     painter.setPen(pen)
     painter.setBrush(brush)
     painter.drawRect(ev.rect())
Пример #13
0
    def __set_brushAlpha(self, alpha):
        """Summary

        Args:
            alpha (TYPE): Description

        Returns:
            TYPE: Description
        """
        brush = QBrush(self.item.brush())
        color = QColor(brush.color())
        color.setAlpha(alpha)
        self.item.setBrush(QBrush(color))
Пример #14
0
 def drawShape(self, event, qp):
     pen = QPen(Qt.yellow)
     pen.setWidth(3)
     # rellenar fondo con patron de imagen
     brush = QBrush()
     brush.setTexture(QPixmap('image/small_image.jpg'))
     # establecer el QBrush
     qp.setBrush(brush)
     qp.setPen(pen)
     qp.drawRoundedRect(QRect(50, 50, 200, 150), 15, 15)
     # utilizar un patron predefinido
     brush.setStyle(Qt.DiagCrossPattern)
     qp.setBrush(brush)
     qp.drawEllipse(350, 50, 150, 150)
Пример #15
0
class WLLineLabel(QPushButton):
    def __init__(self,parent):
        super(WLLineLabel,self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint )
        self.linelength=1000
        self.lineheight=5
        self.resize(self.linelength, self.lineheight)
        self.move(100,100)
        self.stats=None
        #self.setStyleSheet("{background-color:transparent;border:none;color:transparent;}")

        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157)#(220,203,231)
        #self.backgroundColor.setAlpha(255)
        self.brush=QBrush(Qt.SolidPattern)
    def paintEvent(self,event):
        self.brush.setColor(self.backgroundColor)
        self.painter=QPainter(self)
        self.painter.setRenderHint(QPainter.Antialiasing)

        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush)
        #print(self.geometry())
        self.painter.drawRect(0, 0, 1000, 5)
        self.painter.end()

    
    def statsReset(self):
        self.stats=None
        self.backgroundColor.setAlpha(255)
        self.redraw()
    def mousePressEvent(self,ev):
        if self.stats == 'selected' :
            self.stats = None
            self.backgroundColor.setAlpha(255)
        else:
            self.stats = 'selected'
            self.backgroundColor.setRgb(157,157,157)
        self.update()

    def enterEvent(self,ev):
        #print('enter')
        if self.stats != 'selected' :
            self.backgroundColor.setAlpha(0)
            self.update()
        
    def leaveEvent(self,ev):
        if self.stats != 'selected' :
            self.backgroundColor.setAlpha(255)
            self.update()
Пример #16
0
    def __init__(self,  dblock: DBlock):
        super(DBlockTreeItem, self).__init__(dblock, dblock.name)
        self.dblock = dblock
        self.setSelectable(False)
        self.setEditable(False)

        self.tool_tip = "DBlock: " + dblock.name

        if isinstance(dblock, DEvent):
            brush = QBrush()
            brush.setColor(Qt.magenta)
            self.tool_tip = "DEvent: " + dblock.name
            self.setForeground(brush)
            self.setSelectable(True)
Пример #17
0
    def __init__(self,parent=None,text='FigLabelWidget'):
        super(FigLabelWidget,self).__init__(parent)
        self.parent=parent
        self.lx=5
        self.text=text
        self.fid=0
        self.stats=None

        self.linecolor=QPalette().light().color()
        self.linecolor.setRgb(157,157,157)
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(187,187,187)
        self.brush=QBrush(Qt.SolidPattern)
        self.brush2=QBrush(Qt.SolidPattern)

        self.activeLabel()
Пример #18
0
 def __init__(self,parent, text=''):
     QPushButton.__init__(self, parent)
     self.text=text
     self.backgroundColor = QPalette().light().color()
     self.backgroundColor.setRgb(157,157,157) #(220,203,231)
     #self.backgroundColor.setAlpha(0)
     self.brush=QBrush(Qt.SolidPattern)
Пример #19
0
    def mousePressEvent(self, event):
        """Summary

        Args:
            event (QGraphicsSceneMouseEvent): Description

        Returns:
            TYPE: Description
        """
        if event.pos().y() < 10:
            new_color = self.colordialog.getColor(self._shift_color)
            if new_color.isValid() and new_color.name() != self._shift_color.name():
                self._shift_color = new_color
                self._shift_brush = QBrush(new_color)
                if new_color not in self._shift_colors:
                    self._shift_colors.insert(self._shift_color_index, new_color)
                self.update()
        else:
            new_color = self.colordialog.getColor(self._color)
            if new_color.isValid() and new_color.name() != self._color.name():
                self._color = new_color
                self._brush = QBrush(new_color)
                if new_color not in self._colors:
                    self._colors.insert(self._color_index, new_color)
                self.update()
Пример #20
0
    def __init__(self,parent,wide,high,ppath=None):
        QPushButton.__init__(self,parent)

        self.parent=parent
        self.wide=wide
        self.high=high
        self.resize(self.wide,self.high)
        self.xdis=self.wide/10

        #self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(100)
        self.brush=QBrush(Qt.SolidPattern)

        if ppath :
            self.path=ppath
        else :
            self.path=QPainterPath()

            self.path.moveTo(self.wide/2, self.high/2-self.xdis)
            self.path.arcTo(0,0, self.wide-2*self.xdis, self.high-2*self.xdis,45,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2-self.xdis, self.high/2)
            self.path.arcTo(0,0,self.wide-2*self.xdis,self.high-2*self.xdis,135,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2, self.high/2+self.xdis)
            self.path.arcTo(0,0,self.wide-2*self.xdis, self.high-2*self.xdis,225,90)
            self.path.closeSubpath()

            self.path.moveTo(self.wide/2+self.xdis, self.high/2)
            self.path.arcTo(0,0,self.wide-2*self.xdis, self.high-2*self.xdis,315,90)
            self.path.closeSubpath()
Пример #21
0
    def setupMounts(self):
        adapter = app.adapterManager[0]
        if not adapter.useXwared:
            self.tab_mount.setEnabled(False)
            return
        self.table_mounts.setRowCount(0)
        self.table_mounts.clearContents()

        mountsMapping = app.adapterManager[0].mountsFaker.getMountsMapping()
        for i, mount in enumerate(app.adapterManager[0].mountsFaker.mounts):
            self.table_mounts.insertRow(i)
            # drive1: the drive letter it should map to, by alphabetical order
            drive1 = app.adapterManager[0].mountsFaker.driveIndexToLetter(i)
            self.table_mounts.setItem(i, 0, QTableWidgetItem(drive1 + "\\TDDOWNLOAD"))

            # mounts = ['/path/to/1', 'path/to/2', ...]
            self.table_mounts.setItem(i, 1, QTableWidgetItem(mount))

            # drive2: the drive letter it actually is assigned to
            drive2 = mountsMapping.get(mount, "无")

            errors = []

            # check: mapping
            if drive1 != drive2:
                errors.append(
                    "错误:盘符映射在'{actual}',而不是'{should}'。\n"
                    "如果这是个新挂载的文件夹,请尝试稍等,或重启后端,可能会修复此问题。"
                    .format(actual = drive2, should = drive1))

            brush = QBrush()
            if errors:
                brush.setColor(Qt.red)
                errString = "\n".join(errors)
            else:
                brush.setColor(Qt.darkGreen)
                errString = "正常"
            errWidget = QTableWidgetItem(errString)
            errWidget.setForeground(brush)

            self.table_mounts.setItem(i, 2, errWidget)
            del brush, errWidget

        self.table_mounts.resizeColumnsToContents()
Пример #22
0
    def textureRect(self, rect_tile):
        tile_info = rect_tile.data(0)

        if tile_info is None:
            return False

        pm = QPixmap(self.__tiler.tile_to_path(tile_info))  
        if pm.width() != 256:
            #print("Probably didn't get tile:", next_tile_info.x, next_tile_info.y, "\n")
            #TODO: Attempt to texture with a lower res tile
            #Bear in mind that you will have to take Mercator projection into
            #account on the lower res tile.
            
            #First Attempt: didn't work
            #if tile_info.zoom <= self.__tiler.get_min_zoom():
            #    return False
            #
            #find colocated lower res tile
            #(lat,lon) = tile_info.coord()
            #tile_info2 = self.__tiler.coord_to_tile(lat,lon, tile_info.zoom-1)
            #rect_tile.setData(0, tile_info2)
            #print("prev tile: ", tile_info.tile, tile_info.coord())
            #return self.textureRect(rect_tile, depth + 1)

            #until such time as we can pull lower res tiles and figure out
            #which area to render on a rectangle, skip:
            return False

        topLeft = rect_tile.boundingRect().topLeft()
        bottomRight = rect_tile.boundingRect().bottomRight()   
       
        width = bottomRight.x() - topLeft.x()
        height = bottomRight.y() - topLeft.y()

        brush_trans = QTransform()        
        brush_trans.translate(topLeft.x(), topLeft.y())
        brush_trans.scale(width/256.0, height/256.0)

        qb = QBrush(pm)
        qb.setTransform(brush_trans)
        rect_tile.setBrush(qb)
   
        return True
Пример #23
0
    def setupMounts(self):
        self.table_mounts.setRowCount(0)
        self.table_mounts.clearContents()

        permissionCheckResult = app.mountsFaker.permissionCheck()
        permissionCheckFailed = ["无法获得检测权限。运行{}查看原因。".format(constants.PERMISSIONCHECK)]

        mountsMapping = app.mountsFaker.getMountsMapping()
        for i, mount in enumerate(app.mountsFaker.mounts):
            # mounts = ['/path/to/1', 'path/to/2', ...]
            self.table_mounts.insertRow(i)
            self.table_mounts.setItem(i, 0, QTableWidgetItem(mount))
            # drive1: the drive letter it should map to, by alphabetical order
            drive1 = chr(ord('C') + i) + ":"
            self.table_mounts.setItem(i, 1, QTableWidgetItem(drive1))
            # drive2: the drive letter it actually is assigned to
            drive2 = mountsMapping.get(mount, "无")

            # check 1: permission
            errors = permissionCheckResult.get(mount, permissionCheckFailed)

            # check 2: mapping
            if drive1 != drive2:
                errors.append(
                    "警告:盘符映射在'{actual}',而不是'{should}'。需要重启后端修复。".format(
                        actual = drive2,
                        should = drive1))

            brush = QBrush()
            if errors:
                brush.setColor(Qt.red)
                errString = "\n".join(errors)
            else:
                brush.setColor(Qt.darkGreen)
                errString = "正常"
            errWidget = QTableWidgetItem(errString)
            errWidget.setForeground(brush)

            self.table_mounts.setItem(i, 2, errWidget)
            del brush, errWidget

        self.table_mounts.resizeColumnsToContents()
Пример #24
0
    def __init__(self,parent,path=None):
        QPushButton.__init__(self,parent)

        self.parent=parent


        #self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(100)
        self.brush=QBrush(Qt.SolidPattern)
Пример #25
0
class BrushFormation(InstrumentFormation):
  ''' Specialize to Qt <QBrush> '''
  
  def __init__(self, parentSelector, role=""):
    
    InstrumentFormation.__init__(self, name="Brush", parentSelector=parentSelector, role=role)
    self.instrument = QBrush()
    self.styleProperties=[BaseStyleProperty("Color", self.instrument.setColor, self.selector,
                                            resettableValueFactory=ResettableColorValue,
                                            layoutFactory=ColorStylePropertyLayout,
                                            default=self.instrument.color()),
                          BaseStyleProperty("Style", # Was Pattern
                                            self.instrument.setStyle, self.selector,
                                            default=self.instrument.style(),
                                            # ResettableIntValue defaults and works
                                            layoutFactory=ComboBoxStylePropertyLayout,
                                            domainModel = config.BrushModel),]
    
    '''
    sic, BrushPattern is called Style in Qt
    
    Need Pattern, since defaults to NoBrush and that means color is moot.
    If we just have Color, once it is set, no way to go back to unfilled.
    
    TODO: user friendly:  if user chooses color, ensure pattern is not NoBrush
    '''
    
    # TODO gradients and texture not working?
  
  
  def applyTo(self, morph):
    #print "setBrush on morph", self.instrument.color()
    
    # Morph knows it's scale and applies it to self instrument
    morph.scaleInstrument(self.instrument)  # No baseValue, defaults to 1
    # Tell Morph to use self.instrument to draw itself
    morph.setBrush(self.instrument) 
  
  
  """
Пример #26
0
class RoundedPushButton(QPushButton):
    def __init__(self,parent, text=''):
        QPushButton.__init__(self, parent)
        self.text=text
        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157) #(220,203,231)
        #self.backgroundColor.setAlpha(0)
        self.brush=QBrush(Qt.SolidPattern)

    def paintEvent(self,event):
        self.brush.setColor(self.backgroundColor)
        self.painter=QPainter(self)
        self.painter.setRenderHint(QPainter.Antialiasing)
        
        self.painter.setPen(Qt.NoPen)
        self.painter.setBrush(self.brush)
        self.painter.drawRoundedRect(QRect(0,0,self.width(),self.height()), self.width()/10, self.height()/10)
        self.painter.end()

        self.painter3=QPainter(self)
        self.painter3.drawText(1,0,self.width()-2,self.height(),Qt.AlignCenter,self.text)
        self.painter3.end()
Пример #27
0
    def setupMounts(self):
        self.table_mounts.setRowCount(0)
        self.table_mounts.clearContents()

        PermissionError = self.permissionCheck()

        mountsMapping = self.mainWin.mountsFaker.getMountsMapping()
        for i, mount in enumerate(self.mainWin.mountsFaker.mounts):
            # mounts = ['/path/to/1', 'path/to/2', ...]
            self.table_mounts.insertRow(i)
            self.table_mounts.setItem(i, 0, QTableWidgetItem(mount))
            drive1 = chr(ord('C') + i) + ":" # the drive letter it should map to, by alphabetical order
            self.table_mounts.setItem(i, 1, QTableWidgetItem(drive1))
            drive2 = mountsMapping.get(mount, "无") # the drive letter it actually is assigned to

            # check 1: permission
            errors = PermissionError.get(mount, ["无法获得检测权限。运行/opt/xware_desktop/permissioncheck查看原因。"])

            # check 2: mapping
            if drive1 != drive2:
                errors.append("警告:盘符映射在'{actual}',而不是'{should}'。需要重启后端修复。".format(actual = drive2, should = drive1))

            from PyQt5.Qt import Qt
            from PyQt5.QtGui import QBrush

            brush = QBrush()
            if errors:
                brush.setColor(Qt.red)
                errString = "\n".join(errors)
            else:
                brush.setColor(Qt.darkGreen)
                errString = "正常"
            errWidget = QTableWidgetItem(errString)
            errWidget.setForeground(brush)

            self.table_mounts.setItem(i, 2, errWidget)
            del brush, errWidget

        self.table_mounts.resizeColumnsToContents()
    def init(self):
        current_path = os.path.dirname(os.path.abspath(__file__)).split(os.sep)
        current_path = os.path.join(*current_path[1:-2])

        default_image_path = "/" + current_path + "/test/fakeimg.jpg"
        image_path = self.getProperty("file_name", default_image_path)

        self.image = QPixmap(image_path)
        self.image_dimensions = (self.image.width(), self.image.height())
        self.painter = QPainter(self.image)

        custom_pen = QPen(Qt.SolidLine)
        custom_pen.setColor(Qt.black)
        custom_pen.setWidth(1)
        self.painter.setPen(custom_pen)

        custom_brush = QBrush(Qt.SolidPattern)
        custom_brush.setColor(Qt.lightGray)
        self.painter.setBrush(custom_brush)

        self.setIsReady(True)
        AbstractVideoDevice.init(self)
Пример #29
0
 def __init__(self, parent=None):
     super(ColorPanel, self).__init__(parent)
     self.rect = QRectF(0, 0, 30, 30)
     self.setFlag(QGraphicsItem.ItemIgnoresTransformations)
     self.colordialog = QColorDialog()
     # self.colordialog.setOption(QColorDialog.DontUseNativeDialog)
     self._scaf_color_index = -1  # init on -1, painttool will cycle to 0
     self._stap_color_index = -1  # init on -1, painttool will cycle to 0
     self._scaf_color = self._scaf_colors[self._scaf_color_index]
     self._stap_color = self._stap_colors[self._stap_color_index]
     self._scaf_brush = QBrush(self._scaf_color)
     self._stap_brush = QBrush(self._stap_color)
     self._initLabel()
     self.hide()
Пример #30
0
    def __init__(self,parent):
        super(WLLineLabel,self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint )
        self.linelength=1000
        self.lineheight=5
        self.resize(self.linelength, self.lineheight)
        self.move(100,100)
        self.stats=None
        #self.setStyleSheet("{background-color:transparent;border:none;color:transparent;}")

        self.backgroundColor = QPalette().light().color()
        self.backgroundColor.setRgb(157,157,157)#(220,203,231)
        #self.backgroundColor.setAlpha(255)
        self.brush=QBrush(Qt.SolidPattern)
Пример #31
0
    def __init__(self, brojIgraca, lvlNumber, menu_widnow):
        super().__init__()

        self.menu_window = menu_widnow
        oImage = QImage("images\\dk.jpg")
        sImage = oImage.scaled(QSize(1000, 562))  # resize Image to widgets size
        palette = QPalette()
        palette.setBrush(10, QBrush(sImage))  # 10 = Windowrole
        self.setPalette(palette)
        self.barrelsMovement = None
        self.pix112 = QPixmap('images\\luigiL.png')
        self.pix11 = QPixmap('images\\luigi.png')
        self.pix12 = QPixmap('images\\marioL.jpg')
        self.pix1 = QPixmap('images\\mario.jpg')
        self.pix2 = QPixmap('images\\p.png')
        self.pix22 = QPixmap('images\\pL.png')

        self.pix3 = QPixmap('images\\donkeykong1.png')
        self.pixBottleR = QPixmap('images\\barrelR.png')
        self.pix32 = QPixmap('images\\donkeykong1.png')
        self.pixfire = QPixmap('images\\fire.png')

        self.hitSide = False
        self.barrels_speed = 0.1 #promeljiva za brzinu




        self.label2 = QLabel(self)
        self.label12 = QLabel(self)
        self.label4 = QLabel(self)


        self.label3 = QLabel(self)
        self.labelScore = QLabel(self)
        self.labelLifes1 = QLabel(self)
        self.labelLifes2 = QLabel(self)
        self.life1ispis = QLabel(self)
        self.life2ispis = QLabel(self)
        self.label1 = QLabel(self)

        self.labelLevel = QLabel(self)
        self.ispisLabel1 = QLabel(self)
        self.playerRez1 = QLabel(self)
        self.playerRez11 = QLabel(self)
        self.playerRez2 = QLabel(self)
        self.playerRez22 = QLabel(self)

        self.barrelQueue = Queue()
        self.barrelProcess = Process(target=generateBarrel, args=[self.barrelQueue])
        self.barrels = []
        self.barrelProcess.start()

        self.gorilaStop = Queue()
        self.gorilaStart = Queue()
        self.gorilaBug = Process(target=GorilaFreezeProcess, args=[self.gorilaStart, self.gorilaStop])
        self.gorilaBug.start()

        self.fire_positions = [[400, 400], [500, 400], [550, 400],[700,310],[220,310]]
        self.firelabel = QLabel(self)
        self.firelabel.setPixmap(self.pixfire)



        self.zaustavio = False

        self.PointsM = 0
        self.PointsL = 0
        self.trenutniNivo = lvlNumber
        self.kraj = None

        self.quit_menu = QLabel(self)
        self.quit_img = QPixmap('images\\menubutton.png')
        self.quit_menu.setPixmap(self.quit_img)
        self.quit_menu.setGeometry(800, 50, 75, 50)
        self.quit_menu.mousePressEvent = self.go_to_menu

        self.ispisLabel1.setText('Level: ')
        self.ispisLabel1.setStyleSheet('color: blue')

        self.playerRez1.setText('P1: ')
        self.playerRez1.setStyleSheet('color: red')

        self.playerRez2.setText('P2: ')

        self.life1ispis.setText('P1 Life: ')
        self.life1ispis.setStyleSheet('color: red')

        self.life2ispis.setText('P2 Life: ')

        self.playerRez11.setText(str(self.PointsM))
        self.playerRez11.setStyleSheet('color: red')

        self.playerRez22.setText(str(self.PointsL))

        self.left = 400
        self.top = 200
        self.width = 1000
        self.height = 562

        self.key_notifier = KeyNotifier()
        if (brojIgraca == 1):
            self.key_notifier.key_signal.connect(self.__update_position__)
            self.brojIgracaJedan = True

        else:
            self.brojIgracaJedan = False
            self.key_notifier2 = KeyNotifier2()
            self.key_notifier.key_signal.connect(self.__update_position__)  # -----------------
            self.key_notifier2.key_signal2.connect(self.__update_position2__)  # -----------------
            self.key_notifier2.start()

        self.key_notifier.start()

        self.__init_ui__(brLevel, brojIgraca)
Пример #32
0
class EmptyHelixItem(QGraphicsEllipseItem):
    """docstring for EmptyHelixItem"""
    # set up default, hover, and active drawing styles
    _DEFAULT_BRUSH = QBrush(styles.GRAY_FILL)
    _DEFAULT_PEN = QPen(styles.GRAY_STROKE, styles.SLICE_HELIX_STROKE_WIDTH)
    _HOVER_BRUSH = QBrush(styles.BLUE_FILL)
    _HOVER_PEN = QPen(styles.BLUE_STROKE, styles.SLICE_HELIX_HILIGHT_WIDTH)
    _RADIUS = styles.SLICE_HELIX_RADIUS
    temp = styles.SLICE_HELIX_STROKE_WIDTH
    _DEFAULT_RECT = QRectF(0, 0, 2 * _RADIUS, 2 * _RADIUS)
    temp = (styles.SLICE_HELIX_HILIGHT_WIDTH - temp) / 2
    _HOVER_RECT = _DEFAULT_RECT.adjusted(-temp, -temp, temp, temp)
    _Z_DEFAULT = styles.ZSLICEHELIX
    _Z_HOVERED = _Z_DEFAULT + 1
    temp /= 2
    _ADJUSTMENT_PLUS = (temp, temp)
    _ADJUSTMENT_MINUS = (-temp, -temp)

    # _PI = 3.141592
    # _temp = [x*_PI*0.1 for x in range(20)]
    # _temp = [(math.sin(angle) * _RADIUS, math.cos(angle) * _RADIUS) for angle in _temp]
    def __init__(self, row, column, part_item):
        """
        row, column is a coordinate in Lattice terms
        part_item is a PartItem that will act as a QGraphicsItem parent
        """
        super(EmptyHelixItem, self).__init__(parent=part_item)
        self._part_item = part_item
        self._lastvh = None  # for decideAction
        self.hide()
        self._is_hovered = False
        self.setAcceptHoverEvents(True)

        self.setNotHovered()

        x, y = part_item.part().latticeCoordToPositionXY(
            row, column, part_item.scaleFactor())
        self.setPos(x, y)
        self._coord = (row, column)
        self.show()

    # end def

    def virtualHelix(self):
        """
        virtualHelixItem should be the HelixItems only child if it exists
        and virtualHelix should be it member
        """
        temp = self.virtualHelixItem()
        if temp:
            return temp.virtualHelix()
        else:
            return None

    # end def

    def virtualHelixItem(self):
        """
        virtualHelixItem should be the HelixItems only child if it exists
        and virtualHelix should be it member
        """
        temp = self.childItems()
        if len(temp) > 0:
            return temp[0]
        else:
            return None

    # end def

    def part(self):
        return self._part_item.part()

    # end def

    def translateVH(self, delta):
        """
        used to update a child virtual helix position on a hover event
        delta is a tuple of x and y values to translate

        positive delta happens when hover happens
        negative delta when something unhovers
        """
        temp = self.virtualHelixItem()

        # xor the check to translate,
        # convert to a QRectF adjustment if necessary
        check = (delta > 0) ^ self._is_hovered
        if temp and check:
            pass
            # temp.translate(*delta)

    # end def

    def setHovered(self):
        # self.setFlag(QGraphicsItem.ItemHasNoContents, False)
        self.setBrush(self._HOVER_BRUSH)
        self.setPen(self._HOVER_PEN)
        self.update(self.boundingRect())
        # self.translateVH(self._ADJUSTMENT_PLUS)
        self._is_hovered = True
        self.setZValue(self._Z_HOVERED)
        self.setRect(self._HOVER_RECT)

        self._part_item.updateStatusBar("(%d, %d)" % self._coord)

    # end def

    def hoverEnterEvent(self, event):
        """
        hoverEnterEvent changes the HelixItem brush and pen from default
        to the hover colors if necessary.
        """
        self.setHovered()

    # end def

    def setNotHovered(self):
        """
        """
        # drawMe = False if self.virtualHelixItem() else True
        # self.setFlag(QGraphicsItem.ItemHasNoContents, drawMe)
        self.setBrush(self._DEFAULT_BRUSH)
        self.setPen(self._DEFAULT_PEN)
        # self.translateVH(self._ADJUSTMENT_MINUS)
        self._is_hovered = False
        self.setZValue(self._Z_DEFAULT)
        self.setRect(self._DEFAULT_RECT)

        self._part_item.updateStatusBar("")

    # end def

    def hoverLeaveEvent(self, event):
        """
        hoverEnterEvent changes the HelixItem brush and pen from hover
        to the default colors if necessary.
        """
        self.setNotHovered()

    # end def

    def mousePressEvent(self, event):
        action = self.decideAction(event.modifiers())
        action(self)
        self.dragSessionAction = action

    # end def

    def mouseMoveEvent(self, event):
        part_item = self._part_item
        pos_in_parent = part_item.mapFromItem(self, QPointF(event.pos()))
        # Qt doesn't have any way to ask for graphicsitem(s) at a
        # particular position but it *can* do intersections, so we
        # just use those instead
        part_item.probe.setPos(pos_in_parent)
        for ci in part_item.probe.collidingItems():
            if isinstance(ci, EmptyHelixItem):
                self.dragSessionAction(ci)

    # end def

    def autoScafMidSeam(self, strands):
        """docstring for autoScafMidSeam"""
        part = self.part()
        strand_type = StrandType.SCAFFOLD
        idx = part.activeBaseIndex()
        for i in range(1, len(strands)):
            row1, col1, ss_idx1 = strands[i - 1]  # previous strand
            row2, col2, ss_idx2 = strands[i]  # current strand
            vh1 = part.virtualHelixAtCoord((row1, col1))
            vh2 = part.virtualHelixAtCoord((row2, col2))
            strand1 = vh1.scaffoldStrandSet()._strand_list[ss_idx1]
            strand2 = vh2.scaffoldStrandSet()._strand_list[ss_idx2]
            # determine if the pair of strands are neighbors
            neighbors = part.getVirtualHelixNeighbors(vh1)
            if vh2 in neighbors:
                p2 = neighbors.index(vh2)
                if vh2.number() % 2 == 1:
                    # resize and install external xovers
                    try:
                        # resize to the nearest prexover on either side of idx
                        new_lo = util.nearest(
                            idx,
                            part.getPreXoversHigh(strand_type,
                                                  p2,
                                                  max_idx=idx - 10))
                        new_hi = util.nearest(
                            idx,
                            part.getPreXoversLow(strand_type,
                                                 p2,
                                                 min_idx=idx + 10))
                        if strand1.canResizeTo(new_lo, new_hi) and \
                           strand2.canResizeTo(new_lo, new_hi):
                            # do the resize
                            strand1.resize((new_lo, new_hi))
                            strand2.resize((new_lo, new_hi))
                            # install xovers
                            part.createXover(strand1, new_hi, strand2, new_hi)
                            part.createXover(strand2, new_lo, strand1, new_lo)
                    except ValueError:
                        pass  # nearest not found in the expanded list

                    # go back an install the internal xovers
                    if i > 2:
                        row0, col0, ss_idx0 = strands[i -
                                                      2]  # two strands back
                        vh0 = part.virtualHelixAtCoord((row0, col0))
                        strand0 = vh0.scaffoldStrandSet()._strand_list[ss_idx0]
                        if vh0 in neighbors:
                            p0 = neighbors.index(vh0)
                            l0, h0 = strand0.idxs()
                            l1, h1 = strand1.idxs()
                            o_low, o_high = util.overlap(l0, h0, l1, h1)
                            try:
                                l_list = list(filter(lambda x: x > o_low and \
                                        x < o_high,
                                        part.getPreXoversLow(strand_type, p0)))
                                l_x = l_list[len(l_list) // 2]
                                h_list = list(filter(lambda x: x > o_low and \
                                        x < o_high,
                                        part.getPreXoversHigh(strand_type, p0)))
                                h_x = h_list[len(h_list) // 2]
                                # install high xover first
                                part.createXover(strand0, h_x, strand1, h_x)
                                # install low xover after getting new strands
                                # following the breaks caused by the high xover
                                strand3 = vh0.scaffoldStrandSet(
                                )._strand_list[ss_idx0]
                                strand4 = vh1.scaffoldStrandSet(
                                )._strand_list[ss_idx1]
                                part.createXover(strand4, l_x, strand3, l_x)
                            except IndexError:
                                pass  # filter was unhappy

    def autoScafRaster(self, strands):
        """docstring for autoScafRaster"""
        part = self.part()
        idx = part.activeBaseIndex()
        for i in range(1, len(strands)):
            row1, col1, ss_idx1 = strands[i - 1]  # previous strand
            row2, col2, ss_idx2 = strands[i]  # current strand
            vh1 = part.virtualHelixAtCoord((row1, col1))
            vh2 = part.virtualHelixAtCoord((row2, col2))
            strand1 = vh1.scaffoldStrandSet()._strand_list[ss_idx1]
            strand2 = vh2.scaffoldStrandSet()._strand_list[ss_idx2]
            # determine if the pair of strands are neighbors
            neighbors = part.getVirtualHelixNeighbors(vh1)
            if vh2 in neighbors:
                p2 = neighbors.index(vh2)
                if vh2.number() % 2 == 1:
                    # resize and install external xovers
                    try:
                        # resize to the nearest prexover on either side of idx
                        new_lo1 = new_lo2 = util.nearest(
                            idx,
                            part.getPreXoversHigh(StrandType.SCAFFOLD,
                                                  p2,
                                                  max_idx=idx - 8))
                        new_hi = util.nearest(
                            idx,
                            part.getPreXoversLow(StrandType.SCAFFOLD,
                                                 p2,
                                                 min_idx=idx + 8))

                        if vh1.number() != 0:  # after the first helix
                            new_lo1 = strand1.lowIdx(
                            )  # leave alone the lowIdx

                        if vh2.number() != len(strands) - 1:  # before the last
                            new_lo2 = strand2.lowIdx(
                            )  # leave alone the lowIdx

                        if strand1.canResizeTo(new_lo1, new_hi) and \
                           strand2.canResizeTo(new_lo2, new_hi):
                            strand1.resize((new_lo1, new_hi))
                            strand2.resize((new_lo2, new_hi))
                        else:
                            raise ValueError
                        # install xovers
                        part.createXover(strand1, new_hi, strand2, new_hi)
                    except ValueError:
                        pass  # nearest not found in the expanded list
                else:
                    # resize and install external xovers
                    idx = part.activeBaseIndex()
                    try:
                        # resize to the nearest prexover on either side of idx
                        new_lo = util.nearest(
                            idx,
                            part.getPreXoversHigh(StrandType.SCAFFOLD,
                                                  p2,
                                                  max_idx=idx - 8))

                        if strand1.canResizeTo(new_lo, strand1.highIdx()) and \
                           strand2.canResizeTo(new_lo, strand2.highIdx()):
                            strand1.resize((new_lo, strand1.highIdx()))
                            strand2.resize((new_lo, strand2.highIdx()))
                            # install xovers
                            part.createXover(strand1, new_lo, strand2, new_lo)
                        else:
                            raise ValueError
                    except ValueError:
                        pass  # nearest not found in the expanded list

    def mouseReleaseEvent(self, event):
        """docstring for mouseReleaseEvent"""
        part = self.part()
        u_s = part.undoStack()
        strands = []
        # Look at the undo stack in reverse order
        for i in range(u_s.index() - 1, 0, -1):
            # Check for contiguous strand additions
            m = _strand_re.match(u_s.text(i))
            if m:
                strands.insert(0, list(map(int, m.groups())))
            else:
                break

        if len(strands) > 1:
            auto_scaf_type = app().prefs.getAutoScafType()
            util.beginSuperMacro(part, "Auto-connect")
            if auto_scaf_type == "Mid-seam":
                self.autoScafMidSeam(strands)
            elif auto_scaf_type == "Raster":
                self.autoScafRaster(strands)
            util.endSuperMacro(part)

    def decideAction(self, modifiers):
        """ On mouse press, an action (add scaffold at the active slice, add
        segment at the active slice, or create virtualhelix if missing) is
        decided upon and will be applied to all other slices happened across by
        mouseMoveEvent. The action is returned from this method in the form of a
        callable function."""
        vh = self.virtualHelix()
        part = self.part()

        if vh == None:
            return EmptyHelixItem.addVHIfMissing

        idx = part.activeBaseIndex()
        scafSSet, stapSSet = vh.getStrandSets()
        if modifiers & Qt.ShiftModifier:
            if not stapSSet.hasStrandAt(idx - 1, idx + 1):
                return EmptyHelixItem.addStapAtActiveSliceIfMissing
            else:
                return EmptyHelixItem.nop

        if not scafSSet.hasStrandAt(idx - 1, idx + 1):
            return EmptyHelixItem.addScafAtActiveSliceIfMissing
        return EmptyHelixItem.nop

    # end def

    def nop(self):
        self._part_item.updateStatusBar("(%d, %d)" % self._coord)

    def addScafAtActiveSliceIfMissing(self):
        vh = self.virtualHelix()
        part = self.part()
        if vh == None:
            return

        idx = part.activeBaseIndex()
        start_idx = max(0, idx - 1)
        end_idx = min(idx + 1, part.maxBaseIdx())
        vh.scaffoldStrandSet().createStrand(start_idx, end_idx)

        self._part_item.updateStatusBar("(%d, %d)" % self._coord)

    # end def

    def addStapAtActiveSliceIfMissing(self):
        vh = self.virtualHelix()
        part = self.part()

        if vh == None:
            return

        idx = part.activeBaseIndex()
        start_idx = max(0, idx - 1)
        end_idx = min(idx + 1, part.maxBaseIdx())
        vh.stapleStrandSet().createStrand(start_idx, end_idx)

        self._part_item.updateStatusBar("(%d, %d)" % self._coord)

    # end def

    def addVHIfMissing(self):
        vh = self.virtualHelix()
        coord = self._coord
        part = self.part()

        if vh != None:
            return
        u_s = part.undoStack()
        u_s.beginMacro("Slice Click")
        part.createVirtualHelix(*coord)
        # vh.scaffoldStrandSet().createStrand(start_idx, end_idx)
        u_s.endMacro()

        self._part_item.updateStatusBar("(%d, %d)" % self._coord)

    # end def

    if GL:

        def paint(self, painter, option, widget):
            painter.beginNativePainting()

            radius = self._RADIUS

            # GL.glPushAttrib(GL.GL_ALL_ATTRIB_BITS)
            # GL.glClear(GL.GL_COLOR_BUFFER_BIT)

            # Draw the filled circle

            GL.glColor3f(1, 0.5, 0)  # Set to orange

            GL.glBegin(GL.GL_POLYGON)
            for X, Y in self._temp:
                GL.glVertex2f(X, Y)
            # end for
            GL.glEnd()

            # Draw the anti-aliased outline

            # GL.glEnable(GL.GL_BLEND)
            # GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
            # GL.glEnable(GL.GL_LINE_SMOOTH)

            # GL.glBegin(GL.GL_LINE_LOOP)
            # for angle in [x*PI*0.01 for x in range(200)]:
            #     GL.glVertex2f(X + math.sin(angle) * radius, Y + math.cos(angle) * radius)
            # # end for
            # GL.glDisable(GL.GL_BLEND)
            # GL.glEnd()
            # GL.glPopAttrib()
            painter.endNativePainting()
Пример #33
0
 def setBackgroundColor(self, color):
     """ add background color """
     brush = QBrush(color)
     self.scene.setBackgroundBrush(brush)
     self.scene.backgroundBrush()
Пример #34
0
    def __init__(self,
                 freq,
                 samp_rate,
                 bw,
                 gain,
                 device: str,
                 mode: Mode,
                 modulated_data=None,
                 parent=None,
                 testing_mode=False):
        super().__init__(parent)
        self.ui = Ui_SendRecvDialog()
        self.ui.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose)

        self.graphics_view = self.ui.graphicsViewSend if mode == Mode.send else self.ui.graphicsViewReceive

        self.backend_handler = BackendHandler(testing_mode=testing_mode)
        if mode == Mode.spectrum:
            self.update_interval = 1
        else:
            self.update_interval = 50

        if mode == Mode.send and modulated_data is None:
            raise ValueError("I need modulated data to send!")

        if mode == Mode.receive or mode == Mode.spectrum:
            self.ui.spinBoxNRepeat.hide()
            self.ui.labelNRepeat.hide()
            self.ui.lblCurrentRepeatValue.hide()
            self.ui.lblRepeatText.hide()
            self.ui.lSamplesSentText.hide()
            self.ui.progressBar.hide()
            self.ui.stackedWidget.setCurrentIndex(0)
        else:
            self.ui.stackedWidget.setCurrentIndex(1)

        if mode == Mode.send or mode == Mode.spectrum:
            self.ui.lSamplesCaptured.hide()
            self.ui.lSamplesCapturedText.hide()
            self.ui.lSignalSize.hide()
            self.ui.lSignalSizeText.hide()
            self.ui.lTime.hide()
            self.ui.lTimeText.hide()
            self.ui.btnSave.hide()

        if mode == Mode.spectrum:
            self.setWindowTitle("Spectrum analyzer")

        if mode == Mode.send:
            self.ui.btnStart.setIcon(QIcon.fromTheme("media-playback-start"))
            self.setWindowTitle("Send signal")
            self.ui.btnStart.setToolTip("Send data")
            self.ui.btnStop.setToolTip("Stop sending")
            self.ui.progressBar.setMaximum(len(modulated_data))

        self.device_is_sending = False

        self.ui.btnStop.setEnabled(False)
        self.ui.btnClear.setEnabled(False)
        self.ui.btnSave.setEnabled(False)
        self.start = 0
        self.already_saved = True
        self.bw_sr_are_locked = constants.SETTINGS.value(
            "lock_bandwidth_sample_rate", True, bool)

        self.ui.spinBoxFreq.setValue(freq)
        self.ui.spinBoxSampleRate.setValue(samp_rate)
        self.ui.spinBoxBandwidth.setValue(bw)
        self.ui.spinBoxGain.setValue(gain)
        self.ui.spinBoxNRepeat.setValue(
            constants.SETTINGS.value('num_sending_repeats', 1, type=int))

        self.ui.cbDevice.clear()
        items = []
        for device_name in self.backend_handler.DEVICE_NAMES:
            dev = self.backend_handler.device_backends[device_name.lower()]
            if mode == Mode.send and dev.is_enabled and dev.supports_tx:
                items.append(device_name)
            elif mode in (Mode.receive, Mode.spectrum
                          ) and dev.is_enabled and dev.supports_rx:
                items.append(device_name)

        if mode == Mode.send and PluginManager().is_plugin_enabled(
                "NetworkSDRInterface"):
            items.append(NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)

        self.ui.cbDevice.addItems(items)
        if device in items:
            self.ui.cbDevice.setCurrentIndex(items.index(device))

        dev_name = self.ui.cbDevice.currentText()
        nrep = self.ui.spinBoxNRepeat.value()
        self.device = VirtualDevice(self.backend_handler,
                                    dev_name,
                                    mode,
                                    bw,
                                    freq,
                                    gain,
                                    samp_rate,
                                    samples_to_send=modulated_data,
                                    device_ip=self.ui.lineEditIP.text(),
                                    sending_repeats=nrep,
                                    parent=self)
        self.ui.lineEditIP.setVisible(dev_name == "USRP")
        self.ui.labelIP.setVisible(dev_name == "USRP")

        self.recorded_files = []

        self.timer = QTimer(self)

        if mode == Mode.receive:
            self.scene_manager = LiveSceneManager(np.array(
                []), parent=self)  # set really in on_device_started
        elif mode == Mode.send:
            signal = Signal.from_samples(modulated_data, "Modulated Preview",
                                         samp_rate)
            self.scene_manager = SignalSceneManager(signal, parent=self)
            self.send_indicator = self.scene_manager.scene.addRect(
                0, -2, 0, 4, QPen(QColor(Qt.transparent), Qt.FlatCap),
                QBrush(constants.SEND_INDICATOR_COLOR))
            self.send_indicator.stackBefore(
                self.scene_manager.scene.selection_area)
            self.scene_manager.init_scene()
            self.graphics_view.set_signal(signal)
            self.graphics_view.sample_rate = samp_rate
        else:
            self.scene_manager = FFTSceneManager(
                parent=self, graphic_view=self.graphics_view)

        self.graphics_view.setScene(self.scene_manager.scene)
        self.graphics_view.scene_manager = self.scene_manager

        ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])"
        ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange +
                          "\\." + ipRange + "$")
        self.ui.lineEditIP.setValidator(QRegExpValidator(ipRegex))
        self.create_connects()

        self.ui.btnLockBWSR.setChecked(self.bw_sr_are_locked)
        self.on_btn_lock_bw_sr_clicked()
Пример #35
0
    fmt.setSamples(10)
    QSurfaceFormat.setDefaultFormat(fmt)

    scene = MyScene(0., 0., 600., 400.)

    path = QPainterPath()
    path.moveTo(0, 0)
    path.lineTo(50, 110)

    path2 = QPainterPath()
    path2.moveTo(50, -10)
    path2.lineTo(50, 220)

    scene.addPath(path2, QPen(Qt.black))
    scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt.transparent),
                  QBrush(Qt.green))

    scene.addRect(QRectF(200, 0, 100, 200), QPen(Qt.transparent),
                  QBrush(Qt.red))
    scene.addPath(path, QPen(Qt.black), QBrush(Qt.green))
    scene.addText("I Love Qt Programming", QFont("Times", 22, QFont.Bold))

    view = MyView(scene)
    view.setViewport(QOpenGLWidget())
    view.setRenderHints(QPainter.HighQualityAntialiasing)
    view.show()

    layout = QGridLayout()

    app.exec()
Пример #36
0
    def createRow(self,
                  param,
                  name_editable=False,
                  value_editable=True,
                  comments_editable=True,
                  index=-1):
        """
        Create a row in the table for a param.
        Input:
            param: ParamNode
        Return:
            BaseRowItem derived object
        """
        row = self.rowCount()
        if index >= 0:
            row = index
        self.insertRow(row)
        name_item = QtWidgets.QTableWidgetItem(param.name)
        name_item.setData(Qt.UserRole, param)

        if not name_editable:
            name_item.setFlags(Qt.ItemIsEnabled)

        if param.required:
            color = QColor(255, 204, 153)
            brush = QBrush(color)
            name_item.setBackground(brush)
        elif param.user_added:
            color = QColor("cyan")
            brush = QBrush(color)
            name_item.setBackground(brush)

        name_item.setText(param.name)
        self.setItem(row, 0, name_item)

        if param.cpp_type == "bool":
            checkbox = QtWidgets.QCheckBox()
            if param.value == "true":
                checkbox.setCheckState(Qt.Checked)
            else:
                checkbox.setCheckState(Qt.Unchecked)
            checkbox.pressed.connect(self.changed)
            self.setCellWidget(row, 1, checkbox)
        else:
            value_item = QtWidgets.QTableWidgetItem(param.value)
            if not value_editable or param.name == "type":
                value_item.setFlags(Qt.ItemIsEnabled)
            else:
                name_item.setToolTip(param.toolTip())

            self.setItem(row, 1, value_item)

        comments_item = QtWidgets.QTableWidgetItem(param.comments)
        if not comments_editable:
            comments_item.setFlags(Qt.ItemIsEnabled)
        self.setItem(row, 3, comments_item)

        watch_blocks = self._getChildrenOfNodeOptions(param.cpp_type)
        if param.cpp_type == "FileName" or param.cpp_type == "MeshFileName" or param.cpp_type == "FileNameNoExtension":
            self._createFilenameOption(param)
        elif watch_blocks:
            self._createBlockWatcher(param, watch_blocks)
        elif param.options:
            self._createOptions(param)
        elif param.user_added:
            button = QtWidgets.QPushButton("Remove")
            button.clicked.connect(
                lambda checked: self._removeButtonClicked(name_item))
            self.setCellWidget(row, 2, button)
        else:
            option_item = QtWidgets.QTableWidgetItem()
            option_item.setFlags(Qt.NoItemFlags)
            self.setItem(row, 2, option_item)
Пример #37
0
 def addCategory(self, title):
     item = QListWidgetItem(title)
     item.setBackground(QBrush(QColor(S.highlightLight)))
     item.setForeground(QBrush(QColor(S.highlightedTextDark)))
     item.setFlags(Qt.ItemIsEnabled)
     self.list.addItem(item)
Пример #38
0
class GameViewer(QWidget):
    ''' The main game viewer GUI '''

    # Define the colours used for drawing everything
    wall_brush = QBrush(QColor("black"))
    wall_pen = QPen(wall_brush, 0)

    goody0_brush = QBrush(QColor("#00CC00"))
    goody0_pen = QPen(goody0_brush, 0)

    goody1_brush = QBrush(QColor("green"))
    goody1_pen = QPen(goody1_brush, 0)

    baddy_brush =  QBrush(QColor("red"))
    baddy_pen = QPen(baddy_brush, 0)

    ping_brush = QBrush(QColor("white"))

    def __init__(self):
        super(GameViewer, self).__init__()

        self.cell_size = 100  # Arbitrary units
        self.scene = None
        self.game = None
        self.game_generator = None
        self.goody0 = None
        self.goody1 = None
        self.baddy = None
        self.ping_marker = {}
        self.results = defaultdict(int)
        self.round_timer = QTimer(interval=50, timeout=self._play)  # milliseconds
        self.running = False

        self.view = QGraphicsView()
        self.view.scale(1, -1)  # We want x to increase rightwards and y to increase upwards
        self.view.setMinimumSize(500, 500)

        self.round = QLabel()
        self.status = QLabel()
        self.goodies_win_count = QLineEdit(readOnly=True)
        self.draw_count = QLineEdit(readOnly=True)
        self.baddy_wins_count = QLineEdit(readOnly=True)

        self.auto_start = QCheckBox("Auto-start new game", checked=True)

        self.new_game_button = QPushButton("&New Game", clicked=self.new_game, enabled=False)
        self.step_button = QPushButton("S&tep", clicked=self.do_round, enabled=False)
        self.go_stop_button = QPushButton("&Go", clicked=self.toggle_running, enabled=False)

        stats_layout = QHBoxLayout()
        stats_layout.addWidget(QLabel("Goodies:"))
        stats_layout.addWidget(self.goodies_win_count)
        stats_layout.addWidget(QLabel("Draw:"))
        stats_layout.addWidget(self.draw_count)
        stats_layout.addWidget(QLabel("Baddy:"))
        stats_layout.addWidget(self.baddy_wins_count)

        legend_layout = QHBoxLayout()
        pixmap = QPixmap(16, 16)
        pixmap.fill(self.goody0_brush.color())
        goody0_icon = QLabel()
        goody0_icon.setPixmap(pixmap)
        legend_layout.addWidget(goody0_icon)
        self.goody0_name = QLabel()
        legend_layout.addWidget(self.goody0_name)
        legend_layout.addStretch(1)
        pixmap.fill(self.goody1_brush.color())
        goody1_icon = QLabel()
        goody1_icon.setPixmap(pixmap)
        legend_layout.addWidget(goody1_icon)
        self.goody1_name = QLabel()
        legend_layout.addWidget(self.goody1_name)
        legend_layout.addStretch(1)
        pixmap.fill(self.baddy_brush.color())
        baddy_icon = QLabel()
        baddy_icon.setPixmap(pixmap)
        legend_layout.addWidget(baddy_icon)
        self.baddy_name = QLabel()
        legend_layout.addWidget(self.baddy_name)

        info_layout = QFormLayout()
        info_layout.addRow("Round:", self.round)
        info_layout.addRow("Status:", self.status)
        info_layout.addRow(stats_layout)

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(self.new_game_button)
        buttons_layout.addWidget(self.step_button)
        buttons_layout.addWidget(self.go_stop_button)

        layout = QVBoxLayout(self)
        layout.addWidget(self.view)
        layout.addLayout(legend_layout)
        layout.addLayout(info_layout)
        layout.addWidget(self.auto_start)
        layout.addLayout(buttons_layout)


    def set_game(self, game):
        ''' Set the Game object that should be viewed by this GUI '''

        if self.running:
            self.toggle_running()

        # Alter the GUI widgets
        self.game = game
        self.scene = QGraphicsScene(self)
        self.view.setScene(self.scene)
        self.go_stop_button.setEnabled(True)
        self.step_button.setEnabled(True)

        height = game.maze.height
        width = game.maze.width
        cell = self.cell_size

        # Leave a border of cell_size units, and put (0, 0) at the bottom corner of the maze's interior
        self.scene.setSceneRect(-cell, -cell, (width + 2) * cell, (height + 2) * cell)
        self.view.fitInView(self.scene.sceneRect())

        # Create the border
        self.scene.addRect(-cell, -cell, (width + 2) * cell, cell, pen=self.wall_pen, brush=self.wall_brush)
        self.scene.addRect(-cell, height * cell, (width + 2) * cell, cell, pen=self.wall_pen, brush=self.wall_brush)
        self.scene.addRect(-cell, 0, cell, height * cell, pen=self.wall_pen, brush=self.wall_brush)
        self.scene.addRect(width * cell, 0, cell, height * cell, pen=self.wall_pen, brush=self.wall_brush)

        # Add the obstructions:
        for y in range(width):
            for x in range(height):
                if game.maze[x, y] == Maze.wall:
                    self.scene.addRect(x * cell, y * cell, cell, cell, pen=self.wall_pen, brush=self.wall_brush)

        # Add the players
        goody0_pos = game.position[game.goody0]
        goody1_pos = game.position[game.goody1]
        baddy_pos = game.position[game.baddy]
        self.goody0 = self.scene.addEllipse(0, 0, cell, cell, pen=self.goody0_pen, brush=self.goody0_brush)
        self.goody0.setPos(goody0_pos.x * cell, goody0_pos.y * cell)
        self.goody1 = self.scene.addEllipse(0, 0, cell, cell, pen=self.goody1_pen, brush=self.goody1_brush)
        self.goody1.setPos(goody1_pos.x * cell, goody1_pos.y * cell)
        self.baddy = self.scene.addEllipse(0, 0, cell, cell, pen=self.baddy_pen, brush=self.baddy_brush)
        self.baddy.setPos(baddy_pos.x * cell, baddy_pos.y * cell)

        # Add the ping markers
        for player, pen in ((game.goody0, self.goody0_pen), (game.goody1, self.goody1_pen), (game.baddy, self.baddy_pen)):
            marker = self.scene.addEllipse(cell // 4, cell // 4, cell // 2, cell // 2, pen=pen, brush=self.ping_brush)
            marker.hide()
            marker.setZValue(-1)
            self.ping_marker[player] = marker

        # Set the info
        self.round.setText(str(game.round))
        self.status.setText(game.status)
        self.running = False

        # Update the legend
        self.goody0_name.setText(type(game.goody0).__name__)
        self.goody1_name.setText(type(game.goody1).__name__)
        self.baddy_name.setText(type(game.baddy).__name__)

        # Change the window title
        self.setWindowTitle("{} and {} vs. {}".format(type(game.goody0).__name__, type(game.goody1).__name__,
                                                      type(game.baddy).__name__))

    def set_game_generator(self, game_generator):
        ''' Set the game generator (a generator of Game instances) that the GUI can take from '''
        self.game_generator = game_generator
        self.new_game_button.setEnabled(True)
        self.new_game()

    def new_game(self):
        ''' Take the next Game from the generator '''
        if self.game_generator is not None:
            self.set_game(next(self.game_generator))

    def toggle_running(self):
        ''' Switch between automatically stepping through the game and allowing manual "Step" clicks '''
        if self.running:
            self.round_timer.stop()
            self.running = False
        else:
            self.round_timer.start()
            self.running = True
        self._update_widgets()

    def _play(self):
        ''' Private - called to do a round of turns and check if the game has ended '''
        result = self.do_round()
        if result != Game.in_play:
            self.toggle_running()
            if not self.running and self.auto_start.isChecked():
                self.new_game()
                self.toggle_running()


    def _update_widgets(self):
        ''' Private - Make the GUI show the current state of the Game '''
        if self.running:
            self.go_stop_button.setText("&Stop")
            self.step_button.setEnabled(False)
        else:
            self.go_stop_button.setText("&Go")
            if self.game.status == Game.in_play:
                self.step_button.setEnabled(True)
            else:
                self.go_stop_button.setEnabled(False)
                self.step_button.setEnabled(False)
        self.goodies_win_count.setText(str(self.results[Game.goodies_win]))
        self.draw_count.setText(str(self.results[Game.draw]))
        self.baddy_wins_count.setText(str(self.results[Game.baddy_wins]))

    def do_round(self):
        ''' Take a round of turns '''
        self.started = True
        game = self.game
        if game is None:
            return
        result = game.do_round()
        for graphic, player in ((self.goody0, game.goody0), (self.goody1, game.goody1), (self.baddy, game.baddy)):
            new_pos = game.position[player]
            new_x = new_pos.x * self.cell_size
            new_y = new_pos.y * self.cell_size
            graphic.setPos(new_x, new_y)
            if game.ping:
                marker = self.ping_marker[player]
                marker.setPos(new_x, new_y)
                marker.show()

        if result != Game.in_play:
            self.results[result] += 1
        if not self.running:
            self._update_widgets()
        self.round.setText(str(self.game.round))
        self.status.setText(self.game.status)
        return result
Пример #39
0
    def drawBackground(self):
        side = min(self.width(), self.height())
        ''' Keep side size an even number by trunkating odd pixel '''
        side &= ~0x01

        gradient = QRadialGradient()

        painter = QPainter(self)

        pen = QPen(Qt.black)
        pen.setWidth(1)
        ''' Initialize painter '''
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 256.0, side / 256.0)
        painter.setPen(pen)
        ''' Draw external circle '''
        gradient = QRadialGradient(QPointF(-128, -128), 384,
                                   QPointF(-128, -128))
        gradient.setColorAt(0, QColor(224, 224, 224))
        gradient.setColorAt(1, QColor(28, 28, 28))
        painter.setPen(pen)
        painter.setBrush(QBrush(gradient))

        painter.drawEllipse(QPoint(0, 0), 125, 125)
        ''' Draw inner circle '''
        gradient = QRadialGradient(QPointF(128, 128), 384, QPointF(128, 128))
        gradient.setColorAt(0, QColor(224, 224, 224))
        gradient.setColorAt(1, QColor(28, 28, 28))
        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(gradient))
        painter.drawEllipse(QPoint(0, 0), 118, 118)
        ''' Draw inner shield '''
        gradient = QRadialGradient(QPointF(-128, -128), 384,
                                   QPointF(-128, -128))
        gradient.setColorAt(0, QColor(255, 255, 255))
        gradient.setColorAt(1, QColor(224, 224, 224))
        painter.setBrush(gradient)
        painter.setPen(Qt.NoPen)
        painter.drawEllipse(QPoint(0, 0), 115, 115)
        painter.setPen(pen)
        painter.setBrush(Qt.black)
        painter.drawPoint(0, 0)

        line = 10
        ''' Draw scale majorTicks using coords rotation '''
        painter.save()
        painter.setBrush(Qt.black)
        painter.rotate(self.start_angle)
        #          ''' initial angle (first tick) '''
        painter.setBrush(QBrush(Qt.black))
        t_rot = self.stop_angle / (self.minorTicks *
                                   (self.majorTicks - 1) + self.majorTicks - 1)
        for i in range(
                int((self.minorTicks) * (self.majorTicks - 1) +
                    self.majorTicks)):
            if self.minorTicks:
                if (self.minorTicks + 1) == 0:
                    painter.drawLine(QPoint(105, 0), QPoint(105 - line, 0))
                else:
                    painter.drawLine(QPoint(105, 0), QPoint(105 - line / 3, 0))
            else:
                painter.drawLine(QPoint(105, 0), QPoint(105 - line, 0))
            painter.rotate(t_rot)
        painter.restore()
        ''' Draw scale numbers using vector rotation '''
        ''' x' = xcos(a)-ysin(a)                     '''
        ''' y' = xsin(a)-ycos(a)                     '''
        painter.save()
        rotation = (self.start_angle /
                    360) * 2 * pi  #       ''' Initial rotation '''
        painter.setFont(self.digitFont)
        for i in range(int(self.majorTicks)):
            point = QPointF((70 * cos(rotation)), 70 * sin(rotation))
            value = self.scaleFormat.format(self.wmin + i * self.step)
            size = painter.fontMetrics().size(Qt.TextSingleLine, value)
            point.setX(point.x() - size.width() / 2)  #  += int()
            point.setY(point.y() + size.height() / 4)
            painter.drawText(point, value)
            rotation += self.rot_rad

        painter.restore()

        labela = self.labelFormat.format(self.value)
        painter.setFont(self.labelFont)
        point = QPointF()
        size = painter.fontMetrics().size(Qt.TextSingleLine, labela)
        point.setX(point.x() - size.width() / 2)
        point.setY(point.y() + size.height() / 4 + self.labelOffset)
        painter.drawText(point, labela)

        if len(self.label) > 0:  # Draw meter label
            painter.setFont(self.labelFont)
            point = QPointF()
            size = painter.fontMetrics().size(Qt.TextSingleLine, self.label)
            point.setX(point.x() - size.width() / 2)
            point.setY(point.y() + size.height() / 4 + self.labelOffset + 24)
            painter.drawText(point, self.label)
Пример #40
0
 def setBackground(self):
     oImage = QImage('figure2.png')
     sImage = oImage.scaled(QSize(907, 690))
     palette = QPalette()
     palette.setBrush(QPalette.Background, QBrush(sImage))
     self.setPalette(palette)
Пример #41
0
    def doHighlightBlock(self, text):
        """
        Note:  Never set the QTextBlockFormat for a QTextBlock from within
        the highlighter. Depending on how the block format is modified,
        a recursive call to the highlighter may be triggered, which will
        cause the application to crash.

        Likewise, don't try to set the QTextBlockFormat outside the highlighter
        (i.e., from within the text editor).  While the application will not
        crash, the format change will be added to the undo stack.  Attempting
        to undo from that point on will cause the undo stack to be virtually
        frozen, since undoing the format operation causes the text to be
        considered changed, thus triggering the slot that changes the text
        formatting to be triggered yet again.
        """

        lastState = self.currentBlockState()
        # self.setFormat(0, len(text), self._defaultCharFormat)

        # Focus mode
        unfocus = self.unfocusConditions()
        if unfocus:
            fmt = self.format(0)
            fmt.setForeground(QBrush(self.defaultTextColor))
            self.transparentFormat(fmt)
            if type(unfocus) != bool:
                start, end = unfocus
                self.setFormat(0, start, fmt)
                self.setFormat(end, len(text), fmt)
            else:
                self.setFormat(0, len(text), fmt)

        if self.tokenizer != None:
            self.tokenizer.clear()
            block = self.currentBlock()
            nextState = MS.MarkdownStateUnknown
            previousState = self.previousBlockState()

            if block.next().isValid():
                nextState = block.next().userState()

            self.tokenizer.tokenize(text, lastState, previousState, nextState)
            self.setCurrentBlockState(self.tokenizer.getState())

            self.inBlockquote = self.tokenizer.getState(
            ) == MS.MarkdownStateBlockquote

            # STATE FORMATTING
            # FIXME: generic
            if self.currentBlockState() in [
                    MS.MarkdownStatePipeTableHeader,
                    MS.MarkdownStatePipeTableDivider,
                    MS.MarkdownStatePipeTableRow
            ]:
                fmt = QTextCharFormat()
                f = fmt.font()
                f.setFamily("Monospace")
                fmt.setFont(f)
                self.setFormat(0, len(text), fmt)

            # Monospace the blank chars
            i = 0
            while i <= len(text) - 1 and text[i] in [" ", "\t"]:
                fmt = self.format(i)
                fmt.setFontFamily("Monospace")
                self.setFormat(i, 1, fmt)
                i += 1

            #if self.currentBlockState() == MS.MarkdownStateBlockquote:
            #fmt = QTextCharFormat(self._defaultCharFormat)
            #fmt.setForeground(Qt.lightGray)
            #self.setFormat(0, len(text), fmt)

            tokens = self.tokenizer.getTokens()

            for token in tokens:
                if token.type == MTT.TokenUnknown:
                    qWarning(
                        "Highlighter found unknown token type in text block.")
                    continue

                if token.type in [
                        MTT.TokenAtxHeading1,
                        MTT.TokenAtxHeading2,
                        MTT.TokenAtxHeading3,
                        MTT.TokenAtxHeading4,
                        MTT.TokenAtxHeading5,
                        MTT.TokenAtxHeading6,
                        MTT.TokenSetextHeading1Line1,
                        MTT.TokenSetextHeading2Line1,
                ]:
                    self.storeHeadingData(token, text)

                self.applyFormattingForToken(token, text)

            if self.tokenizer.backtrackRequested():
                previous = self.currentBlock().previous()
                self.highlightBlockAtPosition.emit(previous.position())

        if self.spellCheckEnabled:
            self.spellCheck(text)

        # If the block has transitioned from previously being a heading to now
        # being a non-heading, signal that the position in the document no
        # longer contains a heading.

        if self.isHeadingBlockState(lastState) and \
           not self.isHeadingBlockState(self.currentBlockState()):
            self.headingRemoved.emit(self.currentBlock().position())
Пример #42
0
 def __init__(self, shape, pen=None, brush=None):
     self.shape = shape
     self.pen = pen or QPen()
     self.brush = brush or QBrush()
Пример #43
0
    def add_io(self, vbox):
        if self.tx.locktime > 0:
            vbox.addWidget(QLabel("LockTime: %d\n" % self.tx.locktime))

        vbox.addWidget(QLabel(_("Inputs") + ' (%d)' % len(self.tx.inputs())))
        ext = QTextCharFormat()
        rec = QTextCharFormat()
        rec.setBackground(QBrush(ColorScheme.GREEN.as_color(background=True)))
        rec.setToolTip(_("Wallet receive address"))
        chg = QTextCharFormat()
        chg.setBackground(QBrush(ColorScheme.YELLOW.as_color(background=True)))
        chg.setToolTip(_("Wallet change address"))
        twofactor = QTextCharFormat()
        twofactor.setBackground(
            QBrush(ColorScheme.BLUE.as_color(background=True)))
        twofactor.setToolTip(
            _("TrustedCoin (2FA) fee for the next batch of transactions"))

        def text_format(addr):
            if self.wallet.is_mine(addr):
                return chg if self.wallet.is_change(addr) else rec
            elif self.wallet.is_billing_address(addr):
                return twofactor
            return ext

        def format_amount(amt):
            return self.main_window.format_amount(amt, whitespaces=True)

        i_text = QTextEditWithDefaultSize()
        i_text.setFont(QFont(MONOSPACE_FONT))
        i_text.setReadOnly(True)
        cursor = i_text.textCursor()
        for x in self.tx.inputs():
            if x['type'] == 'coinbase':
                cursor.insertText('coinbase')
            else:
                prevout_hash = x.get('prevout_hash')
                prevout_n = x.get('prevout_n')
                cursor.insertText(prevout_hash + ":%-4d " % prevout_n, ext)
                addr = self.wallet.get_txin_address(x)
                if addr is None:
                    addr = ''
                cursor.insertText(addr, text_format(addr))
                if x.get('value'):
                    cursor.insertText(format_amount(x['value']), ext)
            cursor.insertBlock()

        vbox.addWidget(i_text)
        vbox.addWidget(QLabel(_("Outputs") + ' (%d)' % len(self.tx.outputs())))
        o_text = QTextEditWithDefaultSize()
        o_text.setFont(QFont(MONOSPACE_FONT))
        o_text.setReadOnly(True)
        cursor = o_text.textCursor()
        for o in self.tx.get_outputs_for_UI():
            addr, v = o.address, o.value
            cursor.insertText(addr, text_format(addr))
            if v is not None:
                cursor.insertText('\t', ext)
                cursor.insertText(format_amount(v), ext)
            cursor.insertBlock()
        vbox.addWidget(o_text)
Пример #44
0
class qt_drawings:
    """
    Qt data used to draw tiles.
    """

    tile_size = 10

    tile_colors = [
        QColor(235, 180, 40),
        QColor(255, 84, 46),
        QColor(68, 125, 255),
        QColor(83, 223, 56)
    ]
    tile_brushes = [[QBrush(tile_colors[0]),
                     QBrush(tile_colors[1])],
                    [QBrush(tile_colors[2]),
                     QBrush(tile_colors[3])]]

    no_color = QColor(0, 0, 0, 0)
    no_pen = QPen(no_color)
    no_pen.setWidth(0)
    no_brush = QBrush(no_color)

    black_color = QColor(0, 0, 0)
    black_pen = QPen(black_color)
    black_brush = QBrush(black_color)

    cyan_color = QColor(30, 190, 220)
    cyan_brush = QBrush(cyan_color)

    gray_color = QColor(220, 220, 220, 80)
    gray_pen = QPen(gray_color)
    gray_brush = QBrush(gray_color)

    red_color = QColor(255, 40, 40)
    red_brush = QBrush(red_color)
    red_pen = QPen(red_color.darker(130))

    cross_polygon = QPolygonF([
        QPointF(1, 3),
        QPointF(3, 1),
        QPointF(tile_size / 2, 3),
        QPointF(tile_size - 3, 1),
        QPointF(tile_size - 1, 3),
        QPointF(tile_size - 3, tile_size / 2),
        QPointF(tile_size - 1, tile_size - 3),
        QPointF(tile_size - 3, tile_size - 1),
        QPointF(tile_size / 2, tile_size - 3),
        QPointF(3, tile_size - 1),
        QPointF(1, tile_size - 3),
        QPointF(3, tile_size / 2),
    ])

    arrow_polygon = QPolygonF([
        QPointF(2, 5),
        QPointF(tile_size / 2, 1),
        QPointF(tile_size - 2, 5),
        QPointF(tile_size / 2 + 1, 4),
        QPointF(tile_size / 2 + 1, tile_size - 1),
        QPointF(tile_size / 2 - 1, tile_size - 1),
        QPointF(tile_size / 2 - 1, 4),
    ])

    @staticmethod
    def tile_to_brush(tile) -> QBrush:
        return qt_drawings.tile_brushes[tile.is_horizontal][tile.is_positive]

    @staticmethod
    def paint_tile(painter: QPainter, wx: int, wy: int, tile, tile_size: int):
        width = 2 * tile_size if tile.is_horizontal else tile_size
        height = tile_size if tile.is_horizontal else 2 * tile_size
        painter.fillRect(wx, wy, width, height,
                         qt_drawings.tile_to_brush(tile))

        if tile_size > 5:
            painter.drawRect(wx, wy, width, height)
Пример #45
0
    def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant:
        # note: this method is performance-critical.
        # it is called a lot, and so must run extremely fast.
        assert index.isValid()
        col = index.column()
        tx_item = self.transactions.value_from_pos(index.row())
        is_lightning = tx_item.get('lightning', False)
        timestamp = tx_item['timestamp']
        if is_lightning:
            status = 0
            if timestamp is None:
                status_str = 'unconfirmed'
            else:
                status_str = format_time(int(timestamp))
        else:
            tx_hash = tx_item['txid']
            conf = tx_item['confirmations']
            try:
                status, status_str = self.tx_status_cache[tx_hash]
            except KeyError:
                tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
                status, status_str = self.parent.wallet.get_tx_status(tx_hash, tx_mined_info)

        if role == Qt.UserRole:
            # for sorting
            d = {
                HistoryColumns.STATUS:
                    # respect sort order of self.transactions (wallet.get_full_history)
                    -index.row(),
                HistoryColumns.DESCRIPTION:
                    tx_item['label'] if 'label' in tx_item else None,
                HistoryColumns.AMOUNT:
                    (tx_item['bc_value'].value if 'bc_value' in tx_item else 0)\
                    + (tx_item['ln_value'].value if 'ln_value' in tx_item else 0),
                HistoryColumns.BALANCE:
                    (tx_item['balance'].value if 'balance' in tx_item else 0),
                HistoryColumns.FIAT_VALUE:
                    tx_item['fiat_value'].value if 'fiat_value' in tx_item else None,
                HistoryColumns.FIAT_ACQ_PRICE:
                    tx_item['acquisition_price'].value if 'acquisition_price' in tx_item else None,
                HistoryColumns.FIAT_CAP_GAINS:
                    tx_item['capital_gain'].value if 'capital_gain' in tx_item else None,
                HistoryColumns.TXID: tx_hash if not is_lightning else None,
            }
            return QVariant(d[col])
        if role not in (Qt.DisplayRole, Qt.EditRole):
            if col == HistoryColumns.STATUS and role == Qt.DecorationRole:
                icon = "lightning" if is_lightning else TX_ICONS[status]
                return QVariant(read_QIcon(icon))
            elif col == HistoryColumns.STATUS and role == Qt.ToolTipRole:
                if is_lightning:
                    msg = 'lightning transaction'
                else:  # on-chain
                    if tx_item['height'] == TX_HEIGHT_LOCAL:
                        # note: should we also explain double-spends?
                        msg = _("This transaction is only available on your local machine.\n"
                                "The currently connected server does not know about it.\n"
                                "You can either broadcast it now, or simply remove it.")
                    else:
                        msg = str(conf) + _(" confirmation" + ("s" if conf != 1 else ""))
                return QVariant(msg)
            elif col > HistoryColumns.DESCRIPTION and role == Qt.TextAlignmentRole:
                return QVariant(Qt.AlignRight | Qt.AlignVCenter)
            elif col > HistoryColumns.DESCRIPTION and role == Qt.FontRole:
                monospace_font = QFont(MONOSPACE_FONT)
                return QVariant(monospace_font)
            #elif col == HistoryColumns.DESCRIPTION and role == Qt.DecorationRole and not is_lightning\
            #        and self.parent.wallet.invoices.paid.get(tx_hash):
            #    return QVariant(read_QIcon("seal"))
            elif col in (HistoryColumns.DESCRIPTION, HistoryColumns.AMOUNT) \
                    and role == Qt.ForegroundRole and tx_item['value'].value < 0:
                red_brush = QBrush(QColor("#BC1E1E"))
                return QVariant(red_brush)
            elif col == HistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \
                    and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None:
                blue_brush = QBrush(QColor("#1E1EFF"))
                return QVariant(blue_brush)
            return QVariant()
        if col == HistoryColumns.STATUS:
            return QVariant(status_str)
        elif col == HistoryColumns.DESCRIPTION and 'label' in tx_item:
            return QVariant(tx_item['label'])
        elif col == HistoryColumns.AMOUNT:
            bc_value = tx_item['bc_value'].value if 'bc_value' in tx_item else 0
            ln_value = tx_item['ln_value'].value if 'ln_value' in tx_item else 0
            value = bc_value + ln_value
            v_str = self.parent.format_amount(value, is_diff=True, whitespaces=True)
            return QVariant(v_str)
        elif col == HistoryColumns.BALANCE:
            balance = tx_item['balance'].value
            balance_str = self.parent.format_amount(balance, whitespaces=True)
            return QVariant(balance_str)
        elif col == HistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item:
            value_str = self.parent.fx.format_fiat(tx_item['fiat_value'].value)
            return QVariant(value_str)
        elif col == HistoryColumns.FIAT_ACQ_PRICE and \
                tx_item['value'].value < 0 and 'acquisition_price' in tx_item:
            # fixme: should use is_mine
            acq = tx_item['acquisition_price'].value
            return QVariant(self.parent.fx.format_fiat(acq))
        elif col == HistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item:
            cg = tx_item['capital_gain'].value
            return QVariant(self.parent.fx.format_fiat(cg))
        elif col == HistoryColumns.TXID:
            return QVariant(tx_hash) if not is_lightning else QVariant('')
        return QVariant()
Пример #46
0
    def refill(self, host):
        '''
            popupates KPIs table
            to be connected to hostChanged signal (hostsTable)
        '''

        if len(self.hosts) == 0:
            return

        if len(self.nkpis) == 0:
            log('[w] refill kips list is empty, return')
            return

        self.silentMode = True

        self.host = host

        #print('replace this by hType?')

        if self.hosts[host]['port'] == '':
            t = 'h'
            usedKPIs = self.hostKPIs
        else:
            t = 's'
            usedKPIs = self.srvcKPIs

        if t == 'h':
            kpiStyles = kpiStylesNN['host']
            kpiList = self.hostKPIs
        else:
            kpiStyles = kpiStylesNN['service']
            kpiList = self.srvcKPIs

        # go fill the table
        self.setRowCount(len(kpiList))

        kpis = [
        ]  # list of kpi tuples in kpiDescription format (ones to be displayed depending on host/service + checkboxes

        #put enabled ones first:
        for kpin in self.nkpis[host]:
            kpis.append(kpin)

        #populate rest of KPIs (including groups):
        for kpi in kpiList:
            if kpi not in kpis:
                kpis.append(kpi)

        i = 0
        ####################################################################
        #### ### ##     ## ##### #########   ###     ## ### ## #####     ###
        ####  ## ## ###### ##### ######## ######## ##### # ### ##### #######
        #### # # ##   #### ## ## #########  ###### ###### #### #####   #####
        #### ##  ## ###### # # # ########### ##### ###### #### ##### #######
        #### ### ##     ##  ###  ########   ###### ###### ####    ##     ###
        ####################################################################

        self.kpiNames = []  # index for right mouse click events

        for kpiName in kpis:
            self.setRowHeight(i, 10)

            self.kpiNames.append(kpiName)  # index for right mouse click events

            if kpiName[:1] != '.':
                #normal kpis

                cb = myCheckBox(host, kpiName)
                cb.setStyleSheet(
                    "QCheckBox::indicator { width: 10px; height: 10px; margin-left:16px;}"
                )

                if kpiName in self.nkpis[host]:
                    cb.setChecked(True)
                '''
                if kpiName not in kpiStyles:
                    # it can disappear as a result of custom KPI reload
                    log('%s not in the list of KPI styles, removing' % (kpiName))
                    continue 
                '''

                style = kpiStyles[kpiName]
                cb.stateChanged.connect(self.checkBoxChanged)
                self.setCellWidget(i, 0, cb)

                if 'style' in style:
                    self.setCellWidget(
                        i, 2,
                        kpiCell(style['pen'], style['brush'],
                                style['style']))  # customized styles
                else:
                    self.setCellWidget(i, 2, kpiCell(
                        style['pen'], ))  # kpi pen style

                if 'disabled' in style.keys():
                    item = QTableWidgetItem(style['label'])
                    item.setForeground(QBrush(QColor(255, 0, 0)))
                    self.setItem(i, 1, item)  # text name
                else:
                    self.setItem(i, 1,
                                 QTableWidgetItem(style['label']))  # text name

                self.setItem(i, 9, QTableWidgetItem(style['desc']))  # descr

                grp = str(style['group'])

                if grp == '0':
                    grp = ''

                self.setItem(i, 10, QTableWidgetItem(grp))  # group

            else:
                # kpi groups

                self.setCellWidget(i, 0, None)  # no checkbox
                self.setCellWidget(i, 2, None)  # no pen style
                self.setItem(i, 1, QTableWidgetItem(kpiName[1:]))  # text name
                self.item(i, 1).setFont(QFont('SansSerif', 8, QFont.Bold))

                self.setItem(i, 9, QTableWidgetItem())  # no desc
                self.setItem(i, 10, QTableWidgetItem())  # no group

            if kpiName in self.kpiScales[self.host].keys():

                kpiScale = self.kpiScales[self.host][kpiName]

                self.setItem(i, 3, QTableWidgetItem(str(
                    kpiScale['label'])))  # Y-Scale
                self.setItem(i, 4, QTableWidgetItem(str(kpiScale['unit'])))
                self.setItem(i, 5,
                             QTableWidgetItem(str(kpiScale['max_label'])))
                self.setItem(i, 8,
                             QTableWidgetItem(str(kpiScale['last_label'])))
            else:
                #cleanup
                self.setItem(i, 3, QTableWidgetItem())
                self.setItem(i, 4, QTableWidgetItem())
                self.setItem(i, 5, QTableWidgetItem())
                self.setItem(i, 8, QTableWidgetItem())

            i += 1

        self.silentMode = False
        return
Пример #47
0
    def initUI(self):

        fuenteSiacle = self.font()
        fuenteSiacle.setBold(True)
        fuenteSiacle.setPointSize(12)

        # ================= FRAME PANEL DE CONTROL ===================

        paletaBotones = self.palette()
        paletaBotones.setColor(QPalette.Background, QColor("#2EFEC8"))

        frameBotones = QFrame()
        frameBotones.setFrameStyle(QFrame.NoFrame)
        frameBotones.setAutoFillBackground(True)
        frameBotones.setPalette(paletaBotones)
        frameBotones.setFixedWidth(220)

        # ============================================================

        paletaPanel = self.palette()
        paletaPanel.setBrush(QPalette.Background,
                             QBrush(QColor(255, 90, 0), Qt.SolidPattern))
        paletaPanel.setColor(QPalette.Foreground, Qt.white)

        labelSiacle = QLabel("PANEL DE CONTROL", frameBotones)
        labelSiacle.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        labelSiacle.setFont(fuenteSiacle)
        labelSiacle.setAutoFillBackground(True)
        labelSiacle.setPalette(paletaPanel)
        labelSiacle.setFixedSize(220, 46)
        labelSiacle.move(0, 0)

        # ============================================================

        tamanioIcono = QSize(30, 30)

        botonNuevo = Boton(frameBotones)
        botonNuevo.setText(" Nuevo")
        botonNuevo.setToolTip("Nuevo cliente")
        botonNuevo.setCursor(Qt.PointingHandCursor)
        botonNuevo.move(-2, 45)

        botonActualizar = Boton(frameBotones)
        botonActualizar.setText(" Actualizar")
        botonActualizar.setToolTip("Actualizar cliente")
        botonActualizar.setCursor(Qt.PointingHandCursor)
        botonActualizar.move(-2, 82)

        botonEliminar = Boton(frameBotones)
        botonEliminar.setText(" Eliminar")
        botonEliminar.setToolTip("Eliminar cliente")
        botonEliminar.setCursor(Qt.PointingHandCursor)
        botonEliminar.move(-2, 119)

        botonLimpiar = Boton(frameBotones)
        botonLimpiar.setText(" Limpiar tabla")
        botonLimpiar.setToolTip("Limpiar tabla")
        botonLimpiar.setCursor(Qt.PointingHandCursor)
        botonLimpiar.move(-2, 156)

        # ============================================================

        paletaSuscribete = self.palette()
        paletaSuscribete.setBrush(
            QPalette.Background, QBrush(QColor(135, 206, 250),
                                        Qt.SolidPattern))

        fuenteSuscribete = self.font()
        fuenteSuscribete.setBold(True)
        fuenteSuscribete.setFamily("Arial")
        fuenteSuscribete.setPointSize(11)

        labelSuscribete = QLabel(
            "<a href='https://www.youtube.com/c/AndresNiñoPython?"
            "sub_confirmation=1'>SUSCRIBETE.</a>", frameBotones)
        labelSuscribete.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        labelSuscribete.setOpenExternalLinks(True)
        labelSuscribete.setFont(fuenteSuscribete)
        labelSuscribete.setAutoFillBackground(True)
        labelSuscribete.setPalette(paletaSuscribete)
        labelSuscribete.setFixedSize(220, 46)
        labelSuscribete.move(0, 210)

        # ============ FRAME BIENVENIDO - CONFIGURACIÓN ==============

        paletaFrame = self.palette()
        paletaFrame.setColor(QPalette.Background, QColor("blue"))

        frameBienvenido = QFrame()
        frameBienvenido.setFrameStyle(QFrame.NoFrame)
        frameBienvenido.setAutoFillBackground(True)
        frameBienvenido.setPalette(paletaFrame)
        frameBienvenido.setFixedHeight(46)

        # ============================================================

        paletaTitulo = self.palette()
        paletaTitulo.setColor(QPalette.Foreground, Qt.yellow)

        labelBienvenido = QLabel("BIENVENIDO A SIACLE")
        labelBienvenido.setAlignment(Qt.AlignCenter)
        labelBienvenido.setFont(fuenteSiacle)
        labelBienvenido.setPalette(paletaTitulo)

        botonConfiguracion = QPushButton()
        botonConfiguracion.setIcon(QIcon("Imagenes/configuracion.png"))
        botonConfiguracion.setIconSize(QSize(24, 24))
        botonConfiguracion.setToolTip("Configurar Siacle")
        botonConfiguracion.setCursor(Qt.PointingHandCursor)
        botonConfiguracion.setFixedWidth(36)

        disenioFrame = QHBoxLayout()
        disenioFrame.addWidget(labelBienvenido, Qt.AlignCenter)
        disenioFrame.addStretch()
        disenioFrame.addWidget(botonConfiguracion)
        disenioFrame.setContentsMargins(0, 0, 5, 0)
        frameBienvenido.setLayout(disenioFrame)

        # ============================================================

        self.buscarLineEdit = QLineEdit()
        self.buscarLineEdit.setObjectName("Enter")
        self.buscarLineEdit.setPlaceholderText("Nombre del cliente")
        self.buscarLineEdit.setMinimumSize(200, 26)

        botonBuscar = QPushButton("Buscar")
        botonBuscar.setObjectName("Buscar")
        botonBuscar.setCursor(Qt.PointingHandCursor)
        botonBuscar.setMinimumSize(60, 26)

        separadorTodos = QFrame()
        separadorTodos.setFrameShape(QFrame.VLine)
        separadorTodos.setFrameShadow(QFrame.Raised)
        separadorTodos.setFixedSize(1, 26)

        botonTodos = QPushButton("Todos")
        botonTodos.setObjectName("Todos")
        botonTodos.setCursor(Qt.PointingHandCursor)
        botonTodos.setMinimumSize(60, 26)

        nombreColumnas = ("Id", "Nombre", "Apellido", "Sexo",
                          "Fecha de nacimiento", "País", "Teléfono o celular")

        menuMostrarOcultar = QMenu()
        for indice, columna in enumerate(nombreColumnas, start=0):
            accion = QAction(columna, menuMostrarOcultar)
            accion.setCheckable(True)
            accion.setChecked(True)
            accion.setData(indice)

            menuMostrarOcultar.addAction(accion)

        botonMostrarOcultar = QPushButton("Motrar/ocultar columnas")
        botonMostrarOcultar.setCursor(Qt.PointingHandCursor)
        botonMostrarOcultar.setMenu(menuMostrarOcultar)
        botonMostrarOcultar.setMinimumSize(180, 26)

        disenioBuscar = QHBoxLayout()
        disenioBuscar.setSpacing(10)
        disenioBuscar.addWidget(self.buscarLineEdit)
        disenioBuscar.addWidget(botonBuscar)
        disenioBuscar.addWidget(separadorTodos)
        disenioBuscar.addWidget(botonTodos)
        disenioBuscar.addWidget(botonMostrarOcultar)

        # =================== WIDGET  QTableWidget ===================

        self.tabla = QTableWidget()

        # Deshabilitar edición
        self.tabla.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # Deshabilitar el comportamiento de arrastrar y soltar
        self.tabla.setDragDropOverwriteMode(False)

        # Seleccionar toda la fila
        self.tabla.setSelectionBehavior(QAbstractItemView.SelectRows)

        # Seleccionar una fila a la vez
        self.tabla.setSelectionMode(QAbstractItemView.SingleSelection)

        # Especifica dónde deben aparecer los puntos suspensivos "..." cuando se muestran
        # textos que no encajan
        self.tabla.setTextElideMode(Qt.ElideRight)  # Qt.ElideNone

        # Establecer el ajuste de palabras del texto
        self.tabla.setWordWrap(False)

        # Deshabilitar clasificación
        self.tabla.setSortingEnabled(False)

        # Establecer el número de columnas
        self.tabla.setColumnCount(7)

        # Establecer el número de filas
        self.tabla.setRowCount(0)

        # Alineación del texto del encabezado
        self.tabla.horizontalHeader().setDefaultAlignment(Qt.AlignHCenter
                                                          | Qt.AlignVCenter
                                                          | Qt.AlignCenter)

        # Deshabilitar resaltado del texto del encabezado al seleccionar una fila
        self.tabla.horizontalHeader().setHighlightSections(False)

        # Hacer que la última sección visible del encabezado ocupa todo el espacio disponible
        self.tabla.horizontalHeader().setStretchLastSection(True)

        # Ocultar encabezado vertical
        self.tabla.verticalHeader().setVisible(False)

        # Dibujar el fondo usando colores alternados
        self.tabla.setAlternatingRowColors(True)

        # Establecer altura de las filas
        self.tabla.verticalHeader().setDefaultSectionSize(20)

        # self.tabla.verticalHeader().setHighlightSections(True)

        # Establecer las etiquetas de encabezado horizontal usando etiquetas
        self.tabla.setHorizontalHeaderLabels(nombreColumnas)

        # Menú contextual
        self.tabla.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tabla.customContextMenuRequested.connect(self.menuContextual)

        # Establecer ancho de las columnas
        for indice, ancho in enumerate((80, 240, 240, 140, 150, 130), start=0):
            self.tabla.setColumnWidth(indice, ancho)

    # ============================================================

        disenioBuscarTabla = QVBoxLayout()
        disenioBuscarTabla.addLayout(disenioBuscar)
        disenioBuscarTabla.addWidget(self.tabla)
        disenioBuscarTabla.setSpacing(8)
        disenioBuscarTabla.setContentsMargins(10, 10, 10, 0)

        # ===================== LAYOUT DERECHO =======================

        disenioDerecho = QVBoxLayout()
        disenioDerecho.addWidget(frameBienvenido)
        disenioDerecho.addLayout(disenioBuscarTabla)
        disenioDerecho.setContentsMargins(0, 0, 0, 0)

        # ====================== LAYOUT FINAL ======================

        disenioFinal = QGridLayout()
        disenioFinal.addWidget(frameBotones, 0, 0)
        disenioFinal.addLayout(disenioDerecho, 0, 1)
        disenioFinal.setSpacing(0)
        disenioFinal.setContentsMargins(0, 0, 0, 0)

        self.setLayout(disenioFinal)

        # ========= GUARDAR INFORMACIÓN EN EL PORTAPAPELES =========

        self.copiarInformacion = QApplication.clipboard()

        # ======================== EVENTOS =========================

        botonNuevo.clicked.connect(self.Nuevo)
        botonActualizar.clicked.connect(self.Actualizar)
        botonEliminar.clicked.connect(self.Eliminar)
        botonLimpiar.clicked.connect(self.limpiarTabla)

        self.buscarLineEdit.returnPressed.connect(self.Buscar)
        botonBuscar.clicked.connect(self.Buscar)
        botonTodos.clicked.connect(self.Buscar)

        botonConfiguracion.clicked.connect(lambda: Configuracion(self).exec_())

        self.tabla.itemDoubleClicked.connect(self.Suscribete)

        menuMostrarOcultar.triggered.connect(self.mostrarOcultar)
Пример #48
0
    def showWedge(self,
                  angle,
                  color,
                  extended=False,
                  rev_gradient=False,
                  outline_only=False):
        """Summary

        Args:
            angle (TYPE): Description
            color (TYPE): Description
            extended (bool, optional): Description
            rev_gradient (bool, optional): Description
            outline_only (bool, optional): Description
        """
        # Hack to keep wedge in front
        # self.setRotation(self.pre_xover_item_group.rotation())

        self._last_params = (angle, color, extended, rev_gradient,
                             outline_only)
        radius = self._radius
        span = self.pre_xover_item_group.partCrossoverSpanAngle() / 2
        radius_adjusted = radius + (_WEDGE_RECT_GAIN / 2)

        tip = QPointF(radius_adjusted, radius_adjusted)
        EXT = 1.35 if extended else 1.0

        # print("wtf", tip, pos)
        base_p2 = QPointF(1, 1)

        line0 = QLineF(tip, QPointF(base_p2))
        line1 = QLineF(tip, QPointF(base_p2))
        line2 = QLineF(tip, QPointF(base_p2))

        quad_scale = 1 + (.22 *
                          (span - 5) / 55)  # lo+(hi-lo)*(val-min)/(max-min)
        line0.setLength(radius_adjusted * EXT *
                        quad_scale)  # for quadTo control point
        line1.setLength(radius_adjusted * EXT)
        line2.setLength(radius_adjusted * EXT)
        line0.setAngle(angle)
        line1.setAngle(angle - span)
        line2.setAngle(angle + span)

        path = QPainterPath()

        if outline_only:
            self.setPen(getPenObj(color, 0.5, alpha=128, capstyle=Qt.RoundCap))
            path.moveTo(line1.p2())
            path.quadTo(line0.p2(), line2.p2())
        else:
            gradient = QRadialGradient(tip, radius_adjusted * EXT)
            color1 = getColorObj(color, alpha=80)
            color2 = getColorObj(color, alpha=0)
            if rev_gradient:
                color1, color2 = color2, color1

            if extended:
                gradient.setColorAt(0, color1)
                gradient.setColorAt(radius_adjusted / (radius_adjusted * EXT),
                                    color1)
                gradient.setColorAt(
                    radius_adjusted / (radius_adjusted * EXT) + 0.01, color2)
                gradient.setColorAt(1, color2)
            else:
                gradient.setColorAt(0, getColorObj(color, alpha=50))
            brush = QBrush(gradient)
            self.setBrush(brush)

            path.moveTo(line1.p1())
            path.lineTo(line1.p2())
            path.quadTo(line0.p2(), line2.p2())
            path.lineTo(line2.p1())

        self.setPath(path)
        self.show()
Пример #49
0
def make_candlestick(scene, n):
    width = 50
    gap = 10

    scene.addRect(QRectF((width + gap) * n, n, 100, 200), QPen(Qt.transparent),
                  QBrush(Qt.green))
Пример #50
0
    def refresh(self):
        if not self._mdlPlots or not self._mdlOutline or not self._mdlCharacter:
            return

        if not self.isVisible():
            return

        LINE_HEIGHT = 18
        SPACING = 3
        TEXT_WIDTH = self.sldTxtSize.value()
        CIRCLE_WIDTH = 10
        LEVEL_HEIGHT = 12

        s = self.scene
        s.clear()

        # Get Max Level (max depth)
        root = self._mdlOutline.rootItem
        def maxLevel(item, level=0, max=0):
            if level > max:
                max = level
            for c in item.children():
                m = maxLevel(c, level + 1)
                if m > max:
                    max = m
            return max

        MAX_LEVEL = maxLevel(root)

        # Get the list of tracked items (array of references)
        trackedItems = []

        if self.actPlots.isChecked():
            trackedItems += self.plotReferences()

        if self.actCharacters.isChecked():
            trackedItems += self.charactersReferences()

        ROWS_HEIGHT = len(trackedItems) * (LINE_HEIGHT + SPACING )

        fm = QFontMetrics(s.font())
        max_name = 0
        for ref in trackedItems:
            name = references.title(ref)
            max_name = max(fm.width(name), max_name)

        TITLE_WIDTH = max_name + 2 * SPACING

        # Add Folders and Texts
        outline = OutlineRect(0, 0, 0, ROWS_HEIGHT + SPACING + MAX_LEVEL * LEVEL_HEIGHT)
        s.addItem(outline)
        outline.setPos(TITLE_WIDTH + SPACING, 0)

        refCircles = [] # a list of all references, to be added later on the lines

        # A Function to add a rect with centered elided text
        def addRectText(x, w, parent, text="", level=0, tooltip=""):
            deltaH = LEVEL_HEIGHT if level else 0
            r = OutlineRect(0, 0, w, parent.rect().height()-deltaH, parent, title=text)
            r.setPos(x, deltaH)

            txt = QGraphicsSimpleTextItem(text, r)
            f = txt.font()
            f.setPointSize(8)
            fm = QFontMetricsF(f)
            elidedText = fm.elidedText(text, Qt.ElideMiddle, w)
            txt.setFont(f)
            txt.setText(elidedText)
            txt.setPos(r.boundingRect().center() - txt.boundingRect().center())
            txt.setY(0)
            return r

        # A function to returns an item's width, by counting its children
        def itemWidth(item):
            if item.isFolder():
                r = 0
                for c in item.children():
                    r += itemWidth(c)
                return r or TEXT_WIDTH
            else:
                return TEXT_WIDTH

        def listItems(item, rect, level=0):
            delta = 0
            for child in item.children():
                w = itemWidth(child)

                if child.isFolder():
                    parent = addRectText(delta, w, rect, child.title(), level, tooltip=child.title())
                    parent.setToolTip(references.tooltip(references.textReference(child.ID())))
                    listItems(child, parent, level + 1)

                else:
                    rectChild = addRectText(delta, TEXT_WIDTH, rect, "", level, tooltip=child.title())
                    rectChild.setToolTip(references.tooltip(references.textReference(child.ID())))
                    
                    # Find tracked references in that scene (or parent folders)
                    for ref in trackedItems:

                        result = []

                        # Tests if POV
                        scenePOV = False  # Will hold true of character is POV of the current text, not containing folder
                        if references.type(ref) == references.CharacterLetter:
                            ID = references.ID(ref)
                            c = child
                            while c:
                                if c.POV() == ID:
                                    result.append(c.ID())
                                    if c == child: scenePOV = True
                                c = c.parent()

                        # Search in notes/references
                        c = child
                        while c:
                            result += references.findReferencesTo(ref, c, recursive=False)
                            c = c.parent()

                        if result:
                            ref2 = result[0]
                            
                            # Create a RefCircle with the reference
                            c = RefCircle(TEXT_WIDTH / 2, - CIRCLE_WIDTH / 2, CIRCLE_WIDTH, ID=ref2, important=scenePOV)
                            
                            # Store it, with the position of that item, to display it on the line later on
                            refCircles.append((ref, c, rect.mapToItem(outline, rectChild.pos())))

                delta += w

        listItems(root, outline)

        OUTLINE_WIDTH = itemWidth(root)

        # Add Tracked items
        i = 0
        itemsRect = s.addRect(0, 0, 0, 0)
        itemsRect.setPos(0, MAX_LEVEL * LEVEL_HEIGHT + SPACING)

        # Set of colors for plots (as long as they don't have their own colors)
        colors = [
            "#D97777", "#AE5F8C", "#D9A377", "#FFC2C2", "#FFDEC2", "#D2A0BC",
            "#7B0F0F", "#7B400F", "#620C3D", "#AA3939", "#AA6C39", "#882D61",
            "#4C0000", "#4C2200", "#3D0022",
        ]

        for ref in trackedItems:
            if references.type(ref) == references.CharacterLetter:
                color = self._mdlCharacter.getCharacterByID(references.ID(ref)).color()
            else:
                color = QColor(colors[i % len(colors)])

            # Rect
            r = QGraphicsRectItem(0, 0, TITLE_WIDTH, LINE_HEIGHT, itemsRect)
            r.setPen(QPen(Qt.NoPen))
            r.setBrush(QBrush(color))
            r.setPos(0, i * LINE_HEIGHT + i * SPACING)
            r.setToolTip(references.tooltip(ref))
            i += 1

            # Text
            name = references.title(ref)
            txt = QGraphicsSimpleTextItem(name, r)
            txt.setPos(r.boundingRect().center() - txt.boundingRect().center())

            # Line
            line = PlotLine(0, 0,
                            OUTLINE_WIDTH + SPACING, 0)
            line.setPos(TITLE_WIDTH, r.mapToScene(r.rect().center()).y())
            s.addItem(line)
            line.setPen(QPen(color, 5))
            line.setToolTip(references.tooltip(ref))

            # We add the circles / references to text, on the line
            for ref2, circle, pos in refCircles:
                if ref2 == ref:
                    circle.setParentItem(line)
                    circle.setPos(pos.x(), 0)

        # self.view.fitInView(0, 0, TOTAL_WIDTH, i * LINE_HEIGHT, Qt.KeepAspectRatioByExpanding) # KeepAspectRatio
        self.view.setSceneRect(0, 0, 0, 0)
Пример #51
0
    def paintGraph(self, graph, painter):
        brush = QBrush(Qt.SolidPattern)
        pen=QPen()
        brush.setColor(Qt.white)

        if(self.show_subgraphs):
            for node in graph.nodes:
                if type(node)==Graph:
                    subgraph = node
                    self.paintSubgraph(subgraph, painter, pen, brush)

        for edge in graph.edges:
            if("color" in edge.kwargs.keys()):
                pen.setColor(QColor(edge.kwargs["color"]))
            else:
                pen.setColor(QColor("black"))

            if("width" in edge.kwargs.keys()):
                pen.setWidth(int(edge.kwargs["width"]))
            else:
                pen.setWidth(1)

            painter.setPen(pen)
            painter.setBrush(brush)
            if(edge.source.parent_graph !=graph and not self.show_subgraphs):
                gspos = edge.source.parent_graph.global_pos
            else:
                gspos = edge.source.global_pos

            if(edge.dest.parent_graph !=graph and not self.show_subgraphs):
                gspos = edge.dest.parent_graph.global_pos
            else:
                gdpos = edge.dest.global_pos
            painter.drawLine(gspos[0],gspos[1],
            gdpos[0],
            gdpos[1])

         # TODO : add more painting parameters
        for node in graph.nodes:
            if type(node)!=Graph:
                if("color" in node.kwargs.keys()):
                    pen.setColor(QColor(node.kwargs["color"]))
                else:
                    pen.setColor(QColor("black"))
                gpos = node.global_pos

                painter.setPen(pen)
                painter.setBrush(brush)
                if("shape" in node.kwargs.keys()):
                    if(node.kwargs["shape"]=="box"):
                        painter.drawRect(
                                    gpos[0]-node.size[0]/2,
                                    gpos[1]-node.size[1]/2,
                                    node.size[0], node.size[1])

                    if(node.kwargs["shape"]=="circle"):
                        painter.drawEllipse(
                                    gpos[0]-node.size[0]/2,
                                    gpos[1]-node.size[1]/2,
                                    node.size[0], node.size[1])

                else:
                    painter.drawEllipse(
                                gpos[0]-node.size[0]/2,
                                gpos[1]-node.size[1]/2,
                                node.size[0], node.size[1])


                if("label" in node.kwargs.keys()):
                    painter.drawText(
                        gpos[0]-node.size[0]/2,
                        gpos[1]-node.size[1]/2,
                        node.size[0], node.size[1],
                        Qt.AlignCenter|Qt.AlignTop,node.kwargs["label"])
            else:
                if(self.show_subgraphs):
                    self.paintGraph(subgraph, painter)
                else:
                    subgraph = node
                    self.paintSubgraph(subgraph, painter, pen, brush)
Пример #52
0
    def paintEvent(self, *_):
        """
        This is called on self.update() and on resize - makes resizes a bit ugly.
        This method draws every frame and forms the core of the program.
        """
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.translate(self.width() / 2,
                          self.height() / 2)  # Make (0,0) centre

        if self.draw_axes:
            painter.setPen(QPen(QColor(0, 0, 0, 64), 1))
            # Line(x1,y2,x2,y2)
            painter.drawLine(
                QLineF(0,
                       self.height() / 2, 0, -self.height() / 2))
            painter.drawLine(QLineF(self.width() / 2, 0, -self.width() / 2, 0))

        colours = interpolate_hsv(self.col1, self.col2, self.num_dots - 2)
        # self.num_dots slider minimum is 2, so middle num minimum 0 which is ok
        last = None

        for cur_dot_num in range(self.num_dots):
            if self.join_end_dots:
                angle_off = radians(self.angle_factor /
                                    (self.num_dots - 1)) * cur_dot_num
                frame_no = self.frame_no + cur_dot_num * (
                    180 / (self.num_dots - 1)) / self.speedmult
            else:
                angle_off = radians(
                    self.angle_factor / self.num_dots) * cur_dot_num
                frame_no = self.frame_no + cur_dot_num * (
                    180 / self.num_dots) / self.speedmult
            # green = (240/self.num_dots) * (self.num_dots - cur_dot_num)
            # blue = (240/self.num_dots) * cur_dot_num
            # colour = QColor(0, green, blue)
            colour = next(colours).toRgb()
            painter.setPen(QPen(colour))
            painter.setBrush(QBrush(colour))
            # progress = (cos(radians(SPEED_MULT * frame_no)) + 1)/2 * 180
            progress = abs((frame_no * self.speedmult) % (2 * self.halfmax) -
                           self.halfmax)
            # Progress oscillates every 360/speed_mult frames
            # Progress dictates the range of values of x later fed into cos(x)
            # frame_no multiplier dictates frequency of oscillations
            # Progress ranges between 0 and 180 which later gives us a
            # cos(progress) ranging between # 1 and -1, which combines with
            # sometimes-neg wid * hei to give a full range
            # print(self.frame_no,progress)
            height = sin(angle_off) * (self.height() - 100)
            width = cos(angle_off) * (self.width() - 100)
            # (0,0) is the centre
            x = cos(radians(self.x_multiplier * progress)) * width / 2
            y = cos(radians(self.y_multiplier * progress)) * height / 2

            if self.draw_lines:
                painter.setPen(QPen(colour, self.dot_size))
                painter.drawLine(QPointF(x, y), QPointF(0, 0))
                if self.connect_lines:
                    if last:
                        painter.drawLine(QPointF(x, y), last)
                    last = QPointF(x, y)
            else:
                painter.drawEllipse(QPointF(x, y), self.dot_size,
                                    self.dot_size)
# -*- coding: utf-8 -*-
'''
    【简介】
	 界面背景图片设置
    
'''

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPalette, QBrush, QPixmap

app = QApplication(sys.argv)
win = QMainWindow()
win.setWindowTitle("界面背景图片设置")
palette = QPalette()
palette.setBrush(QPalette.Background, QBrush(QPixmap("./images/python.jpg")))
win.setPalette(palette)
# 当背景图片的宽度和高度大于窗口的宽度和高度时
win.resize(460, 255)

# 当背景图片的宽度和高度小于窗口的宽度和高度时
# win.resize(800, 600)
win.show()
sys.exit(app.exec_())
Пример #54
0
class ColorPanel(QGraphicsItem):
    """Summary

    Attributes:
        colordialog (TYPE): Description
        rect (TYPE): Description
    """
    _shift_colors = [getColorObj(x) for x in styles.SCAF_COLORS]
    _colors = [getColorObj(x) for x in styles.STAP_COLORS]
    _PEN = Qt.NoPen

    def __init__(self, parent=None):
        """Summary

        Args:
            parent (None, optional): Description
        """
        super(ColorPanel, self).__init__(parent)
        self.rect = QRectF(0, 0, 30, 30)
        self.setFlag(QGraphicsItem.ItemIgnoresTransformations)
        print(
            "A bug in Qt is about to cause a warning 'Layout still needs update after calling...'"
        )
        print(
            "Please vote to fix here: https://bugreports.qt.io/browse/QTBUG-58699"
        )
        self.colordialog = QColorDialog()
        self._shift_color_index = -1  # init on -1, painttool will cycle to 0
        self._color_index = -1  # init on -1, painttool will cycle to 0
        self._shift_color = self._shift_colors[self._shift_color_index]
        self._color = self._colors[self._color_index]
        self._shift_brush = QBrush(self._shift_color)
        self._brush = QBrush(self._color)
        self._initLabel()
        self.hide()

    def _initLabel(self):
        """Summary

        Returns:
            TYPE: Description
        """
        self._label = label = QGraphicsTextItem("⇧", parent=self)
        label.setPos(28, -4)
        label.setFont(_FONT)

    def boundingRect(self):
        """Summary

        Returns:
            TYPE: Description
        """
        return self.rect

    def paint(self, painter, option, widget=None):
        """Summary

        Args:
            painter (TYPE): Description
            option (TYPE): Description
            widget (None, optional): Description

        Returns:
            TYPE: Description
        """
        painter.setPen(self._PEN)
        painter.setBrush(self._shift_brush)
        painter.drawRect(0, 0, 30, 15)
        painter.setBrush(self._brush)
        painter.drawRect(0, 15, 30, 15)

    def nextColor(self):
        """Summary

        Returns:
            TYPE: Description
        """
        self._color_index += 1
        if self._color_index == len(self._colors):
            self._color_index = 0
        self._color = self._colors[self._color_index]
        self._brush.setColor(self._color)
        self.update()

    def prevColor(self):
        """Summary

        Returns:
            TYPE: Description
        """
        self._color_index -= 1

    def color(self):
        """Summary

        Returns:
            TYPE: Description
        """
        return self._color

    def shiftColorName(self):
        """Summary

        Returns:
            TYPE: Description
        """
        return self._shift_color.name()

    def colorName(self):
        """Summary

        Returns:
            TYPE: Description
        """
        return self._color.name()

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

        Args:
            event (QGraphicsSceneMouseEvent): Description

        Returns:
            TYPE: Description
        """
        if event.pos().y() < 10:
            new_color = self.colordialog.getColor(self._shift_color)
            if new_color.isValid(
            ) and new_color.name() != self._shift_color.name():
                self._shift_color = new_color
                self._shift_brush = QBrush(new_color)
                if new_color not in self._shift_colors:
                    self._shift_colors.insert(self._shift_color_index,
                                              new_color)
                self.update()
        else:
            new_color = self.colordialog.getColor(self._color)
            if new_color.isValid() and new_color.name() != self._color.name():
                self._color = new_color
                self._brush = QBrush(new_color)
                if new_color not in self._colors:
                    self._colors.insert(self._color_index, new_color)
                self.update()
Пример #55
0
    def initUI(self, path_to_options):
        """ initialize the view-scene graphic environment """
        self.scene = QGraphicsScene()
        #self.scene.setSceneRect(0, 0, 640, 480)
        self.view = QGraphicsViewExtend(self.scene)
        self.view.setSceneRect(QRectF(self.view.viewport().rect()))
        self.view.setSceneRect(QRectF(0, 0, 850, 900))
        self.view.setRenderHint(QPainter.Antialiasing)
        layout = QGridLayout()
        layout.addWidget(self.view)
        self.setLayout(layout)
        self.setBackgroundColor(QColor('green'))

        # special properties
        self.svgCardsPath = "../cards"
        self.cardsGraphItems = []  #holds all the cards items
        self.defInsertionPos = QPointF(0, 0)
        self.defAngle = 0
        self.defScale = 0.5
        self.deckBackSVG = 'back_1'
        self.numOfPlayers = 4
        self.playersHandsPos = [(75, 50, 0), (210, 50, 180), (680, 50, 0),
                                (210, 385, 0)]  #(x,y,angle)
        self.defHandSpacing = 24
        self.midCards = []
        self.options_file_path = path_to_options

        # Card fields
        pen = QPen()
        brush = QBrush()
        self.scene.addRect(QRectF(200, 230, 100, 80), pen, brush)
        self.scene.addRect(QRectF(200 + 120, 230, 100, 80), pen, brush)
        self.scene.addRect(QRectF(200 + 120 * 2, 230, 100, 80), pen, brush)
        self.scene.addRect(QRectF(200 + 120 * 3, 230, 100, 80), pen, brush)

        # Player Names
        self.player1_label = self.addPlayerLabel(425, 350, "Player 1")
        self.player2_label = self.addPlayerLabel(0, 240, "Player 2")
        self.player3_label = self.addPlayerLabel(425, 20, "Player 3")
        self.player4_label = self.addPlayerLabel(782, 240, "Player 4")

        self.card1_label = self.addPlayerLabel(200, 210, "")
        self.card2_label = self.addPlayerLabel(200 + 120, 210, "")
        self.card3_label = self.addPlayerLabel(200 + 120 * 2, 210, "")
        self.card4_label = self.addPlayerLabel(200 + 120 * 3, 210, "")

        self.card_label_l = [
            self.card1_label, self.card2_label, self.card3_label,
            self.card4_label
        ]
        self.card_label_pla = [
            self.player1_label, self.player2_label, self.player3_label,
            self.player4_label
        ]

        self.play_1_state = self.addPlayerLabel(200, 250, "")
        self.play_2_state = self.addPlayerLabel(200 + 120, 250, "")
        self.play_3_state = self.addPlayerLabel(200 + 120 * 2, 250, "")
        self.play_4_state = self.addPlayerLabel(200 + 120 * 3, 250, "")
        self.game_indicator = self.addPlayerLabel(650, 5, "Game: ")
        self.mode_label = self.addPlayerLabel(150, 5, "Mode: ")

        playbtn = QPushButton('Start', self)
        playbtn.resize(50, 32)
        playbtn.move(10, 10)
        playbtn.clicked.connect(self.start_clicked)

        options = QPushButton('Options', self)
        options.resize(80, 32)
        options.move(65, 10)
        options.clicked.connect(self.options_clicked)

        nextRound = QPushButton('nextRound', self)
        nextRound.resize(80, 32)
        nextRound.move(150, 10)
        nextRound.setVisible(False)
        nextRound.clicked.connect(self.nextRound_clicked)

        self.scene.addWidget(playbtn)
        self.scene.addWidget(nextRound)
        self.scene.addWidget(options)

        self.my_game = None

        # Testing tree:
        self.my_tree = None

        # Storing game_play
        self.game_play = {}

        self.corrString = ""
        # emit signal:
        self.server_receivedSig.connect(self.parseClient)

        ### Client stuff:
        self.clientTimer = QTimer(self)
        self.tcpSocket = None
        self.games_played = 0
        self.reset_client()

        self.server_thread = None
Пример #56
0
    def general_window(self):
        '''
        Assert of Web-connection
        '''
        try:
            self.pre_start_program()
        except:
            self.message_box()
        '''
        Creating menu, basic widgets,
        buttons and labels
        '''
        menubar = self.menuBar()
        opt_ns_Menu = menubar.addMenu('&Опции')
        self.get_Action = QAction('&Начать', self)
        self.get_Action.setShortcut('Ctrl+r')
        exit_Action = QAction('&Выход', self)
        exit_Action.setShortcut('Ctrl+Q')
        self.get_Action.triggered.connect(self.start_program)
        exit_Action.triggered.connect(self.close)
        opt_ns_Menu.addAction(self.get_Action)
        opt_ns_Menu.addAction(exit_Action)

        try_Menu = menubar.addMenu('&Учебник')
        try_Action = QAction('&Правила к заданиям', self)
        try_Action.triggered.connect(self.buttom_browser)
        try_Menu.addAction(try_Action)

        dop_Menu = menubar.addMenu('&Дополнительно')
        to_addAction_1 = QAction('&О разработчиках', self)
        to_addAction_2 = QAction('&Почему Паланик?', self)
        info_PyQt5 = lambda: QMessageBox.aboutQt(self)
        to_addAction_1.triggered.connect(info_PyQt5)
        to_addAction_2.triggered.connect(self.button_palanuk)
        dop_Menu.addAction(to_addAction_1)
        dop_Menu.addAction(to_addAction_2)

        self.setStatusTip('Строка состояния')
        self.get_Action.setStatusTip('Начать тест')
        exit_Action.setStatusTip('Выход из программы')
        try_Action.setStatusTip('Необходимый атрибут')
        to_addAction_1.setStatusTip('Важная информация')
        to_addAction_2.setStatusTip('Причём тут Чак Паланик?')
        '''
        Window space
        '''
        self.image_background(self, 910, 600)
        back_map = QImage("image_back_1.jpg")
        back_map_2 = back_map.scaled(QSize(910, 600))
        palette = QPalette()
        palette.setBrush(QPalette.Window, QBrush(back_map_2))
        self.setPalette(palette)

        lbl_1 = QLabel('Заполните недостающие формы неправильных глаголов',
                       self)
        lbl_1.setFont(QtGui.QFont("Times", 14, QtGui.QFont.Bold))
        lbl_1.adjustSize()
        lbl_1.move(180, 50)

        self.textEdit = QTextEdit()
        self.statusBar()
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(350, 100, 200, 25)
        self.timer = QBasicTimer()
        self.step = 0

        btn_1 = QLabel('Первая ->', self)
        btn_1.move(60, 148)
        self.line_1 = QLabel(self)
        self.line_1.move(153, 151)
        self.line_1_2 = QLabel(self)
        self.line_1_2.move(153, 200)

        btn_2 = QLabel('Вторая ->', self)
        btn_2.move(260, 150)
        self.line_2 = QLineEdit(self)
        self.line_2.setMaxLength(14)
        self.line_2.setFixedSize(108, 33)
        self.line_2.move(350, 150)
        self.line_2_2 = QLabel(self)
        self.line_2_2.move(353, 200)

        btn_3 = QLabel('Третья ->', self)
        btn_3.move(460, 150)
        self.line_3 = QLineEdit(self)
        self.line_3.setMaxLength(14)
        self.line_3.setFixedSize(108, 33)
        self.line_3.move(540, 150)
        self.line_3_2 = QLabel(self)
        self.line_3_2.move(543, 200)

        btn_t = QLabel('Перевод ->', self)
        btn_t.move(655, 150)
        self.line_t = QLineEdit(self)
        self.line_t.setMaxLength(14)
        self.line_t.setFixedSize(108, 33)
        self.line_t.move(750, 150)
        self.line_t_2 = QLabel(self)
        self.line_t_2.move(753, 200)

        self.draw_fonts(
            self.line_1_2,
            self.line_1,
            self.line_2,
            self.line_2_2,
            self.line_3,
            self.line_3_2,
            self.line_t,
            self.line_t_2,
        )

        pix_map = QPixmap("images.jpeg")
        img = QLabel(self)
        img.setPixmap(pix_map)
        img.setGeometry(60, 270, 225, 225)
        lbl_img = QLabel('Это - Чак Паланик', self)
        lbl_img.setFont(QtGui.QFont("Times", 14, QtGui.QFont.Bold))
        lbl_img.adjustSize()
        lbl_img.move(60, 520)
        img.setStatusTip('Чак Паланик')

        self.choice_verbs()
        self.lbl_limit = QLabel(self)
        self.lbl_limit.setFont(QtGui.QFont('Times', 20, QtGui.QFont.Bold))
        self.lbl_limit.move(400, 295)
        self.lbl_lim_set_stat = QLabel('Cтaрт: Ctrl+r', self)
        self.lbl_lim_set_stat.setFont(
            QtGui.QFont('Times', 12, QtGui.QFont.Bold))
        self.lbl_lim_set_stat.adjustSize()
        self.lbl_lim_set_stat.move(380, 370)

        self.true_limit = QLabel('Правильных ответов:', self)
        self.true_limit.setFont(QtGui.QFont('Times', 14, QtGui.QFont.Bold))
        self.true_limit.adjustSize()
        self.true_limit.move(620, 280)
        self.true_limit_2 = QLabel(self)
        self.true_limit_2.setFont(QtGui.QFont('Times', 18, QtGui.QFont.Bold))
        self.true_limit_2.adjustSize()
        self.true_limit_2.move(700, 320)

        self.btn_back = QPushButton('Назад', self)
        self.btn_back.resize(self.btn_back.sizeHint())
        self.btn_back.clicked.connect(self.back_value)
        self.btn_back.setGeometry(350, 440, 200, 25)
        self.btn_back.blockSignals(True)

        self.btn_assert = QPushButton('Проверить', self)
        self.btn_assert.resize(self.btn_assert.sizeHint())
        self.btn_assert.clicked.connect(self.show_verbs)
        self.btn_assert.setGeometry(490, 480, 200, 25)
        self.btn_assert.blockSignals(True)

        lbl_assert = QLabel(
            'Если вы не заполнили пропуски,\n'
            'то при нажатии этих клавиш\n'
            'вы не сможете изменить ответ.', self)
        lbl_assert.adjustSize()
        lbl_assert.move(490, 510)

        self.btn_next = QPushButton('Далее', self)
        self.btn_next.resize(self.btn_assert.sizeHint())
        self.btn_next.setFocus()
        self.btn_next.setAutoDefault(True)
        self.btn_next.clicked.connect(self.next_value)
        self.btn_next.setGeometry(650, 440, 200, 25)
        self.btn_next.blockSignals(True)
        self.lbl_next = QLabel(self)
        self.lbl_next.move(730, 480)
        self.show()
Пример #57
0
    def initUI(self, id):
        self.setWindowTitle('结果查看')
        self.setWindowIcon(QIcon('./images/icon.jpg'))
        self.setGeometry(10, 10, 900, 800)
        # self.setMaximumSize()
        self.setWindowFlags(Qt.Qt.SubWindow)
        self.taskid = id
        grid = QGridLayout()

        closeBtn = QPushButton('关闭')
        downloadReportBtn = QPushButton('下载报告')
        downloadLogBtn = QPushButton('下载日志')
        closeBtn.resize(closeBtn.sizeHint())
        closeBtn.clicked.connect(self.close)

        downloadReportBtn.resize(downloadReportBtn.sizeHint())
        downloadReportBtn.clicked.connect(self.downloadReport)

        downloadLogBtn.resize(downloadLogBtn.sizeHint())
        downloadLogBtn.clicked.connect(self.downloadLog)

        self.tipLabel = QLabel()
        # self.tipLabel.(QColor(20,150,150))
        self.tipLabel.setFont(QFont('sanserif', 12))
        self.tipLabel.setText('')



        self.errMsgLabel = QLabel()
        self.errMsgLabel.setFont(QFont('sanserif', 16))
        self.errMsgLabel.setText('')
        self.pe_red = QPalette()
        self.pe_red.setColor(QPalette.WindowText, Qt.Qt.red)
        self.errMsgLabel.setPalette(self.pe_red)

        self.tree = QTreeWidget()
        self.tree.setColumnCount(1)
        self.tree.setHeaderLabels([''])
        self.tree.setColumnWidth(0, 750)
        self.featureTree = QTreeWidgetItem()


        grid.addWidget(closeBtn, 1, 9)
        grid.addWidget(downloadReportBtn, 1, 10)
        # grid.addWidget(downloadLogBtn, 1, 10) # 日志下载暂时停用
        grid.addWidget(self.tipLabel, 2, 0, 1, 5)
        grid.addWidget(self.errMsgLabel, 2, 5, 1, 3)
        grid.addWidget(self.tree, 3, 0, 20, 11)
        self.setLayout(grid)

        self.show()

        cf = getter.get_app_conf()
        projectPath = str(cf.get('baseconf', 'projectLocation'))
        reportPath = os.path.join(projectPath, 'reports', str(id), 'report.log')
        # 获取结果 数据库查询
        res = getter.get_task_his_by_id(self.taskid)
        result = res['result']

        if len(result) == 0:
            self.errMsgLabel.setText('没有生成报告,请确定是否执行结束')
            return

        step_flag = None
        scen_flag = None
        total_cnt = 0
        failed_cnt = 0
        for f in result.split('\n'):
            if f.strip().startswith('场景:'):
                total_cnt += 1
                step_flag = True
                scen_flag = True
                self.featureTree = QTreeWidgetItem(self.tree)
                self.featureTree.setText(0, f.strip()[len('场景:'):].strip())
            elif not f.strip().startswith('背景:') and not f.strip().startswith('功能:') and not f.strip() == '':
                backgroundTree = QTreeWidgetItem(self.featureTree)
                if '...' in f:
                    backgroundTree.setText(0, f.replace('\n', '')[: f.index('...')])
                else:
                    backgroundTree.setText(0, f.replace('\n', ''))
                if 'passed' in f:
                    # backgroundTree.setBackground(0, QBrush(QColor(0, 250, 0)))
                    step_flag = True

                if 'failed' in f:
                    backgroundTree.setForeground(0, QBrush(QColor(250, 0, 0)))
                    step_flag = False
                    scen_flag = False
                    failed_cnt += 1

                if step_flag:
                    pass
                    # backgroundTree.setBackground(0, QBrush(QColor(0, 250, 0)))
                else:
                    # backgroundTree.setBackground(0, QBrush(QColor(250, 0, 0)))
                    backgroundTree.setForeground(0, QBrush(QColor(250, 0, 0)))



                if scen_flag:
                    self.featureTree.setForeground(0, QBrush(QColor(0, 250, 0)))
                else:
                    self.featureTree.setForeground(0, QBrush(QColor(255, 0, 0)))

        # file.close()

        self.tipLabel.setText('全部用例:' + str(total_cnt) + '条, 通过用例:' + str(total_cnt - failed_cnt) + '条, 失败用例:' + str(failed_cnt) + '条')
Пример #58
0
import time
from cadnano.gui.views import styles

import cadnano.util as util

from PyQt5.QtCore import QPointF, QRectF, Qt, QEvent

from PyQt5.QtGui import QBrush, QFont, QFontMetrics, QPen, QColor, QPainterPath, QPolygonF
from PyQt5.QtWidgets import QGraphicsItem, QGraphicsPathItem, QGraphicsRectItem, QGraphicsSimpleTextItem

_BASE_WIDTH = styles.PATH_BASE_WIDTH
_toHelixNumFont = styles.XOVER_LABEL_FONT
# precalculate the height of a number font.  Assumes a fixed font
# and that only numbers will be used for labels
_FM = QFontMetrics(_toHelixNumFont)
_ENAB_BRUSH = QBrush(Qt.SolidPattern)  # Also for the helix number label
_NO_BRUSH = QBrush(Qt.NoBrush)
# _RECT = QRectF(0, 0, baseWidth, baseWidth)
_X_SCALE = styles.PATH_XOVER_LINE_SCALE_X  # control point x constant
_Y_SCALE = styles.PATH_XOVER_LINE_SCALE_Y  # control point y constant
_RECT = QRectF(0, 0, _BASE_WIDTH, _BASE_WIDTH)


class XoverNode3(QGraphicsRectItem):
    """
    This is a QGraphicsRectItem to allow actions and also a 
    QGraphicsSimpleTextItem to allow a label to be drawn
    """
    def __init__(self, virtual_helix_item, xover_item, strand3p, idx):
        super(XoverNode3, self).__init__(virtual_helix_item)
        self._vhi = virtual_helix_item
    def paintEvent(self, event):
        qp = QPainter(self)

        qp.setRenderHint(
            QPainter.Antialiasing
        )  # <- Set anti-aliasing  See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration

        size = self.size()
        widget_width, widget_height = size.width(), size.height()

        # Make fonts

        time_label_font = qp.font()
        time_label_font.setPointSize(self.time_label_font_size)

        task_label_font = qp.font()
        task_label_font.setPointSize(self.task_label_font_size)

        # Frame

        qp.setPen(QPen(Qt.black, self.border_size, Qt.SolidLine))
        qp.setBrush(QBrush(Qt.white, Qt.SolidPattern))

        qp.drawRect(
            self.margin_size + self.time_label_margin,  # x_start
            self.margin_size,  # y_start
            widget_width - 2 * self.margin_size -
            self.time_label_margin,  # x_size
            widget_height - 2 * self.margin_size)  # y_size

        ## Starting time label

        #qp.setFont(time_label_font)

        #qp.drawText(0, #self.margin_size,   # x_start
        #            self.margin_size - int(self.time_label_font_size/2), # y_start
        #            self.time_label_margin, # x_size
        #            self.time_label_font_size,   # y_size
        #            Qt.AlignCenter,
        #            self.starting_time_str)

        ## Ending time label

        #qp.setFont(time_label_font)

        #qp.drawText(0, #self.margin_size,   # x_start
        #            widget_height - self.margin_size - int(self.time_label_font_size/2), # y_start
        #            self.time_label_margin, # x_size
        #            self.time_label_font_size,   # y_size
        #            Qt.AlignCenter,
        #            self.ending_time_str)

        # Draw a line for each hour

        qp.setPen(QPen(Qt.gray, 1, Qt.SolidLine))
        qp.setFont(time_label_font)

        if self.starting_time.minute == 0:
            i = 0
        else:
            i = 1

        marker_time = datetime.datetime(year=self.starting_time.year,
                                        month=self.starting_time.month,
                                        day=self.starting_time.day,
                                        hour=self.starting_time.hour + i)

        while marker_time.hour <= self.ending_time.hour:
            time_marker_str = marker_time.strftime("%H:%M")
            marker_time_y_pos = self.timeCoordinateMapper(time_marker_str)

            qp.drawLine(
                self.margin_size + self.time_label_margin,  # x_start
                marker_time_y_pos,  # y_start
                widget_width - self.margin_size,  # x_end
                marker_time_y_pos)  # y_end

            qp.drawText(
                0,  #self.margin_size,   # x_start
                marker_time_y_pos -
                int(self.time_label_font_size / 2),  # y_start
                self.time_label_margin,  # x_size
                self.time_label_font_size,  # y_size
                Qt.AlignCenter,
                time_marker_str)

            if marker_time.hour == 23:
                break

            i += 1
            marker_time = datetime.datetime(year=self.starting_time.year,
                                            month=self.starting_time.month,
                                            day=self.starting_time.day,
                                            hour=self.starting_time.hour + i)

        # Tasks

        qp.setPen(QPen(Qt.black, self.border_size, Qt.SolidLine))
        #qp.setBrush(QBrush(Qt.yellow, Qt.SolidPattern))
        #qp.setBrush(QBrush(QColor("#fcaf3e88"), Qt.SolidPattern))
        qp.setBrush(QBrush(QColor(194, 135, 0, 128), Qt.SolidPattern))

        qp.setFont(task_label_font)

        for task in self.data:
            y_start = self.timeCoordinateMapper(task["start"])
            y_end = self.timeCoordinateMapper(task["end"])
            qp.drawRect(
                self.margin_size + self.time_label_margin,  # x_start
                y_start,  # y_start
                widget_width - 2 * self.margin_size -
                self.time_label_margin,  # x_size
                y_end - y_start)  # y_size

            qp.drawText(
                self.margin_size + self.time_label_margin,  # x_start
                y_start,  # y_start
                widget_width - 2 * self.margin_size -
                self.time_label_margin,  # x_size
                y_end - y_start,  # y_size
                Qt.AlignCenter,
                task["label"])

        # Draw a line to show the current time

        current_time_str = datetime.datetime.now().strftime("%H:%M")
        current_time_y_pos = self.timeCoordinateMapper(current_time_str)

        qp.setPen(QPen(Qt.red, self.border_size, Qt.SolidLine))
        qp.setBrush(QBrush(Qt.red, Qt.SolidPattern))
        qp.drawLine(
            self.margin_size + self.time_label_margin,  # x_start
            current_time_y_pos,  # y_start
            widget_width - self.margin_size,  # x_end
            current_time_y_pos)  # y_end

        # Current time bullet

        bullet_border = 5
        qp.setPen(QPen(Qt.red, bullet_border, Qt.SolidLine))
        qp.setBrush(QBrush(Qt.red, Qt.SolidPattern))
        qp.setRenderHint(
            QPainter.Antialiasing
        )  # <- Set anti-aliasing  See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration

        bullet_radius = 3
        qp.drawEllipse(
            self.margin_size + self.time_label_margin -
            bullet_radius,  # x_start,
            current_time_y_pos - bullet_radius,  # y_start,
            2 * bullet_radius,
            2 * bullet_radius)
Пример #60
0
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        '''
                initCards : 랜덤으로 줘야 해 - 서버에서 해서 뿌려야 할 것 같음. 진영 용택 논의 필요
                clientIndex : 서버에서 받아야 함
                beginnerIndex : 서버에서 받아야 함
        '''
        self.beginnerIndex = 0
        self.clientIndex = 0
        self.isTurn = 1

        self.gm = GM(initCards(5), self.clientIndex, self.beginnerIndex)
        self.gm.distributeCards()
        self.btnGiveHint.clicked.connect(self.clickedGiveHint)
        # 배경 사진 넣기
        background = QImage("background.jpeg")
        palette = QPalette()
        palette.setBrush(10, QBrush(background))
        self.setPalette(palette)
        self.notice.setText(" ")
        self.remainDeck.setText("남은 카드 \n%d" % len(self.gm.cards))
        # 임의 부여함.




        # 들고 있는 카드의 list
        self.deckList = [[self.player0Deck0, self.player0Deck1, self.player0Deck2, self.player0Deck3],
                         [self.player1Deck0, self.player1Deck1, self.player1Deck2, self.player1Deck3],
                         [self.player2Deck0, self.player2Deck1, self.player2Deck2, self.player2Deck3],
                         [self.player3Deck0, self.player3Deck1, self.player3Deck2, self.player3Deck3]]

        # 낸 카드의 list
        self.drpoedCardList = [self.playedRed, self.playedGreen, self.playedBlue, self.playedWhite, self.playedYellow]

        # 버린 카드의 list
        self.thrownCardList = [[self.throwR1, self.throwR2, self.throwR3, self.throwR4, self.throwR5],
                               [self.throwG1, self.throwG2, self.throwG3, self.throwG4, self.throwG5],
                               [self.throwB1, self.throwB2, self.throwB3, self.throwB4, self.throwB5],
                               [self.throwW1, self.throwW2, self.throwW3, self.throwW4, self.throwW5],
                               [self.throwY1, self.throwY2, self.throwY3, self.throwY4, self.throwY5]]

        # 힌트 토큰의 list
        self.hintTokenList = [self.hintToken0, self.hintToken1, self.hintToken2, self.hintToken3,
                              self.hintToken4, self.hintToken5, self.hintToken6, self.hintToken7]

        # 목숨 토큰의 list
        self.lifeTokenList = [self.lifeToken0, self.lifeToken1, self.lifeToken2]

        for card in self.drpoedCardList:
            card.setText("0")
        print(type(self.player3Deck2))
        for deck in self.gm.playerDecks:
            print(deck)
        for i, deck in enumerate(self.deckList):
            # clinet 위치를 어떻게 잡느냐가 관건..
            # 아래 주석은 자신의 카드를 가리기 위한 코드. test 시에는 무시하고 진행한다.
            '''
            if i == self.clientIndex:
                for j in range(4):
                    SetCardDesign("mine", deck[j])
            '''
            for j in range(4):
                SetCardDesign(self.gm.playerDecks[i].getCardOrNone(j).getColor(), deck[j])
                deck[j].setText(str(self.gm.playerDecks[i].getCardOrNone(j)))

        self.btnThrow.clicked.connect(self.ShowThrowDeck)
        self.btnDrop.clicked.connect(self.ShowDropDeck)
        self.btnGiveHint.clicked.connect(self.ShowGiveHint)
        # 다음 내용은 불변.
        # 창 아이콘
        self.setWindowIcon(QIcon('Hanabi.PNG'))
        # 창크기 조절, 출력
        self.setFixedSize(1910, 990)
        self.setWindowTitle('Hanabi')
        self.show()