Ejemplo n.º 1
0
    def setupSceneItems(self):
        if Colors.showFps:
            self.fpsLabel = DemoTextItem("FPS: --", Colors.buttonFont(),
                    Qt.white, -1, None, DemoTextItem.DYNAMIC_TEXT)
            self.fpsLabel.setZValue(1000)
            self.fpsLabel.setPos(Colors.stageStartX,
                    600 - QFontMetricsF(Colors.buttonFont()).height() - 5)

        self.mainSceneRoot = QGraphicsWidget()
        self.scene.addItem(self.mainSceneRoot)

        self.companyLogo = ImageItem(
                QImage(self.imagesDir + '/trolltech-logo.png'),
                1000, 1000, None, True, 0.5)
        self.qtLogo = ImageItem(QImage(self.imagesDir + '/qtlogo_small.png'),
                1000, 1000, None, True, 0.5)
        self.companyLogo.setZValue(100)
        self.qtLogo.setZValue(100)
        self.pausedLabel = DemoTextItem("PAUSED", Colors.buttonFont(),
                Qt.white, -1, None)
        self.pausedLabel.setZValue(100)
        fm = QFontMetricsF(Colors.buttonFont())
        self.pausedLabel.setPos(Colors.stageWidth - fm.width("PAUSED"),
                590 - fm.height())
        self.pausedLabel.setRecursiveVisible(False)
Ejemplo n.º 2
0
    def drawMarkings(self, painter):
        painter.save()
        painter.translate(self.width() / 2, self.height() / 2)
        scale = min((self.width() - self._margins) / 120.0,
                    (self.height() - self._margins) / 120.0)
        painter.scale(scale, scale)

        font = QFont(self.font())
        font.setPixelSize(8)
        metrics = QFontMetricsF(font)

        painter.setFont(font)
        painter.setPen(QPen(QColor(self.scaleColor)))
        tickInterval = 5
        i = 0
        while i < 360:

            if i % 45 == 0:
                painter.drawLine(0, -40, 0, -50)
                painter.drawText(int(-metrics.width(self._pointText[i]) / 2.0),
                                 -52, self._pointText[i])
            else:
                painter.drawLine(0, -45, 0, -50)

            painter.rotate(tickInterval)
            i += tickInterval

        painter.restore()
    def draw_markings(self, painter):
        """ draw markings"""
        painter.save()
        painter.translate(self.width() / 2, self.height() / 2)
        scale = min((self.width() - self._margins) / 120.0,
                    (self.height() - self._margins) / 120.0)
        painter.scale(scale, scale)

        font = QFont(self.font())
        font.setPixelSize(10)
        metrics = QFontMetricsF(font)

        painter.setFont(font)
        painter.setPen(QPen(QBrush(Qt.black), 1, Qt.SolidLine))

        i = 0
        while i < 360:

            if i % 45 == 0:
                painter.drawLine(0, -40, 0, -50)
                painter.drawText(-metrics.width(self._pointText[i]) / 2.0, -52,
                                 self._pointText[i])
            else:
                painter.drawLine(0, -45, 0, -50)

            painter.rotate(15)
            i += 15

        painter.restore()
Ejemplo n.º 4
0
 def minimumSizeHint(self):
     font = QFont(self.font())
     font.setPointSize(font.pointSize() - 1)
     fm = QFontMetricsF(font)
     return QSize(
         fm.width(FractionSlider.WSTRING) * self.__denominator,
         (fm.height() * 4) + FractionSlider.YMARGIN)
Ejemplo n.º 5
0
    def draw_markings(self, painter):
        painter.save()
        painter.translate(self.width()/2, self.height()/2)
        scale = min((self.width() - self._margins)/120.0, (self.height() - self._margins)/120.0)
        painter.scale(scale, scale)

        font = QFont(self.font())
        font.setPixelSize(12)
        metrics = QFontMetricsF(font)

        painter.setFont(font)
        painter.setPen(self.palette().color(QPalette.WindowText))

        i = 0
        while i < 360:
            if i % 45 == 0:
                painter.drawLine(0, -40, 0, -50)
                painter.drawText(-metrics.width(self._point_text[i])/2.0, -52, self._point_text[i])
            else:
                painter.drawLine(0, -45, 0, -50)

            painter.rotate(15)
            i += 15

        painter.restore()
Ejemplo n.º 6
0
    def __init__(self, leftFlow=0, rightFlow=0, maxFlow=100, parent=None):
        super(YPipeWidget, self).__init__(parent)

        self.leftSpinBox = QSpinBox(
            self)  # 因为不会对其进行布局,所以使用self将其父声明为YPipeWidget
        self.leftSpinBox.setRange(0, maxFlow)
        self.leftSpinBox.setValue(leftFlow)
        self.leftSpinBox.setSuffix(" 升每秒")
        self.leftSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.leftSpinBox.valueChanged.connect(self.valueChanged)
        self.rightSpinBox = QSpinBox(self)
        self.rightSpinBox.setRange(0, maxFlow)
        self.rightSpinBox.setValue(rightFlow)
        self.rightSpinBox.setSuffix(" 升每秒")
        self.rightSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.rightSpinBox.valueChanged.connect(self.valueChanged)

        self.label = QLabel(self)
        self.label.setFrameStyle(
            QFrame.WinPanel
            | QFrame.Raised)  #其接受两个对象,第一个是frame sharp,第二个是shadow style。
        self.label.setLineWidth(2)
        self.label.setAlignment(Qt.AlignCenter)
        fm = QFontMetricsF(self.font())
        self.label.setMinimumWidth(fm.width(" 666999 升每秒666 "))  #设置下方最大宽度

        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.setMinimumSize(self.minimumSizeHint())
        self.valueChanged()
Ejemplo n.º 7
0
    def draw_markings(self, painter):
        painter.save()
        painter.translate(self.width() / 2, self.height() / 2)
        scale = min((self.width() - self._margins) / 120.0,
                    (self.height() - self._margins) / 120.0)
        painter.scale(scale, scale)

        font = QFont(self.font())
        font.setPixelSize(12)
        metrics = QFontMetricsF(font)

        painter.setFont(font)
        painter.setPen(self.palette().color(QPalette.WindowText))

        i = 0
        while i < 360:
            if i % 45 == 0:
                painter.drawLine(0, -40, 0, -50)
                painter.drawText(-metrics.width(self._point_text[i]) / 2.0,
                                 -52, self._point_text[i])
            else:
                painter.drawLine(0, -45, 0, -50)

            painter.rotate(15)
            i += 15

        painter.restore()
Ejemplo n.º 8
0
    def drawDirections(self, painter):
        painter.save()
        painter.translate(self.width() / 2,
                          self.height() /
                          2)  # Centers the position on the widget.
        scale = min((self.width() - self.margins) / 120,
                    (self.height() - self.margins) / 120)
        painter.scale(scale, scale)

        font = QFont(self.font())
        font.setPixelSize(10)
        metrics = QFontMetricsF(font)

        painter.setFont(font)
        painter.setPen(self.palette().color(QPalette.Shadow))

        i = 0
        while i < 360:
            # Check if it should draw the directions or if it should draw the lines between the directions.
            if i % 45 == 0:
                painter.drawLine(0, -40, 0, -50)
                painter.drawText(-metrics.width(self.directions[i]) / 2, -52,
                                 self.directions[i])
            else:
                painter.drawLine(0, -45, 0, -50)
            painter.rotate(15)
            i += 15
        painter.restore()
Ejemplo n.º 9
0
    def __init__(self, leftFlow=0, rightFlow=0, maxFlow=100, parent=None):
        super(YPipeWidget, self).__init__(parent)

        self.leftSpinBox = QSpinBox(self)
        self.leftSpinBox.setRange(0, maxFlow)
        self.leftSpinBox.setValue(leftFlow)
        self.leftSpinBox.setSuffix(" l/s")
        self.leftSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.leftSpinBox.valueChanged.connect(self.valueChanged)
        self.rightSpinBox = QSpinBox(self)
        self.rightSpinBox.setRange(0, maxFlow)
        self.rightSpinBox.setValue(rightFlow)
        self.rightSpinBox.setSuffix(" l/s")
        self.rightSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.rightSpinBox.valueChanged.connect(self.valueChanged)

        self.label = QLabel(self)
        self.label.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        self.label.setAlignment(Qt.AlignCenter)
        fm = QFontMetricsF(self.font())
        self.label.setMinimumWidth(fm.width(" 999 l/s "))

        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.setMinimumSize(self.minimumSizeHint())
        self.valueChanged()
Ejemplo n.º 10
0
    def setupSceneItems(self):
        if Colors.showFps:
            self.fpsLabel = DemoTextItem("FPS: --", Colors.buttonFont(),
                                         Qt.white, -1, None,
                                         DemoTextItem.DYNAMIC_TEXT)
            self.fpsLabel.setZValue(1000)
            self.fpsLabel.setPos(
                Colors.stageStartX,
                600 - QFontMetricsF(Colors.buttonFont()).height() - 5)

        self.mainSceneRoot = QGraphicsWidget()
        self.scene.addItem(self.mainSceneRoot)

        self.companyLogo = ImageItem(
            QImage(self.imagesDir + '/trolltech-logo.png'), 1000, 1000, None,
            True, 0.5)
        self.qtLogo = ImageItem(QImage(self.imagesDir + '/qtlogo_small.png'),
                                1000, 1000, None, True, 0.5)
        self.companyLogo.setZValue(100)
        self.qtLogo.setZValue(100)
        self.pausedLabel = DemoTextItem("PAUSED", Colors.buttonFont(),
                                        Qt.white, -1, None)
        self.pausedLabel.setZValue(100)
        fm = QFontMetricsF(Colors.buttonFont())
        self.pausedLabel.setPos(Colors.stageWidth - fm.width("PAUSED"),
                                590 - fm.height())
        self.pausedLabel.setRecursiveVisible(False)
Ejemplo n.º 11
0
    def _drawLabels(self, painter: QPainter):
        """отображение подписей на осях"""
        f_m = QFontMetricsF(self._style['grid']['font'])
        pen = painter.pen()

        text = 'Расход, м³/сутки'
        offset_x = self._margins[0] + self.getDrawArea().width() / 2
        offset_x -= f_m.width(text) / 2
        offset_y = self.height() - self._margins[3] + f_m.height()
        offset_y += 20
        painter.setPen(self._style['grid']['border'])
        painter.drawText(QPointF(offset_x, offset_y), text)

        text = 'Напор, м'
        offset_x = 0 - f_m.height() - 5
        self._drawLabel(painter, f_m, offset_x, text)

        text = 'Мощность, кВт'
        offset_x = self._margins[0] + self.getDrawArea().width() + 10
        painter.setPen(self._charts['etl_pwr'].pen)
        self._drawLabel(painter, f_m, offset_x, text)

        text = 'КПД, %'
        offset_x = self._margins[0] + self.getDrawArea().width() + \
                   self._grid_divs['y1'].width + 40
        painter.setPen(self._charts['etl_eff'].pen)
        self._drawLabel(painter, f_m, offset_x, text)
        painter.setPen(pen)
Ejemplo n.º 12
0
    def drawTwoTexts(
        self,
        p: QPainter,
        firstRect: QRectF,
        secondRect: QRectF,
        innerRadius: float,
        value: float,
    ):
        if not self.m_format:
            return

        if self.useSystemFont:
            font = QFont(self.font())
        else:
            font = QFont('Noto Sans')

        font.setPixelSize(10)
        fm = QFontMetricsF(font)
        maxWidth = fm.width(self.valueToText(self.m_max))
        delta = innerRadius / maxWidth
        timeFontSize = font.pixelSize() * delta * 0.75
        font.setPixelSize(int(timeFontSize))
        p.setFont(font)
        timeTextRect = QRectF(firstRect)
        tomatoesTextRect = QRectF(secondRect)
        p.setPen(self.palette().text().color())
        p.drawText(timeTextRect, Qt.AlignCenter | Qt.AlignBottom,
                   self.valueToText(value))
        tomatoesFontSize = timeFontSize * 0.3
        font.setPixelSize(int(tomatoesFontSize))
        p.setFont(font)
        p.drawText(tomatoesTextRect, Qt.AlignHCenter, self.m_second_format)
Ejemplo n.º 13
0
    def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=50, position=1, parent=None, callback=None, alignment=1, valignment=1):
        QFrame.__init__(self, parent)
        self.numberControl = ToggleSwitch(onColor, offColor, initialState, maxSize, parent, callback)
        
        if position < 3:
            layout =  QVBoxLayout()
        else:
            layout = QHBoxLayout()
            
        self.lbl = lbl
        self.lblcontrol = QLabel(lbl, self)
        
        if position == 3: # left of switch
            self.lblcontrol.setAlignment(Qtc.AlignRight)
        elif position == 4: # right of switch
            self.lblcontrol.setAlignment(Qtc.AlignLeft)
        else:
            # Above or below
            self.lblcontrol.setAlignment(Qtc.AlignCenter)

        # add top or left
        if len(lbl) > 0:
            if position == 1 or position == 3:
                layout.addWidget(self.lblcontrol)

        layout.addWidget(self.numberControl)
        
        # Add bottom or right
        if len(lbl) > 0:
            if position == 2 or position == 4:
                layout.addWidget(self.lblcontrol)
                
        if alignment == 1:        
            halign = Qtc.AlignCenter
        elif alignment == 2:
            halign = Qtc.AlignLeft
        else:
            halign = Qtc.AlignRight

        if valignment == 1:
            valign = Qtc.AlignVCenter
        elif valignment == 2:
            valign = Qtc.AlignTop
        else:
            valign = Qtc.AlignBottom
            
        layout.setAlignment(halign | valign)
        # layout.setAlignment(Qtc.AlignCenter | Qtc.AlignVCenter)
        self.setLayout(layout)
        
        textfont = self.lblcontrol.font()
        metrics = QFontMetricsF(textfont)
        
        maxWidth = max( (maxSize+4),(maxSize*2 + metrics.width(lbl)) )
        maxHeight = max( (maxSize/2+4),(maxSize/2 + metrics.height()+2) )
        #print('Min size: ' + str(maxWidth) + " x " + str(maxHeight))
        
        self.setMinimumSize(int(maxWidth), int(maxHeight))

        self.show()
Ejemplo n.º 14
0
def setFontMetrics():
    """ Application must be running before you mess
    too much with Fonts in Qt5
    """
    global SEQUENCEFONT
    global SEQUENCEFONTMETRICS
    global SEQUENCEFONTCHARWIDTH
    global SEQUENCEFONTCHARHEIGHT
    global SEQUENCEFONTEXTRAWIDTH
    global SEQUENCETEXTXCENTERINGOFFSET
    global SEQUENCETEXTYCENTERINGOFFSET
    SEQUENCEFONT = QFont("Monaco")
    if hasattr(QFont, 'Monospace'):
        SEQUENCEFONT.setStyleHint(QFont.Monospace)
    SEQUENCEFONT.setFixedPitch(True)
    SEQUENCEFONTH = int(PATH_BASE_WIDTH / 3.)
    SEQUENCEFONT.setPixelSize(SEQUENCEFONTH)
    SEQUENCEFONTMETRICS = QFontMetricsF(SEQUENCEFONT)
    SEQUENCEFONTCHARWIDTH = SEQUENCEFONTMETRICS.width("A")
    SEQUENCEFONTCHARHEIGHT = SEQUENCEFONTMETRICS.height()
    SEQUENCEFONTEXTRAWIDTH = PATH_BASE_WIDTH - SEQUENCEFONTCHARWIDTH
    SEQUENCEFONT.setLetterSpacing(QFont.AbsoluteSpacing,
                                 SEQUENCEFONTEXTRAWIDTH)
    SEQUENCETEXTXCENTERINGOFFSET = SEQUENCEFONTEXTRAWIDTH / 4.
    SEQUENCETEXTYCENTERINGOFFSET = PATH_BASE_WIDTH * 0.6
Ejemplo n.º 15
0
 def updateTabWidth(self):
     if not hasattr(self, "_tabWidth"):
         return
     fM = QFontMetricsF(self.font())
     pixelWidth = fM.width(' ') * self._tabWidth
     document = self.document()
     opt = document.defaultTextOption()
     opt.setTabStop(pixelWidth)
     document.setDefaultTextOption(opt)
Ejemplo n.º 16
0
    def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=80, position=1, alignment=1, valignment=1, parent=None):
        QFrame.__init__(self, parent)
        self.numberControl = LEDIndicator(onColor, offColor, initialState, maxSize, parent)
        
        if position < 3:
            layout =  QVBoxLayout()
        else:
            layout = QHBoxLayout()
            
        if len(lbl) == 0:
            lbl = " "
        self.lbl = lbl
        self.lblcontrol = QLabel(lbl, self)
        self.lblcontrol.setAlignment(Qtc.AlignCenter)

        # add top or left
        if len(lbl) > 0:
            if position == 1 or position == 3:
                layout.addWidget(self.lblcontrol)
        else:
            self.hasLabel = False

        layout.addWidget(self.numberControl)
        
        # Add bottom or right
        if len(lbl) > 0:
            if position == 2 or position == 4:
                layout.addWidget(self.lblcontrol)
                
        if alignment == 1:        
            halign = Qtc.AlignCenter
        elif alignment == 2:
            halign = Qtc.AlignLeft
        else:
            halign = Qtc.AlignRight

        if valignment == 1:
            valign = Qtc.AlignVCenter
        elif valignment == 2:
            valign = Qtc.AlignTop
        else:
            valign = Qtc.AlignBottom
            
        layout.setAlignment(halign | valign)
        self.setLayout(layout)
        
        if (len(lbl) > 0):
            textfont = self.lblcontrol.font()
            metrics = QFontMetricsF(textfont)
            
            maxWidth = max( (maxSize+30),(maxSize + metrics.width(lbl)+4) )
            maxHeight = max( (maxSize+35),(maxSize + metrics.height()+2) )
            self.setMinimumSize(maxWidth, maxHeight)
        else:
            self.setMinimumSize(maxSize+2, maxSize+2)  

        self.show()
Ejemplo n.º 17
0
 def updateTabWidth(self):
     if not hasattr(self, "_tabWidth"):
         return
     fM = QFontMetricsF(self.font())
     pixelWidth = fM.width(' ') * self._tabWidth
     document = self.document()
     opt = document.defaultTextOption()
     opt.setTabStop(pixelWidth)
     document.setDefaultTextOption(opt)
Ejemplo n.º 18
0
 def paintEvent(self, event=None):
     font = QFont(self.font())
     font.setPointSize(font.pointSize() - 1)
     fm = QFontMetricsF(font)
     fracWidth = fm.width(FractionSlider.WSTRING)
     indent = fm.boundingRect("9").width() / 2.0
     if not X11:
         fracWidth *= 1.5
     span = self.width() - (FractionSlider.XMARGIN * 2)
     value = self.__numerator / float(self.__denominator)
     painter = QPainter(self)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setRenderHint(QPainter.TextAntialiasing)
     painter.setPen(self.palette().color(QPalette.Mid))
     painter.setBrush(self.palette().brush(QPalette.AlternateBase))
     painter.drawRect(self.rect())
     segColor = QColor(Qt.green).darker(120)
     segLineColor = segColor.darker()
     painter.setPen(segLineColor)
     painter.setBrush(segColor)
     painter.drawRect(FractionSlider.XMARGIN, FractionSlider.YMARGIN, span,
                      fm.height())
     textColor = self.palette().color(QPalette.Text)
     segWidth = span / self.__denominator
     segHeight = fm.height() * 2
     nRect = fm.boundingRect(FractionSlider.WSTRING)
     x = FractionSlider.XMARGIN
     yOffset = segHeight + fm.height()
     for i in range(self.__denominator + 1):
         painter.setPen(segLineColor)
         painter.drawLine(x, FractionSlider.YMARGIN, x, segHeight)
         painter.setPen(textColor)
         y = segHeight
         rect = QRectF(nRect)
         rect.moveCenter(QPointF(x, y + fm.height() / 2.0))
         # painter.drawText(rect, Qt.AlignCenter,
         # QString.number(i))
         painter.drawText(rect, Qt.AlignCenter, str(i))
         y = yOffset
         rect.moveCenter(QPointF(x, y + fm.height() / 2.0))
         painter.drawText(rect, Qt.AlignCenter, str(self.__denominator))
         painter.drawLine(QPointF(rect.left() + indent, y),
                          QPointF(rect.right() - indent, y))
         x += segWidth
     span = int(span)
     y = FractionSlider.YMARGIN - 0.5
     triangle = [
         QPointF(value * span, y),
         QPointF((value * span) + (2 * FractionSlider.XMARGIN), y),
         QPointF((value * span) + FractionSlider.XMARGIN, fm.height())
     ]
     painter.setPen(Qt.yellow)
     painter.setBrush(Qt.darkYellow)
     painter.drawPolygon(QPolygonF(triangle))
Ejemplo n.º 19
0
 def draw(self):
     painter = QPainter(self._neditor.viewport())
     painter.setPen(self.__color)
     metrics = QFontMetricsF(self._neditor.font())
     doc_margin = self._neditor.document().documentMargin()
     offset = self._neditor.contentOffset().x() + doc_margin
     x = round(metrics.width(' ') * self.__position) + offset
     if self.__background:
         width = self._neditor.viewport().width() - x
         rect = QRect(x, 0, width, self._neditor.height())
         painter.fillRect(rect, self.__background_color)
     painter.drawLine(x, 0, x, self._neditor.height())
Ejemplo n.º 20
0
 def draw(self):
     painter = QPainter(self._neditor.viewport())
     painter.setPen(self.__color)
     metrics = QFontMetricsF(self._neditor.font())
     doc_margin = self._neditor.document().documentMargin()
     offset = self._neditor.contentOffset().x() + doc_margin
     x = round(metrics.width(' ') * self.__position) + offset
     if self.__background:
         width = self._neditor.viewport().width() - x
         rect = QRect(x, 0, width, self._neditor.height())
         painter.fillRect(rect, self.__background_color)
     painter.drawLine(x, 0, x, self._neditor.height())
Ejemplo n.º 21
0
 def minimumSizeHint(self):
     '''定义字体、字体大小、根据字体Metrics的大小返回一个QSize对象,设置最小的尺寸'''
     font = QFont(self.font()) # 这声明了和没有声明有什么区别?Constructs a font that is a copy of font.
     # self.font() This property describes the widget's requested font.
     # font = QFont() # 只需要一个实例,因为此函数的目的是返回一个QSize
     font.setPointSize(font.pointSize() - 1) # The point size must be greater than zero. 
     # pointSize() Returns -1 if the font size was specified in pixels.
     fm = QFontMetricsF(font) 
     # print(fm.height(),fm.width(FractionSlider.WSTRING),fm.width(FractionSlider.WSTRING+'666')) # Return 11.0 18.0 36.0
     return QSize(fm.width(FractionSlider.WSTRING) *
                  self.__denominator,
                  (fm.height() * 4) + FractionSlider.YMARGIN)
Ejemplo n.º 22
0
 def _drawGridDivs_y(self, painter: QPainter, step: float, axis_name='y'):
     """отрисовка значений делений на оси Y"""
     if len(self._charts) > 0:
         logger.debug(f"{self._drawGridDivs_y.__doc__} {axis_name}")
         axis: Axis = self._charts[self._base_chart].getAxis(axis_name)
         fm = QFontMetricsF(self._style['grid']['font'])
         for i, div in axis.generateDivSteps():
             text = str(round(div, 8))
             offset_x = self._margins[0] - fm.width(text) - 10
             offset_y = self.height() - self._margins[3] + fm.height() / 4.0
             painter.drawText(QPointF(offset_x,
                                      offset_y - i * step),
                              text)
Ejemplo n.º 23
0
 def drawText(self, p: QPainter, innerRect: QRectF, innerRadius: float, value: float):
     if not self.m_format:
         return
     f = QFont(self.font())
     f.setPixelSize(10)
     fm = QFontMetricsF(f)
     maxWidth = fm.width(self.valueToText(self.m_max))
     delta = innerRadius / maxWidth
     fontSize = f.pixelSize() * delta * 0.75
     f.setPixelSize(int(fontSize))
     p.setFont(f)
     textRect = QRectF(innerRect)
     p.setPen(self.palette().text().color())
     p.drawText(textRect, Qt.AlignCenter, self.valueToText(value))
Ejemplo n.º 24
0
    def __init__(self, columns: int, rows: int, **kwargs: 'Any') -> None:
        super().__init__(device_type='console-text-display', **kwargs)

        self.__text_widget = text = QTextEdit()
        self.__col = 0
        self.__row = 0
        self.__total_cols = columns
        self.__total_rows = rows
        self.__text = ' ' * (self.__total_cols * self.__total_rows)
        self.__show_cursor = False

        text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        text.setFocusPolicy(Qt.NoFocus)

        text.setReadOnly(True)

        text.setStyleSheet('''

            color: white;
            background-color: black;
            border-color: black;
            border-width: 1px;
            border-style: solid;
        ''')

        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        text.setFont(font)

        tdoc = text.document()
        fmetrics = QFontMetricsF(tdoc.defaultFont())
        margins = text.contentsMargins()

        height = fmetrics.lineSpacing()*rows + \
            2*(tdoc.documentMargin() + text.frameWidth()) + \
                margins.top() + margins.bottom()


        width = fmetrics.width('A')*columns + \
            2*(tdoc.documentMargin() + text.frameWidth()) + \
                margins.left() + margins.right()

        text.setFixedHeight(height)
        text.setFixedWidth(width)
Ejemplo n.º 25
0
    def onClickGenerate(self):
        doc = self.teText.document()
        font = QFont()
        font.setPointSizeF(self.sbFontSize.value())
        doc.setDefaultFont(font)
        m = QFontMetricsF(font)

        nbLines = doc.lineCount()
        width = max([m.width(ll) for ll in doc.toPlainText().split("\n")])
        pixmap = QPixmap(width*1.2, m.lineSpacing()*nbLines*1.2)

        pixmap.fill(Qt.white)

        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing, True)
        doc.drawContents(painter)
        painter.end()

        self.laImg.setPixmap(pixmap)
        self.imgToBurn = QImage(pixmap.toImage())
Ejemplo n.º 26
0
 def _drawGridDivs_y(self, painter: QPainter, step: float, axis_name='y0'):
     """отрисовка значений делений на оси Y"""
     # logger.debug(f"{self._drawGridDivs_y.__doc__} {axis_name}")
     f_m = QFontMetricsF(self._style['grid']['font'])
     divs = self._grid_divs[axis_name].divs
     pen = painter.pen()
     painter.setPen(self._style['grid']['border'])
     for i in range(1, len(divs)):
         text = str(divs[i])
         offset_x = 0.0
         if axis_name == 'y0':
             offset_x = self._margins[0] - f_m.width(text) - 10
         elif axis_name == 'y1':
             offset_x = self._margins[0] + self.getDrawArea().width() + 10
             painter.setPen(self._charts['etl_pwr'].pen)
         elif axis_name == 'y2':
             offset_x = self._margins[0] + self.getDrawArea().width() + \
                        self._grid_divs['y1'].width + 40
             painter.setPen(self._charts['etl_eff'].pen)
         offset_y = self.height() - self._margins[3] + f_m.height() / 4.0
         painter.drawText(QPointF(offset_x, offset_y - i * step), text)
     painter.setPen(pen)
    def draw_markings(self, painter):
        """ draw markings"""

        painter.save()
        painter.translate(self.width() / 2, self.height() / 2)
        scale = min((self.width() - self._margins) / 120.0,
                    (self.height() - self._margins) / 120.0)
        painter.scale(scale, scale)

        font = QFont(self.font())
        font.setPixelSize(10)
        metrics = QFontMetricsF(font)

        painter.setFont(font)
        # painter.setPen(self.palette().color(QPalette.Shadow))
        painter.setPen(QPen(QBrush(Qt.black), 1, Qt.SolidLine))

        i = 0
        while i < 360:

            if i % 30 == 0:
                painter.drawLine(0, -40, 0, -50)
                # painter.setPen(self.palette().color(QPalette.Text))
                painter.drawText(-metrics.width(self._pointText[i]) / 2.0, -52,
                                 self._pointText[i])
                # painter.setPen(self.palette().color(QPalette.Shadow))
                if i == 0:
                    painter.setBrush(QBrush(self.brake_color))
                    painter.drawPie(-50, -50, 100, 100, 180 * 16, 16 * 90)
            else:
                painter.drawLine(0, -47, 0, -50)

            painter.rotate(15)
            i += 15

        painter.restore()
Ejemplo n.º 28
0
    def paintEvent(self, e):
        if not len(self.__cluster_container.clusters) or self.width(
        ) == 0 or self.height() == 0:
            return

        painter = QPainter(self)

        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QColor("transparent"))
        painter.setBrush(QColor("red"))

        fm = QFontMetricsF(painter.font())
        neighbor_id = self.__cluster_container.neighbor_id(self.__active_point)

        # draw objects
        for cluster in self.__cluster_container.clusters:
            try:
                painter.setBrush(
                    QColor(self.__colors[
                        self.__cluster_container.clusters.index(cluster)]))
            except IndexError:
                print("Run out of colors")
                exit(1)

            for obj in cluster.objects:
                painter.setPen(QColor("transparent"))
                painter.drawEllipse(obj.x(), obj.y(),
                                    ClustersView.PARTICLE_SIZE.width(),
                                    ClustersView.PARTICLE_SIZE.height())
                painter.setPen(QColor("gray"))
                painter.drawText(obj.pos - QPointF(0, 2), str(obj.id))

            used_cluster_obj, distance = cluster.distance_from_point(
                self.__active_point)
            center_of_obj = QPointF(
                used_cluster_obj.x() + ClustersView.PARTICLE_SIZE.width() / 2,
                used_cluster_obj.y() + ClustersView.PARTICLE_SIZE.height() / 2)

            # draw circle
            painter.setPen(QColor("gray"))
            painter.setBrush(QColor("transparent"))
            painter.setOpacity(0.5)
            painter.drawEllipse(center_of_obj,
                                ClustersView.PARTICLE_SIZE.width() * 2,
                                ClustersView.PARTICLE_SIZE.height() * 2)
            painter.setOpacity(1)

            #draw line
            painter.setPen(
                QColor("#007ACC" if neighbor_id ==
                       cluster.id else "lightGray"))
            painter.drawLine(self.__active_point, center_of_obj)

            #draw text
            formatted_distance = "{:.1f}".format(distance)
            painter.setPen(QColor("gray"))
            painter.drawText(
                center_of_obj -
                QPointF(fm.width(str(formatted_distance)) / 2, 25),
                str(formatted_distance))

        # draw text at active point
        coords = "[{:.1f} {:.1f}]".format(self.__active_point.x(),
                                          self.__active_point.y())
        painter.drawText(
            self.__active_point - QPointF(fm.width(coords) / 2, 15), coords)
Ejemplo n.º 29
0
	def boundingRect(self):
		fm = QFontMetricsF(self.font)
		width = 34 + fm.width(str(self.itemStack.ammount))
		return QRectF(0, 0, width, 35)
    def draw_markings(self, painter):
        """ draw markings"""

        size = self.size()
        w = size.width()
        h = size.height()

        font = QFont(self.font())
        font.setPixelSize(15)
        metrics = QFontMetricsF(font)

        painter.save()

        painter.translate(0, (self._pitch * h) / 25)
        painter.setRenderHint(painter.Antialiasing)

        painter.setPen(self.palette().color(QPalette.Shadow))
        painter.setFont(font)

        #-90º to 90º. steps 0.25º
        for i in range(-900, 925, 25):
            pos = (((i / 10.0) + 12.5) * h / 25.0)
            if i % 100 == 0:
                length = w
                painter.drawText(0, pos, "{}º".format(int(-i / 10)))
                painter.drawText(0, pos, "{}º".format(int(-i / 10)))

            elif i % 50 == 0:
                length = w
                if i != 0:
                    painter.drawText(0, pos, "{}º".format(int(-i / 10)))
                    painter.drawText(0, pos, "{}º".format(int(-i / 10)))

            else:
                length = 0.25 * w

            painter.drawLine((w / 2) - (length / 2), pos,
                             (w / 2) + (length / 2), pos)

        painter.setWorldMatrixEnabled(False)

        painter.restore()
        painter.save()
        painter.translate(self.width() / 2, self.height() / 2)
        scale = min((self.width() - self._margins) / 120.0,
                    (self.height() - self._margins) / 120.0)
        painter.scale(scale, scale)

        font.setPixelSize(10)
        painter.setFont(font)
        painter.setPen(QPen(QBrush(Qt.black), 1, Qt.SolidLine))

        i = 0
        while i < 360:

            if i % 30 == 0:
                painter.drawLine(0, -38, 0, -46)
                # painter.setPen(self.palette().color(QPalette.Text))
                painter.drawText(-metrics.width(self._pointText[i]) / 2.0, -48,
                                 self._pointText[i])
                # painter.setPen(self.palette().color(QPalette.Shadow))

            # else:
            # painter.drawLine(0, -46, 0, -48)

            painter.rotate(15)
            i += 15

        painter.restore()
Ejemplo n.º 31
0
	def GetWidth(self):
		fm = QFontMetricsF(self.font)
		return 34 + fm.width(str(self.itemStack.ammount))
Ejemplo n.º 32
0
    def createGraphics(self):
        """ Create the graphical representation of the FMU's inputs and outputs """
        def variableColor(variable):
            if variable.type == 'Real':
                return QColor.fromRgb(0, 0, 127)
            elif variable.type in ['Integer', 'Enumeration']:
                return QColor.fromRgb(255, 127, 0)
            elif variable.type == 'Boolean':
                return QColor.fromRgb(255, 0, 255)
            elif variable.type == 'String':
                return QColor.fromRgb(0, 128, 0)
            else:
                return QColor.fromRgb(0, 0, 0)

        inputVariables = []
        outputVariables = []
        maxInputLabelWidth = 0
        maxOutputLabelWidth = 0

        textItem = QGraphicsTextItem()
        fontMetrics = QFontMetricsF(textItem.font())

        for variable in self.modelDescription.modelVariables:
            if variable.causality == 'input':
                inputVariables.append(variable)
            elif variable.causality == 'output':
                outputVariables.append(variable)

        for variable in inputVariables:
            maxInputLabelWidth = max(maxInputLabelWidth,
                                     fontMetrics.width(variable.name))

        for variable in outputVariables:
            maxOutputLabelWidth = max(maxOutputLabelWidth,
                                      fontMetrics.width(variable.name))

        from math import floor

        scene = QGraphicsScene()
        self.ui.graphicsView.setScene(scene)
        group = QGraphicsItemGroup()
        scene.addItem(group)
        group.setPos(200.5, -50.5)
        lh = 15  # line height

        w = max(150., maxInputLabelWidth + maxOutputLabelWidth + 20)
        h = max(50., 10 + lh * max(len(inputVariables), len(outputVariables)))

        block = QGraphicsRectItem(0, 0, w, h, group)
        block.setPen(QColor.fromRgb(0, 0, 255))

        pen = QPen()
        pen.setWidthF(1)

        font = QFont()
        font.setPixelSize(10)

        # inputs
        y = floor((h - len(inputVariables) * lh) / 2 - 2)
        for variable in inputVariables:
            text = QGraphicsTextItem(variable.name, group)
            text.setDefaultTextColor(QColor.fromRgb(0, 0, 255))
            text.setFont(font)
            text.setX(3)
            text.setY(y)

            polygon = QPolygonF([
                QPointF(-13.5, y + 4),
                QPointF(1, y + 11),
                QPointF(-13.5, y + 18)
            ])

            path = QPainterPath()
            path.addPolygon(polygon)
            path.closeSubpath()
            contour = QGraphicsPathItem(path, group)
            contour.setPen(QPen(Qt.NoPen))
            contour.setBrush(variableColor(variable))

            y += lh

        # outputs
        y = floor((h - len(outputVariables) * lh) / 2 - 2)
        for variable in outputVariables:
            text = QGraphicsTextItem(variable.name, group)
            text.setDefaultTextColor(QColor.fromRgb(0, 0, 255))
            text.setFont(font)
            text.setX(w - 3 - text.boundingRect().width())
            text.setY(y)

            polygon = QPolygonF([
                QPointF(w, y + 0 + 7.5),
                QPointF(w + 7, y + 3.5 + 7.5),
                QPointF(w, y + 7 + 7.5)
            ])

            path = QPainterPath()
            path.addPolygon(polygon)
            path.closeSubpath()
            contour = QGraphicsPathItem(path, group)
            pen = QPen()
            pen.setColor(variableColor(variable))
            pen.setJoinStyle(Qt.MiterJoin)
            contour.setPen(pen)

            y += lh
Ejemplo n.º 33
0
class DialGauge(QFrame):
    def __init__(self,
                 barColor='blue',
                 backgroundColor='white',
                 fontColor='black',
                 minValue=0,
                 maxValue=100,
                 maxSize=80,
                 isFloat=False,
                 showValue=False,
                 fixedOrMin=True,
                 parent=None):
        QFrame.__init__(self, parent)

        self.maxSize = maxSize
        super().setMinimumSize(maxSize, maxSize)
        if fixedOrMin:
            super().setMaximumSize(maxSize, maxSize)

        self.backgroundColor = backgroundColor
        self.barColor = barColor
        self.fontColor = fontColor
        self.isFloat = isFloat
        self.showValue = showValue

        self.value = minValue

        self.minValue = minValue
        self.maxValue = maxValue

        self.textfont = QFont(self.font())
        #font.setPixelSize(10)
        self.textfont.setPixelSize(16)
        self.metrics = QFontMetricsF(self.textfont)

        self.startAngle = 0.0
        self.endAngle = 360.0
        self.degScaler = 16.0  # The span angle must be specified in 1/16 of a degree units
        self.penWidth = max(int(0.1 * maxSize), 6)
        self.halfPenWidth = int(self.penWidth / 2)

    def getValue(self):
        if (isFloat):
            return float(self.value)
        else:
            return int(self.value)

    def setValue(self, newValue):
        if newValue > self.maxValue:
            newValue = self.maxValue
        elif newValue < self.minValue:
            newValue = self.minValue

        self.value = float(newValue)

        super().update()

    def paintEvent(self, event):
        super().paintEvent(event)

        #self.painter.setPen(self.backgroundColor)
        size = self.size()

        percentRange = float(self.value -
                             self.minValue) / float(self.maxValue -
                                                    self.minValue)
        endAngle = self.startAngle + round(
            percentRange * float(self.endAngle - self.startAngle), 0)

        # Now convert angles to 1/16 scale
        startAngle = int(round(self.startAngle * self.degScaler, 0))
        endAngle = int(round(endAngle * self.degScaler, 0))

        rect = QtCore.QRect(self.halfPenWidth, self.halfPenWidth,
                            size.width() - self.penWidth,
                            size.height() - self.penWidth)
        brush = QBrush(QColor(self.backgroundColor))

        # Set up the painting canvass
        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)

        if self.showValue:
            painter.setFont(self.textfont)
            # painter.setPen(QPen(Qtc.black))
            painter.setPen(QPen(QColor(self.fontColor)))

            if (self.isFloat):
                printText = "%.2f" % self.value
            else:
                printText = str(int(self.value))

            painter.drawText(
                size.width() / 2 - self.metrics.width(printText) / 2,
                size.height() / 2, printText)

        painter.save()
        # painter.translate(self.width()/2, self.height()/2)
        painter.translate(self.width(), 0)
        # painter.scale(self.width()/120.0, self.width()/120.0)
        painter.rotate(90.0)

        # First draw complete circle
        painter.setPen(QPen(QColor(self.backgroundColor), self.penWidth))
        painter.drawArc(rect, startAngle, self.endAngle * self.degScaler)
        # First draw complete circle
        painter.setPen(QPen(QColor(self.barColor), self.penWidth))
        painter.drawArc(rect, startAngle, -endAngle)
        painter.setPen(QPen(QColor('darkgray'), 2))
        painter.drawEllipse(1, 1,
                            rect.width() + self.penWidth - 2,
                            rect.width() + self.penWidth - 2)
        painter.drawEllipse(1 + self.penWidth, 1 + self.penWidth,
                            rect.width() - self.penWidth - 2,
                            rect.width() - self.penWidth - 2)
        painter.restore()

        painter.end()
Ejemplo n.º 34
0
    def paintEvent(self, event=None):
        font = QFont(self.font())
        font.setPointSize(font.pointSize() - 1)
        # Returns -1 if the font size was specified in pixels.
        fm = QFontMetricsF(font)
        fracWidth = fm.width(FractionSlider.WSTRING) # 一个字母所占的宽度
        indent = fm.boundingRect("9").width() / 2.0 # 半个字母的宽度
        # Returns the bounding rectangle of the characters in the string specified by text. 
        if not X11:
            fracWidth *= 1.5
        span = self.width() - (FractionSlider.XMARGIN * 2) # 尺子的宽度
        value = self.__numerator / float(self.__denominator) # 当前滑块的值

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing) # 设置抗锯齿
        painter.setRenderHint(QPainter.TextAntialiasing) # 设置字体抗锯齿
        painter.setPen(self.palette().color(QPalette.Midlight)) # setPen 可以接受Pen、PenStyle、Color对象 这里指的是Color
        # painter.setPen(QColor(220,100,100)) # 这里设置的是QWidght的边框
        painter.setBrush(self.palette().brush(
                QPalette.AlternateBase))
        # setBrush() : Sets the brush for the given color role to the specified brush for all groups in the palette.
        # [Color Role] QPalette.AlternateBase : Used as the alternate background color in views with alternating row colors
        # self.palette() This property holds the widget's palette 其会和默认的调色版混合呈现,但是其一般不能传递到窗口,需要特殊设置,推荐使用CSS 
        painter.drawRect(self.rect())
        segColor = QColor(Qt.gray).lighter(80) # 尺度条颜色:lighter(factor) 150表示50%亮,对于darker(factor) 300表示3倍暗
        segLineColor = segColor.darker() # 默认200 lighter默认 150
        painter.setPen(segLineColor)
        painter.setBrush(segColor)
        painter.drawRect(FractionSlider.XMARGIN,
                         FractionSlider.YMARGIN, span, fm.height())
        textColor = self.palette().color(QPalette.Text)
        segWidth = span / self.__denominator
        segHeight = fm.height() * 2
        nRect = fm.boundingRect(FractionSlider.WSTRING)
        x = FractionSlider.XMARGIN
        yOffset = segHeight + fm.height()
        for i in range(self.__denominator + 1):
            painter.setPen(segLineColor) # 设置线的颜色作为Pen
            painter.drawLine(x, FractionSlider.YMARGIN, x, segHeight) # 划竖线,从(x,ymargin)开始,到(x,segheight)为止。
            painter.setPen(textColor)
            y = segHeight
            rect = QRectF(nRect)
            rect.moveCenter(QPointF(x, y + fm.height() / 2.0))
            #painter.drawText(rect, Qt.AlignCenter,
                             #QString.number(i))
            painter.drawText(rect, Qt.AlignCenter,str(i))            
            y = yOffset
            rect.moveCenter(QPointF(x, y + fm.height() / 2.0))
            painter.drawText(rect, Qt.AlignCenter,
                             str(self.__denominator))
            painter.drawLine(QPointF(rect.left() + indent, y),
                             QPointF(rect.right() - indent, y))
            x += segWidth
        span = int(span)
        y = FractionSlider.YMARGIN - 0.5
        triangle = [QPointF(value * span, y),
                    QPointF((value * span) +
                            (2 * FractionSlider.XMARGIN), y),
                    QPointF((value * span) +
                            FractionSlider.XMARGIN, fm.height())]
        triangledict = (QPointF(value * span, y),
                    QPointF((value * span) +
                            (2 * FractionSlider.XMARGIN), y),
                    QPointF((value * span) +
                            FractionSlider.XMARGIN, fm.height()))
        painter.setPen(QColor(Qt.yellow).darker(100))
        # painter.setBrush(Qt.darkYellow)
        painter.setBrush(QColor(Qt.yellow).darker(200))
        painter.drawPolygon(QPolygonF(triangle))