Python PyQt4.QtGui 模块,QFontMetrics() 实例源码

我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用PyQt4.QtGui.QFontMetrics()

项目:pyDashboard    作者:jtsmith2    | 项目源码 | 文件源码
def resizeEvent(self, e):

        fontsize = 1

        font = self.label.font()

        while(True):


                f = QtGui.QFont(font)
                f.setPixelSize(fontsize)
                r = QtGui.QFontMetrics(f).boundingRect(self.label.text())
                if (r.height() < self.height()-30 and r.width() < self.width()-30):
                        fontsize += 1
                else:
                        break

        font.setPixelSize(fontsize)
        self.label.setFont(font)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, parent, title='', padding=1, ratio=1., ani_range=5):
        QtGui.QWidget.__init__(self, parent)
        self.font = QtGui.QFont('Droid Sans', 14, QtGui.QFont.Bold)
        self.font_metrics = QtGui.QFontMetrics(self.font)
        self.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Preferred)
        self.padding = padding
        if title:
            self.title = title
            top_margin = self.font_metrics.height()+self.padding+4
        else:
            self.title = None
            top_margin = 0
        self.setContentsMargins(2, 2+top_margin, 2, 2)

        self._fgd_line = self.fgd_lines[0]
        self.border_anim = QtCore.QPropertyAnimation(self, 'fgd_line')
        self.border_anim.setStartValue(self.fgd_lines[0])
        self.border_anim.setEndValue(self.fgd_lines[1])
        self.border_anim.valueChanged.connect(lambda value: self.update())
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, text, parent):
        BaseTextWidget.__init__(self, text, parent)
        self.main = parent
        self.font = QtGui.QFont('Fira Sans', 22)
        self.font_metrics = QtGui.QFontMetrics(self.font)
        self.setMinimumSize(self.font_metrics.width(self.text), self.font_metrics.height())
        self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Maximum)
        while len(self.text) < 16:
            self.text += ' '
        self.text = QtCore.QString.fromUtf8(self.text)
        self.text_list = QtCore.QStringList([l for l in self.text])
        self.cursor = TextCursorWidget(self, self.font_metrics.ascent())
        self.cursor.hide()
        self.cursor_timer = QtCore.QTimer()
        self.cursor_timer.setInterval(500)
        self.cursor_timer.timeout.connect(lambda: self.cursor.setVisible(False if self.cursor.isVisible() else True))
        self._editing = False
项目:mol    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, parent=None):
        QtGui.QComboBox.__init__(self, parent)
        self.setEditable(True)
        self.setInsertPolicy(QtGui.QComboBox.NoInsert)
        self.setMaximumWidth(100)
        self.p_model = QtGui.QStandardItemModel()
        self.name_model = QtGui.QStandardItemModel()
        self.setModel(self.p_model)

        metrics = QtGui.QFontMetrics(self.view().font())
        ctrl_width = []
        note_width = []
        for i in range(128):
            ctrl = Controllers[i]
            ctrl_str = '{} - {}'.format(i, ctrl)
            ctrl_item = QtGui.QStandardItem(ctrl_str)
            ctrl_item.setData(i, IdRole)
            ctrl_item.setData(ctrl, NameRole)
            ctrl_width.append(metrics.width(ctrl_str))
            ctrl_name_item = QtGui.QStandardItem(ctrl)
            ctrl_name_item.setData(i, IdRole)
            note = NoteNames[i].title()
            note_str = '{} - {}'.format(i, note)
            note_item = QtGui.QStandardItem(note_str)
            note_item.setData(i, IdRole)
            note_item.setData(note, NameRole)
            note_width.append(metrics.width(note_str))
            note_name_item = QtGui.QStandardItem(note)
            note_name_item.setData(i, IdRole)
            self.p_model.appendRow([ctrl_item, note_item])
            self.name_model.appendRow([ctrl_name_item, note_name_item])

        self.ctrl_width = max(ctrl_width)
        self.note_width = max(note_width)
        self.ref_size = self.width()

        self.activated.connect(lambda i: self.lineEdit().setCursorPosition(0))
        self.currentIndexChanged.connect(lambda i: self.lineEdit().setCursorPosition(0))
项目:Webradio_v2    作者:Acer54    | 项目源码 | 文件源码
def adjustFont(self):
        # --- fetch current parameters ----
        f = self.font()
        cr = self.contentsRect()
        if self.maxFont is not None:
            maximum = self.maxFont.pointSize()
        else:
            maximum = 999
        # --- 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:
                wouldfit = max(fs - 1, 1)
                if wouldfit > maximum:
                    print wouldfit
                    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)
项目:linkchecker-gui    作者:linkcheck    | 项目源码 | 文件源码
def __init__ (self, parent=None):
        """Set Scintilla options for font, colors, etc."""
        super(Editor, self).__init__(parent)
        # Use Courier font with fixed width
        font = QtGui.QFont("Consolas", 11)
        font.setFixedPitch(True)

        # Set the default font of the editor
        # and take the same font for line numbers
        self.setFont(font)
        self.setMarginsFont(font)

        # line number margin for 4 digits (plus 2px extra space)
        margin = QtGui.QFontMetrics(font).width("0"*4)+2
        # Display line numbers, margin 0 is for line numbers
        self.setMarginWidth(0, margin)
        self.setMarginLineNumbers(0, True)

        # Show whitespace to help detect whitespace errors
        self.setWhitespaceVisibility(True)

        # Use boxes as folding visual
        self.setFolding(self.BoxedTreeFoldStyle)

        # Braces matching
        self.setBraceMatching(self.SloppyBraceMatch)

        # Editing line color
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QtGui.QColor("#e5e5cb"))

        # line numbers margin colors
        self.setMarginsBackgroundColor(QtGui.QColor("#e5e5e5"))
        self.setMarginsForegroundColor(QtGui.QColor("#333333"))

        # folding margin colors (foreground,background)
        self.setFoldMarginColors(QtGui.QColor("#f5f5dc"),
                                 QtGui.QColor("#aaaaaa"))
项目:orquesta    作者:ej-f    | 项目源码 | 文件源码
def setup(self):
        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)
        fontmetrics = QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(0, fontmetrics.width('0000'))
        self.setMarginLineNumbers(0, True)
        self.setMarginsBackgroundColor(QColor('#cccccc'))
        self.setMarginSensitivity(1, True)
        self.marginClicked.connect(self.on_margin_clicked)
        self.markerDefine(QsciScintilla.RightTriangle, self.ARROW_MARKER_NUM)
        self.setMarkerBackgroundColor(QColor('#ee1111'), self.ARROW_MARKER_NUM)
        self.markerDefine(QsciScintilla.Circle, self.REC_MARKER_NUM)
        self.setMarkerBackgroundColor(QColor('#87CEEB'), self.REC_MARKER_NUM)
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#FFA07A'))
        self.my_lexer = OrLexer(self)
        self.setLexer(self.my_lexer)
        self.setAutoCompletionThreshold(1)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
        self.tracking_marker = None
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        QtGui.QLabel.__init__(self, *args, **kwargs)
        self.font_metrics = QtGui.QFontMetrics(self.font())
        self.full_text = ''
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        QtGui.QLabel.__init__(self, *args, **kwargs)
        self.font_metrics = QtGui.QFontMetrics(self.font())
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def compute_metrics(self):
        self.font_metrics = QtGui.QFontMetrics(self.font)
        cat = max([self.font_metrics.width(c) for c in digits+uppercase])*4 + self.font_metrics.width('    ')
        name = max([self.font_metrics.width(c) for c in self.chars])*16 + self.spacing
        self.prog_size = cat+name
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def redraw(self, *args):
        self.compute(self.col_spin.value(), self.vertical_chk.isChecked())
        if self.mode == TEXT:
            self.printview.resetTransform()
            self.page.hide()
            self.printview.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
            self.printview.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
            self.printscene.removeItem(self.monotext)
            self.monotext = QtGui.QGraphicsTextItem()
            self.monotext.setPlainText(self.text.replace('\t\t', '        ').replace('\t', '    '))
            self.monotext.setFont(self.monofont)
            self.printscene.addItem(self.monotext)
            self.printview.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
            #for some reason, very long plain text contents always set QGraphicsTextItem's height to 2012, then we use metrics
            self.printview.setSceneRect(0, 0, self.monotext.boundingRect().width(), QtGui.QFontMetrics(self.monofont).lineSpacing()*len(self.text.split('\n')))
            self.printview.verticalScrollBar().setValue(0)
            self.printview.horizontalScrollBar().setValue(0)
            return
        self.monotext.hide()
        self.printview.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.printview.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.printview.setAlignment(QtCore.Qt.AlignCenter)
        self.page.setText(self.text)
        self.page.show()
        self.printview.setSceneRect(self.page.boundingRect())
        self.printview.fitInView(self.page.boundingRect(), QtCore.Qt.KeepAspectRatio)
        self.pagebank_chk.toggled.connect(self.page.setPageBank)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, parent=None, text='', text_align=QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter, label_pos=RIGHT, path=None):
        QtGui.QWidget.__init__(self, parent)
        self.text = text
        self.text_align = text_align
        self.font = QtGui.QFont('Droid Sans', 9, QtGui.QFont.Bold)
        self.font_metrics = QtGui.QFontMetrics(self.font)
        text_split = text.split('\n')
        text_height = self.font_metrics.height()*len(text_split)
        text_width = max([self.font_metrics.width(t) for t in text_split])
        self.label_rect = QtCore.QRectF(0, 0, text_width, text_height)
#        self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        if path:
            self.path = path
            self.path_rect = self.path.boundingRect()
        if not self.path_rect:
            self.setMinimumSize(self.label_rect.width(), self.label_rect.height())
        else:
            self.label_pos = label_pos
            if label_pos in (TOP, BOTTOM):
                self.setMinimumSize(max(self.label_rect.width(), self.path_rect.width()), self.label_rect.height()+self.path_rect.height()+2)
                self.label_rect.setWidth(max(self.label_rect.width(), self.path_rect.width()))
            else:
                self.setMinimumSize(self.label_rect.width()+self.path_rect.width()+2, max(self.label_rect.height(), self.path_rect.height()))
                self.label_rect.setHeight(max(self.label_rect.height(), self.path_rect.height()))
            if label_pos == TOP:
                self.path_rect.moveTop(self.label_rect.bottom()+2)
                if self.path_rect.width() < self.label_rect.width():
                    self.path_rect.moveLeft((self.label_rect.width()-self.path_rect.width())/2)
            elif label_pos == BOTTOM:
                self.label_rect.moveTop(self.path_rect.bottom()+2)
                if self.path_rect.width() < self.label_rect.width():
                    self.path_rect.moveLeft((self.label_rect.width()-self.path_rect.width())/2)
            elif label_pos == LEFT:
                self.path_rect.moveLeft(self.label_rect.right()+2)
                if self.path_rect.height() < self.label_rect.height():
                    self.path_rect.moveTop((self.label_rect.height()-self.path_rect.height())/2)
            else:
                self.label_rect.moveLeft(self.path_rect.right()+2)
                if self.path_rect.height() < self.label_rect.height():
                    self.path_rect.moveTop((self.label_rect.height()-self.path_rect.height())/2)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, parent, mode=ADSR, show_points=True):
        QtGui.QWidget.__init__(self, parent)
        self.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Preferred)
        self.mode = mode
        self.show_points = show_points
        self.setContentsMargins(2, 2, 2, 2)
        self.setMinimumSize(68, 40)
        self.attack = 127
        self.attack_level = 127
        self.decay = 127
        self.sustain = 64
        self.decay2 = 127
        self.sustain2 = 64
        self.release = 64
        self.attack_point = None
        self.decay_point = None
        self.sustain_point = None
        self.decay2_point = None
        self.sustain2_point = None
        self.release_end = None
        self.envelope = None
        self.current_cursor = self.current_delta = self.hover_point = None
        self.font_metrics = QtGui.QFontMetrics(QtGui.QFont('Droid Sans', 10, QtGui.QFont.Bold))
        self.create_cursors()
        self.reset_envelope()
        self.env_rect = QtCore.QRectF(12, 4, self.width()-25, self.height()-9)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, parent=None, value_list=None, name='', wheel_dir=True, default=0):
        QtGui.QComboBox.__init__(self, parent)
        self.combo_padding = 2
        self.spacing = 4
        self.setFont(QtGui.QFont('Droid Sans', 10, QtGui.QFont.Bold))
        self.font_metrics = QtGui.QFontMetrics(QtGui.QFont('Droid Sans', 10, QtGui.QFont.Bold))
        self.label_font = QtGui.QFont('Droid Sans', 9, QtGui.QFont.Bold)
        self.label_font_metrics = QtGui.QFontMetrics(self.label_font)
#        self.list = ListView(self)
#        self.setFocusPolicy(QtCore.Qt.WheelFocus)
#        self.list.indexChanged.connect(self.setCurrentIndex)
        if name:
            self.name = name
            self.setMinimumSize(10, self.font_metrics.height()+self.label_font_metrics.height()+self.spacing+self.combo_padding*2)
            self.setMaximumHeight(self.font_metrics.height()+self.label_font_metrics.height()+self.spacing+self.combo_padding*2)
        else:
            self.name = None
            self.setMinimumSize(10, self.font_metrics.height()+self.combo_padding*2)
            self.setMaximumHeight(self.font_metrics.height()+self.combo_padding*2)
#        self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
        self.value_list = []
        self.wheel_dir = 1 if wheel_dir else -1
        if value_list:
            self.add_items(value_list)
#            if not 0 <= default <= len(value_list):
#                default = 0
            self.setCurrentIndex(default)
#            self._setValue(default)
        else:
            self.current = 'None'
#            self.setCurrentIndex(-1)
        self.currentIndexChanged.connect(self.indexChanged)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, text, parent):
        BaseTextWidget.__init__(self, text, parent)
        self.font = QtGui.QFont('Fira Sans', 12)
        self.font_metrics = QtGui.QFontMetrics(self.font)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, text, parent, fixed=False, font_size=12, max_size=None, bold=False):
        BaseTextWidget.__init__(self, text, parent)
        self.font = QtGui.QFont('Fira Sans', font_size, weight=QtGui.QFont.DemiBold if bold else QtGui.QFont.Normal)
        self.font_metrics = QtGui.QFontMetrics(self.font)
        self.setMinimumSize(self.font_metrics.width(self.text), self.font_metrics.height())
        self.setMaximumHeight(self.font_metrics.height())
        if fixed:
            self.setMaximumWidth(self.font_metrics.width(self.text) if max_size is None else max_size)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, parent):
        BaseDisplayWidget.__init__(self, parent)
        self.currentIndex = 0
        self.count = len(self.value_list)
        self.text_align = QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter
        self.font = QtGui.QFont('Fira Sans', 9)
        self.font_metrics = QtGui.QFontMetrics(self.font)
        self.setMinimumSize(max([self.font_metrics.width(txt) for txt in self.value_list if isinstance(txt, QtCore.QString)]), self.font_metrics.height())
#        self.setMaximumSize(self.minimumSize())
#        if fixed:
#            self.setMaximumWidth(self.font_metrics.width(self.text) if max_size is None else max_size)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, parent):
        self.font = QtGui.QFont('Fira Sans', 11, QtGui.QFont.Light)
        self.font_metrics = QtGui.QFontMetrics(self.font)
        self.text = '0'
        DisplayButton.__init__(self, parent)
        self.normal_frame_border_pen = self.normal_frame_border_pen.lighter(105)
        self.normal_frame_border_brush = self.normal_frame_border_brush.lighter(125)
        self.frame_border_pen = self.normal_frame_border_pen
        self.frame_border_brush = self.normal_frame_border_brush
        self.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
        self.setMinimumHeight(max(self.path.boundingRect().height(), self.font_metrics.height()))
        self.setMaximumWidth(self.path.boundingRect().width()+self.font_metrics.width('0')*3+4)
        self.setAcceptHoverEvents(False)
        self.brush = self.off_brush
        self.setConn(0)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, parent):
        self.path = QtGui.QPainterPath()
        self.path.addEllipse(0, 0, 11, 11)
        self.path.addEllipse(2, 5, .5, .5)
        self.path.addEllipse(2.878, 2.878, .5, .5)
        self.path.addEllipse(5.25, 2, .5, .5)
        self.path.addEllipse(7.878, 2.878, .5, .5)
        self.path.addEllipse(9, 5, .5, .5)
        self.font = QtGui.QFont('Fira Sans', 11, QtGui.QFont.Light)
        self.font_metrics = QtGui.QFontMetrics(self.font)
        self.text = 'MIDI'
        DisplayButton.__init__(self, parent)
#        self._setState(False)
        self.brush = self.off_brush
        self.normal_frame_border_pen = self.normal_frame_border_pen.lighter(105)
        self.normal_frame_border_brush = self.normal_frame_border_brush.lighter(125)
        self.focus_frame_border_brush = self.focus_frame_border_brush.lighter(125)
        self.frame_border_pen = self.normal_frame_border_pen
        self.frame_border_brush = self.normal_frame_border_brush
        self.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Maximum)
        self.setMinimumHeight(max(self.path.boundingRect().height(), self.font_metrics.height()))
#        self.setMaximumHeight(32)
        self.setToolTip('Open MIDI connections dialog\n(right click for direct access menu)')
        self.led_timer = QtCore.QTimer()
        self.led_timer.setSingleShot(True)
        self.led_timer.setInterval(256)
        self.led_timer.timeout.connect(self.reset)
        self.midi_in_pen = QtGui.QPen(QtCore.Qt.darkRed)
项目:remotefreebox-gui    作者:MaximeCheramy    | 项目源码 | 文件源码
def setElidedText(label, text):
    metrics = QFontMetrics(label.font())
    elidedText = metrics.elidedText(text, Qt.ElideRight, label.width())
    label.setText(elidedText)
项目:Webradio_v2    作者:Acer54    | 项目源码 | 文件源码
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)
项目:XAFSmass    作者:kklmn    | 项目源码 | 文件源码
def __init__(self, parent=None, width=5, height=0.4):
        fig = mpl.figure.Figure(figsize=(width, height), dpi=96)
        self.fig = fig
        Canvas.__init__(self, fig)
        bg = self.palette().window().color()
        cl = (bg.redF(), bg.greenF(), bg.blueF())
#        fig.set_edgecolor(cl)
        fig.set_facecolor(cl)
        self.setParent(parent)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.updateGeometry()
        fm = QtGui.QFontMetrics(self.font())
        self.fontsize = int(fm.height()) / 1.25
项目:XAFSmass    作者:kklmn    | 项目源码 | 文件源码
def __init__(self, parent=None, width=6, height=5):
        fig = mpl.figure.Figure(figsize=(width, height), dpi=96)
        self.fig = fig
        self.axes = fig.add_subplot(111)
        self.fig.subplots_adjust(left=0.15, right=0.97, bottom=0.15, top=0.97)
#        self.axes.hold(False)  # clear axes every time plot() is called
        Canvas.__init__(self, fig)
        self.setParent(parent)
        self.updateGeometry()
        fm = QtGui.QFontMetrics(self.font())
        self.fontsize = int(fm.height()) / 1.25
项目:PyGenAlg    作者:RaphDeau    | 项目源码 | 文件源码
def __init__(self, top=None):
        """
        Initialize the editor
        """
        super(Code_Editor, self).__init__(top)

        ## define the font to use
        font = QtGui.QFont()
        font.setFamily("Consolas")
        font.setFixedPitch(True)
        # the font metrics here will help
        # building the margin width later
        fm = QtGui.QFontMetrics(font)

        ## set the default font of the editor
        ## and take the same font for line numbers
        self.setFont(font)
        self.setMarginsFont(font)
        ## Line numbers
        self.setMarginLineNumbers(1, True)

        ## Folding visual : we will use boxes
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        ## Braces matching
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        ## Editing line color
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QtGui.QColor("#CDA869"))

        ## Margins colors
        # line numbers margin
        self.setMarginsBackgroundColor(QtGui.QColor("#333333"))
        self.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

        # folding margin colors (foreground,background)
        self.setFoldMarginColors(QtGui.QColor("#99CC66"), QtGui.QColor("#333300"))

        ## Choose a lexer
        lexer = QsciLexerPython()
        lexer.setDefaultFont(font)
        self.setLexer(lexer)
项目:siren    作者:ozsolarwind    | 项目源码 | 文件源码
def showPeriod(self, period):
        self.visual_group.setVisible(False)
        while len(self.visual_items) > 0:
            self.visual_group.removeFromGroup(self.visual_items[-1])
            self.visual_items.pop()
        for i in range(len(self.stations)):
            if period >= len(self.data[i]):
                continue
            if self.data[i][period] <= 0:
                continue
            st = self.scene._stations.stations[self.stn_items[i]]
            p = self.scene.mapFromLonLat(QtCore.QPointF(st.lon, st.lat))
            size = math.sqrt(self.data[i][period] * self.scene.capacity_area / math.pi)
            east = self.destinationxy(st.lon, st.lat, 90., size)
            pe = self.scene.mapFromLonLat(QtCore.QPointF(east.x(), st.lat))
            north = self.destinationxy(st.lon, st.lat, 0., size)
            pn = self.scene.mapFromLonLat(QtCore.QPointF(st.lon, north.y()))
            x_d = p.x() - pe.x()
            y_d = pn.y() - p.y()
            el = QtGui.QGraphicsEllipseItem(p.x() - x_d / 2, p.y() - y_d / 2, x_d, y_d)
            el.setBrush(QtGui.QColor(self.scene.colors[st.technology]))
            el.setOpacity(1)
            if self.scene.colors['border'] != '':
                el.setPen(QtGui.QColor(self.scene.colors['border']))
            else:
                el.setPen(QtGui.QColor(self.scene.colors[st.technology]))
            el.setZValue(1)
            self.visual_items.append(el)
            self.visual_group.addToGroup(self.visual_items[-1])
        if  self.detailCombo.currentText() == 'Diurnal':
            txt = self.periodCombo.currentText() + ' ' + self.hourCombo.currentText()
        else:
            txt = self.periodCombo.currentText() + ' ' + self.dayCombo.currentText() + ' ' + self.hourCombo.currentText()
        itm = QtGui.QGraphicsSimpleTextItem(txt)
        new_font = itm.font()
        new_font.setPointSizeF(self.scene.width() / 50)
        itm.setFont(new_font)
        itm.setBrush(QtGui.QColor(self.scene.colors['station_name']))
        fh = int(QtGui.QFontMetrics(new_font).height() * 1.1)
        p = QtCore.QPointF(self.scene.upper_left[0] + fh / 2, self.scene.upper_left[1] + fh / 2)
        frll = self.scene.mapToLonLat(p)
        p = self.scene.mapFromLonLat(QtCore.QPointF(frll.x(), frll.y()))
        p = QtCore.QPoint(p.x(), p.y())
        itm.setPos(p.x(), p.y())
        itm.setZValue(1)
        self.visual_items.append(itm)
        self.visual_group.addToGroup(self.visual_items[-1])
        self.visual_group.setVisible(True)
        QtCore.QCoreApplication.processEvents()
        QtCore.QCoreApplication.flush()
        if self.do_loop and not self.scene.exitLoop:
            if self.loopSpin.value() > 0:
                time.sleep(self.loopSpin.value())
项目:pyDashboard    作者:jtsmith2    | 项目源码 | 文件源码
def drawLines(self, qp):

        pen = QtGui.QPen(QtCore.Qt.white, 1, QtCore.Qt.SolidLine)
        qp.setPen(pen)

        self.defaultFontSize = qp.fontInfo().pixelSize()
        if(self.syncedTitleFontSize is None):
                fontsize = 1
                font = qp.font()
                while(True):

                        f = QtGui.QFont(font)
                        f.setPixelSize(fontsize)
                        r = QtGui.QFontMetrics(f).boundingRect(str(self.calDate.month)+'/'+str(self.calDate.day)+"/"+str(self.calDate.year))
                        if (r.height() < self.height()-30 and r.width() < self.width()-30):
                                fontsize += 1
                        else:
                                self.titleHeight = r.height()
                                break
                fontsize = fontsize/2
        else:
                fontsize = self.syncedTitleFontSize

        font = qp.font()
        f = QtGui.QFont(font)
        f.setPixelSize(fontsize)
        r = QtGui.QFontMetrics(f).boundingRect(str(self.calDate.month)+'/'+str(self.calDate.day)+"/"+str(self.calDate.year))
        self.titleHeight = r.height()
        self.titleWidth = r.width()

        self.titleFontSize = fontsize
        self.syncedTitleFontSize = None

        font.setPixelSize(fontsize)
        qp.setFont(font)

        qp.drawText((self.width()-self.titleWidth)/2, self.titleHeight, str(self.calDate.month)+'/'+str(self.calDate.day)+"/"+str(self.calDate.year))

        font.setPixelSize(self.defaultFontSize)
        qp.setFont(font)

        hours = self.calSpan.total_seconds()/3600
        for x in xrange(int(hours+1)):
                qp.drawLine(0, 25+self.titleHeight+(self.height()-50-self.titleHeight)/hours*x, self.width(), 25+self.titleHeight+(self.height()-50-self.titleHeight)/hours*x)
                qp.drawText(5, 40+self.titleHeight+(self.height()-50-self.titleHeight)/hours*x, (self.dtCalStart+datetime.timedelta(hours=x)).strftime('%I%p').lstrip("0").replace(" 0", " "))

        pen = QtGui.QPen(QtCore.Qt.blue, 1, QtCore.Qt.SolidLine)
        qp.setPen(pen)

        if self.showCurrentTime and self.dtCalStart < datetime.datetime.now(self.dtCalStart.tzinfo) and self.dtCalEnd > datetime.datetime.now(self.dtCalEnd.tzinfo):
                span = datetime.datetime.now(self.dtCalStart.tzinfo) - self.dtCalStart
                spanHours = span.total_seconds()/3600.0
                relHeight = spanHours/hours
                qp.drawLine(0, 25+self.titleHeight+(self.height()-50-self.titleHeight)*relHeight, self.width(), 25+self.titleHeight+(self.height()-50-self.titleHeight)*relHeight)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def right_click(self, event):
        if event.button() != QtCore.Qt.RightButton: return
        rows = set([self.blofeld_model_proxy.mapToSource(index).row() for index in self.blofeld_sounds_table.selectedIndexes()])
        index = self.blofeld_sounds_table.indexAt(event.pos())
        sound = self.blofeld_model.item(self.blofeld_model_proxy.mapToSource(index).row(), SOUND).data(SoundRole).toPyObject()
        menu = QtGui.QMenu()
        menu.setSeparatorsCollapsible(False)
        header = QtGui.QAction(sound.name, menu)
        header.setSeparator(True)
        menu.addAction(header)
        edit_item = QtGui.QAction('Edit...', menu)
        summary_item = QtGui.QAction('Show summary', menu)
        sep = QtGui.QAction(menu)
        sep.setSeparator(True)
        dump_request_item = QtGui.QAction('Request dump', menu)
        dump_send_item = QtGui.QAction('Dump to Blofeld', menu)
        menu.addActions([edit_item, summary_item, sep, dump_request_item, dump_send_item])
        if len(rows) > 1:
            dump_bulk_send_item = QtGui.QAction('Dump selected sounds', menu)
            menu.addAction(dump_bulk_send_item)
        menu.show()
        fm = QtGui.QFontMetrics(edit_item.font())
        minsize = 0
        for a in menu.actions():
            if a == header: continue
            width = fm.width(a.text())
            if width > minsize:
                minsize = width
        frame_delta = menu.width()-minsize
        menu.setMinimumWidth(frame_delta+QtGui.QFontMetrics(header.font()).width(header.text()))
        res = menu.exec_(event.globalPos())
        if not res: return
        elif res == edit_item:
            self.activate_editor.emit(sound.bank, sound.prog)
        elif res == summary_item:
            self.summary_request.emit(sound)
        elif res == dump_request_item:
            self.dump_request.emit((sound.bank, sound.prog))
        elif res == dump_send_item:
            res = QtGui.QMessageBox.question(self, 'Dump selected sound',
                                             'You are going to send a sound dump to the Blofeld at location "{}{:03}".\nThis action cannot be undone. Do you want to proceed?'.format(uppercase[sound.bank], sound.prog+1), 
                                             QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel
                                             )
            if not res == QtGui.QMessageBox.Ok: return
            self.dump_send.emit(sound)
        elif rows > 1 and res == dump_bulk_send_item:
            first = self.blofeld_model.item(min(rows), SOUND).data(SoundRole).toPyObject()
            last = self.blofeld_model.item(max(rows), SOUND).data(SoundRole).toPyObject()
            res = QtGui.QMessageBox.question(self, 'Dump selected sounds',
                                             'You are going to send a sound dump to the Blofeld for locations "{}{:03}" through "{}{:03}".\nThis action cannot be undone. Do you want to proceed?'.format(uppercase[first.bank], first.prog+1, uppercase[last.bank], last.prog+1), 
                                             QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel
                                             )
            if not res == QtGui.QMessageBox.Ok: return
            self.dump_bulk_send.emit((first.bank, first.prog), (last.bank, last.prog))