Exemple #1
0
    def __init__(self, parent, limit=default_limit):
        QtGui.QPlainTextEdit.__init__(self, parent)
        self.summary_line = -1
        self.draw_summary_limit = False
        self.text_font = QtGui.QFont('Bitstream Vera Sans Mono', 10)
        #        self.text_font.setStyleHint(QtGui.QFont.TypeWriter)
        self.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap)
        self.metrics = QtGui.QFontMetrics(self.text_font)
        self.margin = self.document().documentMargin()
        self.limit = self.metrics.width('a' * limit) + self.margin
        self.setTabStopWidth(self.metrics.width(' ' * 8))
        self.document().setDefaultFont(self.text_font)
        self.limit_pen = QtGui.QPen(QtCore.Qt.lightGray)
        self.limit_pen.setStyle(QtCore.Qt.DotLine)

        self.highlight = Highlighter(self.document(), limit)
        self.lineNumbers = LineNumbers(self)

        self.summary_line_changed.connect(self.highlight.set_summary_line)
        self.textChanged.connect(self.changed)
        self.textChanged.connect(self.pos_update)
        self.blockCountChanged.connect(self.updateLineNumbersWidth)
        self.updateRequest.connect(self.updateLineNumbers)
        self.updateLineNumbersWidth()
        self.cursorPositionChanged.connect(self.pos_update)
Exemple #2
0
 def __naturalsh(self):
     fm = QtGui.QFontMetrics(self.font())
     spacing = self.__spacing
     N = len(self.__items)
     width = max((fm.width(text) for text in self.__items), default=0)
     height = N * fm.height() + (N - 1) * spacing
     return QSizeF(width, height)
Exemple #3
0
    def __init__(self, width, height, data):
        super(ViewMode, self).__init__()

        self.dataModel = data
        self.width = width
        self.height = height
        self.cursorX = 0
        self.cursorY = 0

        self.refresh = True

        self.addHandler(self.dataModel)

        # background brush
        self.backgroundBrush = QtGui.QBrush(QtGui.QColor(0, 0, 128))

        # text font
        self.font = QtGui.QFont('Terminus', 12, QtGui.QFont.Light)

        # font metrics. assume font is monospaced
        self.font.setKerning(False)
        self.font.setFixedPitch(True)
        fm = QtGui.QFontMetrics(self.font)
        self.fontWidth = fm.width('a')
        self.fontHeight = fm.height()

        self.Special = string.ascii_letters + string.digits + ' .;\':;=\"?-!()/\\_'

        self.textPen = QtGui.QPen(QtGui.QColor(192, 192, 192), 1,
                                  QtCore.Qt.SolidLine)
        self.resize(width, height)
    def __init__(self, text, textType, parent=None):
        super(TextEditorWidget, self).__init__(parent)

        font = QtGui.QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)

        fontmetrics = QtGui.QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(0, fontmetrics.width("00000") + 6)
        self.setMarginLineNumbers(0, True)
        self.setMarginsBackgroundColor(QtGui.QColor("#cccccc"))

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QtGui.QColor("#ffe4e4"))

        if textType == CSS:
            lexer = QsciLexerCSS()
        elif textType == JSON:
            lexer = QsciLexerJavaScript()
        else:
            lexer = QsciLexerHTML()
        lexer.setDefaultFont(font)
        self.setLexer(lexer)
        self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier')

        self.setText(text)
Exemple #5
0
 def sizeHint(self):
     metrics = QtGui.QFontMetrics(self.font())
     # On Mac OS X 10.8, the scrollbar doesn't show up correctly
     # with 3 lines
     return QtCore.QSize(
         QtGui.QTextEdit.sizeHint(self).width(),
         (metrics.height() + 1) * 4 + 5)
Exemple #6
0
    def __init__(self, args):
        self.width = args.width
        self.height = args.height
        self.keys = []
        self.app = QtGui.QApplication(sys.argv)
        super(Terminal, self).__init__()
        
        self.font = QtGui.QFont("Monospace", 10)
        self.font.setStyleHint(QtGui.QFont.TypeWriter)
        font_metrics = QtGui.QFontMetrics(self.font)
        self.cell_width = font_metrics.maxWidth() + 2
        self.cell_height = font_metrics.height()
        win_width = self.cell_width * args.width
        win_height = self.cell_height * args.height

        self.pixmap_buffer = QtGui.QPixmap(win_width, win_height)
        self.pixmap_buffer.fill(Qt.black)
        
        self.resize(win_width, win_height)
        self.setMinimumSize(win_width, win_height)
        self.setMaximumSize(win_width, win_height)
        self.setWindowTitle("DCPU-16 terminal")
        
        self.app.setQuitOnLastWindowClosed(False)
        self.closed = False
    def setFontSize(self, newFontSize):
        oldValue = self.scrollbar.value()
        oldCellWidth = QtGui.QFontMetrics(self.font).width("W")

        self.fontSize = newFontSize
        self.font = QtGui.QFont(self.fontName, self.fontSize)
        self.fontMetrics = QtGui.QFontMetrics(
            self.font)  #How do I do this correctly so I don't duplicate code?
        self.updatePanelHeight()

        newValue = self.scrollbar.value()
        newCellWidth = QtGui.QFontMetrics(self.font).width("W")
        ratio = float(newCellWidth / oldCellWidth)

        self.emit(QtCore.SIGNAL('SequencePanelUpdate'))
        self.scrollbar.setValue(int(oldValue * ratio))
Exemple #8
0
    def paint_event_text_doesnt_fit_test(self):
        """
        Test the paintEvent method when text fits the label
        """
        font = QtGui.QFont()
        metrics = QtGui.QFontMetrics(font)

        with patch('openlp.core.ui.slidecontroller.QtGui.QLabel'), \
                patch('openlp.core.ui.slidecontroller.QtGui.QPainter') as mocked_qpainter:

            # GIVEN: An instance of InfoLabel, with mocked text return, width and rect methods
            info_label = InfoLabel()
            test_string = 'Label Text'
            mocked_rect = MagicMock()
            mocked_text = MagicMock()
            mocked_width = MagicMock()
            mocked_text.return_value = test_string
            info_label.rect = mocked_rect
            info_label.text = mocked_text
            info_label.width = mocked_width

            # WHEN: The instance is narrower than its text, and the paintEvent method is called
            label_width = metrics.boundingRect(test_string).width() - 10
            info_label.width.return_value = label_width
            info_label.paintEvent(MagicMock())

            # THEN: The text should be drawn aligned left with an elided test_string
            elided_test_string = metrics.elidedText(test_string, QtCore.Qt.ElideRight, label_width)
            mocked_qpainter().drawText.assert_called_once_with(mocked_rect(), QtCore.Qt.AlignLeft, elided_test_string)
Exemple #9
0
    def paintEvent(self, event):
        retval = super(PMXCodeEdit, self).paintEvent(event)
        font_metrics = QtGui.QFontMetrics(self.document().defaultFont())

        if self.multiEditMode:
            painter = QtGui.QPainter(self.viewport())
            extraSelections = []
            for cursor in self.cursors:
                if cursor.hasSelection():
                    selection = QtGui.QTextEdit.ExtraSelection()
                    selection.format.setBackground(QtCore.Qt.gray)
                    selection.format.setProperty(
                        QtGui.QTextFormat.FullWidthSelection, True)
                    selection.cursor = cursor
                    extraSelections.append(selection)
                rec = self.cursorRect(cursor)
                cursor = QtCore.QLine(
                    rec.x(), rec.y(), rec.x(),
                    rec.y() + font_metrics.ascent() + font_metrics.descent())
                painter.setPen(QtGui.QPen(QtCore.Qt.blue))
                painter.drawLine(cursor)
            self.setExtraSelections(extraSelections)
            if self.cursors.isDragCursor:
                pen = QtGui.QPen(QtCore.Qt.blue)
                pen.setWidth(2)
                painter.setPen(pen)
                color = QtGui.QColor(QtCore.Qt.yellow)
                color.setAlpha(128)
                painter.setBrush(QtGui.QBrush(color))
                painter.setOpacity(0.2)
                painter.drawRect(self.cursors.getDragCursorRect())
            painter.end()
        return retval
Exemple #10
0
 def headerData(self, section, orientation, role):
     """In case the columns have not been set yet, don't even try to get
     information out of them
     """
     assert object_thread(self)
     if orientation == Qt.Vertical:
         if role == Qt.SizeHintRole:
             if self.header_icon != None:
                 return QtCore.QVariant(
                     QtCore.QSize(self.iconSize.width() + 10,
                                  self._vertical_header_height))
             else:
                 # if there is no icon, the line numbers will be displayed, so create some space for those
                 return QtCore.QVariant(
                     QtCore.QSize(
                         QtGui.QFontMetrics(self._header_font).size(
                             Qt.TextSingleLine, str(self._rows)).width() +
                         10, self._vertical_header_height))
         if role == Qt.DecorationRole:
             return self.form_icon
         elif role == Qt.DisplayRole:
             if self.header_icon != None:
                 return QtCore.QVariant('')
     return super(CollectionProxy, self).headerData(section, orientation,
                                                    role)
Exemple #11
0
    def paint_event_text_fits_test(self):
        """
        Test the paintEvent method when text fits the label
        """
        font = QtGui.QFont()
        metrics = QtGui.QFontMetrics(font)

        with patch('openlp.core.ui.slidecontroller.QtGui.QLabel'), \
                patch('openlp.core.ui.slidecontroller.QtGui.QPainter') as mocked_qpainter:

            # GIVEN: An instance of InfoLabel, with mocked text return, width and rect methods
            info_label = InfoLabel()
            test_string = 'Label Text'
            mocked_rect = MagicMock()
            mocked_text = MagicMock()
            mocked_width = MagicMock()
            mocked_text.return_value = test_string
            info_label.rect = mocked_rect
            info_label.text = mocked_text
            info_label.width = mocked_width

            # WHEN: The instance is wider than its text, and the paintEvent method is called
            info_label.width.return_value = metrics.boundingRect(test_string).width() + 10
            info_label.paintEvent(MagicMock())

            # THEN: The text should be drawn centered with the complete test_string
            mocked_qpainter().drawText.assert_called_once_with(mocked_rect(), QtCore.Qt.AlignCenter, test_string)
    def update_pixmap(self):
        font = QtGui.QFont("Courier", self.fsize)
        fm = QtGui.QFontMetrics(font)
        height = fm.leading() + fm.overlinePos() + fm.underlinePos()
        #width  = fm.size(QtCore.Qt.AlignTop, self.seq).width()
        width = self.fsize * len(self.seq)

        self.pixmap = QtGui.QPixmap(width,height)
        self.pixmap.fill()
        p = QtGui.QPainter(self.pixmap)
        x = 0
        y = height - fm.underlinePos()*2

        p.setFont(font)

        for letter in self.seq:
            letter = letter.upper()
            if self.style=="nt":
                letter_brush = QtGui.QBrush(QtGui.QColor(self.ntbg.get(letter,"#ffffff" )))
                letter_pen = QtGui.QPen(QtGui.QColor(self.ntfg.get(letter, "#000000")))
            else:
                letter_brush = QtGui.QBrush(QtGui.QColor(self.aabg.get(letter,"#ffffff" )))
                letter_pen = QtGui.QPen(QtGui.QColor(self.aafg.get(letter,"#000000" )))

            p.setPen(letter_pen)
            p.fillRect(x,0,width, height,letter_brush)
            p.drawText(x, y, letter)
            x += float(width)/len(self.seq)
        p.end()
Exemple #13
0
 def draw(self, painter, x, y):
     painter.setPen(QtGui.QColor(0x450045))
     font = QtGui.QFont(QtGui.QFont('Decorative', 20))
     fontMetrics = QtGui.QFontMetrics(font)
     width = fontMetrics.boundingRect(self.string).width()
     painter.setFont(font)
     painter.drawText(x - width / 2, y, self.string)
Exemple #14
0
    def _texto(self,
               painter,
               cadena,
               x=0,
               y=0,
               magnitud=12,
               fuente=None,
               color=negro,
               alineado_a_derecha=False):
        "Imprime un texto respespetando el desplazamiento de la camara."
        r, g, b, _ = color.obtener_componentes()
        painter.setPen(QtGui.QColor(r, g, b))

        nombre_de_fuente = painter.font().family()

        font = QtGui.QFont(nombre_de_fuente, magnitud)
        painter.setFont(font)

        if alineado_a_derecha:
            fm = QtGui.QFontMetrics(font)
            w = fm.width(cadena) + 1
            h = fm.height()
            painter.drawText(x - w, y - h, cadena)
        else:
            painter.drawText(x, y, cadena)
Exemple #15
0
    def setExtraChars(self, chars):
        """Display a widget with buttons for the 'extra' characters.
        """
        # This works by adding a widget dynamically to the existing
        # frame. When a new file is loaded this widget is removed
        # and regenerated.
        layout0 = self.ui.frame_chars.layout()
        if layout0:
            layout0.removeWidget(self.xcWidget)
            self.xcWidget.deleteLater()

        else:
            layout0 = QtGui.QVBoxLayout(self.ui.frame_chars)
            layout0.setMargin(1)
            layout0.setSpacing(0)

        self.xcWidget = QtGui.QWidget()
        layout = QtGui.QHBoxLayout(self.xcWidget)
        layout.setMargin(0)
        layout.setSpacing(1)

        fm = QtGui.QFontMetrics(self.font())
        h = fm.height()
        for ch in chars:
            b = QtGui.QPushButton(ch)
            b.setFixedSize(h, h + 4)
            b.setFlat(True)
            layout.addWidget(b)
            QtCore.QObject.connect(b, QtCore.SIGNAL("clicked()"), self.char)

        layout0.addWidget(self.xcWidget)
 def variableInfo(self):
     self.ieds=[]
     class MyLog():
         def __init__(self):
             self.text=""
         def write(self,text):
             self.text+=text
         def clear(self):
             self.text=""
     mylog = MyLog()
     for v in self.getSelectedDefinedVariables():
         d = QtGui.QDialog()
         l = QtGui.QVBoxLayout()
         d.setLayout(l)
         lb = QtGui.QLabel("Variable: %s %s" % (v.id,repr(v.shape)))
         l.addWidget(lb)
         te = QtGui.QTextEdit()
         v.info(device=mylog)
         f = te.currentFont()
         fm = QtGui.QFontMetrics(f)
         minWidth = min(max(map(fm.width,mylog.text.split("\n"))),65*fm.width("W"))
         minHeight = min(len(mylog.text.split()),30)
         te.setMinimumHeight(fm.height()*minHeight)
         te.setMinimumWidth(minWidth)
         te.setText(mylog.text)
         te.setReadOnly(True)
         mylog.clear()
         l.addWidget(te)
         b = QtGui.QPushButton("Close")
         l.addWidget(b)
         self.connect(b,QtCore.SIGNAL("clicked()"),d.hide)
         d.show()
         self.ieds.append(d)
Exemple #17
0
    def print_(self):
        dialog = QtGui.QPrintDialog(self.printer)
        if not dialog.exec_():
            return
        self.printer.setPaperSize(QtGui.QPrinter.A5)
        painter = QtGui.QPainter(self.printer)
        pageRect = self.printer.pageRect()
        painter.setPen(QtCore.Qt.black)

        font = QtGui.QFont("Times", 11)
        fm = QtGui.QFontMetrics(font)
        fontLineHeight = fm.height()

        painter.setFont(font)

        rect = QtCore.QRectF(pageRect.width() / 6,
                             pageRect.height() / 20,
                             pageRect.width() * 5 / 6,
                             pageRect.height() / 3)

        text = "%s %s %s\n%s\n" % (self.pt.title, self.pt.fname, self.pt.sname,
                                   self.pt.address)
        text += "Our ref %d\n\n" % self.pt.serialno
        painter.drawText(rect, text)

        option = QtGui.QTextOption(QtCore.Qt.AlignCenter)
        option.setWrapMode(QtGui.QTextOption.WordWrap)

        y = pageRect.height() / 3
        painter.drawLine(0, int(y), int(pageRect.width()), int(y))

        y += fontLineHeight * 1.5

        font.setBold(True)
        painter.setFont(font)
        rect = QtCore.QRectF(0, y, pageRect.width(), fontLineHeight * 1.5)
        painter.drawText(rect, "You have the following appointments with us",
                         option)
        font.setBold(False)
        painter.setFont(font)

        for appt in self.appts:
            y += fontLineHeight * 1.5
            atime = localsettings.wystimeToHumanTime(appt.atime)
            adate = localsettings.longDate(appt.date)

            text = "%s - %s with %s" % (atime, adate, appt.dent_inits)

            rect = QtCore.QRectF(0, y, pageRect.width(), fontLineHeight * 1.5)

            painter.drawText(rect, text, option)

        y = pageRect.height() * 2 / 3

        painter.drawLine(0, int(y), int(pageRect.width()), int(y))
        font.setItalic(True)
        painter.setFont(font)

        rect = QtCore.QRectF(0, y, pageRect.width(), pageRect.height() * 1 / 3)
        painter.drawText(rect, localsettings.APPOINTMENT_CARD_FOOTER, option)
Exemple #18
0
    def paint(self, painter, option, widget):
        """
        Paints the camera item onto the scene.
        :param painter: painter object used for painting.
        :param option:
        :param widget:
        :return:
        """

        painter.setPen(QtCore.Qt.white)
        painter.drawEllipse(-15, -15, 30, 30)

        font = painter.font()
        font.setPixelSize(15)
        if self.model.is_selected():
            painter.setPen(QtCore.Qt.red)
        else:
            painter.setPen(QtCore.Qt.blue)
        font.setStyleHint(QtGui.QFont.TypeWriter)
        font.setFamily("Courier Code")
        painter.setFont(font)
        metrics = QtGui.QFontMetrics(font)
        name = self.model.get_name()
        text_length = metrics.width(name)
        text_height = metrics.height()

        bounding_rect = metrics.boundingRect(name)
        bounding_rect.moveTo(-text_length / 2, -text_height / 3)
        painter.drawRects(bounding_rect)
        painter.drawText(-text_length / 2, text_height / 2, str(name))
Exemple #19
0
    def resizeEvent(self, ev):
        item_width = self._calcStringWidth((self._item_size * 2) + 1)
        hex_display_width = self.hex_display.width()

        old_items_per_row = self._items_per_row
        self._items_per_row = (hex_display_width / item_width)

        # Refresh the scroll bar
        row_height = QtGui.QFontMetrics(self.display_font).lineSpacing()
        total_rows = len(self._data) / (self._items_per_row * self._item_size)
        window_height = self.horizontal_layout.geometry().height()
        self._visible_rows = (window_height / row_height) - 3

        old_value = self.scrollbar.value() * 1.0
        old_max = self.scrollbar.maximum()
        scrollbar_ratio = (old_value / old_max) if (old_max > 0) else 0

        new_max = (total_rows - self._visible_rows) + 1
        if (new_max < 0): new_max = 0
        self.scrollbar.setMaximum(new_max)
        self.scrollbar.setMinimum(0)
        self.scrollbar.setSingleStep(1)
        self.scrollbar.setValue(new_max * scrollbar_ratio)

        if (old_items_per_row != self._items_per_row):
            self._formatData(
                self._data,
                self._start_address,
                self._item_size,
                self._items_per_row
                )



        self._refreshContent()
Exemple #20
0
 def redraw(self, *args):
     self.compute(self.col_spin.value(), self.vertical_chk.isChecked())
     if self.mode == TEXT:
         self.printview.resetTransform()
         self.page.hide()
         self.printview.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
         self.printview.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
         self.printscene.removeItem(self.monotext)
         self.monotext = QtGui.QGraphicsTextItem()
         self.monotext.setPlainText(self.text.replace('\t\t', '        ').replace('\t', '    '))
         self.monotext.setFont(self.monofont)
         self.printscene.addItem(self.monotext)
         self.printview.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
         #for some reason, very long plain text contents always set QGraphicsTextItem's height to 2012, then we use metrics
         self.printview.setSceneRect(0, 0, self.monotext.boundingRect().width(), QtGui.QFontMetrics(self.monofont).lineSpacing()*len(self.text.split('\n')))
         self.printview.verticalScrollBar().setValue(0)
         self.printview.horizontalScrollBar().setValue(0)
         return
     self.monotext.hide()
     self.printview.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
     self.printview.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
     self.printview.setAlignment(QtCore.Qt.AlignCenter)
     self.page.setText(self.text)
     self.page.show()
     self.printview.setSceneRect(self.page.boundingRect())
     self.printview.fitInView(self.page.boundingRect(), QtCore.Qt.KeepAspectRatio)
     self.pagebank_chk.toggled.connect(self.page.setPageBank)
Exemple #21
0
    def paintEvent(self, event):
        if self.screen.data.acq:
            opt = QtGui.QStyleOptionSlider()
            self.timeSlider.initStyleOption(opt)
            sr = self.style().subControlRect(QtGui.QStyle.CC_Slider, opt,
                                             QtGui.QStyle.SC_SliderHandle,
                                             self)
            halfHandleWidth = (0.5 * sr.width()) + 0.5

            painter = QtGui.QPainter(self)
            painter.setRenderHint(QtGui.QPainter.Antialiasing)

            painter.setPen(QtCore.Qt.black)
            # scaleCount = self.timeSlider.geometry().width() / 50
            scaleCount = 20
            metrics = QtGui.QFontMetrics(self.font())
            for i in range(scaleCount):
                value = int((float)(self.screen.data.totalFrame - 1) /
                            (scaleCount - 1) * i)
                position = QtGui.QStyle.sliderPositionFromValue(
                    self.timeSlider.minimum(), self.timeSlider.maximum(),
                    value,
                    self.timeSlider.width() - halfHandleWidth * 2)
                painter.drawLine(
                    position + self.timeSlider.geometry().x() +
                    halfHandleWidth, 15, position +
                    self.timeSlider.geometry().x() + halfHandleWidth, 50)
                painter.drawText(
                    position + self.timeSlider.geometry().x() +
                    halfHandleWidth - 25, 55, 50, 10,
                    QtCore.Qt.AlignCenter | QtCore.Qt.TextWordWrap, str(value))
Exemple #22
0
 def _paintNotes(self, painter, xValues):
     font = painter.font()
     fontMetric = QtGui.QFontMetrics(font)
     baseline = (self.numLines() -
                 1) * self._qScore.ySpacing + self._base + self.parentItem(
                 ).alternateHeight()
     dot = self._qScore.scale
     potential = False
     for drumIndex in range(0, self.numLines()):
         lineHeight = baseline + (self._qScore.ySpacing / 2.0) - 1
         lineIndex = self.lineIndex(drumIndex)
         for noteTime, x in enumerate(xValues):
             if (lineIndex == self._potentialDrum
                     and noteTime in self._potentialSet):
                 text = self._potentialHead
                 potential = True
                 painter.setPen(QtGui.QColor(QtCore.Qt.blue))
             else:
                 text = self._measure.noteAt(noteTime, lineIndex)
             if text == DBConstants.EMPTY_NOTE:
                 painter.drawLine(x + dot, lineHeight,
                                  x + self._qScore.xSpacing - dot,
                                  lineHeight)
             else:
                 br = fontMetric.tightBoundingRect(text)
                 left = x + (self._qScore.xSpacing - br.width() + 2) / 2 - 2
                 offset = br.y() - (self._qScore.ySpacing - br.height()) / 2
                 painter.drawText(QtCore.QPointF(left, baseline - offset),
                                  text)
             if potential:
                 painter.setPen(QtGui.QColor(QtCore.Qt.black))
                 potential = False
         baseline -= self._qScore.ySpacing
Exemple #23
0
    def paintEvent(self, event):

        painter = QtGui.QPainter(self.viewport())

        # CurrentLine background
        if self.highlightCurrentLine:
            r = self.cursorRect()
            r.setX(0) #Sets the left edge of the rectangle to the given coordinate.
            r.setWidth( self.viewport().width() )

            painter.fillRect( r, QtGui.QBrush( self.line_col ) )
            painter.setPen( self.limit_color )
            painter.drawRect( r )

            #painter.setPen( self.limit_color )
            #painter.drawRoundRect ( r )

        # LimitLine
        if self.LimitLine > 0:
            x = ( QtGui.QFontMetrics( self.font() ).width( "X" ) * self.LimitLine ) - self.horizontalScrollBar().value()
            painter.setPen( self.limit_color )
            painter.drawLine( x, painter.window().top(), x, painter.window().bottom() )
        painter.end()

        # Tabs and spaces
        if self.showSpaces :
            pass #self.printWhiteSpaces(event)

        # Callbacks from plugins
        if self.paint_callbacks :
            for pc in self.paint_callbacks:
                pc.paint(event)
        QtGui.QPlainTextEdit.paintEvent(self,event)
Exemple #24
0
    def itemRect(self, index):
        if not index.isValid():
            return QtCore.QRect()

        # Check whether the index's row is in the list of rows represented
        # by slices.

        if index.column() != 1:
            valueIndex = self.model().index(index.row(), 1, self.rootIndex())
        else:
            valueIndex = index

        if self.model().data(valueIndex) > 0.0:

            listItem = 0
            for row in range(index.row() - 1, -1, -1):
                if self.model().data(self.model().index(
                        row, 1, self.rootIndex())) > 0.0:
                    listItem += 1

            if index.column() == 0:

                itemHeight = QtGui.QFontMetrics(
                    self.viewOptions().font).height()
                return QtCore.QRect(self.totalSize,
                                    int(self.margin + listItem * itemHeight),
                                    self.totalSize - self.margin,
                                    int(itemHeight))
            elif index.column() == 1:
                return self.viewport().rect()

        return QtCore.QRect()
Exemple #25
0
    def __init__(self, text, parent):
        super(DragLabel, self).__init__(parent)

        metric = QtGui.QFontMetrics(self.font())
        size = metric.size(QtCore.Qt.TextSingleLine, text)

        image = QtGui.QImage(size.width() + 12,
                             size.height() + 12,
                             QtGui.QImage.Format_ARGB32_Premultiplied)
        image.fill(QtGui.qRgba(0, 0, 0, 0))

        font = QtGui.QFont()
        font.setStyleStrategy(QtGui.QFont.ForceOutline)

        painter = QtGui.QPainter()
        painter.begin(image)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        painter.setBrush(QtCore.Qt.white)
        painter.drawRoundedRect(
            QtCore.QRectF(0.5, 0.5,
                          image.width() - 1,
                          image.height() - 1), 25, 25, QtCore.Qt.RelativeSize)

        painter.setFont(font)
        painter.setBrush(QtCore.Qt.black)
        painter.drawText(QtCore.QRect(QtCore.QPoint(6, 6), size),
                         QtCore.Qt.AlignCenter, text)
        painter.end()

        self.setPixmap(QtGui.QPixmap.fromImage(image))
        self.labelText = text
Exemple #26
0
 def drawId(painter, rect, id, align=QtCore.Qt.AlignCenter):
     """ drawId(painter: QPainter, rect: QRect, id: int,
                align: QtCore.Qt.Align) -> None
     Draw the rounded id number on a rectangular area
     
     """
     painter.save()
     painter.setRenderHints(QtGui.QPainter.Antialiasing)
     painter.setPen(CurrentTheme.ANNOTATED_ID_BRUSH.color())
     painter.setBrush(CurrentTheme.ANNOTATED_ID_BRUSH)
     font = QtGui.QFont()
     font.setStyleStrategy(QtGui.QFont.ForceOutline)
     font.setBold(True)
     painter.setFont(font)
     fm = QtGui.QFontMetrics(font)
     size = fm.size(QtCore.Qt.TextSingleLine, str(id))
     size = max(size.width(), size.height())
     
     x = rect.left()
     if align & QtCore.Qt.AlignHCenter:
         x = rect.left() + rect.width()//2-size//2
     if align & QtCore.Qt.AlignRight:
         x = rect.left() + rect.width()-size
     y = rect.top()
     if align & QtCore.Qt.AlignVCenter:
         y = rect.top() + rect.height()//2-size//2
     if align & QtCore.Qt.AlignBottom:
         y = rect.top() + rect.height()-size
         
     newRect = QtCore.QRect(x, y, size, size)
     painter.drawEllipse(newRect)
     painter.setPen(CurrentTheme.ANNOTATED_ID_PEN)
     painter.drawText(newRect, QtCore.Qt.AlignCenter, str(id))
     painter.restore()
Exemple #27
0
    def texto(self,
              cadena,
              x=0,
              y=0,
              magnitud=10,
              fuente=None,
              color=colores.negro):
        self.canvas.begin(self._imagen)
        r, g, b, a = color.obtener_componentes()
        self.canvas.setPen(QtGui.QColor(r, g, b))
        dx = x
        dy = y

        if not fuente:
            fuente = self.canvas.font().family()

        font = QtGui.QFont(fuente, magnitud)
        self.canvas.setFont(font)
        metrica = QtGui.QFontMetrics(font)

        for line in cadena.split('\n'):
            self.canvas.drawText(dx, dy, line)
            dy += metrica.height()

        self.canvas.end()
 def __init__(self, mobj, parent):
     KineticsDisplayItem.__init__(self, mobj, parent)
     self.bg = QtGui.QGraphicsRectItem(self)
     self.bg.setAcceptHoverEvents(True)
     self.gobj = QtGui.QGraphicsSimpleTextItem(self.mobj.name, self.bg)
     self.gobj.mobj = self.mobj
     classname = self.mobj.className
     # classname = 'PoolBase'
     # doc = moose.element('/classes/%s' % (classname)).docs
     # print "docs ",self.gobj.mobj, " ",doc
     # doc = doc.split('Description:')[-1].split('Name:')[0].strip()
     self._conc = self.mobj.conc
     self._n    = self.mobj.n
     doc = "Conc\t: "+str(self._conc)+"\nn\t: "+str(self._n)
     self.gobj.setToolTip(doc)
     self.gobj.setFont(PoolItem.font)
     if not PoolItem.fontMetrics:
         PoolItem.fontMetrics = QtGui.QFontMetrics(self.gobj.font())
     self.bg.setRect(0, 
                     0, 
                     self.gobj.boundingRect().width()
                     +PoolItem.fontMetrics.width('  '), 
                     self.gobj.boundingRect().height())
     self.bg.setPen(Qt.QColor(0,0,0,0))
     self.gobj.setPos(PoolItem.fontMetrics.width(' '), 0)
    def updateBB(self, personIdx):
        action = ' '
        if self.personBox[personIdx].actionBox.currentIndex():
            self.parent.viewer.globalItem[personIdx].setPen(
                QtGui.QPen(QtCore.Qt.green, 1))
            action = self.personBox[personIdx].actionBox.itemText(
                self.personBox[personIdx].actionBox.currentIndex())
        else:
            self.parent.viewer.globalItem[personIdx].setPen(
                QtGui.QPen(QtCore.Qt.red, 1))

        newfont = QtGui.QFont()
        fm = QtGui.QFontMetrics(newfont)
        factor = self.parent.viewer.globalItem[personIdx].rect().width(
        ) / fm.width(action)
        newfont.setPointSizeF(newfont.pointSizeF() * factor)

        self.parent.viewer._scene.removeItem(
            self.parent.viewer.bbActionLabel[personIdx])
        self.parent.viewer.bbActionLabel[
            personIdx] = self.parent.viewer._scene.addSimpleText('%s' % action)
        self.parent.viewer.bbActionLabel[personIdx].setPen(QtCore.Qt.white)
        self.parent.viewer.bbActionLabel[personIdx].setBrush(QtCore.Qt.blue)

        self.parent.viewer.bbActionLabel[personIdx].setFont(newfont)
        self.parent.viewer.bbActionLabel[personIdx].setPos(
            QtCore.QPointF(
                self.parent.viewer.globalItem[personIdx].rect().x(),
                self.parent.viewer.globalItem[personIdx].rect().y() +
                (self.parent.viewer.globalItem[personIdx].rect().height() /
                 2)))
        '''
Exemple #30
0
    def texto(self,
              cadena,
              x=0,
              y=0,
              magnitud=10,
              fuente=None,
              color=colores.negro):
        self.canvas.begin(self._imagen)
        r, g, b, a = color.obtener_componentes()
        self.canvas.setPen(QtGui.QColor(r, g, b))
        dx = x
        dy = y

        if fuente:
            nombre_de_fuente = Texto.cargar_fuente_desde_cache(fuente)
        else:
            nombre_de_fuente = self.canvas.font().family()

        font = QtGui.QFont(nombre_de_fuente, magnitud)
        self.canvas.setFont(font)
        metrica = QtGui.QFontMetrics(font)

        for line in cadena.split('\n'):
            self.canvas.drawText(
                QtCore.QRect(dx, dy, self._imagen.width(),
                             self._imagen.height()),
                QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop, line)
            dy += metrica.height()

        self.canvas.end()