Python PyQt5.QtGui.QFontMetrics() Examples

The following are code examples for showing how to use PyQt5.QtGui.QFontMetrics(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: dcc   Author: amimo   File: Banners.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, themes, dataModel, viewMode):
        self.width = 0
        self.height = 0
        self.dataModel = dataModel
        self.viewMode = viewMode
        self.qpix = self._getNewPixmap(self.width, self.height)
        self.backgroundBrush = QtGui.QBrush(themes['background'])

        # text font
        self.font = themes['font']

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

        self.textPen = QtGui.QPen(QtGui.QColor(192, 192, 192), 0, QtCore.Qt.SolidLine) 
Example 2
Project: dcc   Author: amimo   File: Banners.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, themes, dataModel, viewMode):
        self.width = 0
        self.height = 0
        self.dataModel = dataModel
        self.viewMode = viewMode
        self.backgroundBrush = QtGui.QBrush(themes['background'])

        self.qpix = self._getNewPixmap(self.width, self.height)

        # text font
        self.font = themes['font']

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

        self.textPen = QtGui.QPen(themes['pen'], 0, QtCore.Qt.SolidLine) 
Example 3
Project: kucher   Author: Zubax   File: group_box_widget.py    GNU General Public License v3.0 6 votes vote down vote up
def set_icon(self, icon_name: str):
        if self._current_icon == icon_name:
            return

        _logger.debug('Changing icon from %r to %r', self._current_icon, icon_name)
        self._current_icon = icon_name

        icon_size = QFontMetrics(QFont()).height()
        icon_path = get_icon_path(icon_name)

        # This hack adds a custom icon to the GroupBox: make it checkable, and then, using styling, override
        # the image of the check box with the custom icon.
        self.setCheckable(True)     # This is needed to make the icon visible
        self.setStyleSheet(f'''
            QGroupBox::indicator {{
                width:  {icon_size}px;
                height: {icon_size}px;
                image: url({icon_path});
            }}
        ''')

        # We don't actually want it to be checkable, so override this thing to return it back to normal again
        # noinspection PyUnresolvedReferences
        self.toggled.connect(lambda _: self.setChecked(True)) 
Example 4
Project: MeiTingTrunk   Author: Xunius   File: meta_tab.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,lib_folder,parent=None):
        '''
        Args:
            parent (QWidget): parent widget.
            lib_folder (str): abspath to lib_current_folder.

        This modified QLineEdit accepts a file path as its text, and displays
        an elided version of the file name part of the path.
        '''

        super(FileLineEdit,self).__init__(parent)
        self.fm=QFontMetrics(self.font())
        self.lib_folder=lib_folder
        self.parent=parent

        self.type_label=QtWidgets.QLabel()
        self.file_type_icon=QIcon.fromTheme('emblem-documents',
            self.style().standardIcon(QStyle.SP_FileIcon)).pixmap(
                    QSize(16,16))
        self.link_type_icon=QIcon.fromTheme('emblem-symbolic-link',
            self.style().standardIcon(QStyle.SP_FileLinkIcon)).pixmap(
                    QSize(16,16))

        self.editingFinished.connect(self.checkNewValue) # focus out or return 
Example 5
Project: interSubs   Author: oltodosel   File: interSubs.py    MIT License 6 votes vote down vote up
def highligting(self, color, underline_width):
		color = QColor(color)
		color = QColor(color.red(), color.green(), color.blue(), 200)
		painter = QPainter(self)

		if config.hover_underline:
			font_metrics = QFontMetrics(self.font())
			text_width = font_metrics.width(self.word)
			text_height = font_metrics.height()

			brush = QBrush(color)
			pen = QPen(brush, underline_width, Qt.SolidLine, Qt.RoundCap)
			painter.setPen(pen)
			if not self.skip:
				painter.drawLine(0, text_height - underline_width, text_width, text_height - underline_width)

		if config.hover_hightlight:
			x = y = 0
			y += self.fontMetrics().ascent()

			painter.setPen(color)
			painter.drawText(x, y + config.outline_top_padding - config.outline_bottom_padding, self.word) 
Example 6
Project: poitagger   Author: dlr-eoc   File: geoview.py    GNU General Public License v3.0 6 votes vote down vote up
def handlePaintRequest(self, printer):
        painter = QtGui.QPainter()
        painter.begin(printer)
        painter.setPen(QtGui.QPen(QtGui.QColor(0, 0, 0)))
        
        self.view.render(painter,painter.deviceTransform().map(QtCore.QPoint(0,45)))   #painter.deviceTransform().map(QtCore.QPoint(0,45))
        
        font = QtGui.QFont("times", 12)
        painter.setFont(font)
        fm = QtGui.QFontMetrics(font)
        text = "Flug: " + self.imgdir
        pixelsWidth = fm.width(text)
        pixelsHeight = fm.height()
        painter.drawText(20, 20, pixelsWidth, pixelsHeight, QtCore.Qt.AlignLeft, text)
        
        painter.end()
        
        
        #self.actionUAV_position.
        
    #def handlePan(self,toggle):
    #    self.view.panMap(self.view.lat,self.view.lon) 
Example 7
Project: FeelUOwn   Author: feeluown   File: player_control_panel.py    GNU General Public License v3.0 6 votes vote down vote up
def on_player_song_changed(self, song):
        if song is None:
            self.song_source_label.setText('歌曲来源')
            self.song_title_label.setText('No song is playing.')
            return
        source_name_map = {p.identifier: p.name
                           for p in self._app.library.list()}
        font_metrics = QFontMetrics(QApplication.font())
        text = '{} - {}'.format(song.title_display, song.artists_name_display)
        # width -> three button + source label + text <= progress slider
        # three button: 63, source label: 150
        elided_text = font_metrics.elidedText(
            text, Qt.ElideRight, self.progress_slider.width() - 200)
        self.song_source_label.setText(source_name_map[song.source])
        self.song_title_label.setText(elided_text)
        loop = asyncio.get_event_loop()
        loop.create_task(self.update_mv_btn_status(song)) 
Example 8
Project: MARA_Framework   Author: xtiankisutsa   File: Banners.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, themes, dataModel, viewMode):
        self.width = 0
        self.height = 0
        self.dataModel = dataModel
        self.viewMode = viewMode
        self.qpix = self._getNewPixmap(self.width, self.height)
        self.backgroundBrush = QtGui.QBrush(themes['background'])

        # text font
        self.font = themes['font']

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

        self.textPen = QtGui.QPen(QtGui.QColor(192, 192, 192), 0, QtCore.Qt.SolidLine) 
Example 9
Project: MARA_Framework   Author: xtiankisutsa   File: Banners.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, themes, dataModel, viewMode):
        self.width = 0
        self.height = 0
        self.dataModel = dataModel
        self.viewMode = viewMode
        self.backgroundBrush = QtGui.QBrush(themes['background'])

        self.qpix = self._getNewPixmap(self.width, self.height)
        

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

        self.textPen = QtGui.QPen(themes['pen'], 0, QtCore.Qt.SolidLine) 
Example 10
Project: sane-subfeed   Author: BluABK   File: elided_label.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def elide_text(self, p_str):
        """
        Elide text based on configurable values.
        :param p_str:   Text.
        :return:        Elided text.
        """
        # Get font metrics/info.
        metrics = QFontMetrics(self.font())

        # Get latest configurable values
        elided_modifier = read_config(*self.cfg_elided_mod_entry)
        lines = read_config(*self.cfg_lines_entry)
        unicode_weight_modifier = read_config('GridView', 'elided_text_unicode_weight_modifier')

        # Non-ASCII needs to be elided at an earlier width.
        elided_modifier -= get_unicode_weight(p_str, unicode_weight_modifier)

        # If the string text is wider than width, return an elided version of the string
        elided = metrics.elidedText(p_str, Qt.ElideRight, self.width() * elided_modifier * lines)
        return elided 
Example 11
Project: spyrit   Author: pvaret   File: SplittableTextView.py    GNU General Public License v2.0 6 votes vote down vote up
def lineHeight( self ):

    font = self.font()

    ## Generate the layout for one line of text using this font:
    layout = QTextLayout( u"---", font )
    layout.beginLayout()
    line = layout.createLine()
    layout.endLayout()

    ## Obtain the font's leading metric, if positive. (Qt ignores the leading
    ## if it's negative at this point in time.)
    fm = QFontMetrics( font )
    leading = max( fm.leading(), 0 )

    ## This here is the actual line height for this font. Phew.
    return int( line.height() + leading ) 
Example 12
Project: dcc   Author: amimo   File: SourceViewMode.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, themes, width, height, data, cursor, widget=None):
        super(SourceViewMode, self).__init__()

        self.themes = themes

        self.dataModel = data
        self.addHandler(self.dataModel)

        self.width = width
        self.height = height

        self.cursor = cursor
        self.widget = widget

        self.refresh = True

        # background brush
        self.backgroundBrush = QtGui.QBrush(self.themes['background'])

        # text font
        self.font = self.themes['font']

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

        self.textPen = QtGui.QPen(self.themes['pen'], 0, QtCore.Qt.SolidLine)
        self.resize(width, height)

        self.Paints = {}
        self.Ops = []
        self.newPix = None

        self.selector = TextSelection.DefaultSelection(themes, self)

        self.LINES = self.dataModel.current_class.get_source().split('\n') 
Example 13
Project: dcc   Author: amimo   File: cemu.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, qp, rows, cols):
        self.qp = qp
        self._x = 0
        self._y = 0
        self._rows = rows
        self._cols = cols

        fm = QtGui.QFontMetrics(self.qp.font())
        self.fontWidth = fm.width('a')
        self.fontHeight = fm.height() 
Example 14
Project: dcc   Author: amimo   File: BinViewMode.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, themes, width, height, data, cursor, widget=None):
        super(BinViewMode, self).__init__()

        self.dataModel = data
        self.addHandler(self.dataModel)
        self.themes = themes

        self.width = width
        self.height = height

        self.cursor = cursor
        self.widget = widget

        self.refresh = True

        self.selector = TextSelection.DefaultSelection(themes, self)

        # background brush
        self.backgroundBrush = QtGui.QBrush(self.themes['background'])

        self.font = self.themes['font']

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

        self.textPen = QtGui.QPen(self.themes['pen'], 0, QtCore.Qt.SolidLine)
        self.resize(width, height)

        self.Paints = {}
        self.newPix = None
        self.Ops = [] 
Example 15
Project: kucher   Author: Zubax   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def _unittest_icons():
    import math
    import glob
    from PyQt5.QtWidgets import QApplication, QMainWindow, QGroupBox, QGridLayout, QLabel, QSizePolicy
    from PyQt5.QtGui import QFont, QFontMetrics

    app = QApplication([])

    all_icons = list(map(lambda x: os.path.splitext(os.path.basename(x))[0],
                         glob.glob(os.path.join(get_absolute_path('view', 'icons'), '*'))))
    print('All icons:', len(all_icons), all_icons)

    grid_size = int(math.ceil(math.sqrt(len(all_icons))))

    icon_size = QFontMetrics(QFont()).height()

    def render_icon(name: str, row: int, col: int):
        icon = get_icon(name)
        icon_label = QLabel()
        icon_label.setAlignment(Qt.AlignCenter)
        icon_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        icon_label.setPixmap(icon.pixmap(icon_size, icon_size))
        layout.addWidget(icon_label, row, col)

    win = QMainWindow()
    container = QGroupBox(win)
    layout = QGridLayout()

    for idx, ic in enumerate(all_icons):
        render_icon(ic, idx // grid_size, idx % grid_size)

    container.setLayout(layout)
    win.setCentralWidget(container)
    win.show()

    for _ in range(1000):
        time.sleep(0.005)
        app.processEvents()

    win.close() 
Example 16
Project: kucher   Author: Zubax   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: QWidget):
        super(_TableModel, self).__init__(parent)

        self._data: TaskStatisticsView = TaskStatisticsView()

        self._icon_size = QFontMetrics(QFont()).height() 
Example 17
Project: kucher   Author: Zubax   File: fault_status_widget.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: QWidget):
        super(Widget, self).__init__(parent)

        self._last_displayed: TaskSpecificStatusReport.Fault = None

        self._line_height = QFontMetrics(QFont()).height()

        self._task_icon_display = QLabel(self)
        self._task_name_display = self._make_line_display()

        self._error_code_dec = self._make_line_display('Exit code in decimal')
        self._error_code_hex = self._make_line_display('Same exit code in hexadecimal')
        self._error_code_bin = self._make_line_display('Same exit code in binary, for extra convenience')

        self._error_description_display = self._make_line_display('Error description', False)
        self._error_comment_display = self._make_text_display()

        self.setLayout(
            lay_out_vertically(
                lay_out_horizontally(QLabel('The task', self),
                                     self._task_icon_display,
                                     (self._task_name_display, 3)),
                lay_out_horizontally(QLabel('has failed with exit code', self),
                                     (self._error_code_dec, 1),
                                     (self._error_code_hex, 1),
                                     (self._error_code_bin, 2),
                                     QLabel('which means:', self)),
                lay_out_horizontally((self._error_description_display, 1)),
                lay_out_horizontally((self._error_comment_display, 1)),
                (None, 1),
            )
        ) 
Example 18
Project: kucher   Author: Zubax   File: run_status_widget.py    GNU General Public License v3.0 5 votes vote down vote up
def _make_vertical_separator(parent: QWidget) -> QWidget:
    # https://stackoverflow.com/questions/10053839/how-does-designer-create-a-line-widget
    line = QFrame(parent)
    line.setFrameShape(QFrame.VLine)
    line.setStyleSheet('QFrame { color: palette(mid); };')
    line.setMinimumWidth(QFontMetrics(QFont()).width('__') * 2)
    return line 
Example 19
Project: kucher   Author: Zubax   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def font_height(self):
        return max(QFontMetrics(self._monospace_font).height(),
                   QFontMetrics(self._special_event_font).height(),
                   QFontMetrics(QFont()).height()) 
Example 20
Project: kucher   Author: Zubax   File: value_display_widget.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: QWidget):
        super(_Comment, self).__init__(parent)
        self.setAlignment(Qt.AlignCenter)
        self._icon_size = QFontMetrics(QFont()).height()        # As large as font
        self._pixmap_cache: typing.Dict[str, QPixmap] = {}
        self._current_icon_name: typing.Optional[str] = None
        # Initializing defaults
        self.reset() 
Example 21
Project: reporta   Author: jbentham   File: rp_pyqt.py    Apache License 2.0 5 votes vote down vote up
def measure_text(self, txt="ABCD"):
        fm = QFontMetrics(LABEL_FONT)
        self.label_wd, self.label_ht = fm.width(txt)*LABEL_SCALE, fm.height()*LABEL_SCALE

    # Add labels to part 
Example 22
Project: MeiTingTrunk   Author: Xunius   File: meta_tab.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,field,parent=None):
        '''
        Args:
            field (str): field name of this textedit, e.g. title, year ...
            parent (QWidget): parent widget.

        This modified QTextEdit doesn't show scroll bar, but adjusts height
        acorrding to contents and width.
        '''

        super(AdjustableTextEdit,self).__init__(parent)

        self.field=field # field name, e.g. title, year, tags_l ...
        self.fm=QFontMetrics(self.font())
        # pop up tooltip
        self.tooltip_label=QtWidgets.QLabel()
        self.tooltip_label.setWindowFlags(Qt.SplashScreen)
        self.tooltip_label.setMargin(3)
        self.tooltip_label.setStyleSheet('''
                background-color: rgb(235,225,120)
                ''')
        self.tooltip_text=''
        self.label_enabled=False

        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.textChanged.connect(self.resizeTextEdit)
        self.document().documentLayout().documentSizeChanged.connect(
                self.resizeTextEdit)
        self.setTabChangesFocus(True) 
Example 23
Project: plexdesktop   Author: coryo   File: delegates.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent=None):
        super().__init__(parent)
        s = Settings()
        browser_font_size = int(s.value('browser_font', 9))
        self.title_font = QtGui.QFont('Open Sans Extrabold', browser_font_size)
        self.summary_font = QtGui.QFont('Open Sans',
                                        browser_font_size * 0.95,
                                        QtGui.QFont.Bold)
        self.title_font_metrics = QtGui.QFontMetrics(self.title_font)
        self.summary_font_metrics = QtGui.QFontMetrics(self.title_font)
        self.last_icon_size = self.parent().iconSize().height() 
Example 24
Project: Eyecandy-py   Author: Alquimista   File: effector.py    MIT License 5 votes vote down vote up
def size(self):
        """Get width and height of text"""

        # Font
        font = QtGui.QFont(self._style.fontname)
        font.setLetterSpacing(
            QtGui.QFont.AbsoluteSpacing, self._style.spacing)
        font.setHintingPreference(QtGui.QFont.PreferNoHinting)
        font.setStyleStrategy(QtGui.QFont.PreferMatch)
        font.setPixelSize(self._style.fontsize * self._ssampling)
        font.setItalic(self._style.italic)
        font.setBold(self._style.bold)

        # Fontmetric Size
        fontmetrics = QtGui.QFontMetrics(font)
        height = fontmetrics.height()
        width = fontmetrics.width(self.text)

        # VSfilter size
        pixelsize = font.pixelSize()
        scaling = pixelsize / (height if height > 0 else 1)
        width = width * scaling * (self._style.scalex / 100)
        height = pixelsize * (self._style.scaley / 100)

        return (round(width / self._ssampling, 4),
                round(height / self._ssampling, 4)) 
Example 25
Project: meditor   Author: liuyug   File: vim.py    MIT License 5 votes vote down vote up
def __init__(self, parent):
        super(VimEmulator, self).__init__(parent)
        self._mode_label = QtWidgets.QLabel(self)
        self._leader_label = QtWidgets.QLabel(self)
        font = self._mode_label.font()
        font.setBold(True)
        fontmetrics = QtGui.QFontMetrics(font)
        font_width = fontmetrics.width('O')

        self._mode_label.setFont(font)
        self._leader_label.setFont(font)
        self._mode_label.setMinimumWidth(font_width * 7)
        self._leader_label.setMinimumWidth(font_width * 3)
        self._mode_label.setAlignment(QtCore.Qt.AlignCenter)
        self._leader_label.setAlignment(QtCore.Qt.AlignCenter)
        self.setLeaderChar('')

        self._command_edit = VimCommand(self)

        h_layout = QtWidgets.QHBoxLayout(self)
        h_layout.setContentsMargins(0, 0, 0, 0)
        h_layout.addWidget(self._mode_label)
        h_layout.addWidget(self._command_edit)
        h_layout.addWidget(self._leader_label)

        self._mode_label.setBuddy(self._command_edit)
        self._leader_label.setBuddy(self._command_edit)

        self._command_edit.returnPressed.connect(
            partial(self.handleCommandMode, 'return'))
        self._command_edit.escapePressed.connect(
            partial(self.handleCommandMode, 'escape'))

        self.setMode('normal')
        self._vertical_edit = {} 
Example 26
Project: meditor   Author: liuyug   File: editor.py    MIT License 5 votes vote down vote up
def do_set_margin_width(self):
        length = max(len('%s' % self.lines()) + 1, self._min_margin_width)
        fontmetrics = QtGui.QFontMetrics(self._margin_font)
        self.setMarginWidth(0, fontmetrics.width('0' * length)) 
Example 27
Project: BUAAAIHomeWork   Author: potato-cat   File: circle_indicator.py    GNU General Public License v3.0 5 votes vote down vote up
def paint(self, painter, option, widget):
        painter.setPen(self.color)
        painter.setFont(self.font)
        fontMetrics = QFontMetrics(self.font)
        painter.drawPixmap(0, 0, self.bubble)
        painter.drawText((self.size - fontMetrics.
                          width(str(self.num))) / 2,
                         (self.size + fontMetrics.
                          height()) / 2 - self.size / 10, str(self.num)) 
Example 28
Project: GeoMop   Author: GeoMop   File: editor_appearance.py    GNU General Public License v3.0 5 votes vote down vote up
def set_default_appearence(cls, editor):
        """Set default applicatin editor appearents"""
        # Set the default font
        cls.font.fromString(cfg.config.font)
        editor.setFont(cls.font)
        editor.setMarginsFont(cls.font)
        editor.lexer.setFont(cls.font)

        # Margin 0 is used for line numbers
        fontmetrics = QtGui.QFontMetrics(cls.font)
        editor.setMarginsFont(cls.font)
        editor.setMarginWidth(0, fontmetrics.width("00000") + 6)
        editor.setMarginLineNumbers(0, True)
        editor.setMarginsBackgroundColor(QtGui.QColor("#cccccc"))

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

        # 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)
        editor.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        # Current line visible with special background color
        editor.setCaretLineVisible(True)
        editor.setCaretLineBackgroundColor(QtGui.QColor("#e4e4e4")) 
Example 29
Project: MDT   Author: robbert-harms   File: tab_map_specific.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, controller, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self._controller = controller

        current_model = self._controller.get_model()

        self._current_map = None
        self.colormap.addItems(['-- Use global --'] + current_model.get_config().get_available_colormaps())
        self.colormap.currentIndexChanged.connect(self._update_colormap)
        self.data_clipping_min.valueChanged.connect(self._update_clipping_min)
        self.data_clipping_max.valueChanged.connect(self._update_clipping_max)
        self.data_scale_min.valueChanged.connect(self._update_scale_min)
        self.data_scale_max.valueChanged.connect(self._update_scale_max)

        self.data_set_use_scale.stateChanged.connect(self._set_use_scale)
        self.use_data_scale_min.stateChanged.connect(self._set_use_data_scale_min)
        self.use_data_scale_max.stateChanged.connect(self._set_use_data_scale_max)

        self.data_set_use_clipping.stateChanged.connect(self._set_use_clipping)
        self.use_data_clipping_min.stateChanged.connect(self._set_use_data_clipping_min)
        self.use_data_clipping_max.stateChanged.connect(self._set_use_data_clipping_max)

        self._title_timer = TimedUpdate(self._update_map_title)
        self.map_title.textChanged.connect(lambda: self._title_timer.add_delayed_callback(500))
        self.map_title.setFixedHeight(QFontMetrics(self.map_title.font()).lineSpacing() * 3)

        self._colorbar_label_timer = TimedUpdate(self._update_colorbar_label)
        self.data_colorbar_label.textChanged.connect(lambda : self._colorbar_label_timer.add_delayed_callback(500))
        self.data_colorbar_label.setFixedHeight(QFontMetrics(self.data_colorbar_label.font()).lineSpacing() * 3)

        self.info_Clipping.set_collapse(True)

        self._auto_enable_scale_min = False
        self._auto_enable_scale_max = False
        self._auto_enable_clipping_min = False
        self._auto_enable_clipping_max = False

        self.reset()
        self._update_scaling_delays() 
Example 30
Project: vimiv-qt   Author: karlch   File: widgets.py    GNU General Public License v3.0 5 votes vote down vote up
def paintEvent(self, event):
        """Override paint event to additionally paint the current value."""
        super().paintEvent(event)
        self._init_style()

        text = str(self.value())
        rect = self.geometry()
        painter = QPainter(self)
        font_metrics = QFontMetrics(self.font())

        x = (rect.width() - font_metrics.width(text)) // 2
        y = rect.height() - (rect.height() - font_metrics.capHeight()) // 2
        painter.drawText(x, y, text) 
Example 31
Project: vimiv-qt   Author: karlch   File: widgets.py    GNU General Public License v3.0 5 votes vote down vote up
def _init_style(self):
        """Initialize the stylesheet.

        This is called on the first paintEvent to ensure all sizes and fonts are
        correct.
        """
        font_height = QFontMetrics(self.font()).capHeight()
        groove_height = font_height + 2 * self.PADDING
        total_height = groove_height + 2 * self.HANDLE_MARGIN
        sheet = f"""
        QSlider {{
            height: {total_height:d}px;
        }}

        QSlider::sub-page {{
            background-color: {self._left_color};
        }}

        QSlider::handle {{
            width: 24px;
            background-color: {self._handle_color};
            margin: -{SliderWithValue.HANDLE_MARGIN}px 0px;
        }}

        QSlider::groove {{
            background-color: {self._right_color};
            height: {groove_height}px;
        }}
        """
        styles.apply(self, append=sheet) 
Example 32
Project: linux-show-player   Author: FrancescoCeruti   File: equalizer10.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout())
        self.layout().setAlignment(Qt.AlignTop)

        self.groupBox = QGroupBox(self)
        self.groupBox.resize(self.size())
        self.groupBox.setTitle(
            translate('Equalizer10Settings', '10 Bands Equalizer (IIR)'))
        self.groupBox.setLayout(QGridLayout())
        self.groupBox.layout().setVerticalSpacing(0)
        self.layout().addWidget(self.groupBox)

        self.sliders = {}

        for n in range(10):
            label = QLabel(self.groupBox)
            label.setMinimumWidth(QFontMetrics(label.font()).width('000'))
            label.setAlignment(QtCore.Qt.AlignCenter)
            label.setNum(0)
            self.groupBox.layout().addWidget(label, 0, n)

            slider = QSlider(self.groupBox)
            slider.setRange(-24, 12)
            slider.setPageStep(1)
            slider.setValue(0)
            slider.setOrientation(QtCore.Qt.Vertical)
            slider.valueChanged.connect(label.setNum)
            self.groupBox.layout().addWidget(slider, 1, n)
            self.groupBox.layout().setAlignment(slider, QtCore.Qt.AlignHCenter)
            self.sliders['band' + str(n)] = slider

            fLabel = QLabel(self.groupBox)
            fLabel.setStyleSheet('font-size: 8pt;')
            fLabel.setAlignment(QtCore.Qt.AlignCenter)
            fLabel.setText(self.FREQ[n])
            self.groupBox.layout().addWidget(fLabel, 2, n) 
Example 33
Project: AutoSplit64   Author: Kainev   File: update_dialog.py    GNU General Public License v3.0 5 votes vote down vote up
def set_update_info(self, version_info):
        self._update_info = version_info

        # Set version
        self.available_lb.setText("AutoSplit64 Version {} is now available!".format(self._update_info["latest"]["version"]))

        # Set Highlights
        self.highlights_te.clear()
        self.highlights_te.append("Highlights:\n")
        cursor = self.highlights_te.textCursor()
        cursor.insertList(QtGui.QTextListFormat.ListDisc)

        for highlight in self._update_info["latest"]["version_features"]:
            self.highlights_te.insertPlainText(highlight)
            self.highlights_te.append("")

        cursor.deletePreviousChar()

        highlights_font = self.highlights_te.document().defaultFont()
        font_metrics = QtGui.QFontMetrics(highlights_font)
        text_size = font_metrics.size(0, self.highlights_te.toPlainText())
        text_height = text_size.height() + 20

        self.highlights_te.setFixedHeight(text_height)

        # Set Blog Label
        url_link = "<a href=\"{}\">read the blog post</a>".format(self._update_info["latest"]["version_post"])
        self.blog_lb.setText("For more details, " + url_link)

        # Set Current Version
        self.current_info_lb.setText(self._update_info["current"]["version"])

        # Set New Version
        self.new_info_lb.setText(self._update_info["latest"]["version"])

        # Set Patch Size
        self.size_info_lb.setText("{} MB".format(str(self._update_info["latest"]["patch_size"]))) 
Example 34
Project: ImageDatabase   Author: Darmo117   File: components.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_text(self, event, painter):
        metrics = QtG.QFontMetrics(self.font())
        elided_text = metrics.elidedText(self.text(), QtC.Qt.ElideRight, self.width())
        painter.drawText(event.rect(), QtC.Qt.AlignCenter, elided_text) 
Example 35
Project: mkYARA   Author: fox-it   File: mkyara_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
def populate_form(self):
        self.setWindowTitle('mkYARA :: Generated Yara Rule')
        self.resize(800, 600)
        self.layout = QtWidgets.QVBoxLayout(self)
        self.top_layout = QtWidgets.QHBoxLayout()
        self.bottom_layout = QtWidgets.QHBoxLayout()
        self.bottom_layout.setAlignment(Qt.AlignRight | Qt.AlignBottom)
        # layout.addStretch()

        self.layout.addWidget(QtWidgets.QLabel("Generated Yara rule from 0x{:x} to 0x{:x}".format(self.start_addr, self.end_addr)))
        self.text_edit = QtWidgets.QTextEdit()
        font = QtGui.QFont()
        font.setFamily("Consolas")
        font.setStyleHint(QtGui.QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.text_edit.setFont(font)
        metrics = QtGui.QFontMetrics(font)
        self.text_edit.setTabStopWidth(4 * metrics.width(' '))

        self.text_edit.insertPlainText(self.yara_rule)
        self.layout.addWidget(self.text_edit)

        self.ok_btn = QtWidgets.QPushButton("OK")
        self.ok_btn.setFixedWidth(100)
        self.ok_btn.clicked.connect(self.ok_btn_clicked)
        self.bottom_layout.addWidget(self.ok_btn)

        self.layout.addLayout(self.top_layout)
        self.layout.addLayout(self.bottom_layout) 
Example 36
Project: scm-workbench   Author: barry-scott   File: wb_diff_side_by_side_view.py    Apache License 2.0 5 votes vote down vote up
def __init__( self, app, parent, name=None ):
        super().__init__( parent )
        self.name = name

        self.style_normal = self.STYLE_DEFAULT
        self.style_line_numbers = self.STYLE_LASTPREDEFINED + 1
        self.style_line_numbers_for_diff = self.STYLE_LASTPREDEFINED

        self.emptyUndoBuffer()

        self.setMarginWidth( 0, 0 )
        self.setMarginWidth( 1, 0 )
        self.setMarginWidth( 2, 0 )

        # make some styles
        self.setFont( app.codeFont() )
        self.styleSetFromSpec( self.style_normal,
                'fore:%s,back:%s' % (app.defaultFgRgb(), app.defaultBgRgb()) )
        self.styleSetFromSpec( self.style_line_numbers,
                'fore:%s,back:%s' % (app.defaultFgRgb(), app.defaultBgRgb()) )
        self.styleSetFromSpec( self.style_line_numbers_for_diff,
                'fore:%s,back:%s' % (app.defaultFgRgb(), '#0d0d0d') )

        # Calculate space for 6 digits
        fontmetrics = QtGui.QFontMetrics( app.codeFont() )

        width = fontmetrics.width( '123456' )

        self.setScrollWidth( width )
        self.setMaximumWidth( width )
        self.setMinimumWidth( width )

        # no scroll bars on the line number control
        self.setVScrollBar( False )
        self.setHScrollBar( False ) 
Example 37
Project: Python-Googlefit   Author: pinae   File: timed_diagram.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, padding=4, y_unit="kg", y_format="{:3.0f}", *args):
        super(TimedDigram, self).__init__(*args)
        self.padding = padding
        self.y_unit = y_unit
        self.data = []
        self.x_range = datetime.now(), datetime.now()
        self.y_range = 0.0, 0.0
        self.y_format = y_format
        self.gray_line_color = QColor(140, 140, 140)
        self.axis_number_color = QColor(0, 0, 0)
        self.gray_pen = QPen(self.gray_line_color, 1, Qt.SolidLine)
        self.text_pen = QPen(self.axis_number_color, 1, Qt.SolidLine)
        self.gray_brush = QBrush(self.gray_line_color)
        self.font = QFont("Helvetica", pointSize=8, weight=0, italic=0)
        self.fm = QFontMetrics(self.font) 
Example 38
Project: overboard   Author: jotaf98   File: window.py    GNU General Public License v3.0 5 votes vote down vote up
def resize_table(self):
    """Resize the column headers to fully contain the header text
    (note that Qt's resizeColumnsToContents ignores the headers)"""
    table = self.table
    table.resizeColumnsToContents()
    
    max_width = int(0.9 * table.parentWidget().width())  # don't let any column become wider than 90% of the sidebar
    header = table.horizontalHeader()
    metrics = QtGui.QFontMetrics(table.horizontalHeaderItem(0).font())
    for col in range(table.columnCount()):
      text = table.horizontalHeaderItem(col).text()
      text_width = metrics.boundingRect(text).width()
      header.resizeSection(col, min(max_width, max(table.sizeHintForColumn(col), text_width + 20)))  # needs some extra width 
Example 39
Project: MARA_Framework   Author: xtiankisutsa   File: SourceViewMode.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, themes, width, height, data, cursor, widget=None):
        super(SourceViewMode, self).__init__()

        self.themes = themes

        self.dataModel = data
        self.addHandler(self.dataModel)

        self.width = width
        self.height = height

        self.cursor = cursor
        self.widget = widget

        self.refresh = True

        # background brush
        self.backgroundBrush = QtGui.QBrush(self.themes['background'])

        # text font
        self.font = self.themes['font']

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

        self.textPen = QtGui.QPen(self.themes['pen'], 0, QtCore.Qt.SolidLine)
        self.resize(width, height)

        self.Paints = {}
        self.Ops = []
        self.newPix = None

        self.selector = TextSelection.DefaultSelection(themes, self)

        self.LINES = self.dataModel.current_class.get_source().split('\n') 
Example 40
Project: MARA_Framework   Author: xtiankisutsa   File: cemu.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, qp, rows, cols):
        self.qp = qp
        self._x = 0
        self._y = 0
        self._rows = rows
        self._cols = cols

        fm = QtGui.QFontMetrics(self.qp.font())
        self.fontWidth  = fm.width('a')
        self.fontHeight = fm.height() 
Example 41
Project: MARA_Framework   Author: xtiankisutsa   File: BinViewMode.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, themes, width, height, data, cursor, widget=None):
        super(BinViewMode, self).__init__()

        self.dataModel = data
        self.addHandler(self.dataModel)
        self.themes = themes

        self.width = width
        self.height = height

        self.cursor = cursor
        self.widget = widget

        self.refresh = True

        self.selector = TextSelection.DefaultSelection(themes, self)

        # background brush
        self.backgroundBrush = QtGui.QBrush(self.themes['background'])

        self.font = self.themes['font']

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


        
        self.textPen = QtGui.QPen(self.themes['pen'], 0, QtCore.Qt.SolidLine)
        self.resize(width, height)

        self.Paints = {}
        self.newPix = None
        self.Ops = [] 
Example 42
Project: Hydra   Author: CountryTk   File: Messagebox.py    GNU General Public License v3.0 5 votes vote down vote up
def resize_contents(self):
        text = self.text()

        font = QFont("", 0)
        metrics = QFontMetrics(font)

        width = metrics.width(text)
        height = metrics.height()

        self.setMinimumWidth(width + 40)
        self.setMinimumHeight(height + 15) 
Example 43
Project: Dwarf   Author: iGio90   File: dialog_input.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, dialog, *__args):
        super().__init__(*__args)
        self.dialog = dialog

        self.setStyleSheet('padding: 0; padding: 0 5px;')

        bar = QScrollBar()
        bar.setFixedHeight(0)
        bar.setFixedWidth(0)
        font_metric = QFontMetrics(self.font())
        row_height = font_metric.lineSpacing()
        self.setFixedHeight(row_height + 10)  # 10 == 2*5px padding
        self.setMinimumWidth(400) 
Example 44
Project: adviser   Author: DigitalPhonetics   File: ChatWidget.py    GNU General Public License v3.0 5 votes vote down vote up
def sizeHint(self):
        size = QLabel.sizeHint(self)
        max_width = self.container.width() * 0.8
        fm = QFontMetrics(self.font())
        fm_width = fm.width(self.text()) + 30
        return QSize(min((fm_width, max_width)), size.height()) 
Example 45
Project: AnalogGaugeWidgetPyQt   Author: StefanHol   File: analoggaugewidget.py    Apache License 2.0 5 votes vote down vote up
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])
        # painter.restore() 
Example 46
Project: AnalogGaugeWidgetPyQt   Author: StefanHol   File: analoggaugewidget.py    Apache License 2.0 5 votes vote down vote up
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):
        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])
        # painter.restore() 
Example 47
Project: PyQt   Author: PyQt5   File: ChatWidget.py    GNU General Public License v3.0 5 votes vote down vote up
def init(self):
        self.setUtf8(True)
        lexer = QsciLexerJSON(self)
        self.setLexer(lexer)
        self.setAutoCompletionCaseSensitivity(False)  # 忽略大小写
        self.setAutoCompletionSource(self.AcsAll)
        self.setAutoCompletionThreshold(1)  # 一个字符就弹出补全
        self.setAutoIndent(True)  # 自动缩进
        self.setBackspaceUnindents(True)
        self.setBraceMatching(self.StrictBraceMatch)
        self.setIndentationGuides(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setTabWidth(4)
        self.setWhitespaceSize(1)
        self.setWhitespaceVisibility(self.WsVisible)
        self.setWhitespaceForegroundColor(Qt.gray)
        self.setWrapIndentMode(self.WrapIndentFixed)
        self.setWrapMode(self.WrapWord)
        # 折叠
        self.setFolding(self.BoxedTreeFoldStyle, 2)
        self.setFoldMarginColors(QColor("#676A6C"), QColor("#676A6D"))
        font = self.font() or QFont()
        font.setFamily("Consolas")
        font.setFixedPitch(True)
        font.setPointSize(13)
        self.setFont(font)
        self.setMarginsFont(font)
        self.fontmetrics = QFontMetrics(font)
        lexer.setFont(font)
        self.setMarginWidth(0, self.fontmetrics.width(str(self.lines())) + 6)
        self.setMarginLineNumbers(0, True)
        self.setMarginsBackgroundColor(QColor("gainsboro"))
        self.setMarginWidth(1, 0)
        self.setMarginWidth(2, 14)  # 折叠区域
        # 绑定自动补齐热键Alt+/
        completeKey = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Slash), self)
        completeKey.setContext(Qt.WidgetShortcut)
        completeKey.activated.connect(self.autoCompleteFromAll) 
Example 48
Project: PyQt   Author: PyQt5   File: VerificationCode.py    GNU General Public License v3.0 5 votes vote down vote up
def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        # 背景白色
        painter.fillRect(event.rect(), QBrush(Qt.white))
        # 绘制边缘虚线框
        painter.setPen(Qt.DashLine)
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(self.rect())
        # 随机画条线
        for _ in range(3):
            painter.setPen(QPen(QTCOLORLIST[qrand() % 5], 1, Qt.SolidLine))
            painter.setBrush(Qt.NoBrush)
            painter.drawLine(QPoint(0, qrand() % self.height()),
                             QPoint(self.width(), qrand() % self.height()))
            painter.drawLine(QPoint(qrand() % self.width(), 0),
                             QPoint(qrand() % self.width(), self.height()))
        # 绘制噪点
        painter.setPen(Qt.DotLine)
        painter.setBrush(Qt.NoBrush)
        for _ in range(self.width()):  # 绘制噪点
            painter.drawPoint(QPointF(qrand() % self.width(), qrand() % self.height()))
        # super(WidgetCode, self).paintEvent(event)  # 绘制文字
        # 绘制跳动文字
        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.width(self.text())) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        for i, ch in enumerate(self.text()):
            index = (self.step + i) % 16
            painter.setPen(TCOLORLIST[qrand() % 6])
            painter.drawText(x, y - ((SINETABLE[index] * metrics.height()) / 400), ch)
            x += metrics.width(ch) 
Example 49
Project: spyrit   Author: pvaret   File: WorldInputUI.py    GNU General Public License v2.0 5 votes vote down vote up
def refresh( self ):

    ## Unlike the output UI, which is very specific to the problem domain --
    ## i.e. MU*s, the input box should be whatever's convenient to the
    ## user, and already configured in their system. This is why we use
    ## system default values when nothing specific is configured.

    style_elements = []

    input_settings = self.settings._ui._input
    if input_settings._font._color:

      style_elements.append( u"color: %s" \
                             % input_settings._font._color )

    if input_settings._font._name:

      style_elements.append( u"font-family: %s" \
                             % input_settings._font._name )

    if input_settings._font._size:

      style_elements.append( u"font-size: %dpt" \
                             % input_settings._font._size )

    if input_settings._background._color:

      style_elements.append( u"background-color: %s" \
                             % input_settings._background._color )

    if style_elements:
      self.setStyleSheet( u"QTextEdit { %s }" % " ; ".join( style_elements ) )

    font_height = QFontMetrics( self.font() ).height()
    self.setMinimumHeight( font_height*3 ) 
Example 50
Project: dcc   Author: amimo   File: HexViewMode.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, themes, width, height, data, cursor, widget=None):
        super(HexViewMode, self).__init__()

        self.dataModel = data
        self.width = width
        self.height = height

        self.refresh = True
        self.selector = TextSelection.HexSelection(themes, self)
        self.widget = widget

        self.addHandler(self.dataModel)

        # background brush
        self.backgroundBrush = QtGui.QBrush(themes['background'])

        # text font
        self.font = themes['font']

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

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

        self.textPen = QtGui.QPen(themes['pen'], 1, QtCore.Qt.SolidLine)

        self.cursor = cursor

        self.HexColumns = [1, 4, 8, 16, 32, 36, 40]
        self.idxHexColumns = 3  # 32 columns

        self.newPix = None
        self.Ops = []
        self.gap = 5

        self.highpart = True
        self.resize(width, height)

        self.ann_w = Annotation(self.widget, self) 
Example 51
Project: kucher   Author: Zubax   File: editor_delegate.py    GNU General Public License v3.0 4 votes vote down vote up
def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget:
        """
        The set of editors that we have defined here are only good for small-dimensioned registers with a few values.
        They are not good for unstructured data and large arrays. For that, shall the need arise, we'll need to define
        dedicated complex widgets. Luckily, it is very easy to do, just not really necessary at the moment.
        The framework doesn't care what kind of widget we're displaying when editing, it's just a basic pop-up that
        appears on top of the view.
        """
        register = self._get_register_from_index(index)
        _logger.info('Constructing editor for %r', register)

        if self._can_use_bool_switch(register):
            editor = QComboBox(parent)
            editor.setEditable(False)
            editor.addItem(get_icon('cancel'), 'False (0)')
            editor.addItem(get_icon('ok'), 'True (1)')
        elif self._can_use_spinbox(register):
            minimum, maximum = register.min_value[0], register.max_value[0]

            try:
                dtype = Register.get_numpy_type(register.type_id)
                float_decimals = int(abs(math.log10(numpy.finfo(dtype).resolution)) + 0.5) + 1
            except ValueError:
                float_decimals = None

            if float_decimals is not None:
                step = (maximum - minimum) / _MIN_PREFERRED_NUMBER_OF_STEPS_IN_FULL_RANGE
                try:
                    step = 10 ** round(math.log10(step))
                except ValueError:
                    step = 1        # Math domain error corner case

                step = min(1.0, step)                       # Step can't be greater than one for UX reasons
                _logger.info('Constructing QDoubleSpinBox with single step set to %r', step)
                editor = QDoubleSpinBox(parent)
                editor.setSingleStep(step)
                editor.setDecimals(float_decimals)
            else:
                editor = QSpinBox(parent)

            editor.setMinimum(minimum)
            editor.setMaximum(maximum)
        else:
            editor = QPlainTextEdit(parent)
            editor.setFont(get_monospace_font())
            editor.setMinimumWidth(QFontMetrics(editor.font()).width('9' * (MAX_LINE_LENGTH + 5)))

        editor.setFont(Model.get_font())

        self._message_display_callback('Press Esc to cancel editing')

        return editor 
Example 52
Project: MARA_Framework   Author: xtiankisutsa   File: HexViewMode.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def __init__(self, themes, width, height, data, cursor, widget=None):
        super(HexViewMode, self).__init__()

        self.dataModel = data
        self.width = width
        self.height = height

        self.refresh = True
        self.selector = TextSelection.HexSelection(themes, self)
        self.widget = widget

        self.addHandler(self.dataModel)

        # background brush
        self.backgroundBrush = QtGui.QBrush(themes['background'])

        # text font
        self.font = themes['font']
        
        # font metrics. assume font is monospaced
        self.font.setKerning(False)
        self.font.setFixedPitch(True)
        fm = QtGui.QFontMetrics(self.font)
        self._fontWidth  = fm.width('a')
        self._fontHeight = fm.height()

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

        self.textPen = QtGui.QPen(themes['pen'], 1, QtCore.Qt.SolidLine)

        self.cursor = cursor

        self.HexColumns = [1, 4, 8, 16, 32, 36, 40]
        self.idxHexColumns = 3 # 32 columns

        self.newPix = None
        self.Ops = []
        self.gap = 5

        self.highpart = True
        self.resize(width, height)

        self.ann_w = Annotation(self.widget, self) 
Example 53
Project: Hydra   Author: CountryTk   File: TextEditor.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, parent=None):
        super().__init__(parent)

        self.fileName = None
        self.parent = parent
        self.debugging = False
        self.line = None
        self.column = None

        self.wordlist = []
        self.searchtext = None

        self.font = QFont()
        self.font.setFamily("Inconsolata")
        self.pointSize = editor["pointSize"]
        self.font.setPointSize(self.pointSize)
        self.dialog = MessageBox(self)
        self.verticalScrollBar().setStyleSheet(
            """
            background-color: transparent;
            """
        )

        self.horizontalScrollBar().setStyleSheet(
            """
            background-color: transparent;
            """
        )

        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setCaretForegroundColor(QColor("#FFFFFF"))
        self.setEdgeColumn(121)
        self.setEdgeMode(1)
        self.setEdgeColor(QColor("#8c8c8c"))
        self.setFont(self.font)
        self.setMarginSensitivity(1, True)
        self.markerDefine(QsciScintilla.RightArrow, 8)
        self.setMarkerBackgroundColor(QColor("#FF0000"), 8)
        self.indicator_number = 0
        self.indicator_value = 222
        self.indicator_color = QColor("#FF0000")
        self.draw_under_text = True
        # Initializing some stuff
        self.set_brace_colors(
            QColor("#98b4f9"), QColor("#edf40e"), QColor("#98b4f9"), QColor("red")
        )

        self.cursorPositionChanged.connect(self.change_col)
        self.textChanged.connect(self.check_lines)

        self.set_linenumbers(QFontMetrics(self.font))
        self.setFoldMarginColors(QColor("#212121"), QColor("#212121"))
        self.set_indentation_settings() 
Example 54
Project: sane-subfeed   Author: BluABK   File: elided_label.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(self, text, parent, font: QFont, cfg_lines_entry, cfg_elided_mod_entry):
        """
        Elided label (superclass).
        :param text:                    String to put on QLabel.
        :param parent:                  Parent ptr.
        :param cfg_lines_entry:         QFont font to use.
        """
        QLabel.__init__(self, text)
        self.parent = parent

        # Unescape HTML/XML codes, if any (usually happens with youtube.search() results)
        text = BeautifulSoup(text, "html.parser").text

        self.setFont(font)

        # Set label type independent config entries
        self.cfg_lines_entry: list = cfg_lines_entry
        self.cfg_elided_mod_entry: list = cfg_elided_mod_entry

        # Elided overwrites the original, so we need to keep a copy.
        self.original_text = text

        # Get font metrics/info.
        metrics = QFontMetrics(self.font())

        # Lines of text to show (determines height of title text item).
        lines = read_config(*self.cfg_lines_entry)

        # Offset the unicode because it has tall characters and its line spacing is thus larger than ASCII's.
        #
        # If set to 2 there will be 1px clearing beneath unicode,
        # but ASCII will show 1px of its supposedly cut-off next line.
        unicode_height_offset = read_config('GridView', 'tile_unicode_line_height_offset')

        # Set height equal to lines and add some newline spacing for unicode.
        self.setFixedHeight((metrics.height() * lines) + (unicode_height_offset * lines))

        # Set alignment and enable word wrapping so the text newlines instead of continuing OOB
        self.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
        self.setWordWrap(True)

        # Finally, set the text string.
        self.setText(text, elided=True) 
Example 55
Project: gr-guiextra   Author: ghostop14   File: digitalnumbercontrol.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, minFreqHz = 0, maxFreqHz=6000000000, parent=None,  ThousandsSeparator=',', backgroundColor='black', fontColor='white', clickCallback=None):
        QFrame.__init__(self, parent)
        
        self.updateInt.connect(self.onUpdateInt)
        self.updateFloat.connect(self.onUpdateFloat)
        
        self.minFreq = int(minFreqHz)
        self.maxFreq = int(maxFreqHz)
        self.numDigitsInFreq = len(str(maxFreqHz))
 
        self.ThousandsSeparator = ThousandsSeparator
        self.clickCallback = clickCallback
        
        # See https://doc.qt.io/archives/qt-4.8/qframe.html for a description
        #self.setLineWidth(2)
        #self.setMidLineWidth(0)
        #self.setFrameStyle(QFrame.Sunken)
        #self.setContentsMargins(2,2,2,2)

        #self.setStyleSheet("border: 2;border-style: inset;")
        
        self.readOnly = False
                    
        # self.setColors(Qt.black, Qt.white)
        self.setColors(QColor(backgroundColor), QColor(fontColor))
        self.numberFont = QFont("Arial", 12, QFont.Normal)

        self.curFreq = minFreqHz
        
        self.debugClick = False
        
        # Determine what our width minimum is
        teststr = ""
        for i in range(0,self.numDigitsInFreq):
            teststr += "0"
            
        fm = QFontMetrics(self.numberFont)
        if len(self.ThousandsSeparator) > 0:
            # The -1 makes sure we don't count an extra for 123,456,789.  Answer should be 2 not 3.
            numgroups = int(float(self.numDigitsInFreq-1) / 3.0)
            if (numgroups > 0):
                for i in range(0,numgroups):
                    teststr += self.ThousandsSeparator
                    
            textstr = teststr
        else:
            textstr = teststr

        width=fm.horizontalAdvance(textstr)
        
        self.minwidth = width
        # print("min width: " + str(width))
        if (self.minwidth < 410):
            self.minwidth = 410
            
        self.setMaximumHeight(70)
        self.setMinimumWidth(self.minwidth)
        # Show the control
        self.show()