コード例 #1
0
ファイル: printer.py プロジェクト: maximerobin/Ufwi
    def __draw(self, start_page, simulate=False):
        vpos = 0

        vpos += self.printer.drawHCenteredTitle(tr('Table of contents'), vpos)
        vpos += 10

        for row in self.table:
            if row['section']:
                vpos += 2

            size = row['size']

            fontmetrics = QFontMetrics(QFont(self.printer.FONT_NAME, size))

            if vpos + fontmetrics.height() >= self.printer.height():
                vpos = 10
                if not simulate:
                    self.printer.newPage()
                else:
                    start_page += 1

            if not simulate:
                page_num = row['page_num'] + start_page
                title = row['title']
                num_w = fontmetrics.width(unicode(page_num))

                self.printer.drawText(title + '.' * 300, vpos, halign=Qt.AlignLeft, size=size, width=self.printer.width() - num_w)
                self.printer.drawText(unicode(page_num), vpos, halign=Qt.AlignRight, size=size)

            vpos += fontmetrics.height()

        return start_page
コード例 #2
0
 def getMinimumWidth(self, items=None):
     fm = QFontMetrics(self.font())
     opt = QStyleOptionComboBox()
     style = self.style()
     mw = self.maxWidth
     if items is not None:
         for str in items:
             opt.currentText = QString(str)
             sz = QSize(fm.width(opt.currentText), fm.height())
             mw = max(
                 mw,
                 style.sizeFromContents(QStyle.CT_ComboBox, opt, sz,
                                        self).width())
     elif mw == 0 and self.count() > 0:
         for i in range(0, self.count()):
             opt.currentText = self.itemText(i)
             sz = QSize(fm.width(opt.currentText), fm.height())
             mw = max(
                 mw,
                 style.sizeFromContents(QStyle.CT_ComboBox, opt, sz,
                                        self).width())
     elif mw == 0:
         opt.currentText = QString(' ')
         sz = QSize(fm.width(opt.currentText), fm.height())
         mw = max(
             mw,
             style.sizeFromContents(QStyle.CT_ComboBox, opt, sz,
                                    self).width())
     self.maxWidth = mw
     return mw
コード例 #3
0
ファイル: epoint.py プロジェクト: feeling1982113/edd
    def __updateShape(self):

        fBBox = QFontMetrics(self.Font).boundingRect(self.Name)

        if self.__polygon.boundingRect().width() < fBBox.width():
            self.__polygon = QPolygonF(QRectF(fBBox).normalized().adjusted(-fBBox.width() / 4,
                                                                           -fBBox.height() / 4,
                                                                           fBBox.height(),
                                                                           fBBox.height() / 2))
コード例 #4
0
 def adjustFont(self):
     # --- fetch current parameters ----
     f = self.font()
     cr = self.contentsRect()
     if self.maxFont is not None:
         maximum = self.maxFont.pointSize()
     else:
         maximum = self.font().pointSize()
     # --- find the font size that fits the contentsRect ---
     fs = 1
     while True:
         f.setPointSize(fs)
         br = QFontMetrics(f).boundingRect(self.text())
         if br.height() <= cr.height() and br.width() <= cr.width():
             fs += 1
         else:
             if self.wordWrap() == False:
                 wouldfit = (max(fs - 1, 1))  # if the length have to fit into the label
                 if wouldfit > maximum:
                     wouldfit = maximum
                 f.setPointSize(wouldfit)  # if wordwrap is wanted by the user... he expects wordwrap.
             else:
                 wouldfit = max(fs - 1, 1)*1.5
                 if wouldfit > maximum:
                     wouldfit = maximum
                 f.setPointSize(wouldfit)  # if wordwrap is wanted by the user... he expects wordwrap.
                 #f.setPointSize(max(fs - 1, 1)*1.5)  # if wordwrap is wanted by the user... he expects wordwrap.
             break
     # --- update font size ---
     self.setFont(f)
コード例 #5
0
    def create_scale_marker_values_text(self):
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        # painter.save()
        font = QFont(self.scale_fontname, self.scale_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.ScaleValueColor)
        painter.setPen(pen_shadow)

        text_radius_factor = 0.8
        text_radius = self.widget_diameter/2 * text_radius_factor

        scale_per_div = int((self.value_max - self.value_min) / self.scala_main_count)

        angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        for i in range(self.scala_main_count + 1):
            # text = str(int((self.value_max - self.value_min) / self.scala_main_count * i))
            text = str(int(self.value_min + scale_per_div * i))
            w = fm.width(text) + 1
            h = fm.height()
            painter.setFont(QFont(self.scale_fontname, self.scale_fontsize))
            angle = angle_distance * i + float(self.scale_angle_start_value - self.angle_offset)
            x = text_radius * math.cos(math.radians(angle))
            y = text_radius * math.sin(math.radians(angle))
            # print(w, h, x, y, text)
            text = [x - int(w/2), y - int(h/2), int(w), int(h), Qt.AlignCenter, text]
            painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
コード例 #6
0
ファイル: graphics.py プロジェクト: davidmorrill/facets
    def text_size ( self, text ):
        """ Returns the size (dx,dy) of the specified text using the current
            font.
        """
        rect = QFontMetrics( self.font ).boundingRect( text )

        return ( rect.width(), rect.height() )
コード例 #7
0
 def adjustFont(self):
     # --- fetch current parameters ----
     f = self.font()
     cr = self.contentsRect()
     if self.maxFont is not None:
         maximum = self.maxFont.pointSize()
     else:
         maximum = self.font().pointSize()
     # --- find the font size that fits the contentsRect ---
     fs = 1
     while True:
         f.setPointSize(fs)
         br = QFontMetrics(f).boundingRect(self.text())
         if br.height() <= cr.height() and br.width() <= cr.width():
             fs += 1
         else:
             if self.wordWrap() == False:
                 wouldfit = (max(fs - 1, 1)
                             )  # if the length have to fit into the label
                 if wouldfit > maximum:
                     wouldfit = maximum
                 f.setPointSize(
                     wouldfit
                 )  # if wordwrap is wanted by the user... he expects wordwrap.
             else:
                 wouldfit = max(fs - 1, 1) * 1.5
                 if wouldfit > maximum:
                     wouldfit = maximum
                 f.setPointSize(
                     wouldfit
                 )  # if wordwrap is wanted by the user... he expects wordwrap.
                 #f.setPointSize(max(fs - 1, 1)*1.5)  # if wordwrap is wanted by the user... he expects wordwrap.
             break
     # --- update font size ---
     self.setFont(f)
コード例 #8
0
ファイル: CompletionsWidget.py プロジェクト: straszheim/spec
    def show_completions(self, completions, parent):
        self.last_completions = completions
        self.parent = parent

        self.clear()
        if not completions:
            self.hide()
            return
        
        maxcomp = max(map(len, completions))
        total   = sum(map(len, completions))
        rowcol = math.ceil(math.sqrt(maxcomp))
        log.debug("completions=%s max completion has len %d, total %d, rowcol=%d", completions, maxcomp, total, rowcol)

        the_completions = self.last_completions[:]

        if self.cur_position >= len(the_completions):
            self.cur_position = len(the_completions) - 1

        if len(the_completions) > 0:
            the_completions[self.cur_position] = "<b>" + the_completions[self.cur_position] + "</b>"

        self.setText('<br>'.join(the_completions))
        p = parent.mapToGlobal(QPoint(0,0))
        self.show()
        ph = parent.height()
        pw = parent.width()
        mh = self.height()
        mw = self.width()
        self.move(QPoint(p.x() + (pw-mw)/2, p.y() + (ph-mh)/2))

        font = self.font()
        metrics = QFontMetrics(font)
        log.debug("chwidth=%d h=%d", metrics.averageCharWidth(), metrics.height())
コード例 #9
0
ファイル: pilqterm.py プロジェクト: wyongfei/pyilper
    def __init__(self,parent, font_name, font_size, cols, rows, colorscheme):
        super().__init__(parent)
        self.callback_scrollbar= None
#
#       determine font metrics and terminal window size in pixel
#
        font= QFont(font_name)
        font.setPixelSize(font_size)
        metrics= QFontMetrics(font)
        font_width=metrics.width("A")
        font_height=metrics.height()
        width= font_width*cols
        height= int(font_height* rows)
#
#       create terminal window and scrollbar
#
        self.hbox= QHBoxLayout()
        self.terminalwidget= QTerminalWidget(self,font_name,font_size,font_height, width,height, colorscheme)
        self.hbox.addWidget(self.terminalwidget)
        self.hbox.setAlignment(self.terminalwidget,Qt.AlignLeft)
        self.scrollbar= QScrollBar()
        self.hbox.addWidget(self.scrollbar)
        self.hbox.setAlignment(self.scrollbar,Qt.AlignLeft)
        self.setLayout(self.hbox)
#
#       initialize scrollbar
#
        self.scrollbar.valueChanged.connect(self.do_scrollbar)
        self.scrollbar.setEnabled(False)
コード例 #10
0
ファイル: table.py プロジェクト: Mouchnino/moneyguru
 def _updateFontSize(self):
     from ..app import APP_INSTANCE
     font = self.view.font()
     font.setPointSize(APP_INSTANCE.prefs.tableFontSize)
     self.view.setFont(font)
     fm = QFontMetrics(font)
     self.view.verticalHeader().setDefaultSectionSize(fm.height()+2)
コード例 #11
0
 def rebuild( self ):
     """
     Rebuilds the path for this connection based on the given connection \
     style parameters that have been set.
     
     :return     <QPainterPath>
     """
     # create the path
     path            = self.rebuildPath()
     self._polygons  = self.rebuildPolygons(path)
     
     if ( self._textItem ):
         point   = path.pointAtPercent(0.5)
         metrics = QFontMetrics(self._textItem.font())
         
         point.setY(point.y() - metrics.height() / 2.0)
         
         self._textItem.setPos(point)
     
     # create the path for the item
     for poly in self._polygons:
         path.addPolygon(poly)
     
     # unmark as dirty
     self.setDirty(False)
     
     return path
コード例 #12
0
ファイル: xchartaxis.py プロジェクト: satishgoda/DPS_PIPELINE
 def minimumLabelHeight(self):
     """
     Returns the minimum height that will be required based on this font size
     and labels list.
     """
     metrics = QFontMetrics(self.labelFont())
     return max(self._minimumLabelHeight,
                metrics.height() + self.verticalLabelPadding())
コード例 #13
0
ファイル: interpret.py プロジェクト: bogdanvuk/pyde
    def __init__(self, view: Amendment('view/', lambda v: hasattr(v, 'mode') and (v.mode.name == 'ipython') and (v.widget is None))): #, orig_editor=None):
        if view.widget is None:
            self.globals = {}
            self.globals['ddic'] = ddic
            for a in ddic['actions']:
                self.globals[a] = ddic['actions'][a]
                
            self.locals = {}
#             ddic.provide('interactive', -1)
        else:
            self.globals = view.widget.globals
            self.locals = view.widget.locals
        
        super().__init__(view)

        # Set the default font
        font = QFont()
        font.setFamily('DejaVu Sans Mono')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
#        self.parser = Parser(self, 'python3')
#         self.ca = PyInterpretContentAssist()
        fontmetrics = QFontMetrics(font)

        # Brace matching: enable for a brace immediately before or after
        # the current position
        #
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Current line visible with special background color
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor("#ffe4e4"))

        # Set Python lexer
        # Set style for Python comments (style number 1) to a fixed-width
        # courier.
        #
#         self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'DejaVu Sans Mono'.encode())
        

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented
        # here: http://www.scintilla.org/ScintillaDoc.html)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        self.SendScintilla(QsciScintilla.SCI_SETVSCROLLBAR, 0)
        
        self.setMinimumSize(fontmetrics.width("00000"), fontmetrics.height()+4)
        
        self.markerDefine(QsciScintilla.RightArrow,
            self.ARROW_MARKER_NUM)
#         self.setMarkerBackgroundColor(QColor("#ee1111"),
#             self.ARROW_MARKER_NUM)

        self.prompt_begin = 0
        self.focus_view = None
        self.interactive = False
コード例 #14
0
ファイル: qhexedit.py プロジェクト: Loremipsum1988/brickv
 def setFont(self, f):
     # recalculate all of our metrics/offsets
     fm = QFontMetrics(f)
     self.font_width  = fm.width('X')
     self.font_height = fm.height()
     self.updateScrollbars()
     # TODO: assert that we are using a fixed font & find out if we care?
     QAbstractScrollArea.setFont(self,f)
     return
コード例 #15
0
ファイル: qhexedit.py プロジェクト: jose1711/brickv
 def setFont(self, f):
     # recalculate all of our metrics/offsets
     fm = QFontMetrics(f)
     self.font_width  = fm.width('X')
     self.font_height = fm.height()
     self.updateScrollbars()
     # TODO: assert that we are using a fixed font & find out if we care?
     QAbstractScrollArea.setFont(self,f)
     return
コード例 #16
0
ファイル: linechart.py プロジェクト: mireq/pyboincgui
	def __calcMaxTextSize(self, font, hodnoty):
		fm = QFontMetrics(font);
		x = 0
		y = fm.height()
		for hodnota in hodnoty:
			w = fm.width(hodnota)
			if w > x:
				x = w
		return (x, y)
コード例 #17
0
ファイル: item_view.py プロジェクト: Mouchnino/moneyguru
 def __init__(self, ds):
     rowFM = QFontMetrics(ds.rowFont())
     self.splitFM = QFontMetrics(ds.splitFont())
     headerFM = QFontMetrics(ds.headerFont())
     self.rowHeight = rowFM.height() + CELL_MARGIN * 2
     self.splitHeight = self.splitFM.height() + CELL_MARGIN * 2
     self.headerHeight = headerFM.height() + CELL_MARGIN * 2
     spannedRowIndexes = set()
     for rowIndex in range(ds.rowCount()):
         extraRole = nonone(ds.data(rowIndex, 0, EXTRA_ROLE), 0)
         if extraRole & EXTRA_SPAN_ALL_COLUMNS:
             spannedRowIndexes.add(rowIndex)
     self.columns = []
     for colIndex in range(ds.columnCount()):
         col = ds.columnAtIndex(colIndex)
         sumWidth = 0
         maxWidth = 0
         # We need to have *at least* the width of the header.
         minWidth = headerFM.width(col.display) + CELL_MARGIN * 2
         for rowIndex in range(ds.rowCount()):
             if rowIndex in spannedRowIndexes:
                 continue
             data = ds.data(rowIndex, colIndex, Qt.DisplayRole)
             if data:
                 font = ds.data(rowIndex, colIndex, Qt.FontRole)
                 fm = QFontMetrics(font) if font is not None else rowFM
                 width = fm.width(data) + CELL_MARGIN * 2
                 width += ds.indentation(rowIndex, colIndex)
                 sumWidth += width
                 maxWidth = max(maxWidth, width)
             pixmap = ds.data(rowIndex, colIndex, Qt.DecorationRole)
             if pixmap is not None:
                 width = pixmap.width() + CELL_MARGIN * 2
                 maxWidth = max(maxWidth, width)
         avgWidth = sumWidth // ds.rowCount()
         maxWidth = max(maxWidth, minWidth)
         if col.cantTruncate: # if it's a "can't truncate" column, we make no concession
             minWidth = maxWidth
         cs = ColumnStats(colIndex, col, avgWidth, maxWidth, minWidth)
         self.columns.append(cs)
     self.maxWidth = sum(cs.maxWidth for cs in self.columns)
     self.minWidth = sum(cs.minWidth for cs in self.columns)
コード例 #18
0
ファイル: layout.py プロジェクト: glasmasin/moneyguru
 def __init__(self, page):
     font = QFont(QApplication.font())
     font.setBold(True)
     fm = QFontMetrics(font)
     titleBase = page.viewPrinter.title
     titleLineCount = len(titleBase.split('\n'))
     titleHeight = fm.height() * titleLineCount
     rect = QRect(page.pageRect.topLeft(), QSize(page.pageRect.width(), titleHeight))
     LayoutElement.__init__(self, rect)
     self.page = page
     self.font = font
コード例 #19
0
ファイル: table.py プロジェクト: glasmasin/moneyguru
 def _updateFontSize(self, prefs):
     font = self.view.font()
     font.setPointSize(prefs.tableFontSize)
     self.view.setFont(font)
     fm = QFontMetrics(font)
     self.view.verticalHeader().setDefaultSectionSize(fm.height()+2)
     # (#14, #15) When a new font was selected in the preferences panel,
     # the column would redraw but not resize appropriately.  A call
     # to resize(sizeHint()) was added on the update of the size info
     # in the custom drawing for the amount field.
     self.view.resize(self.view.sizeHint())
コード例 #20
0
 def setRect(self, fm=None):
     if fm is None:
         font = self.font()
         if font is None:
             return
         fm = QFontMetrics(font)
     lineHeight = fm.height()
     height = lineHeight * self._dataLen() * 1.1
     width = max(fm.width(data) for data in self._iterData()) + 10
     if height != self._rect.height() or width != self._rect.width():
         self.prepareGeometryChange()
         self._rect.setBottomRight(QPointF(width, height))
コード例 #21
0
ファイル: locator.py プロジェクト: hlamer/completer
 def sizeHint(self):
     """QWidget.sizeHint implementation. Returns height of 1 line of text
     """
     fm = QFontMetrics(self.font())
     h = max(fm.height(), 14) + 4
     w = fm.width('x') * 17 + 4
     opt = QStyleOptionFrameV2()
     opt.initFrom(self);
     return self.style().sizeFromContents(QStyle.CT_LineEdit,
                                          opt,
                                          QSize(w, h).expandedTo(QApplication.globalStrut()),
                                          self)
コード例 #22
0
ファイル: HtmlLineEdit.py プロジェクト: michaupl/wordtester
 def __init__(self, parent=None):
     super(HtmlLineEdit, self).__init__(parent)
     
     self.setLineWrapMode(QTextEdit.NoWrap)
     self.setTabChangesFocus(True)
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     fm = QFontMetrics(self.font())
     h = int(fm.height() * (1.4 if platform.system() == "Windows" \
                                else 1.2))
     self.setMinimumHeight(int(h*1.3))
     self.setMaximumHeight(int(h * 1.6))
コード例 #23
0
ファイル: QGraphicsListData.py プロジェクト: Whatang/DrumBurp
 def setRect(self, fm = None):
     if fm is None:
         font = self.font()
         if font is None:
             return
         fm = QFontMetrics(font)
     lineHeight = fm.height()
     height = lineHeight * self._dataLen() * 1.1
     width = max(fm.width(data) for data in self._iterData()) + 10
     if height != self._rect.height() or width != self._rect.width():
         self.prepareGeometryChange()
         self._rect.setBottomRight(QPointF(width, height))
コード例 #24
0
 def paint(self, painter, dummyOption, dummyWidget = None):
     painter.save()
     try:
         font = self.font()
         if font is None:
             font = painter.font()
         else:
             painter.setFont(font)
         fm = QFontMetrics(painter.font())
         self.setRect(fm)
         lineHeight = fm.height()
         for index, data in enumerate(self._iterData()):
             painter.drawText(QPoint(5, (index + 1) * lineHeight), data)
     finally:
         painter.restore()
コード例 #25
0
 def paint(self, painter, dummyOption, dummyWidget=None):
     painter.save()
     try:
         font = self.font()
         if font is None:
             font = painter.font()
         else:
             painter.setFont(font)
         fm = QFontMetrics(painter.font())
         self.setRect(fm)
         lineHeight = fm.height()
         for index, data in enumerate(self._iterData()):
             painter.drawText(QPoint(5, (index + 1) * lineHeight), data)
     finally:
         painter.restore()
コード例 #26
0
 def getMinimumWidth(self, items = None):
     fm = QFontMetrics(self.font())
     opt = QStyleOptionComboBox()
     style = self.style()
     mw = self.maxWidth
     if items is not None:
         for str in items:
             opt.currentText = QString(str)
             sz = QSize(fm.width(opt.currentText), fm.height())
             mw = max(mw, style.sizeFromContents(QStyle.CT_ComboBox, 
                                                 opt, sz, self).width())
     elif mw == 0 and self.count() > 0:
         for i in range(0, self.count()):
             opt.currentText = self.itemText(i)
             sz = QSize(fm.width(opt.currentText), fm.height())
             mw = max(mw, style.sizeFromContents(QStyle.CT_ComboBox, 
                                                 opt, sz, self).width())
     elif mw == 0:
         opt.currentText = QString(' ')
         sz = QSize(fm.width(opt.currentText), fm.height())
         mw = max(mw, style.sizeFromContents(QStyle.CT_ComboBox, 
                                             opt, sz, self).width())
     self.maxWidth = mw
     return mw
コード例 #27
0
    def populate(self, phrase, ts, process_space=True):
        phrase_pos = 0
        processed = False
        matches = self.__class__.whitespace.finditer(phrase)
        font = QFont(ts.font)
        if self.valign is not None:
            font.setPixelSize(font.pixelSize() / 1.5)
        fm = QFontMetrics(font)
        single_space_width = fm.width(' ')
        height, descent = fm.height(), fm.descent()
        for match in matches:
            processed = True
            left, right = match.span()
            if not process_space:
                right = left
            space_width = single_space_width * (right - left)
            word = phrase[phrase_pos:left]
            width = fm.width(word)
            if self.current_width + width < self.line_length:
                self.commit(word, width, height, descent, ts, font)
                if space_width > 0 and self.current_width + space_width < self.line_length:
                    self.add_space(space_width)
                phrase_pos = right
                continue

            # Word doesn't fit on line
            if self.hyphenate and len(word) > 3:
                tokens = hyphenate_word(word)
                for i in range(len(tokens) - 2, -1, -1):
                    word = ''.join(tokens[0:i + 1]) + '-'
                    width = fm.width(word)
                    if self.current_width + width < self.line_length:
                        self.commit(word, width, height, descent, ts, font)
                        return phrase_pos + len(word) - 1, True
            if self.current_width < 5:  # Force hyphenation as word is longer than line
                for i in range(len(word) - 5, 0, -5):
                    part = word[:i] + '-'
                    width = fm.width(part)
                    if self.current_width + width < self.line_length:
                        self.commit(part, width, height, descent, ts, font)
                        return phrase_pos + len(part) - 1, True
            # Failed to add word.
            return phrase_pos, True

        if not processed:
            return self.populate(phrase + ' ', ts, False)

        return phrase_pos, False
コード例 #28
0
ファイル: text.py プロジェクト: 089git/calibre
    def populate(self, phrase, ts, process_space=True):
        phrase_pos = 0
        processed = False
        matches = self.__class__.whitespace.finditer(phrase)
        font = QFont(ts.font)
        if self.valign is not None:
            font.setPixelSize(font.pixelSize()/1.5)
        fm = QFontMetrics(font)
        single_space_width = fm.width(' ')
        height, descent = fm.height(), fm.descent()
        for match in matches:
            processed = True
            left, right = match.span()
            if not process_space:
                right = left
            space_width = single_space_width * (right-left)
            word = phrase[phrase_pos:left]
            width = fm.width(word)
            if self.current_width + width < self.line_length:
                self.commit(word, width, height, descent, ts, font)
                if space_width > 0  and self.current_width + space_width < self.line_length:
                    self.add_space(space_width)
                phrase_pos = right
                continue

            # Word doesn't fit on line
            if self.hyphenate and len(word) > 3:
                tokens = hyphenate_word(word)
                for i in range(len(tokens)-2, -1, -1):
                    word = ''.join(tokens[0:i+1])+'-'
                    width = fm.width(word)
                    if self.current_width + width < self.line_length:
                        self.commit(word, width, height, descent, ts, font)
                        return phrase_pos + len(word)-1, True
            if self.current_width < 5: # Force hyphenation as word is longer than line
                for i in range(len(word)-5, 0, -5):
                    part = word[:i] + '-'
                    width = fm.width(part)
                    if self.current_width + width < self.line_length:
                        self.commit(part, width, height, descent, ts, font)
                        return phrase_pos + len(part)-1, True
            # Failed to add word.
            return phrase_pos, True

        if not processed:
            return self.populate(phrase+' ', ts, False)

        return phrase_pos, False
コード例 #29
0
    def __init__(self, parent=None):
        super(RichTextLineEdit, self).__init__(parent)

        self.monofamily = QString("courier")
        self.sansfamily = QString("helvetica")
        self.seriffamily = QString("times")
        self.setLineWrapMode(QTextEdit.NoWrap)
        self.setTabChangesFocus(True)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        fm = QFontMetrics(self.font())
        h = int(fm.height() * (1.4 if platform.system() == "Windows" else 1.2))
        self.setMinimumHeight(h)
        self.setMaximumHeight(int(h * 1.2))
        self.setToolTip("Press <b>Ctrl+M</b> for the text effects "
                        "menu and <b>Ctrl+K</b> for the color menu")
コード例 #30
0
    def create_digital_indicator(self):
        """ Main value indicator inside the Gauge """
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        # Place the coordinate origin in the center
        painter.translate(*self.center_p())
        # painter.save()
        # xShadow = 3.0
        # yShadow = 3.0
        font = QFont(self.value_fontname, self.value_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.DisplayValueColor)
        painter.setPen(pen_shadow)

        text_radius = self.widget_diameter / 2 * self.text_radius_factor

        # angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        # for i in range(self.scala_main_count + 1):
        text = str(int(self.value))
        w = fm.width(text) + 1
        h = fm.height()
        painter.setFont(QFont(self.value_fontname, self.value_fontsize))

        # Mitte zwischen Skalenstart und Skalenende:
        # Skalenende = Skalenanfang - 360 + Skalenlaenge
        # Skalenmitte = (Skalenende - Skalenanfang) / 2 + Skalenanfang
        angle_end = float(self.scale_angle_start_value +
                          self.scale_angle_size - 360)
        angle = (angle_end - self.scale_angle_start_value
                 ) / 2 + self.scale_angle_start_value

        x = text_radius * math.cos(math.radians(angle))
        y = text_radius * math.sin(math.radians(angle))
        # print(w, h, x, y, text)
        text = [
            x - int(w / 2), y - int(h / 2),
            int(w),
            int(h), Qt.AlignCenter, text
        ]
        painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
コード例 #31
0
 def paint(self, painter, dummyOption, dummyWidget=None):
     painter.save()
     try:
         scheme = self._qScore.parent().colourScheme
         painter.setPen(QPen(scheme.text.borderColour))
         font = self.font()
         if font is None:
             font = painter.font()
         else:
             painter.setFont(font)
         fm = QFontMetrics(painter.font())
         self.setRect(fm)
         lineHeight = fm.height()
         for index, data in enumerate(self._iterData()):
             painter.drawText(QPoint(5, (index + 1) * lineHeight), data)
     finally:
         painter.restore()
コード例 #32
0
ファイル: QGraphicsListData.py プロジェクト: Whatang/DrumBurp
 def paint(self, painter, dummyOption, dummyWidget = None):
     painter.save()
     try:
         scheme = self._qScore.parent().colourScheme
         painter.setPen(QPen(scheme.text.borderColour))
         font = self.font()
         if font is None:
             font = painter.font()
         else:
             painter.setFont(font)
         fm = QFontMetrics(painter.font())
         self.setRect(fm)
         lineHeight = fm.height()
         for index, data in enumerate(self._iterData()):
             painter.drawText(QPoint(5, (index + 1) * lineHeight), data)
     finally:
         painter.restore()
コード例 #33
0
    def __init__(self, parent=None):
        super(RichTextLineEdit, self).__init__(parent)

        self.monofamily = QString("courier")
        self.sansfamily = QString("helvetica")
        self.seriffamily = QString("times")
        self.setLineWrapMode(QTextEdit.NoWrap)
        self.setTabChangesFocus(True)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        fm = QFontMetrics(self.font())
        h = int(fm.height() * (1.4 if platform.system() == "Windows"
                                   else 1.2))
        self.setMinimumHeight(h)
        self.setMaximumHeight(int(h * 1.2))
        self.setToolTip("Press <b>Ctrl+M</b> for the text effects "
                "menu and <b>Ctrl+K</b> for the color menu")
コード例 #34
0
ファイル: mainwindow.py プロジェクト: grengojbo/blink-qt
    def setupUi(self):
        super(MainWindow, self).setupUi(self)

        self.search_box.shortcut = QShortcut(self.search_box)
        self.search_box.shortcut.setKey('CTRL+F')

        self.output_devices_group = QActionGroup(self)
        self.input_devices_group = QActionGroup(self)
        self.alert_devices_group = QActionGroup(self)

        # adjust search box height depending on theme as the value set in designer isn't suited for all themes
        search_box = self.search_box
        option = QStyleOptionFrameV2()
        search_box.initStyleOption(option)
        frame_width = search_box.style().pixelMetric(QStyle.PM_DefaultFrameWidth, option, search_box)
        if frame_width < 4:
            search_box.setMinimumHeight(20 + 2*frame_width)

        # adjust status combo-box font size to fit the combo-box
        option = QStyleOptionComboBox()
        self.status.initStyleOption(option)
        frame_width = self.status.style().pixelMetric(QStyle.PM_DefaultFrameWidth, option, self.status)
        font = self.status.font()
        font.setFamily('Sans Serif')
        font.setPointSize(font.pointSize() - 1) # make it 1 point smaller then the default font size
        font_metrics = QFontMetrics(font)
        if font_metrics.height() > self.status.maximumHeight() - 2*frame_width:
            pixel_size = 11 - (frame_width - 2) # subtract 1 pixel for every frame pixel over 2 pixels
            font.setPixelSize(pixel_size)
        self.status.setFont(font)

        # adjust the combo boxes for themes with too much padding (like the default theme on Ubuntu 10.04)
        option = QStyleOptionComboBox()
        self.status.initStyleOption(option)
        font_metrics = self.status.fontMetrics()
        text_width = max(font_metrics.width(self.status.itemText(index)) for index in xrange(self.status.count()))
        frame_width = self.status.style().pixelMetric(QStyle.PM_ComboBoxFrameWidth, option, self.status)
        arrow_width = self.status.style().subControlRect(QStyle.CC_ComboBox, option, QStyle.SC_ComboBoxArrow, self.status).width()
        wide_padding = self.status.style().subControlRect(QStyle.CC_ComboBox, option, QStyle.SC_ComboBoxEditField, self.status).height() < 10
        self.status.setFixedWidth(text_width + arrow_width + 2*frame_width + 30) # 30? Don't ask.
        self.status.setStyleSheet("""QComboBox { padding: 0px 3px 0px 3px; }""" if wide_padding else "")
        self.identity.setStyleSheet("""QComboBox { padding: 0px 4px 0px 4px; }""" if wide_padding else "")
コード例 #35
0
    def paintSection(self, painter, rect, logicalIndex):
        gradient = QLinearGradient(0, 0, 0, rect.height())
        if self._mouse_over:
            gradient.setColorAt(0.0, QColor("#808080"))
            gradient.setColorAt(1.0, QColor("#474747"))
        else:
            gradient.setColorAt(0.0, QColor("#727272"))
            gradient.setColorAt(1.0, QColor("#363636"))
        painter.fillRect(rect, QBrush(gradient))

        if self._is_current_project:
            painter.setPen(QColor(0, 204, 82))
        else:
            painter.setPen(QColor(Qt.white))
        font = painter.font()
        font.setBold(True)
        painter.setFont(font)
        font_metrics = QFontMetrics(painter.font())
        ypos = (rect.height() / 2) + (font_metrics.height() / 3)
        painter.drawText(10, ypos, self.title)
コード例 #36
0
    def paintSection(self, painter, rect, logicalIndex):
        gradient = QLinearGradient(0, 0, 0, rect.height())
        if self._mouse_over:
            gradient.setColorAt(0.0, QColor("#808080"))
            gradient.setColorAt(1.0, QColor("#474747"))
        else:
            gradient.setColorAt(0.0, QColor("#727272"))
            gradient.setColorAt(1.0, QColor("#363636"))
        painter.fillRect(rect, QBrush(gradient))

        if self._is_current_project:
            painter.setPen(QColor(0, 204, 82))
        else:
            painter.setPen(QColor(Qt.white))
        font = painter.font()
        font.setBold(True)
        painter.setFont(font)
        font_metrics = QFontMetrics(painter.font())
        ypos = (rect.height() / 2) + (font_metrics.height() / 3)
        painter.drawText(10, ypos, self.title)
コード例 #37
0
 def maxNotchSize( self, orientation ):
     """
     Returns the maximum size for this ruler based on its notches and the
     given orientation.
     
     :param      orientation | <Qt.Orientation>
     
     :return     <int>
     """
     metrics = QFontMetrics(QApplication.font())
     
     if orientation == Qt.Vertical:
         notch = ''
         for n in self.notches():
             if len(str(n)) > len(str(notch)):
                 notch = str(n)
         
         return metrics.width(notch)
     else:
         return metrics.height()
コード例 #38
0
ファイル: SpeedReader.py プロジェクト: gokmen/Apps
    def setText(self, text = ''):
        """ This function is used to update label text.

        :param text: New text to update label
        :type text: string

        """
        # Store the text
        self.text = text

        # Create a qfont for system font
        # We will use the font to calculate metrics
        font = QFont(self.font, 10, QFont.Normal)
        fm = QFontMetrics(font)

        # Calculate base_width/height over system font
        self.font_base_width = fm.width(self.text)
        self.font_base_height = fm.height()

        # Re-paint the text
        self.update()
コード例 #39
0
    def create_values_text(self):
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        # painter.save()
        # xShadow = 3.0
        # yShadow = 3.0
        font = QFont(self.value_fontname, self.value_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.DisplayValueColor)
        painter.setPen(pen_shadow)

        text_radius = self.widget_diameter / 2 * self.text_radius_factor

        # angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        # for i in range(self.scala_main_count + 1):
        frac, whole = math.modf(self.value)

        text = ("%0.1f" % (abs(frac)*10)) + 'E' + str(int(whole)) + ' ' + self.units
        w = fm.width(text) + 1
        h = fm.height()
        painter.setFont(QFont(self.value_fontname, self.value_fontsize))

        # Mitte zwischen Skalenstart und Skalenende:
        # Skalenende = Skalenanfang - 360 + Skalenlaenge
        # Skalenmitte = (Skalenende - Skalenanfang) / 2 + Skalenanfang
        angle_end = float(self.scale_angle_start_value + self.scale_angle_size - 360)
        angle = (angle_end - self.scale_angle_start_value) / 2 + self.scale_angle_start_value

        x = text_radius * math.cos(math.radians(angle))
        y = text_radius * math.sin(math.radians(angle))
        # print(w, h, x, y, text)
        text = [x - int(w/2), y - int(h/2), int(w), int(h), Qt.AlignCenter, text]
        painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
コード例 #40
0
ファイル: mapwidget.py プロジェクト: loongfee/Roam
    def _calc_size(self):
        realSize = self.realsize
        canvaswidth = self.canvas.width()
        mapunitsperpixel = abs(self.canvas.mapUnitsPerPixel())
        mapunits = self.canvas.mapUnits()
        prefered_units = roam.config.settings.get("prefer_units", "meters")
        newunits = QGis.fromLiteral(prefered_units, QGis.Meters)
        mapunitsperpixel *= QGis.fromUnitToUnitFactor(mapunits, newunits)
        mapunits = newunits

        # Convert the real distance into pixels
        barwidth = realSize / mapunitsperpixel

        if barwidth < 30:
            barwidth = canvaswidth / 4

        while barwidth > canvaswidth / 3:
            barwidth /= 3

        realSize = barwidth * mapunitsperpixel

        # Round
        powerof10 = math.floor(math.log10(realSize))
        scaler = math.pow(10.0, powerof10)
        realSize = round(realSize / scaler) * scaler
        barwidth = realSize / mapunitsperpixel
        label, realSize = self._label_size(mapunits, realSize)
        metrics = QFontMetrics(self.font)
        fontwidth = metrics.width(label)
        fontheight = metrics.height()

        sizelabel = QLocale.system().toString(realSize)
        sizelabel = "{} {}".format(sizelabel, label)

        barwidth = self._adjust_bar_size(barwidth, mapunits)
        barwidth = barwidth + fontwidth

        return barwidth, realSize, sizelabel, (fontwidth, fontheight)
コード例 #41
0
ファイル: mapwidget.py プロジェクト: zoujun8666/Roam
    def _calc_size(self):
        realSize = self.realsize
        canvaswidth = self.canvas.width()
        mapunitsperpixel = abs(self.canvas.mapUnitsPerPixel())
        mapunits = self.canvas.mapUnits()
        prefered_units = roam.config.settings.get("prefer_units", "meters")
        newunits = QGis.fromLiteral(prefered_units, QGis.Meters)
        mapunitsperpixel *= QGis.fromUnitToUnitFactor(mapunits, newunits)
        mapunits = newunits

        # Convert the real distance into pixels
        barwidth = realSize / mapunitsperpixel

        if barwidth < 30:
            barwidth = canvaswidth / 4

        while barwidth > canvaswidth / 3:
            barwidth /= 3

        realSize = barwidth * mapunitsperpixel

        # Round
        powerof10 = math.floor(math.log10(realSize))
        scaler = math.pow(10.0, powerof10)
        realSize = round(realSize / scaler) * scaler
        barwidth = realSize / mapunitsperpixel
        label, realSize = self._label_size(mapunits, realSize)
        metrics = QFontMetrics(self.font)
        fontwidth = metrics.width(label)
        fontheight = metrics.height()

        sizelabel = QLocale.system().toString(realSize)
        sizelabel = "{} {}".format(sizelabel, label)

        barwidth = self._adjust_bar_size(barwidth, mapunits)
        barwidth = barwidth + fontwidth

        return barwidth, realSize, sizelabel, (fontwidth, fontheight)
コード例 #42
0
    def paint_text(self, QPainter):
        """
        Render the node text (branch name)

        :param QPainter: interface to the canvas
        """

        # Set up font and text settings
        text_font = QFont()
        text_font.setPointSize(NODE_TEXT_FONT_SIZE)
        QPainter.setFont(text_font)
        QPainter.setPen(NODE_TEXT_COLOR)

        # Measure size of strings so they can be centered properly
        font_metrics = QFontMetrics(text_font)
        label_text_width = font_metrics.width(self.branch.name)
        label_text_height = font_metrics.height()

        # Position and render text
        label_margin_left = (NODE_WIDTH - label_text_width) / 2
        label_margin_top = (NODE_HEIGHT - label_text_height) / 2
        label_position = QPointF(label_margin_left, label_margin_top / 2 + label_text_height)
        QPainter.drawText(label_position, self.branch.name)
コード例 #43
0
    def paintEvent(self, event):
        # Initialize QPainter properties
        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)
        if self.height() <= self.width() / self.ref_aspect_ratio:
            v_scale = self.height()
            h_scale = v_scale * self.ref_aspect_ratio
        else:
            h_scale = self.width()
            v_scale = h_scale / self.ref_aspect_ratio
        # Scale all objects proportionate to window size
        painter.scale(h_scale / self.width_ref, v_scale / self.height_ref)
        painter.setClipPath(self.dial)  # Don't allow objects or text to extend outside of main dial shape
        painter.save()

        # First draw main gauge background
        pen = QPen(painter.pen())
        pen.setWidth(1)
        pen.setColor(Qt.black)
        painter.setPen(pen)
        painter.setBrush(QColor(100, 100, 100, 255))  # self.dial_bg)
        painter.drawPath(self.dial)

        # Add Minor and Major Alarm limit bars
        pen.setWidth(16)
        pen.setCapStyle(Qt.FlatCap)
        pen.setJoinStyle(Qt.BevelJoin)

        pen.setColor(Qt.yellow)
        painter.setPen(pen)
        painter.setBrush(Qt.NoBrush)
        painter.drawPath(self.low_arc)
        painter.drawPath(self.high_arc)

        pen.setColor(Qt.red)
        painter.setPen(pen)
        painter.drawPath(self.lolo_arc)
        painter.drawPath(self.hihi_arc)

        painter.restore()

        # Display PV current value
        painter.save()
        font = QFont()
        font.setPixelSize(45)
        painter.setFont(font)
        sevr = self.channel.sevr.lower()
        if sevr == 'major':
            color = Qt.red
        elif sevr == 'minor':
            color = Qt.yellow
        elif sevr == 'invalid':
            color = Qt.magenta
        else:
            color = Qt.green
        pen.setColor(color)
        painter.setPen(pen)
        font_metric = QFontMetrics(font)
        painter.translate(self.dial_width / 2, self.dial_height / 2)
        label = self.format_label(self.channel_value)
        painter.drawText(QPointF(0.0 - font_metric.width(label) / 2.0, font_metric.height() / 2.0),
                         label)

        # Display PV name
        painter.setFont(self.pv_label_font)
        pen.setColor(Qt.black)  # Qt.darkCyan)
        pen.setWidth(1)
        painter.setPen(pen)
        # brush = QBrush(Qt.darkCyan)
        # painter.setBrush(brush)
        font_metric = QFontMetrics(self.pv_label_font)
        pv_label = self.channel.egu  # self.channel.name + ' (' + self.channel.egu + ')'
        painter.drawText(QPointF(0.0 - font_metric.width(pv_label) / 2.0,
                                 (self.dial_height / 2.0) + (font_metric.height() * 1.5)),
                         pv_label)
        # painter.drawPath(self.pv_label_path)
        painter.restore()

        # Next add division markers
        painter.save()
        painter.translate(self.dial_width / 2, self.dial_height * 0.98)
        pen.setColor(Qt.black)  # Qt.cyan)
        pen.setWidth(2)
        painter.setPen(pen)
        for i in range(0, 31):
            if (i % 5) != 0:
                painter.drawLine(-self.dial_width / 2.1, 0.0, -self.dial_width / 2.2, 0.0)
            else:
                painter.drawLine(-self.dial_width / 2.1, 0.0, -self.dial_width / 2.3, 0.0)
            painter.rotate(6.0)
        painter.restore()

        # Layout division text labels
        painter.save()
        painter.translate(self.dial_width / 2, self.dial_height * 0.98)
        pen.setColor(Qt.black)  # Qt.cyan)
        painter.setPen(pen)
        font = QFont()
        font.setPixelSize(18)
        painter.setFont(font)
        font_metric = QFontMetrics(font)
        labels = linspace(self.lim_low, self.lim_hi, 7)
        painter.rotate(-90)
        for i in range(0, 7):
            label = self.format_label(labels[i])
            painter.drawText(QPointF(0.0 - font_metric.width(label) / 2.0, -self.dial_height * 0.75), label)
            painter.rotate(30)
        painter.restore()

        # Draw needle at appropriate angle for data
        painter.save()
        painter.translate(self.dial_width / 2, self.dial_height * 0.98)
        painter.rotate(-180 * (1.0 - self.percentage))

        pen.setColor(QColor(self.needle_color).darker(200))
        pen.setWidth(1)
        painter.setPen(pen)
        painter.setBrush(self.needle_color)
        painter.drawPolygon(self.needle)
        painter.restore()

        # if self.percentage <= 0.5:
        #     shadow = max(490 * self.percentage, 127)
        #     needle_left_color = QColor(0, shadow, shadow)  # Qt.darkCyan  # QColor(80,80,80,255)
        #     needle_right_color = Qt.cyan  # QColor(230,230,230,255)
        # else:
        #     shadow = max(125 / self.percentage, 127)
        #     needle_left_color = Qt.cyan  # QColor(230,230,230,255)
        #     needle_right_color = QColor(0, shadow, shadow)  # Qt.darkCyan  # QColor(80,80,80,255)
        #
        # # Draw Highlight side of needle
        # pen.setWidth(1)
        # pen.setColor(Qt.gray)  # needle_left_color)
        # painter.setPen(pen)
        # painter.setBrush(Qt.gray)  # needle_left_color)
        # painter.drawPolygon(self.needle_left)
        #
        # # Draw shadow side of needle
        # pen.setColor(Qt.gray)  # needle_right_color)
        # painter.setPen(pen)
        # painter.setBrush(Qt.gray)  # needle_right_color)
        # painter.drawPolygon(self.needle_right)
        # painter.restore()

        # Draw needle axel pin
        painter.save()
        pen.setWidth(1)
        pen.setColor(Qt.black)
        painter.setPen(pen)
        painter.setBrush(QColor(50, 50, 50, 255))  # self.pin_bg)
        painter.translate(self.dial_width / 2, self.dial_height * 0.98)
        painter.drawEllipse(self.pin_rect)
        painter.restore()

        # Draw glass reflection and shadow effects
        # painter.save()
        # painter.translate(self.dial_width / 2.0, self.dial_height / 2.0)
        # painter.setPen(Qt.NoPen)
        # painter.setBrush(QColor(0, 0, 0, 20))
        # painter.drawEllipse(self.shadow_rect)
        # painter.setBrush(self.gloss_gradient)
        # painter.drawEllipse(self.gloss_rect)
        # painter.restore()

        painter.end()
コード例 #44
0
class asciiItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
        self.initFont()
        self.initMetricsValues()
#        self.initCursor()

    def initPosition(self):
        self.setPos(485, 25)
#        self.setTextInteractionFlags(Qt.TextSelectableByMouse)

    def initValues(self, whex):
        self.whex = whex
        self.bdiff = self.whex.bdiff
        #Buffer
        self.buffer = []
        self.bufferLines = 0 
        #Line
        self.currentLine = 0
        #Offset
        self.startOffset = 0
        self.fontPixel = 14
        #Current Positions
        self.currentPos = 0

#    def initCursor(self):
#        self.cursor = asciiCursor(self)
#        self.bdiff.scene.addItem(self.cursor)

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.darkCyan))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        self.setFont(self.font)

        self.sfont = QFont("Gothic")
        self.sfont.setFixedPitch(1)
        self.sfont.setBold(False)
        self.sfont.setPixelSize(self.fontPixel)

        self.metric = QFontMetrics(self.font)

        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 1
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * 16)
#        print "start ASCII blank"
#        print self.startBlank

    #Print Operations
    def printBuffer(self, buff):
        del self.buffer
        self.buffer = buff

        count = 0
        printer = QString()

        for char in buff:
            if char > "\x20" and char < "\x7e":
               printer.append(char)
            else:
                printer.append(".")
            if count < 15:
                count += 1
            else:
                printer.append("\n")
                count = 0

        #Clear and set
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(printer)
        cursor.movePosition(QTextCursor.Start)


    def colorizeDiff(self, diffinfos):
        cursor = self.textCursor()
        cursor.setPosition(QTextCursor.Start)

        text = self.toPlainText()

        keys = diffinfos.keys()
        keys.sort()

        for offset in keys:
            difflen = diffinfos[offset]
            pos = offset + (offset / 16)
#            count =  offset / 16

#            print "offset ", offset, " count ", count

            count = difflen + (((offset + difflen) / 16) - (offset / 16))
#            count = difflen
            cursor.setPosition(pos, QTextCursor.MoveAnchor)
#            print "L", l, " len ", pos + difflen
            cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, count)

            format = QTextCharFormat()
            format.setFont(self.sfont)
            format.setForeground(QBrush(QColor(Qt.red)))
            cursor.setCharFormat(format)
            cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor)
コード例 #45
0
ファイル: factura.py プロジェクト: luismejiadev/pyqt_billing
    def imprimir(self, printer):

        leftMargin = 72
        widthCol = 100

        arialFont = QFont("Helvetica", 16, 3)

        fuente = QFontMetrics(arialFont)
        arialLineHeight = fuente.height()

        fondo = QPixmap(":/images/res/fondo.png")
        painter = QPainter(printer)
        pageRect = printer.pageRect()
        page = 1

        painter.save()
        if self.vistaprevia:
            painter.drawPixmap(0, 0, 530, 830, fondo)

        painter.setFont(arialFont)

        y = 180
        x = 35
        painter.drawText(x, y, self.editmodel.fecha.toString("dd   MM   yy"))

        y = 210
        x = 85

        painter.drawText(x, y, self.editmodel.cliente)

        painter.setFont(arialFont)

        cajasFont = QFont("Helvetica", 10, 2)
        x = -5
        y = 295

        painter.setFont(cajasFont)
        painter.drawText(x, y - arialLineHeight - 1, "Cajas")

        for row in self.editmodel.lines:
            painter.setFont(cajasFont)
            x = 2
            painter.drawText(x, y, row.cantidad())

            painter.setFont(arialFont)
            total = moneyfmt(row.total, 2, "")
            x = 470 - fuente.width(total)
            painter.drawText(x, y, total)

            x = 310
            painter.drawText(x, y, moneyfmt(row.itemPrice, 2, ""))

            x = 30
            painter.drawText(x, y, row.unidades())

            x = 80
            painter.drawText(x, y, row.itemDescription)

            y += arialLineHeight

        total = moneyfmt(self.editmodel.total, 2, "")
        y = 690
        x = 470 - fuente.width(total)
        painter.drawText(x, y, total)

        painter.setPen(Qt.black)
        #        printer.newPage()
        painter.restore()
コード例 #46
0
ファイル: hexItem.py プロジェクト: kzwkt/dff
class hexItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
        self.initFont()
        self.initMetricsValues()

    def initPosition(self):
        self.setPos(95, 25)

    def initValues(self, whex):
        self.whex = whex
        self.bdiff = self.whex.bdiff
        self.hexview = self.whex.view
        #Buffer
        self.buffer = []
        self.fontPixel = 14
        #Current Position

        self.bytesPerLine = self.bdiff.bytesPerLine
        self.groupBytes = self.bdiff.groupBytes

        #Selection
        self.select = False
        self.xsel = 0
        self.ysel = 0

    def initDocument(self):
        self.document = QTextDocument()
        self.setDocument(self.document)

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.black))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        #        self.setFont(self.font)
        self.setFont(self.font)

        #Search Highlight font
        self.sfont = QFont("Gothic")
        self.sfont.setFixedPitch(1)
        self.sfont.setBold(False)
        self.sfont.setPixelSize(self.fontPixel)

        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 2 * self.groupBytes
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * self.bytesPerLine) - (
            self.charW * (self.bytesPerLine - 1))

    #Print Operations

    def dumpHexBuffer(self, buff):
        self.printFullBuffer(buff)

    def dumpEOF(self):
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText("\t\tEnd of file")
        cursor.movePosition(QTextCursor.Start)

    def printFullBuffer(self, buff):
        del self.buffer
        pos = str(len(buff)) + 'B'
        self.buffer = struct.unpack(pos, buff)
        count = 0
        fullBuff = QString()
        for byte in self.buffer:
            fullBuff.append("%.2x" % byte)
            if count < 15:
                fullBuff.append(" ")
                count += 1
            else:
                fullBuff.append("\n")
                count = 0

        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(fullBuff)
        cursor.movePosition(QTextCursor.Start)

    def colorizeDiff(self, diffinfos):
        cursor = self.textCursor()
        cursor.setPosition(QTextCursor.Start)

        text = self.toPlainText()

        keys = diffinfos.keys()
        keys.sort()
        for offset in keys:
            difflen = diffinfos[offset]
            pos = (offset * 2) + offset
            count = difflen + (((offset + difflen) / 16) - (offset / 16))

            cursor.setPosition(pos, QTextCursor.MoveAnchor)
            cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor,
                                count)

            format = QTextCharFormat()
            format.setFont(self.sfont)
            format.setForeground(QBrush(QColor(Qt.red)))
            cursor.setCharFormat(format)
            cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor)
コード例 #47
0
ファイル: hexItem.py プロジェクト: palaniyappanBala/dff
class hexItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
#        self.initDocument()
        self.initFont()
        self.initMetricsValues()
#        self.initCursor()

    def initPosition(self):
        self.setPos(95, 25)

    def initValues(self, whex):
        self.whex = whex
        self.heditor = self.whex.heditor
        self.hexview = self.whex.view
        #Buffer
        self.buffer = []
        self.fontPixel = 14
        #Current Position

        self.bytesPerLine = self.heditor.bytesPerLine
        self.groupBytes = self.heditor.groupBytes

        #Selection
        self.select = False
        self.xsel = 0
        self.ysel = 0

    def initDocument(self):
        self.document = QTextDocument()
        self.setDocument(self.document)

#    def initSyntaxHighlighter(self):
#        self.search = self.heditor.right.search
#        self.highlighter = highlighter(self)

#    def initCursor(self):
#        self.cursor = hexCursor(self)
#        self.heditor.whex.view.scene.addItem(self.cursor)
 
    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.black))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
#        self.setFont(self.font)
        self.setFont(self.font)

        #Search Highlight font
        self.sfont = QFont("Gothic")
        self.sfont.setFixedPitch(1)
        self.sfont.setBold(False)
        self.sfont.setPixelSize(self.fontPixel)

        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 2 * self.groupBytes
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * self.bytesPerLine) - (self.charW * (self.bytesPerLine - 1))
#        print "start blank"
#        print self.startBlank

#    def getPatternOffsets(self, buff):
#       plist = self.search.searchedPatterns
#        startoffset = self.heditor.currentOffset
#        offlist = {}

#        for pattern, offsetlist  in plist.iteritems():
#            for offset in offsetlist:
#                if offset >= startoffset and offset <= startoffset + self.heditor.readSize:
#                    offlist[offset - self.heditor.currentOffset] = len(pattern) / 2
#        return offlist

    #Print Operations

    def dumpHexBuffer(self, buff):
        self.printFullBuffer(buff)
#        searchofflist = self.getPatternOffsets(buff)
#        if len(searchofflist) > 0:
#            highoffsets = searchofflist.keys()
#            highoffsets.sort()
#            self.highlighter(searchofflist)
            
    def printFullBuffer(self, buff):
        del self.buffer
        pos = str(len(buff)) + 'B'
        self.buffer = struct.unpack(pos, buff)
        count = 0
        fullBuff = QString()
        for byte in self.buffer:
            fullBuff.append("%.2x" % byte)
            if count < 15:
                fullBuff.append(" ")
                count += 1
            else:
                fullBuff.append("\n")
                count = 0

        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(fullBuff)
        cursor.movePosition(QTextCursor.Start)
#        if len(self.search.searchedPatterns) > 0:
#            self.highlighter.highlightBlock(self.document.toPlainText())

    def getXPos(self, x):
        count = 0
        current = self.byteW + (self.charW / 2) + (self.startBlank / 2)
        while current < x:
            count += 1
            current = current + self.byteW + self.charW
        return count

    def getYPos(self, y):
        count = 0
        current = self.byteH
        while current < y:
            count += 1
            current = current + self.byteH
        return count

    def highlighter(self, searchofflist):
        offsets = searchofflist.keys()
        cursor = self.textCursor()
        cursor.setPosition(QTextCursor.Start)
        for offset in offsets:
            len = searchofflist[offset]
            pos = (offset * 2) + offset
            cursor.setPosition(pos, QTextCursor.MoveAnchor)
            l = 0
            while l < len:
                cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor)
                l += 1

            format = QTextCharFormat()
            format.setFont(self.sfont)
            format.setForeground(QBrush(QColor(Qt.red)))
            cursor.setCharFormat(format)
            cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor)



    ############## #
    # MOUSE EVENTS # ###########################
    ############## #

    def mouseMoveEvent(self, event):
        pos = event.pos()
        x = pos.x()
        y = pos.y()
        xpos = self.getXPos(x)
        ypos = self.getYPos(y)
        self.heditor.selection.select(self.heditor.selection.xstart, self.heditor.selection.ystart, xpos, ypos)
        self.heditor.infos.update()
        self.heditor.right.decode.update()

    def mousePressEvent(self, event):
        button = event.button()
        pos = event.pos()
        if event.button() == 1:
            #Get CLicked coordonates
            x = pos.x()
            y = pos.y()
            xpos = self.getXPos(x)
            ypos = self.getYPos(y)
            #refresh cursors
            self.whex.hexcursor.draw(xpos, ypos)
            self.whex.asciicursor.draw(xpos, ypos)

            self.heditor.selection.select(xpos, ypos, xpos, ypos, True)
            self.heditor.right.decode.update()
            self.heditor.infos.update()

    def mouseReleaseEvent(self, event):
        pass
コード例 #48
0
ファイル: vaultmanager.py プロジェクト: LucaLanziani/bluepass
 def sizeHint(self):
     fm = QFontMetrics(self.font())
     width = fm.width('999-999') + 10
     height = fm.height() + 8
     return QSize(width, height)
コード例 #49
0
ファイル: mapwidget.py プロジェクト: zoujun8666/Roam
class ScaleBarItem(QGraphicsItem):
    def __init__(self, canvas, parent=None):
        super(ScaleBarItem, self).__init__(parent)
        self.canvas = canvas
        self.realsize = 100
        black = QColor(Qt.black)
        black.setAlpha(150)
        white = QColor(Qt.white)
        white.setAlpha(150)
        blackpen = QPen(black, 4)
        whitepen = QPen(white, 8)
        self.pens = [whitepen, blackpen]
        self.whitepen = QPen(white, 1)
        self.blackbrush = QBrush(black)
        self.ticksize = 10
        self.fontsize = 15
        self.font = QFont()
        self.font.setPointSize(self.fontsize)
        self.font.setStyleHint(QFont.Times, QFont.PreferAntialias)
        self.font.setBold(True)
        self.metrics = QFontMetrics(self.font)

    def boundingRect(self):
        try:
            width, realsize, label, fontsize = self._calc_size()
            halfheight = (self.ticksize + fontsize[1]) / 2
            halfwidth = (width + fontsize[0]) / 2
            return QRectF(-halfwidth, -halfheight, halfwidth, halfheight)
        except ZeroDivisionError:
            return QRectF()

    def paint(self, painter, styleoptions, widget=None):
        try:
            width, realsize, label, fontsize = self._calc_size()
        except ZeroDivisionError:
            return

        mapunits = self.canvas.mapUnits()

        # painter.drawRect(self.boundingRect())
        array = QPolygon()
        canvasheight = self.canvas.height()
        canvaswidth = self.canvas.width()
        margin = 20
        originy = 0
        originx = 0

        self.setPos(margin, canvasheight - margin)

        x1, y1 = originx, originy
        x2, y2 = originx, originy + self.ticksize
        x3, y3 = originx + width, originy + self.ticksize
        midx, midy = originx + width / 2, originy + self.ticksize / 2
        x4, y4 = originx + width, originy

        for pen in self.pens:
            painter.setPen(pen)
            # Drwa the scale bar
            painter.drawLine(x1, y1, x2, y2)
            painter.drawLine(x2, y2, x3, y3)
            painter.drawLine(x3, y3, x4, y4)
            painter.drawLine(midx, midy, midx, y1)

        # Draw the text
        fontwidth = self.metrics.width("0")
        fontheight = self.metrics.height()
        fontheight /= 2
        fontwidth /= 2
        path = QPainterPath()
        point = QPointF(x1 - fontwidth, y1 - fontheight)
        path.addText(point, self.font, "0")
        painter.setPen(self.whitepen)
        painter.setBrush(self.blackbrush)
        painter.setRenderHints(QPainter.Antialiasing)
        painter.setFont(self.font)
        painter.drawPath(path)

        fontwidth = self.metrics.width(label)
        fontheight = self.metrics.height()
        fontheight /= 2
        fontwidth /= 2
        point = QPointF(x4 - fontwidth, y4 - fontheight)
        path.addText(point, self.font, label)
        painter.drawPath(path)

    def _calc_size(self):
        realSize = self.realsize
        canvaswidth = self.canvas.width()
        mapunitsperpixel = abs(self.canvas.mapUnitsPerPixel())
        mapunits = self.canvas.mapUnits()
        prefered_units = roam.config.settings.get("prefer_units", "meters")
        newunits = QGis.fromLiteral(prefered_units, QGis.Meters)
        mapunitsperpixel *= QGis.fromUnitToUnitFactor(mapunits, newunits)
        mapunits = newunits

        # Convert the real distance into pixels
        barwidth = realSize / mapunitsperpixel

        if barwidth < 30:
            barwidth = canvaswidth / 4

        while barwidth > canvaswidth / 3:
            barwidth /= 3

        realSize = barwidth * mapunitsperpixel

        # Round
        powerof10 = math.floor(math.log10(realSize))
        scaler = math.pow(10.0, powerof10)
        realSize = round(realSize / scaler) * scaler
        barwidth = realSize / mapunitsperpixel
        label, realSize = self._label_size(mapunits, realSize)
        metrics = QFontMetrics(self.font)
        fontwidth = metrics.width(label)
        fontheight = metrics.height()

        sizelabel = QLocale.system().toString(realSize)
        sizelabel = "{} {}".format(sizelabel, label)

        barwidth = self._adjust_bar_size(barwidth, mapunits)
        barwidth = barwidth + fontwidth

        return barwidth, realSize, sizelabel, (fontwidth, fontheight)

    def _label_size(self, unit, currentsize):
        if unit == QGis.Meters:
            if currentsize > 1000:
                return "km", currentsize / 1000
            elif currentsize < 0.01:
                return "mm", currentsize * 1000
            elif currentsize < 0.1:
                return "cm", currentsize * 100
            else:
                return "m", currentsize
        elif unit == QGis.Feet:
            print currentsize
            if currentsize > 5280.0:
                return "miles", currentsize / 5000
            elif currentsize == 5280.0:
                return "mile", currentsize / 5000
            elif currentsize < 1:
                return "inches", currentsize * 10
            elif currentsize == 1.0:
                return "foot", currentsize
            else:
                return "feet", currentsize
        elif unit == QGis.Degrees:
            if currentsize == 1.0:
                return "degree", currentsize
            else:
                return "degrees", currentsize
        else:
            return str(unit), currentsize

    def _adjust_bar_size(self, barsize, unit):
        if unit == QGis.Feet:
            if barsize > 5280.0 or barsize == 5280.0:
                return (barsize * 5290) / 5000
            elif barsize < 1:
                return (barsize * 10) / 12

        return barsize
コード例 #50
0
    def _setMinimumHeight(self):
        fnt = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fntSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
        fm = QFontMetrics(QFont(fnt, fntSize))

        self.setMinimumHeight(fm.height() + 10)
コード例 #51
0
ファイル: qtztextwidget.py プロジェクト: parapente/PiFi
class ZTextWidget(QWidget):
    upper_buf = []
    upper_buf_height = 0
    upper_win_cursor = [] # Upper win cursor x,y
    lower_win_cursor = 1 # Lower win cursor x (y cannot be changed!)
    fixed_font = None
    fixed_font_metrics = None
    fixed_font_width = 0
    fixed_font_height = 0
    buf = []
    width = 80
    height = 26
    cur_win = 0 # Default win is the lower (1 is for upper win)
    cur_fg = 10
    cur_bg = 2
    cur_style = 0
    max_char = 0
    start_pos = 0
    top_pos = 0
    cur_pos = 0
    input_buf = []
    _cursor_visible = False
    _ostream = None
    returnPressed = pyqtSignal(QString)
    keyPressed = pyqtSignal(int)

    def __init__(self,parent = None,flags = Qt.Widget):
        super(ZTextWidget,self).__init__(parent,flags)
        sp = QSizePolicy()
        sp.setHorizontalPolicy(QSizePolicy.Fixed)
        sp.setVerticalPolicy(QSizePolicy.Fixed)
        self.set_fixed_font("DeJa Vu Sans Mono", 9)
        self.setSizePolicy(sp)
        self.setFocusPolicy(Qt.StrongFocus)
        self._ostream = [ZStream(), ZStream(), ZStream(), ZStream()]
        self._ostream[0].selected = True
        for i in xrange(self.width *  self.height * 4):
            self.buf.append(0)

    def paintEvent(self,e):
        painter = QPainter(self)
        painter.fillRect(0, 0, self.width * self.fixed_font_width + 2, self.height * self.fixed_font_height, Qt.black)
        painter.setPen(Qt.gray)
        painter.setRenderHint(QPainter.TextAntialiasing)
        painter.setFont(self.fixed_font)
        painter.setBackgroundMode(Qt.OpaqueMode)
        # Print main window
        l = self.height
        while (l > 0):
            c = 1
            while (c <= self.width):
                y = self.fixed_font_metrics.ascent() + (l - 1) * self.fixed_font_height
                x = 1 + ((c - 1) * self.fixed_font_width)
                #print "**",l,"**",c
                if self.buf[(((self.height - l) * self.width) + c - 1) * 4] == 0:
                    painter.setPen(self.ztoq_color(self.cur_fg))
                else:
                    painter.setPen(self.ztoq_color(self.buf[(((self.height - l) * self.width) + c - 1) * 4]))
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1] == 0:
                    painter.setBackground(QBrush(self.ztoq_color(self.cur_bg)))
                else:
                    painter.setBackground(QBrush(self.ztoq_color(self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1])))
                # Set appropriate font style
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] == 0:
                    f = painter.font()
                    f.setBold(False)
                    f.setItalic(False)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 1: # Reverse video
                    painter.setPen(self.ztoq_color(self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1]))
                    painter.setBackground(QBrush(self.ztoq_color(self.buf[(((self.height - l) * self.width) + c - 1) * 4])))
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 2: # Bold
                    f = painter.font()
                    f.setBold(True)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 4: # Italic
                    f = painter.font()
                    f.setItalic(True)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 3] <> 0:
                    painter.drawText(x,y,self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 3])
                c += 1
            l -= 1
            c = 1
        # Print upper window
        if self.upper_buf <> []:
            l = 1
            while (l <= self.upper_buf_height):
                c = 1
                while (c <= self.width):
                    y = self.fixed_font_metrics.ascent() + (l - 1) * self.fixed_font_height
                    x = 1 + ((c - 1) * self.fixed_font_width)
                    #print "**",l,"**",c
                    if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 3] <> 0:
                        painter.setPen(self.ztoq_color(self.upper_buf[(((l - 1) * self.width) + c - 1) * 4]))
                        painter.setBackground(QBrush(self.ztoq_color(self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 1])))
                        # Set appropriate font style
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] == 0:
                            f = painter.font()
                            f.setBold(False)
                            f.setItalic(False)
                            painter.setFont(f)
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 1: # Reverse video
                            painter.setPen(self.ztoq_color(self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 1]))
                            painter.setBackground(QBrush(self.ztoq_color(self.upper_buf[(((l - 1) * self.width) + c - 1) * 4])))
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 2: # Bold
                            f = painter.font()
                            f.setBold(True)
                            painter.setFont(f)
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 4: # Italic
                            f = painter.font()
                            f.setItalic(True)
                            painter.setFont(f)
                        painter.drawText(x,y,self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 3])
                    c += 1
                l += 1
        # Print cursor if visible
        if self._cursor_visible:
            self.display_cursor()

    def sizeHint(self):
        size = QSize()
        size.setWidth(self.width * self.fixed_font_width + 2)
        size.setHeight(self.height * self.fixed_font_height)
        return size

    def set_fixed_font(self,name,size):
        self.fixed_font = QFont(name, size)
        self.fixed_font.setFixedPitch(True)
        self.fixed_font.setKerning(False)
        self.fixed_font_metrics = QFontMetrics(self.fixed_font)
        self.fixed_font_width = self.fixed_font_metrics.averageCharWidth()
        self.fixed_font_height = self.fixed_font_metrics.height()
        #print self.fixed_font_width, self.fixed_font_height

    def ztoq_color(self,c):
        if c == 2:
            return Qt.black
        elif c == 3:
            return Qt.red
        elif c == 4:
            return Qt.green
        elif c == 5:
            return Qt.yellow
        elif c == 6:
            return Qt.blue
        elif c == 7:
            return Qt.magenta
        elif c == 8:
            return Qt.cyan
        elif c == 9:
            return Qt.white
        elif c == 10:
            return Qt.lightGray
        elif c == 11:
            return Qt.gray
        elif c == 12:
            return Qt.darkGray

    def set_cursor(self,x,y):
        self.upper_win_cursor = [x,y]

    def set_window(self,w):
        if w < 2:
            self.cur_win = w
        else:
            sys.exit("Unknown window {0}!?!".args(w))

    def prints(self,txt):
        if self._ostream[0].selected:
            if self.cur_win == 0: # Lower win
                # TODO: Buffering
                c = self.lower_win_cursor
                i = 0
                total = len(txt)
                #print "Total -", total
                while (i < total):
                    s = ""
                    while (i < total) and (txt[i] <> '\n') and (c <= self.width):
                        s += txt[i]
                        i += 1
                        c += 1
                    self.print_line(s)
                    #print "--> [i, c, total]", i, c, total, " ++ ", s
                    if c > self.width:
                        self.insert_new_line()
                        self.lower_win_cursor = 1
                        c = 1
                    elif (i < total) and (txt[i] == '\n'):
                        self.insert_new_line()
                        self.lower_win_cursor = 1
                        c = 1
                        i += 1
                    #elif (i == total) and (txt[i-1] <> '\n'):
                    else:
                        self.lower_win_cursor += len(s)
            else:
                i = self.upper_win_cursor[0]
                j = 0
                l = self.upper_win_cursor[1]
                #print "-", i, l, "-", txt
                #print "len upperbuf=", len(self.upper_buf)
                while (i <= self.width) and (j < len(txt)):
                    if txt[j] <> '\n':
                        self.upper_buf[(((l - 1) * self.width) + (i - 1)) * 4] = self.cur_fg
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 1] = self.cur_bg
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 2] = self.cur_style
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 3] = txt[j]
                        i += 1
                        j += 1
                    else:
                        self.upper_win_cursor = [1,l + 1]
                        i = 1
                        l += 1
                        j += 1
                self.upper_win_cursor[0] += j
            self.update()

    def print_line(self,txt):
        col = self.lower_win_cursor
        #print "Column:", col, txt
        if self.cur_win == 0: # Lower win
            for i in xrange(len(txt)):
                self.buf[(col - 1 + i) * 4] = self.cur_fg
                self.buf[((col - 1 + i) * 4) + 1] = self.cur_bg
                self.buf[((col - 1 + i) * 4) + 2] = self.cur_style
                self.buf[((col - 1 + i) * 4) + 3] = txt[i]

    def print_char(self,c):
        col = self.lower_win_cursor
        if self.cur_win == 0: # Lower win
            if c <> '\n':
                self.buf[(col - 1) * 4] = self.cur_fg
                self.buf[((col - 1) * 4) + 1] = self.cur_bg
                self.buf[((col - 1) * 4) + 2] = self.cur_style
                self.buf[((col - 1) * 4) + 3] = c
                self.lower_win_cursor += 1
            if self.lower_win_cursor > self.width: # If we exceed screen width
                #print "I insert a newline"
                self.insert_new_line()
                self.lower_win_cursor = 1
            elif c == '\n':
                self.insert_new_line()
                self.lower_win_cursor = 1
        self.update()

    def set_max_input(self,m):
        self.max_char = m

    def show_cursor(self):
        self.cur_pos = self.lower_win_cursor
        self.top_pos = self.cur_pos
        self.start_pos = self.cur_pos
        self.input_buf = []
        self._cursor_visible = True
        self.update()

    def hide_cursor(self):
        self._cursor_visible = False
        self.update()

    def display_cursor(self):
        painter = QPainter(self)
        col = self.cur_pos
        y = self.fixed_font_metrics.ascent() + ((self.height - 1) * self.fixed_font_height)
        x = 1 + ((col - 1) * self.fixed_font_width)
        painter.setPen(self.ztoq_color(self.cur_fg))
        painter.setBackground(QBrush(self.ztoq_color(self.cur_bg)))
        painter.drawText(x,y,unichr(0x2581))

    def keyPressEvent(self,e):
        if e.key() == Qt.Key_Left:
            if self.cur_pos > self.start_pos:
                self.cur_pos -= 1
                self.update()
            e.accept()
            self.keyPressed.emit(131)
        elif e.key() == Qt.Key_Right:
            if self.cur_pos < self.top_pos:
                self.cur_pos += 1
                self.update()
            e.accept()
            self.keyPressed.emit(132)
        elif e.key() == Qt.Key_Up:
            # TODO: Up in history
            e.accept()
            self.keyPressed.emit(129)
            pass
        elif e.key() == Qt.Key_Down:
            # TODO: Down in history
            e.accept()
            self.keyPressed.emit(130)
            pass
        elif e.key() == Qt.Key_Backspace:
            if self.cur_pos > self.start_pos:
                self.cur_pos -= 1
                self.top_pos -= 1
                col = self.cur_pos - 1
                for i in xrange(4):
                    self.buf[col * 4 + i] = 0
                del self.input_buf[self.cur_pos - self.start_pos]
                #print self.input_buf
                self.lower_win_cursor -= 1
                self.update()
            # self.keyPressed.emit() # No keycode available for zscii
            e.accept()
        elif e.key() == Qt.Key_Delete:
            # TODO: Fix it!
            if self.cur_pos < self.top_pos:
                self.top_pos -= 1
                col = self.cur_pos - 1
                for i in xrange(4):
                    self.buf[col * 4 + i] = 0
                del self.input_buf[self.cur_pos - self.start_pos]
                self.lower_win_cursor -= 1
                self.update()
            e.accept()
            self.keyPressed.emit(8)
        elif (e.key() == Qt.Key_Return) or (e.key() == Qt.Key_Enter):
            # TODO: Learn how to properly convert a list of chars to a string. There MUST be another way! >:-S
            text = ""
            for i in xrange(len(self.input_buf)):
                text += self.input_buf[i]
            #print text
            self.print_char('\n')
            self.hide_cursor()
            self.keyPressed.emit(13)
            self.returnPressed.emit(text)
            e.accept()
        elif ((e.key() >= Qt.Key_F1) and (e.key() <= Qt.Key_F12)):
            e.accept()
            self.keyPressed.emit(133 + e.key() - Qt.Key_F1)
        elif e.key() == Qt.Key_Escape:
            e.accept()
            self.keyPressed.emit(27)
        elif e.text().isEmpty() == False:
            #print self.cur_pos, self.start_pos, self.max_char
            if (self.cur_pos - self.start_pos) < self.max_char:
                self.cur_pos += 1
                self.top_pos += 1
                if (self.cur_pos - self.start_pos) <= len(self.input_buf):
                    self.input_buf.insert(self.cur_pos - self.start_pos - 1, unicode(e.text()))
                    #print "CurPos:", self.cur_pos
                    col = self.cur_pos - 2
                    self.buf[col * 4 + 3] = unicode(e.text())
                    self.buf[col * 4 + 2] = 0
                    self.buf[col * 4 + 1] = self.cur_bg
                    self.buf[col * 4] = self.cur_fg
                    self.lower_win_cursor += 1
                else:
                    self.input_buf.append(unicode(e.text()))
                    self.print_char(e.text())
                #print self.input_buf
                self.update()
            e.accept()
            t = ord(str(e.text()))
            if ((t > 31) and (t < 127)) or ((t > 154) and (t <252)):
                self.keyPressed.emit(t)
        else:
            e.ignore()

    def set_text_colour(self,fg):
        self.cur_fg = fg

    def set_text_background_colour(self,bg):
        self.cur_bg = bg

    def set_font_style(self,s):
        if s == 0:
            self.cur_style = 0
        else:
            self.cur_style |= s

    def clear(self):
        for i in xrange(self.width *  self.height * 4):
            self.buf[i] = 0
        self.upper_buf = []
        self.upper_buf_height = 0
        self.upper_win_cursor = [] # Upper win cursor x,y
        self.lower_win_cursor = 1 # Lower win cursor x (y cannot be changed!)
        self.cur_win = 0 # Default win is the lower (1 is for upper win)

    def split_window(self,lines,ver):
        if self.upper_buf_height > lines: # New upper win is smaller. I should copy the rest of the buffer to main buffer
            #print "Copying..."
            l = lines + 1
            while l <= self.upper_buf_height:
                for i in xrange(self.width * 4):
                    self.buf[(((self.height - l + 1) * self.width) * 4) + i] = self.upper_buf[(((l - 1) * self.width) * 4) + i]
                l += 1
        self.upper_buf_height = lines
        if (self.upper_buf == []) or (ver == 3):
            for i in xrange(self.upper_buf_height*self.width*4): # It isn't necessary to occupy that much memory but it helps to be prepared! :-P
                self.upper_buf.append(0)
        if (self.upper_win_cursor == []) or (self.upper_win_cursor[1] > lines):
            self.upper_win_cursor = [1,1]

    def select_ostream(self,n):
        if n <> 0:
            self._ostream[n - 1].selected = True

    def deselect_ostream(self,n):
        self._ostream[n - 1].selected = False

    def insert_new_line(self):
        #print "New line"
        # TODO: Not just insert new lines but also remove old unwanted ones
        for i in xrange(self.width * 4):
            self.buf.insert(0, 0)

    def read_line(self, callback):
        QObject.connect(self, SIGNAL("returnPressed(QString)"), callback)

    def disconnect_read_line(self, callback):
        QObject.disconnect(self, SIGNAL("returnPressed(QString)"), callback)

    def read_char(self, callback):
        QObject.connect(self, SIGNAL("keyPressed(int)"), callback)
        print 'Connect char'

    def disconnect_read_char(self, callback):
        QObject.disconnect(self, SIGNAL("keyPressed(int)"), callback)
        print 'Disconnect char'

    def selected_ostreams(self):
        s = []
        for i in xrange(4):
            if self._ostream[i].selected == True:
                s.append(i+1)
        return s

    def new_line(self):
        if self._ostream[0].selected:
            if self.cur_win == 0: # Lower win
                self.insert_new_line()
                self.lower_win_cursor = 1
            else: # Upper win
                l = self.upper_win_cursor[1]
                self.upper_win_cursor = [1,l + 1]
コード例 #52
0
ファイル: results_model.py プロジェクト: stevexyz/dupeguru
 def appPrefsChanged(self, prefs):
     font = self.view.font()
     font.setPointSize(prefs.tableFontSize)
     self.view.setFont(font)
     fm = QFontMetrics(font)
     self.view.verticalHeader().setDefaultSectionSize(fm.height() + 2)
コード例 #53
0
ファイル: asciiItem.py プロジェクト: kzwkt/dff
class asciiItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
        self.initFont()
        self.initMetricsValues()
#        self.initCursor()

    def initPosition(self):
        self.setPos(485, 25)
#        self.setTextInteractionFlags(Qt.TextSelectableByMouse)

    def initValues(self, whex):
        self.whex = whex
        self.heditor = self.whex.heditor
        #Buffer
        self.buffer = []
        self.bufferLines = 0
        #Line
        self.currentLine = 0
        #Offset
        self.startOffset = 0
        self.fontPixel = 14
        #Current Positions
        self.currentPos = 0

#    def initCursor(self):
#        self.cursor = asciiCursor(self)
#        self.heditor.scene.addItem(self.cursor)

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.darkCyan))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        self.setFont(self.font)
        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 1
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * 16)
#        print "start ASCII blank"
#        print self.startBlank

#Print Operations

    def printBuffer(self, buff):
        del self.buffer
        self.buffer = buff

        count = 0
        printer = QString()

        for char in buff:
            if char > "\x20" and char < "\x7e":
                printer.append(char)
            else:
                printer.append(".")
            if count < 15:
                count += 1
            else:
                printer.append("\n")
                count = 0

        #Clear and set
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(printer)
        cursor.movePosition(QTextCursor.Start)
        #Update pixel Informations

    def updateCurrentSelection(self, posx, posy):
        self.currentSelection = self.heditor.currentOffset + (
            (posy * 16) + posx)

    def getXPos(self, x):
        count = 0
        current = self.byteW + (self.startBlank / 2)
        while current < x:
            count += 1
            current = current + self.byteW
        return count

    def getYPos(self, y):
        count = 0
        current = self.byteH
        while current < y:
            count += 1
            current = current + self.byteH
        return count

    def mouseMoveEvent(self, event):
        pos = event.pos()
        x = pos.x()
        y = pos.y()
        xpos = self.getXPos(x)
        ypos = self.getYPos(y)
        self.heditor.selection.select(self.heditor.selection.xstart,
                                      self.heditor.selection.ystart, xpos,
                                      ypos)
        if not self.heditor.preview:
            self.heditor.infos.update()
            self.heditor.right.decode.update()

    def mousePressEvent(self, event):
        button = event.button()
        pos = event.pos()

        if event.button() == 1:
            #Get Clicked coordonates
            x = pos.x()
            y = pos.y()
            #Transform pixel into cursor position
            xpos = self.getXPos(x)
            ypos = self.getYPos(y)

            self.whex.asciicursor.draw(xpos, ypos)
            self.whex.hexcursor.draw(xpos, ypos)
            #Refresh hexadecimal cursor
            self.heditor.selection.select(xpos, ypos, xpos, ypos, True)
            if not self.heditor.preview:
                self.heditor.right.decode.update()
                self.heditor.infos.update()

    def mouseReleaseEvent(self, event):
        pass
コード例 #54
0
 def sizeHint(self):
     fm = QFontMetrics(self.font())
     h = fm.height()
     w = fm.width(self.displayText()) + (fm.width(' ') * 2)
     return QSize(w, h)
コード例 #55
0
    def setupTabs(self, elmerDefs, Section, ID):
        """Creates the tabs of the dynamic widget according to the elmerDefs

        Args:
        -----
        elmerDefs: QDomDocument
            contents of the Elmder efs files in xml-format
        Section: str
            Type of base layout
        ID: int
            ID of the dynamiceditor-instance        
        """
        self.ID = ID
        self.qhash.clear()

        layout = self.layout()
        if (layout is not None):
            item = layout.takeAt(0)
            while (item != 0):
                item = None
                if (self.tabWidget is not None):
                    self.tabWidget.clear()
                    self.tabWidget = None
                item = layout.takeAt(0)
            self.layout = None

        # get root element
        self._root = elmerDefs.documentElement()

        self.tabWidget = QtGui.QTabWidget()
        self.tabWidget.setUsesScrollButtons(True)
        self.tabWidget.setElideMode(QtCore.Qt.ElideNone)

        self._all_stuff = self._root.firstChildElement("ALL")
        self._element = self._root.firstChildElement("PDE")

        self.tabs = 0

        while (self._element.isNull() is False):
            self._name = self._element.firstChildElement("Name")
            grid = QtGui.QGridLayout()
            params = 0
            for x in range(0, 2):
                if (x == 0):
                    if (str(self._name.text()).strip() == "General"):
                        continue
                    self._section = self._all_stuff.firstChildElement(Section)
                else:
                    self._section = self._element.firstChildElement(Section)

                self._param = self._section.firstChildElement("Parameter")

                while (self._param.isNull() is False):
                    h = hash_entry_t()
                    # label
                    widget_type = self._param.attribute("Widget", "Edit")
                    widget_enabled = self._param.attribute("Enabled", "True")
                    widget_visible = self._param.attribute("Visible", "True")
                    paramType = str(
                        self._param.firstChildElement("Type").text()).strip()
                    labelName = str(
                        self._param.firstChildElement("Name").text()).strip()
                    sifName = str(
                        self._param.firstChildElement(
                            "SifName").text()).strip()
                    if (sifName == ""):
                        sifName = labelName
                    paramDefault = str(
                        self._param.firstChildElement(
                            "DefaultValue").text()).strip()
                    whatis = str(
                        self._param.firstChildElement(
                            "Whatis").text()).strip()
                    statusTip = str(
                        self._param.firstChildElement(
                            "StatusTip").text()).strip()
                    fullName = "/" + str(self._name.text()).strip() + "/"
                    fullName = fullName + Section + "/" + labelName + "/" + str(
                        ID)
                    h.widget = None
                    if (widget_type == "Edit"):
                        edit = DynLineEdit()
                        h.widget = edit.lineEdit
                        edit.lineEdit.setText(paramDefault)
                        edit.name = fullName
                        edit.lineEdit.returnPressed.connect(edit.editSlot)
                        edit.lineEdit.textChanged.connect(
                            self._textChangedSlot)

                    elif (widget_type == "TextEdit"):
                        textEdit = QtGui.QTextEdit()
                        currentFont = textEdit.currentFont()
                        fontMetrics = QFontMetrics(currentFont)
                        fontHeight = fontMetrics.height()
                        textEdit.setMinimumHeight(5 * fontHeight)
                        textEdit.setMaximumHeight(8 * fontHeight)
                        h.widget = textEdit

                    elif (widget_type == "Combo"):
                        combo = QtGui.QComboBox()
                        h.widget = combo
                        count = 0
                        active = 0
                        item = self._param.firstChildElement("Item")
                        while (item.isNull() is False):
                            itemType = item.attribute("Type", "")
                            if (itemType == "Active"):
                                active = count
                            itemName = item.firstChildElement("Name")
                            count += 1
                            combo.insertItem(count,
                                             str(itemName.text()).strip())
                            item = item.nextSiblingElement("Item")
                        combo.setCurrentIndex(active)
                        combo.currentIndexChanged.connect(self._comboSlot)

                    elif (widget_type == "CheckBox"):
                        l = QtGui.QCheckBox()
                        h.widget = l
                        l.setText("")
                        l.setChecked(False)
                        if (paramDefault == "True"):
                            l.setChecked(True)
                        l.stateChanged.connect(self._lSlot)

                    elif (widget_type == "Label"):
                        label = QtGui.QLabel()
                        font = QFont()
                        font.setBold(True)
                        font.setUnderline(True)
                        label.setFont(font)
                        label.setText(labelName)
                        h.widget = label

                    if (h.widget):
                        h.widget.setWhatsThis(whatis)
                        h.widget.setStatusTip(statusTip)
                        h.widget.setProperty("dom address", fullName)
                        h.elem = self._param
                        if (widget_enabled == "False"):
                            h.widget.setEnabled(False)
                        if (widget_type != "TextEdit"):
                            h.widget.setFixedHeight(18)
                        if (widget_type == "TextEdit"):
                            textEditLabel = QtGui.QLabel()
                            textEditLabel.setText(labelName)
                            h.label = textEditLabel
                            grid.addWidget(h.widget, params, 0, 1, 2)

                            if (widget_visible == "False"):
                                h.label.hide()
                                h.widget.hide()

                        elif (widget_type != "Label"):
                            label = QtGui.QLabel()
                            label.setText(labelName)
                            h.label = label
                            grid.addWidget(h.label, params, 0)
                            grid.addWidget(h.widget, params, 1)

                            if (widget_visible == "False"):
                                h.label.hide()
                                h.widget.hide()
                        else:
                            h.label = None
                            grid.addWidget(h.widget, params, 0)
                        self.qhash.update({fullName: h})

                    self._param = self._param.nextSiblingElement("Parameter")
                    params += 1

            dummyWidget = QtGui.QWidget()
            grid.addWidget(dummyWidget, params, 0)
            grid.setRowStretch(params, 1)

            frmWidget = QtGui.QWidget()
            frmWidget.setLayout(grid)

            src = QtGui.QScrollArea()
            src.setWidget(frmWidget)
            src.setMinimumHeight(300)
            src.setWidgetResizable(True)

            if (params > 0):
                self.tabWidget.addTab(src, str(self._name.text()).strip())

            self.tabs += 1
            self._element = self._element.nextSiblingElement("PDE")

        # Buttons:
        lbl = QtGui.QLabel()
        lbl.setText("Name:")
        self.nameEdit = QtGui.QLineEdit()
        self.nameEdit.setText(Section + " " + str(ID + 1))

        self.applyButton = QtGui.QPushButton("&Apply")
        # applyButton.setIcon(addIcon)
        self.applyButton.clicked.connect(self._applyButtonClicked)

        self.discardButton = QtGui.QPushButton("&Remove")
        # discardButton.setIcon(removeIcon)
        self.discardButton.clicked.connect(self._discardButtonClicked)

        self.okButton = QtGui.QPushButton("&OK")
        # okButton.setIcon(okIcon)
        self.okButton.clicked.connect(self._okButtonClicked)

        self.newButton = QtGui.QPushButton("&New")
        # self.newButton.setIcon(newIcon)
        self.newButton.clicked.connect(self._newButtonClicked)

        nameLayout = QtGui.QHBoxLayout()
        nameLayout.addWidget(lbl)
        nameLayout.addWidget(self.nameEdit)

        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.addWidget(self.newButton)
        buttonLayout.addWidget(self.applyButton)
        buttonLayout.addWidget(self.okButton)
        buttonLayout.addWidget(self.discardButton)

        spareButtonLayout = QtGui.QHBoxLayout()
        self.spareButton = QtGui.QPushButton("SpareButton")
        self.spareButton.setVisible(False)
        spareButtonLayout.addWidget(self.spareButton)
        self.spareButton.clicked.connect(self._spareButtonClicked)

        self.spareScroll = QtGui.QScrollArea()
        self.spareScroll.hide()

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.tabWidget)
        mainLayout.addWidget(self.spareScroll)
        mainLayout.addLayout(spareButtonLayout)
        mainLayout.addLayout(nameLayout)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle(Section)