예제 #1
1
 def headerData(self, section, orientation, role):
     """
     Public method to get header data from the model.
     
     @param section section number (integer)
     @param orientation orientation (Qt.Orientation)
     @param role role of the data to retrieve (integer)
     @return requested data
     """
     if role == Qt.SizeHintRole:
         fm = QFontMetrics(QFont())
         height = fm.height() + fm.height() // 3
         width = \
             fm.width(self.headerData(section, orientation, Qt.DisplayRole))
         return QSize(width, height)
     
     if orientation == Qt.Horizontal:
         if role == Qt.DisplayRole:
             try:
                 return self.__headers[section]
             except IndexError:
                 return None
         
         return None
     
     return QAbstractTableModel.headerData(self, section, orientation, role)
예제 #2
0
 def resizeEvent(self, event):
     super(MyQLabel, self).resizeEvent(event)
     if not self.text():
         return
     #--- fetch current parameters ----
     f = self.font()
     cr = self.contentsRect()
     #--- iterate to find the font size that fits the contentsRect ---
     dw = event.size().width() - event.oldSize().width()  # width change
     dh = event.size().height() - event.oldSize().height()  # height change
     fs = max(f.pixelSize(), 1)
     while True:
         f.setPixelSize(fs)
         br = QFontMetrics(f).boundingRect(self.text())
         if dw >= 0 and dh >= 0:  # label is expanding
             if br.height() <= cr.height() and br.width() <= cr.width():
                 fs += 1
             else:
                 f.setPixelSize(max(fs - 1, 1))  # backtrack
                 break
         else:  # label is shrinking
             if br.height() > cr.height() or br.width() > cr.width():
                 fs -= 1
             else:
                 break
         if fs < 1: break
     #--- update font size ---
     self.setFont(f)
예제 #3
0
    def resizeEvent(self, event):
        super().resizeEvent(event)
        f = self.font()
        cr = self.contentsRect()

        dw = event.size().width() - event.oldSize().width()  # width change
        dh = event.size().height() - event.oldSize().height()  # height change
        fs = max(f.pixelSize(), 1)
        while True:
            f.setPixelSize(fs)
            text = self.questionAnswerStr()
            br = QFontMetrics(f).boundingRect(text)  # question and answer string
            if dw >= 0 and dh >= 0:
                if br.height() <= cr.height() and br.width() <= cr.width():
                    fs += 1
                else:
                    f.setPixelSize(max(fs - 1, 1))  # backtrack
                    break
            else:
                if br.height() > cr.height() or br.width() > cr.width():
                    fs -= 1
                else:
                    break

            if fs < 1:
                break
        self.setFont(f)
예제 #4
0
 def __adjustLabelPos(self):
     """ 根据专辑名是否换行来调整标签位置 """
     maxWidth = self.width() - 40 - 385
     # 设置专辑名歌手名标签的长度
     fontMetrics = QFontMetrics(QFont('Microsoft YaHei', 24, 63))
     albumLabelWidth = sum([fontMetrics.width(i) for i in self.albumName])
     self.albumNameLabel.setFixedWidth(min(maxWidth, albumLabelWidth))
     newAlbumName_list = list(self.albumName)  # type:list
     totalWidth = 0
     isWrap = False
     for i in range(len(self.albumName)):
         totalWidth += fontMetrics.width(self.albumName[i])
         if totalWidth > maxWidth:
             newAlbumName_list.insert(i, '\n')
             isWrap = True
             break
     if isWrap:
         index = newAlbumName_list.index('\n')
         # 再次根据换行后的长度决定是否使用省略号
         newAlbumName = ''.join(newAlbumName_list)
         secondLineText = fontMetrics.elidedText(newAlbumName[index + 1:],
                                                 Qt.ElideRight, maxWidth)
         newAlbumName = newAlbumName[:index + 1] + secondLineText
         self.albumNameLabel.setText(newAlbumName)
         self.albumNameLabel.setFixedSize(maxWidth, 110)
         self.songerNameLabel.move(self.albumNameLabel.x(), 155)
         self.yearTconLabel.move(self.albumNameLabel.x(), 177)
     else:
         self.albumNameLabel.setText(self.albumName)
         self.albumNameLabel.setFixedSize(totalWidth, 54)
         self.songerNameLabel.move(self.albumNameLabel.x(), 93)
         self.yearTconLabel.move(self.albumNameLabel.x(), 115)
예제 #5
0
 def adjustText(self):
     """ 根据文本长度决定是否插入换行符 """
     maxWidth = self.width() - 232
     # 设置专辑名歌手名标签的长度
     fontMetrics = QFontMetrics(QFont('Microsoft YaHei', 13))
     songerAlbumWidth = sum([fontMetrics.width(i)
                             for i in self.songerAlbumLabel.text()])
     self.songerAlbumLabel.setFixedWidth(min(maxWidth, songerAlbumWidth))
     # 调整专辑名标签
     fontMetrics = QFontMetrics(QFont('Microsoft YaHei', 21, 75))
     newSongName_list = list(self.songName)  # type:list
     totalWidth = 0
     isWrap = False
     for i in range(len(self.songName)):
         totalWidth += fontMetrics.width(self.songName[i])
         if totalWidth > maxWidth:
             newSongName_list.insert(i, '\n')
             isWrap = True
             break
     if isWrap:
         self.songNameLabel.setText(''.join(newSongName_list))
         self.songNameLabel.move(186, 6)
         self.songerAlbumLabel.move(186, 101)
         self.songNameLabel.setFixedSize(maxWidth, 83)
     else:
         self.songNameLabel.move(186, 26)
         self.songerAlbumLabel.move(186, 82)
         self.songNameLabel.setFixedSize(totalWidth, 46)
         self.songNameLabel.setText(self.songName)
예제 #6
0
파일: GridScene.py 프로젝트: jopohl/urh
    def draw_frequency_marker(self, x_pos, frequency):
        if frequency is None:
            self.clear_frequency_marker()
            return

        y1 = self.sceneRect().y()
        y2 = self.sceneRect().y() + self.sceneRect().height()

        if self.frequency_marker is None:
            pen = QPen(constants.LINECOLOR, 0)
            self.frequency_marker = [None, None]
            self.frequency_marker[0] = self.addLine(x_pos, y1, x_pos, y2, pen)
            self.frequency_marker[1] = self.addSimpleText("")
            self.frequency_marker[1].setBrush(QBrush(constants.LINECOLOR))
            font = QFont()
            font.setBold(True)
            font.setPointSize(int(font.pointSize() * 1.25)+1)
            self.frequency_marker[1].setFont(font)

        self.frequency_marker[0].setLine(x_pos, y1, x_pos, y2)
        scale_x, scale_y = self.__calc_x_y_scale(self.sceneRect())
        self.frequency_marker[1].setTransform(QTransform.fromScale(scale_x, scale_y), False)
        self.frequency_marker[1].setText("Tune to " + Formatter.big_value_with_suffix(frequency, decimals=3))
        font_metric = QFontMetrics(self.frequency_marker[1].font())
        text_width = font_metric.width("Tune to") * scale_x
        text_width += (font_metric.width(" ") * scale_x) / 2
        self.frequency_marker[1].setPos(x_pos-text_width, 0.95*y1)
예제 #7
0
    def draw_frequency_marker(self, x_pos, frequency):
        if frequency is None:
            self.clear_frequency_marker()
            return

        y1 = self.sceneRect().y()
        y2 = self.sceneRect().y() + self.sceneRect().height()

        if self.frequency_marker is None:
            pen = QPen(constants.LINECOLOR, 0)
            self.frequency_marker = [None, None]
            self.frequency_marker[0] = self.addLine(x_pos, y1, x_pos, y2, pen)
            self.frequency_marker[1] = self.addSimpleText("")
            self.frequency_marker[1].setBrush(QBrush(constants.LINECOLOR))
            font = QFont()
            font.setBold(True)
            font.setPointSize(int(font.pointSize() * 1.25)+1)
            self.frequency_marker[1].setFont(font)

        self.frequency_marker[0].setLine(x_pos, y1, x_pos, y2)
        scale_x, scale_y = util.calc_x_y_scale(self.sceneRect(), self.parent())
        self.frequency_marker[1].setTransform(QTransform.fromScale(scale_x, scale_y), False)
        self.frequency_marker[1].setText("Tune to " + Formatter.big_value_with_suffix(frequency, decimals=3))
        font_metric = QFontMetrics(self.frequency_marker[1].font())
        text_width = font_metric.width("Tune to") * scale_x
        text_width += (font_metric.width(" ") * scale_x) / 2
        self.frequency_marker[1].setPos(x_pos-text_width, 0.95*y1)
예제 #8
0
    def paintEvent(self, event):
        sineTable = (
            0,
            38,
            71,
            92,
            100,
            92,
            71,
            38,
            0,
            -38,
            -71,
            -92,
            -100,
            -92,
            -71,
            -38,
        )

        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.width(self.text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QColor()

        painter = QPainter(self)

        for i, ch in enumerate(self.text):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            painter.drawText(x,
                             y - ((sineTable[index] * metrics.height()) / 400),
                             ch)
            x += metrics.width(ch)
예제 #9
0
 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)
예제 #10
0
 def __adjustLabel(self):
     """ 根据当前窗口的宽度设置标签文本和位置 """
     fontMetrics = QFontMetrics(QFont("Microsoft YaHei", 12, 75))
     # 字符串的最大宽度
     maxWidth = self.width() - 30
     songNameWidth, songerNameWidth = 0, 0
     # 调整歌名
     for index, char in enumerate(self.songName):
         if songNameWidth + fontMetrics.width(char) > maxWidth:
             self.songNameLabel.setText(self.songName[:index])
             break
         songNameWidth += fontMetrics.width(char)
     self.songNameLabel.setFixedWidth(songNameWidth)
     # 调整歌手名
     fontMetrics = QFontMetrics(QFont("Microsoft YaHei", 11))
     for index, char in enumerate(self.songerName):
         if songerNameWidth + fontMetrics.width(char) > maxWidth:
             self.songerNameLabel.setText(self.songerName[:index])
             break
         songerNameWidth += fontMetrics.width(char)
     self.songerNameLabel.setFixedWidth(songerNameWidth)
     # 调整标签位置
     self.songNameLabel.move(int(self.width() / 2 - songNameWidth / 2), 0)
     self.songerNameLabel.move(int(self.width() / 2 - songerNameWidth / 2),
                               30)
예제 #11
0
    def redraw_legend(self, force_show=False):
        if not (force_show or self.always_show_symbols_legend):
            self.hide_legend()
            return

        num_captions = len(self.centers) + 1
        if num_captions != len(self.captions):
            self.clear_legend()

            fmt = "{0:0" + str(self.bits_per_symbol) + "b}"
            for i in range(num_captions):
                font = QFont()
                font.setPointSize(16)
                font.setBold(True)
                self.captions.append(self.addSimpleText(fmt.format(i), font))

        view_rect = self.parent().view_rect()  # type: QRectF
        padding = 0
        fm = QFontMetrics(self.captions[0].font())

        for i, caption in enumerate(self.captions):
            caption.show()
            scale_x, scale_y = util.calc_x_y_scale(self.separation_areas[i].rect(), self.parent())
            try:
                caption.setPos(view_rect.x() + view_rect.width() - fm.width(caption.text()) * scale_x,
                               self.centers[i] + padding)
            except IndexError:
                caption.setPos(view_rect.x() + view_rect.width() - fm.width(caption.text()) * scale_x,
                               self.centers[i - 1] - padding - fm.height() * scale_y)

            caption.setTransform(QTransform.fromScale(scale_x, scale_y), False)
예제 #12
0
    def text(self, text: str, pos: QRectF, color: QColor=None, size: int=20, shaded: int=0,
             bold: bool=False,shrinkToFit=10) -> None:
        if not isinstance(text,str):
            text = "{}".format(text)

        self._font.setPointSize(size)
        if bold:
            self._font.setWeight(QFont.Black)
        else:
            self._font.setWeight(QFont.Bold)
        self._painter.setFont(self._font)

        fm = QFontMetrics(self._font)
        if pos.width() == 0:
            pos.setWidth(fm.width(text))
        if pos.height() == 0:
            pos.setHeight(fm.height())

        if size > shrinkToFit:
            #
            if fm.width(text) > pos.width() or fm.height() > pos.height()+2:
                self.text(text,pos,color,size-1,shaded,bold,shrinkToFit)
                return

        if shaded:
            diff = size//4 if isinstance(shaded,bool) and shaded == True else shaded
            self._painter.setPen(self._fgs)
            pos2 = pos.translated(diff, diff)
            self._painter.drawText(pos2, Qt.AlignCenter, text)
        p = QPen(color if color is not None else self._fg)
        self._painter.setPen(p)
        self._painter.drawText(pos, Qt.AlignCenter, text)
예제 #13
0
 def __calculateHeaderSizes(self):
     """
     Private method to calculate the section sizes of the horizontal header.
     """
     fm = QFontMetrics(QFont())
     for section in range(self.__passwordModel.columnCount()):
         header = self.passwordsTable.horizontalHeader().sectionSizeHint(
             section)
         if section == 0:
             try:
                 header = fm.horizontalAdvance("averagebiglongsitename")
             except AttributeError:
                 header = fm.width("averagebiglongsitename")
         elif section == 1:
             try:
                 header = fm.horizontalAdvance("averagelongusername")
             except AttributeError:
                 header = fm.width("averagelongusername")
         elif section == 2:
             try:
                 header = fm.horizontalAdvance("averagelongpassword")
             except AttributeError:
                 header = fm.width("averagelongpassword")
         try:
             buffer = fm.horizontalAdvance("mm")
         except AttributeError:
             buffer = fm.width("mm")
         header += buffer
         self.passwordsTable.horizontalHeader().resizeSection(
             section, header)
     self.passwordsTable.horizontalHeader().setStretchLastSection(True)
예제 #14
0
 def __init__(self):
     super(PapersModel, self).__init__()
     metric = QFontMetrics(QFont())
     # TODO Could probably be done better
     self.yearWidth = metric.width("8888") + 10
     self.PDFwidth = metric.width("Open PDF") + 33
     self.docs = []
예제 #15
0
 def shorten_filename(self, name, width):
     """根据给定的宽度截断文件名并添加...,返回截断后的文件名。"""
     metrics = QFontMetrics(self.font())
     if metrics.width(name) > width - self.reso_width / 128:
         for i in range(4, len(name)):  # 从第4个字符开始计算长度
             if metrics.width(name[:i]) > width - self.reso_width / 128:
                 return name[:i] + '...'
     return name
예제 #16
0
    def get_text_width(self):
        sizer = QFontMetrics(self.m_portgrp_font)

        if self.m_name_truncked:
            return (sizer.width(self.m_print_name) +
                    sizer.width(self.m_trunck_sep) +
                    sizer.width(self.m_print_name_right))

        return sizer.width(self.m_print_name)
예제 #17
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     painter.setRenderHint(QPainter.Antialiasing)
     # Get coordinates for the window
     size_window = self.size()
     xcenter = size_window.width() // 2
     ycenter = size_window.height() // 2
     font = painter.font()
     metrics = QFontMetrics(font)
     font_height = metrics.capHeight()
     width_n = metrics.width("N")
     width_s = metrics.width("S")
     width_w = metrics.width("W")
     width_e = metrics.width("E")
     extent = min(size_window.width() - width_w - width_e, size_window.height() - 2 * font_height)
     # Draw labels
     painter.drawText(xcenter - width_n // 2, ycenter - extent // 2, "N")
     painter.drawText(xcenter - width_s // 2, ycenter + extent // 2 + font_height, "S")
     painter.drawText(xcenter - extent // 2 - width_w + 2, ycenter + font_height // 2, "W")
     painter.drawText(xcenter + extent // 2, ycenter + font_height // 2, "E")
     # Draw coordinate system
     diameter = extent - 8
     radius = diameter // 2
     painter.drawEllipse(xcenter - radius, ycenter - radius, diameter, diameter)
     diameter23 = diameter * 2 // 3
     radius23 = diameter23 // 2
     painter.drawEllipse(xcenter - radius23, ycenter - radius23, diameter23, diameter23)
     diameter13 = diameter // 3
     radius13 = diameter13 // 2
     painter.drawEllipse(xcenter - radius13, ycenter - radius13, diameter13, diameter13)
     # Draw satellites
     brushGps = QBrush(self.get_color("blue"))
     brushGlonass = QBrush(self.get_color("red"))
     brushBeidou = QBrush(self.get_color("orange"))
     brushGalileo = QBrush(self.get_color("green"))
     sat_radius = 7
     for sat in self.satellites_tracked:
         # Make radius linear in elevation
         if sat.sv_number in self.satellites_used:
             r = radius * (180 - 2 * sat.elevation) // 180
             if r < 0:
                 r = 0
             x = xcenter + int(r * math.sin(sat.azimuth * math.pi / 180.0))
             y = ycenter - int(r * math.cos(sat.azimuth * math.pi / 180.0))
             if 1*64 <= sat.sv_number < 2*64:
                 brush = brushGlonass
             elif 2*64 <= sat.sv_number < 3*64:
                 brush = brushBeidou
             elif 3*64 <= sat.sv_number < 4*64:
                 brush = brushGalileo
             else:
                 brush = brushGps
             painter.setBrush(brush)
             painter.drawEllipse(x - sat_radius // 2, y - sat_radius // 2, sat_radius, sat_radius)
     painter.end()
예제 #18
0
    def makeShort(self):
        self.short = self.long
        metrics = QFontMetrics(self.font())
        width = metrics.width(self.short)

        if width >= self.width():
            while width >= self.width():
                self.short = self.short[:-1]
                width = metrics.width(self.short + '...')

            self.short = self.short + '...'
예제 #19
0
    def __init__(self, cookieJar, parent=None):
        """
        Constructor
        
        @param cookieJar reference to the cookie jar (CookieJar)
        @param parent reference to the parent widget (QWidget)
        """
        super(CookiesExceptionsDialog, self).__init__(parent)
        self.setupUi(self)

        self.__cookieJar = cookieJar

        self.removeButton.clicked.connect(self.exceptionsTable.removeSelected)
        self.removeAllButton.clicked.connect(self.exceptionsTable.removeAll)

        self.exceptionsTable.verticalHeader().hide()
        self.__exceptionsModel = CookieExceptionsModel(cookieJar)
        self.__proxyModel = QSortFilterProxyModel(self)
        self.__proxyModel.setSourceModel(self.__exceptionsModel)
        self.searchEdit.textChanged.connect(
            self.__proxyModel.setFilterFixedString)
        self.exceptionsTable.setModel(self.__proxyModel)

        self.domainEdit.setCompleter(
            QCompleter(cookieJar.cookieDomains(), self.domainEdit))

        f = QFont()
        f.setPointSize(10)
        fm = QFontMetrics(f)
        height = fm.height() + fm.height() // 3
        self.exceptionsTable.verticalHeader().setDefaultSectionSize(height)
        self.exceptionsTable.verticalHeader().setMinimumSectionSize(-1)
        for section in range(self.__exceptionsModel.columnCount()):
            header = self.exceptionsTable.horizontalHeader().sectionSizeHint(
                section)
            if section == 0:
                try:
                    header = fm.horizontalAdvance(
                        "averagebiglonghost.averagedomain.info")
                except AttributeError:
                    header = fm.width("averagebiglonghost.averagedomain.info")
            elif section == 1:
                try:
                    header = fm.horizontalAdvance(self.tr("Allow For Session"))
                except AttributeError:
                    header = fm.width(self.tr("Allow For Session"))
            try:
                buffer = fm.horizontalAdvance("mm")
            except AttributeError:
                buffer = fm.width("mm")
            header += buffer
            self.exceptionsTable.horizontalHeader().resizeSection(
                section, header)
예제 #20
0
 def __init__(self, cookieJar, parent=None):
     """
     Constructor
     
     @param cookieJar reference to the cookie jar (CookieJar)
     @param parent reference to the parent widget (QWidget)
     """
     super(CookiesDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.addButton.setEnabled(False)
     
     self.__cookieJar = cookieJar
     
     self.removeButton.clicked.connect(self.cookiesTable.removeSelected)
     self.removeAllButton.clicked.connect(self.cookiesTable.removeAll)
     
     self.cookiesTable.verticalHeader().hide()
     model = CookieModel(cookieJar, self)
     self.__proxyModel = QSortFilterProxyModel(self)
     self.__proxyModel.setSourceModel(model)
     self.searchEdit.textChanged.connect(
         self.__proxyModel.setFilterFixedString)
     self.cookiesTable.setModel(self.__proxyModel)
     self.cookiesTable.doubleClicked.connect(self.__showCookieDetails)
     self.cookiesTable.selectionModel().selectionChanged.connect(
         self.__tableSelectionChanged)
     self.cookiesTable.model().modelReset.connect(self.__tableModelReset)
     
     fm = QFontMetrics(QFont())
     height = fm.height() + fm.height() // 3
     self.cookiesTable.verticalHeader().setDefaultSectionSize(height)
     self.cookiesTable.verticalHeader().setMinimumSectionSize(-1)
     for section in range(model.columnCount()):
         header = self.cookiesTable.horizontalHeader()\
             .sectionSizeHint(section)
         if section == 0:
             header = fm.width("averagebiglonghost.averagedomain.info")
         elif section == 1:
             header = fm.width("_session_id")
         elif section == 4:
             header = fm.width(
                 QDateTime.currentDateTime().toString(Qt.LocalDate))
         buffer = fm.width("mm")
         header += buffer
         self.cookiesTable.horizontalHeader().resizeSection(section, header)
     self.cookiesTable.horizontalHeader().setStretchLastSection(True)
     self.cookiesTable.model().sort(
         self.cookiesTable.horizontalHeader().sortIndicatorSection(),
         Qt.AscendingOrder)
     
     self.__detailsDialog = None
예제 #21
0
 def __init__(self, cookieJar, parent=None):
     """
     Constructor
     
     @param cookieJar reference to the cookie jar (CookieJar)
     @param parent reference to the parent widget (QWidget)
     """
     super(CookiesDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.addButton.setEnabled(False)
     
     self.__cookieJar = cookieJar
     
     self.removeButton.clicked.connect(self.cookiesTable.removeSelected)
     self.removeAllButton.clicked.connect(self.cookiesTable.removeAll)
     
     self.cookiesTable.verticalHeader().hide()
     model = CookieModel(cookieJar, self)
     self.__proxyModel = QSortFilterProxyModel(self)
     self.__proxyModel.setSourceModel(model)
     self.searchEdit.textChanged.connect(
         self.__proxyModel.setFilterFixedString)
     self.cookiesTable.setModel(self.__proxyModel)
     self.cookiesTable.doubleClicked.connect(self.__showCookieDetails)
     self.cookiesTable.selectionModel().selectionChanged.connect(
         self.__tableSelectionChanged)
     self.cookiesTable.model().modelReset.connect(self.__tableModelReset)
     
     fm = QFontMetrics(QFont())
     height = fm.height() + fm.height() // 3
     self.cookiesTable.verticalHeader().setDefaultSectionSize(height)
     self.cookiesTable.verticalHeader().setMinimumSectionSize(-1)
     for section in range(model.columnCount()):
         header = self.cookiesTable.horizontalHeader()\
             .sectionSizeHint(section)
         if section == 0:
             header = fm.width("averagebiglonghost.averagedomain.info")
         elif section == 1:
             header = fm.width("_session_id")
         elif section == 4:
             header = fm.width(
                 QDateTime.currentDateTime().toString(Qt.LocalDate))
         buffer = fm.width("mm")
         header += buffer
         self.cookiesTable.horizontalHeader().resizeSection(section, header)
     self.cookiesTable.horizontalHeader().setStretchLastSection(True)
     self.cookiesTable.model().sort(
         self.cookiesTable.horizontalHeader().sortIndicatorSection(),
         Qt.AscendingOrder)
     
     self.__detailsDialog = None
예제 #22
0
파일: dockwidget.py 프로젝트: dglent/enki
    def sizeHint(self):
        """QToolBar.sizeHint implementation
        """
        wis = self.iconSize()
        size = QToolBar.sizeHint(self)
        fm = QFontMetrics(self.font())

        if self._dock.features() & QDockWidget.DockWidgetVerticalTitleBar:
            size.setHeight(size.height() + fm.width(self._dock.windowTitle()) + wis.width())
        else:
            size.setWidth(size.width() + fm.width(self._dock.windowTitle()) + wis.width())

        return size
예제 #23
0
파일: dockwidget.py 프로젝트: gpa14/enki
    def sizeHint(self):
        """QToolBar.sizeHint implementation
        """
        wis = self.iconSize()
        size = QToolBar.sizeHint(self)
        fm = QFontMetrics(self.font())

        if self._dock.features() & QDockWidget.DockWidgetVerticalTitleBar:
            size.setHeight(size.height() + fm.width(self._dock.windowTitle()) + wis.width())
        else:
            size.setWidth(size.width() + fm.width(self._dock.windowTitle()) + wis.width())

        return size
예제 #24
0
 def getTextWidth(self):
     """ 计算文本的总宽度 """
     songFontMetrics = QFontMetrics(QFont('Microsoft YaHei', 14))
     self.songNameWidth = sum(
         [songFontMetrics.width(i) for i in self.songName])
     # 检测歌手名是否全是英文
     self.isMatch = re.match(r'^[a-zA-Z]+$', self.songerName)
     if not self.isMatch:
         songerFontMetrics = QFontMetrics(QFont('Microsoft YaHei', 12, 75))
     else:
         songerFontMetrics = QFontMetrics(QFont('Microsoft YaHei', 11, 75))
     # 总是会少一个字符的长度
     self.songerNameWidth = sum(
         [songerFontMetrics.width(i) for i in self.songerName])
예제 #25
0
 def __adjustLabelText(self):
     """ 调整歌手名和年份流派标签长度和文本 """
     maxWidth = self.width() - 40 - 294
     fontMetrics = QFontMetrics(QFont('Microsoft YaHei', 9))
     songerWidth = fontMetrics.width(self.songerName)
     yearTconWidth = fontMetrics.width(self.yearTconLabel.text())
     self.songerNameLabel.setFixedWidth(min(maxWidth, songerWidth))
     self.yearTconLabel.setFixedWidth(min(maxWidth, yearTconWidth))
     # 加省略号
     self.songerNameLabel.setText(
         fontMetrics.elidedText(self.songerName, Qt.ElideRight, maxWidth))
     self.yearTconLabel.setText(
         fontMetrics.elidedText(self.yearTconLabel.text(), Qt.ElideRight,
                                maxWidth))
예제 #26
0
class Danmu(QLabel):
    def __init__(self,
                 parent,
                 dmtext,
                 dmcolor,
                 dmstartx,
                 dmstarty,
                 dmfont="Microsoft YaHei"):
        super(Danmu, self).__init__(parent)
        self.dmQfont = QFont(dmfont, 25, 75)  #字体、大小、粗细
        self.setStyleSheet("color:" + dmcolor)
        self.dmtext = dmtext
        self.setText(self.dmtext)
        self.metrics = QFontMetrics(self.dmQfont)
        self.height = self.metrics.height() + 5
        self.setFixedHeight(self.height)
        self.width = self.metrics.width(dmtext) + 4
        self.setFixedWidth(self.width)
        self.setFont(self.dmQfont)

        self.fly = QPropertyAnimation(self, b'pos')  #弹幕飞行动画
        self.fly.setDuration(10000)  #飞行10秒
        self.fly.setStartValue(QtCore.QPoint(dmstartx, dmstarty))
        self.fly.setEndValue(QtCore.QPoint(0 - self.width, dmstarty))
        self.fly.start()
        self.fly.finished.connect(self.deleteLater)

    #为文字添加描边
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.save()
        path = QPainterPath()
        pen = QPen(QColor(0, 0, 0, 230))
        painter.setRenderHint(QPainter.Antialiasing)  #反走样
        pen.setWidth(4)
        length = self.metrics.width(self.dmtext)
        w = self.width
        px = (length - w) / 2
        if px < 0:
            px = -px
        py = (self.height - self.metrics.height()) / 2 + self.metrics.ascent()
        if py < 0:
            py = -py
        path.addText(px - 2, py, self.dmQfont, self.dmtext)
        painter.strokePath(path, pen)
        painter.drawPath(path)
        painter.fillPath(path, QBrush(QColor(255, 255, 255)))
        painter.restore()
        QLabel.paintEvent(self, event)
예제 #27
0
    def build_bonus_fields(self):
        for bonus_field in self._bonus_fields:
            brush = bonus_field["Brush"]
            pen = bonus_field["Pen"]
            bonus_fields = []

            for coords in bonus_field["Coords"]:
                label = bonus_field["Name"]
                if coords == Coords.central():
                    label = '✸'
                square = self._board_squares[coords]
                square.setZValue(2)
                bonus_fields.append(square)
                field_name = QGraphicsSimpleTextItem(label)
                font = field_name.font()
                font.setPointSize(10)
                if coords == Coords.central():
                    font.setPointSize(20)
                fm = QFontMetrics(font)
                field_name.setZValue(2.1)
                field_name.setFont(font)
                x = coords.x * SQUARE_SIZE + (SQUARE_SIZE - fm.width(label)) / 2
                y = coords.y * SQUARE_SIZE + (SQUARE_SIZE - fm.height()) / 2
                field_name.setPos(x, y)
                field_name.setBrush(bonus_field["Label brush"])

                self._labels[(x, y)] = field_name
                self.scene.addItem(field_name)

            paint_graphic_items(bonus_fields, pen, brush)
예제 #28
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent reference to the parent widget (QWidget)
     """
     super(WebDatabasesDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.removeButton.clicked.connect(self.databasesTree.removeSelected)
     self.removeAllButton.clicked.connect(self.databasesTree.removeAll)
     
     model = WebDatabasesModel(self)
     self.__proxyModel = E5TreeSortFilterProxyModel(self)
     self.__proxyModel.setFilterKeyColumn(-1)
     self.__proxyModel.setSourceModel(model)
     
     self.searchEdit.textChanged.connect(
         self.__proxyModel.setFilterFixedString)
     
     self.databasesTree.setModel(self.__proxyModel)
     fm = QFontMetrics(self.font())
     header = fm.width("m") * 30
     self.databasesTree.header().resizeSection(0, header)
     self.databasesTree.model().sort(
         self.databasesTree.header().sortIndicatorSection(),
         Qt.AscendingOrder)
     self.databasesTree.expandAll()
예제 #29
0
파일: generaltab.py 프로젝트: nomns/Parse99
    def __init__(self, settings):
        super(QWidget, self).__init__()
        self._layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.setLayout(self._layout)
        self.settings = settings

        # eq directory
        widget = QWidget()
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        widget.setLayout(layout)
        label = QLabel("Everquest Directory: ")
        layout.addWidget(label)
        text = QLineEdit()
        text.setText(self.settings.get_value("general", "eq_directory"))
        text.setToolTip(self.settings.get_value("general", "eq_directory"))
        text.setDisabled(True)
        self._text_eq_directory = text
        layout.addWidget(text, 1)
        button = QPushButton("Browse...")
        button.clicked.connect(self._get_eq_directory)
        layout.addWidget(button)
        self._layout.addWidget(widget, 0, Qt.AlignTop)

        # eq directory info
        frame = QFrame()
        frame.setFrameShadow(QFrame.Sunken)
        frame.setFrameShape(QFrame.Box)
        frame_layout = QBoxLayout(QBoxLayout.LeftToRight)
        frame.setLayout(frame_layout)
        widget = QWidget()
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        widget.setLayout(layout)
        self._label_eq_directory = QLabel()
        layout.addWidget(self._label_eq_directory, 1)
        frame_layout.addWidget(widget, 1, Qt.AlignCenter)
        self._layout.addWidget(frame, 1)

        # parse interval
        widget = QWidget()
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        widget.setLayout(layout)
        label = QLabel("Seconds between parse checks: ")
        layout.addWidget(label, 0, Qt.AlignLeft)
        text = QLineEdit()
        text.setText(str(self.settings.get_value("general", "parse_interval")))
        text.editingFinished.connect(self._parse_interval_editing_finished)
        text.setMaxLength(3)
        self._text_parse_interval = text
        metrics = QFontMetrics(QApplication.font())
        text.setFixedWidth(metrics.width("888888"))
        layout.addWidget(text, 0, Qt.AlignLeft)
        self._layout.addWidget(widget, 0, Qt.AlignTop | Qt.AlignLeft)

        # spacing at bottom of window
        widget = QWidget()
        self._layout.addWidget(widget, 1)

        # setup
        if settings.get_value("general", "eq_directory") is not None:
            self._check_directory_stats()
예제 #30
0
파일: window.py 프로젝트: zisecheng/retext
	def createTab(self, fileName):
		self.previewBlocked = False
		self.editBoxes.append(ReTextEdit(self))
		self.highlighters.append(ReTextHighlighter(self.editBoxes[-1].document()))
		if enchant_available and self.actionEnableSC.isChecked():
			self.highlighters[-1].dictionary = \
			enchant.Dict(self.sl) if self.sl else enchant.Dict()
			self.highlighters[-1].rehighlight()
		if globalSettings.useWebKit:
			self.previewBoxes.append(self.getWebView())
		else:
			self.previewBoxes.append(QTextBrowser())
			self.previewBoxes[-1].setOpenExternalLinks(True)
		self.previewBoxes[-1].setVisible(False)
		self.fileNames.append(fileName)
		markupClass = self.getMarkupClass(fileName)
		self.markups.append(self.getMarkup(fileName))
		self.highlighters[-1].docType = (markupClass.name if markupClass else '')
		liveMode = globalSettings.restorePreviewState and globalSettings.previewState
		self.actionPreviewChecked.append(liveMode)
		self.actionLivePreviewChecked.append(liveMode)
		metrics = QFontMetrics(self.editBoxes[-1].font())
		self.editBoxes[-1].setTabStopWidth(globalSettings.tabWidth * metrics.width(' '))
		self.editBoxes[-1].textChanged.connect(self.updateLivePreviewBox)
		self.editBoxes[-1].undoAvailable.connect(self.actionUndo.setEnabled)
		self.editBoxes[-1].redoAvailable.connect(self.actionRedo.setEnabled)
		self.editBoxes[-1].copyAvailable.connect(self.enableCopy)
		self.editBoxes[-1].document().modificationChanged.connect(self.modificationChanged)
		if globalSettings.useFakeVim:
			self.installFakeVimHandler(self.editBoxes[-1])
		return self.getSplitter(-1)
예제 #31
0
    def paint_real_time_tips(self, qp: QPainter):
        if not self.__enable_real_time_tips or self.__l_pressing:
            return

        qp.drawLine(0, self.__mouse_on_coordinate.y(), self.__width,
                    self.__mouse_on_coordinate.y())
        qp.drawLine(self.__mouse_on_coordinate.x(), 0,
                    self.__mouse_on_coordinate.x(), self.__height)

        tip_text = self.format_real_time_tip()

        fm = QFontMetrics(self.__tip_font)
        text_width = fm.width(tip_text)
        text_height = fm.height()
        tip_area = QRect(self.__mouse_on_coordinate,
                         QSize(text_width, text_height))

        tip_area.setTop(tip_area.top() - fm.height())
        tip_area.setBottom(tip_area.bottom() - fm.height())
        if tip_area.right() > self.__axis_width:
            tip_area.setLeft(tip_area.left() - text_width)
            tip_area.setRight(tip_area.right() - text_width)

        qp.setFont(self.__tip_font)
        qp.setBrush(QColor(36, 169, 225))

        qp.drawRect(tip_area)
        qp.drawText(tip_area, Qt.AlignLeft, tip_text)
예제 #32
0
    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)
예제 #33
0
    def paint(self,
              painter: QPainter,
              option: 'QStyleOptionGraphicsItem',
              widget: Optional[QWidget] = ...) -> None:
        # painting circle
        if self.node.isInvalid():
            painter.setBrush(self._invalid_brush)
            text = '!'
        elif self.node.isDirty():
            painter.setBrush(self._dirty_brush)
            text = '?'
        else:
            painter.setBrush(self._valid_brush)
            text = "\N{CHECK MARK}"

        painter.setPen(self._pen if not self._hovered else self._pen_hovered)
        painter.drawEllipse(-self.radius, -self.radius, 2 * self.radius,
                            2 * self.radius)

        # Text in the status
        painter.setPen(self._pen_text)
        font = QFont('Ubuntu', self.radius * 2 - 6)
        fm = QFontMetrics(font)
        painter.setFont(font)
        painter.drawText(-fm.width(text) / 2, fm.height() / 2 - 4, text)
예제 #34
0
    def draw_indicator(indicator: int):
        pixmap = QPixmap(24, 24)

        painter = QPainter(pixmap)
        w, h = pixmap.width(), pixmap.height()

        painter.fillRect(0, 0, w, h, QBrush((QColor(0, 0, 200, 255))))

        pen = QPen(QColor("white"))
        pen.setWidth(2)
        painter.setPen(pen)

        font = util.get_monospace_font()
        font.setBold(True)
        font.setPixelSize(16)
        painter.setFont(font)

        f = QFontMetrics(painter.font())
        indicator_str = str(indicator) if indicator < 10 else "+"

        fw = f.width(indicator_str)
        fh = f.height()
        painter.drawText(math.ceil(w / 2 - fw / 2), math.ceil(h / 2 + fh / 4), indicator_str)

        painter.end()
        return QIcon(pixmap)
예제 #35
0
    def addPort(self, name, isOutput = False, flags = 0, ptr = None):
        port = QNEPort(self)
        port.setName(name)
        port.setIsOutput(isOutput)
        port.setNEBlock(self)
        port.setPortFlags(flags)
        port.setPtr(ptr)

        fontmetrics = QFontMetrics(self.scene().font());
        width = fontmetrics.width(name)
        height = fontmetrics.height()
        if width > self.width - self.horzMargin:
            self.width = width + self.horzMargin
        self.height += height

        path = QPainterPath()
        path.addRoundedRect(-self.width/2, -self.height/2, self.width, self.height, 5, 5)
        self.setPath(path)

        y = -self.height / 2 + self.vertMargin + port.radius()
        for port_ in self.childItems():
            if port_.type() != QNEPort.Type:
                continue

            if port_.isOutput():
                port_.setPos(self.width/2 + port.radius(), y)
            else:
                port_.setPos(-self.width/2 - port.radius(), y)
            y += height;

        return port
예제 #36
0
    def lock(self):
        """
        Sets the default properties for the Python lexer.
        """
        # Lexer Initialization
        lexer = QsciLexerPython(self.ui.code_editor)
        lexer.setDefaultFont(self.font)
        self.ui.code_editor.setLexer(lexer)

        # Auto Completion
        api = QsciAPIs(lexer)
        for var in dir(builtins):
            if not (var[0] == "_"):
                api.add(var)
        api.prepare()

        self.ui.code_editor.setAutoCompletionThreshold(1)
        self.ui.code_editor.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        # Auto Indentation
        self.ui.code_editor.setAutoIndent(True)
        self.ui.code_editor.setIndentationGuides(True)
        self.ui.code_editor.setIndentationsUseTabs(True)
        self.ui.code_editor.setIndentationWidth(4)

        # Font Settings
        font_metrics = QFontMetrics(self.font)
        self.ui.code_editor.setMinimumSize(int(font_metrics.width("0" * 80)),
                                           0)
예제 #37
0
    def paintEvent(self, event):
        sineTable = (0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38)

        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.width(self.text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QColor()

        painter = QPainter(self)

        for i, ch in enumerate(self.text):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), ch)
            x += metrics.width(ch)
예제 #38
0
def formatString(self, string, x, y):
    font = QFont('Microsoft YaHei', 18)
    #font.setPixelSize(22)
    self.dialog.setFont(font)
    self.dialog.setStyleSheet(
        "QLabel{border-radius:15;padding:15px;background: rgb(0,128,255);color:white;width:auto;height:auto;word-wrap: break-word}"
    )
    self.dialog.setText(string)
    #字体宽高
    metr = QFontMetrics(self.dialog.font())
    stringWidth = metr.width(self.dialog.text())
    stringHeight = metr.height()
    lineCount = 1
    if stringWidth < 300:
        dialogWidth = stringWidth + 40
        dialogHeight = stringHeight * lineCount + 40
        dialogX = x + 248 / 2 - stringWidth + 60
    else:
        lineCount = math.ceil(stringWidth / 300)
        dialogWidth = 300 + 40
        dialogHeight = stringHeight * lineCount + 40
        dialogX = x + 248 / 2 - 250

    dialogDetail = {
        'dialogX': dialogX,
        'dialogY': y - stringHeight * lineCount + 20,
        'dialogWidth': dialogWidth,
        'dialogHeight': dialogHeight
    }
    return dialogDetail
예제 #39
0
파일: editor.py 프로젝트: YieldNull/cinter
    def __init__(self, parent=None):
        super(CodeEditor, self).__init__(parent)
        self.numArea = LineNumArea(self)

        # Binding signals to slots
        self.blockCountChanged.connect(self.updateNumWidth)
        self.updateRequest.connect(self.updateNum)
        self.cursorPositionChanged.connect(self.highlightLine)
        self.textChanged.connect(self.highlightCode)

        # editor config
        font = QFont()
        font.setFamily("Courier")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(12)
        self.setFont(font)
        metrics = QFontMetrics(font)
        self.setTabStopWidth(4 * metrics.width('a'))  # tab width

        # highlighter
        self.highlighter = Highlighter(self.document())

        # init
        self.updateNumWidth(0)
        self.highlightLine()
예제 #40
0
    def onSet(self):
        #from subprocess import call
        #call("notepad ./Project/Sequences/DefaultSequence.py")

        self.editor = QsciScintilla()

        # define the font to use
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        fm = QFontMetrics(font)

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

        ## Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.editor.setMarginWidth(0, fm.width("00000") + 5)
        self.editor.setMarginLineNumbers(0, True)

        ## Edge Mode shows a red vetical bar at 80 chars
        self.editor.setEdgeMode(QsciScintilla.EdgeLine)
        self.editor.setEdgeColumn(80)
        self.editor.setEdgeColor(QColor("#FF0000"))

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

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

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

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

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

        ## Choose a lexer
        lexer = QsciLexerPython()
        lexer.setDefaultFont(font)
        api = QsciStrictAPIs(lexer)
        api.prepare()
        lexer.setDefaultFont(font)
        self.editor.setLexer(lexer)
        self.editor.setMinimumSize(1024, 768)
        self.editor.show()
        ## Show this file in the editor
        text = open("./Project/Sequences/DefaultSequence.py").read()
        self.editor.setText(text)
예제 #41
0
    def paint(self, painter, option, index):
        extra = index.data(Qt.UserRole + 1)
        if not extra:
            return QStyledItemDelegate.paint(self, painter, option, index)

        else:
            if option.state & QStyle.State_Selected:
                painter.fillRect(option.rect, option.palette.color(QPalette.Inactive, QPalette.Highlight))

            title = index.data()
            extra = " - {}".format(extra)
            painter.drawText(option.rect, Qt.AlignLeft, title)

            fm = QFontMetrics(option.font)
            w = fm.width(title)
            r = QRect(option.rect)
            r.setLeft(r.left() + w)
            painter.save()
            if option.state & QStyle.State_Selected:
                painter.setPen(QColor(S.highlightedTextLight))
            else:
                painter.setPen(QColor(S.textLight))

            painter.drawText(r, Qt.AlignLeft, extra)
            painter.restore()
예제 #42
0
    def get_base_font_size(self):
        """Gets the base font size for all the UI elements.

        Returns:
            int: Base font size.

        """
        self.__logger.info(
            "Calculating appropriated base font size for UI elements...")
        font_fits = False

        # Base font size will be calculated using self.label_password attribute
        font = self.label_password.font()
        font_size = font.pointSize()

        while not font_fits:
            fm = QFontMetrics(font)
            pixels_wide = fm.width(self.label_password.text())
            pixels_high = fm.height()

            bound = fm.boundingRect(0, 0, pixels_wide, pixels_high,
                                    Qt.TextWordWrap | Qt.AlignLeft,
                                    self.label_password.text())

            if bound.width() <= self.label_password.width() and \
                    bound.height() <= self.label_password.height():
                font_fits = True
            else:
                font.setPointSize(font.pointSize() - 1)
                font_size = font_size - 1

        self.__logger.info("Base font size = " + str(font_size))
        return font_size
예제 #43
0
    def __init__(self, name, currentValue):
        super(QDialog, self).__init__()
        self.setWindowTitle(name)
        self.resize(800, 600)
        self.codeEdit = QsciScintilla()
        self.codeEdit.setText(currentValue)
        fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        self.codeEdit.setFont(fixedWidthFont)
        fontmetrics = QFontMetrics(fixedWidthFont)
        self.codeEdit.setMarginWidth(0, fontmetrics.width("000"))
        self.codeEdit.setMarginLineNumbers(0, True)
        self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc"))

        self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        self.codeEdit.setCaretLineVisible(True)
        self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4"))
        lexer = QsciLexerPython()
        lexer.setDefaultFont(fixedWidthFont)
        self.codeEdit.setLexer(lexer)
        self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        self.codeEdit.setUtf8(True)

        self.codeEdit.setTabWidth(4)
        self.codeEdit.setIndentationsUseTabs(True)
        self.codeEdit.setIndentationGuides(True)
        self.codeEdit.setTabIndents(True)
        self.codeEdit.setAutoIndent(True)

        self.cancelButton = QPushButton('Cancel')
        self.cancelButton.clicked.connect(self.cancel)
        self.acceptButton = QPushButton('Accept')
        self.acceptButton.clicked.connect(self.accept)

        self.pythonButton = QRadioButton('Python')
        self.pythonButton.setChecked(True)
        self.pythonButton.clicked.connect(self.pythonClicked)
        self.cppButton = QRadioButton('C++')
        self.cppButton.clicked.connect(self.cppClicked)

        hLayout0 = QHBoxLayout()
        hLayout0.addWidget(self.pythonButton)
        hLayout0.addWidget(self.cppButton)
        container0 = QWidget()
        container0.setLayout(hLayout0)

        verticalLayout = QVBoxLayout()
        verticalLayout.addWidget(container0)
        verticalLayout.addWidget(self.codeEdit)

        container = QWidget()
        hLayout =QHBoxLayout()
        hLayout.addWidget(self.cancelButton)
        hLayout.addWidget(self.acceptButton)
        container.setLayout(hLayout)

        verticalLayout.addWidget(container)
        self.setLayout(verticalLayout)

        self.language = 'python'
예제 #44
0
 def paintEvent(self, ev) -> None:
     if self._text is not None:
         painter = QPainter(self)
         font = painter.font()
         fm = QFontMetrics(font)
         width = fm.width(self._text)
         painter.drawText(self.width() // 2 - width // 2, 14, self._text)
         painter.end()
예제 #45
0
 def __calculateHeaderSizes(self):
     """
     Private method to calculate the section sizes of the horizontal header.
     """
     fm = QFontMetrics(QFont())
     for section in range(self.__zoomValuesModel.columnCount()):
         header = self.zoomValuesTable.horizontalHeader()\
             .sectionSizeHint(section)
         if section == 0:
             header = fm.width("extraveryveryverylongsitename")
         elif section == 1:
             header = fm.width("averagelongzoomvalue")
         buffer = fm.width("mm")
         header += buffer
         self.zoomValuesTable.horizontalHeader()\
             .resizeSection(section, header)
     self.zoomValuesTable.horizontalHeader().setStretchLastSection(True)
예제 #46
0
    def __init__(self, *args, **kwargs):
        if "windowtype" in kwargs:
            self.windowname = kwargs["windowtype"]
            del kwargs["windowtype"]
        else:
            self.windowname = "XML Object"

        super().__init__(*args, **kwargs)

        self.resize(900, 500)
        self.setMinimumSize(QSize(300, 300))

        self.centralwidget = QWidget(self)
        self.setWidget(self.centralwidget)
        self.entity = None

        font = QFont()
        font.setFamily("Consolas")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(10)


        self.dummywidget = QWidget(self)
        self.dummywidget.setMaximumSize(0,0)

        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.addWidget(self.dummywidget)


        self.goto_id_action = ActionWithOwner("Go To ID", self, action_owner=self)

        self.addAction(self.goto_id_action)

        self.goto_shortcut = QKeySequence(Qt.CTRL+Qt.Key_G)


        self.goto_id_action.setShortcut(self.goto_shortcut)
        #self.goto_id_action.setShortcutContext(Qt.WidgetShortcut)
        self.goto_id_action.setAutoRepeat(False)

        self.goto_id_action.triggered_owner.connect(self.open_new_window)

        self.textbox_xml = XMLTextEdit(self.centralwidget)
        self.button_xml_savetext = QPushButton(self.centralwidget)
        self.button_xml_savetext.setText("Save XML")
        self.button_xml_savetext.setMaximumWidth(400)
        self.textbox_xml.setLineWrapMode(QTextEdit.NoWrap)
        self.textbox_xml.setContextMenuPolicy(Qt.CustomContextMenu)
        self.textbox_xml.customContextMenuRequested.connect(self.my_context_menu)

        metrics = QFontMetrics(font)
        self.textbox_xml.setTabStopWidth(4 * metrics.width(' '))
        self.textbox_xml.setFont(font)

        self.verticalLayout.addWidget(self.textbox_xml)
        self.verticalLayout.addWidget(self.button_xml_savetext)
        self.setWindowTitle(self.windowname)
예제 #47
0
class CodeViewer(QObject):
    """QScintilla based viewer for JSON"""
    def __init__(self, qsciScintillaWidget,  parent=None):
        super().__init__(parent)

        self.qsciScintillaWidget = qsciScintillaWidget

        self.qsciScintillaWidget.setReadOnly(True)

        # Set default font
        font = QFont()
        font.setFamily("Courier New")
        font.setFixedPitch(True)
        font.setPointSize(14)

        self.qsciScintillaWidget.setFont(font)

        # Set margin 0 - used for line numbers
        self.fontMetrics = QFontMetrics(font)
        self.qsciScintillaWidget.setMarginsFont(font)
        self.qsciScintillaWidget.setMarginLineNumbers(0, True)
        self.qsciScintillaWidget.setMarginsBackgroundColor(QColor("#444444"))
        self.qsciScintillaWidget.setMarginsForegroundColor(QColor("#A9B7C6"))
        self.qsciScintillaWidget.setMarginWidth(1, 0)

        self.qsciScintillaWidget.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        lexer = QsciLexerJavaScript()

        lexer.setFont(font)
        # Background color
        lexer.setPaper(QColor("#333333"))
        lexer.setDefaultPaper(QColor("#333333"))
        # Text color
        lexer.setDefaultColor(QColor("#00CCCC"))
        # Text colorization
        # Colorization for: 'some string'
        lexer.setColor(QColor("#A5C261"), QsciLexerJavaScript.SingleQuotedString)
        # Colorization for: "some string"
        lexer.setColor(QColor("#A5C261"), QsciLexerJavaScript.DoubleQuotedString)
        # Colorization for: 13 33 45
        lexer.setColor(QColor("#6897BB"), QsciLexerJavaScript.Number)
        # Colorization for: {} + = ; :
        lexer.setColor(QColor("#A9B7C6"), QsciLexerJavaScript.Operator)
        # Colorization for: true, false
        lexer.setColor(QColor("#FF00BB"), QsciLexerJavaScript.Keyword)
        # Colorization for: valueOfSomething, functionAdd()
        lexer.setColor(QColor("#FF00BB"), QsciLexerJavaScript.Identifier)

        self.qsciScintillaWidget.setLexer(lexer)

        self.qsciScintillaWidget.textChanged.connect(self.on_qsciScintillaWidget_textChanged)

    @pyqtSlot()
    def on_qsciScintillaWidget_textChanged(self):
        marginWidth = self.fontMetrics.width(str(self.qsciScintillaWidget.lines())) + 10
        self.qsciScintillaWidget.setMarginWidth(0, marginWidth)
        self.qsciScintillaWidget.setMarginWidth(1, 5)
예제 #48
0
 def __init__(self, cookieJar, parent=None):
     """
     Constructor
     
     @param cookieJar reference to the cookie jar (CookieJar)
     @param parent reference to the parent widget (QWidget)
     """
     super(CookiesExceptionsDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.__cookieJar = cookieJar
     
     self.removeButton.clicked.connect(
         self.exceptionsTable.removeSelected)
     self.removeAllButton.clicked.connect(
         self.exceptionsTable.removeAll)
     
     self.exceptionsTable.verticalHeader().hide()
     self.__exceptionsModel = CookieExceptionsModel(cookieJar)
     self.__proxyModel = QSortFilterProxyModel(self)
     self.__proxyModel.setSourceModel(self.__exceptionsModel)
     self.searchEdit.textChanged.connect(
         self.__proxyModel.setFilterFixedString)
     self.exceptionsTable.setModel(self.__proxyModel)
     
     cookieModel = CookieModel(cookieJar, self)
     self.domainEdit.setCompleter(QCompleter(cookieModel, self.domainEdit))
     
     f = QFont()
     f.setPointSize(10)
     fm = QFontMetrics(f)
     height = fm.height() + fm.height() // 3
     self.exceptionsTable.verticalHeader().setDefaultSectionSize(height)
     self.exceptionsTable.verticalHeader().setMinimumSectionSize(-1)
     for section in range(self.__exceptionsModel.columnCount()):
         header = self.exceptionsTable.horizontalHeader()\
             .sectionSizeHint(section)
         if section == 0:
             header = fm.width("averagebiglonghost.averagedomain.info")
         elif section == 1:
             header = fm.width(self.tr("Allow For Session"))
         buffer = fm.width("mm")
         header += buffer
         self.exceptionsTable.horizontalHeader()\
             .resizeSection(section, header)
예제 #49
0
 def __init__(self, parent):
     super().__init__(parent)
     font = self.font()
     font.setPointSize(16)
     met = QFontMetrics(font)
     scoreLineHeight = met.height()
     self.setFont(font)
     self.setMinimumHeight(scoreLineHeight)
     self.setMinimumWidth(met.width('30'))
예제 #50
0
 def setFont(self, f):
     # recalculate all of our metrics/offsets
     fm = QFontMetrics(f)
     self.font_width = fm.width('X')
     self.font_height = fm.height()
     self.updateScrollbars()
     # TODO: assert that we are using a fixed font & find out if we care?
     QAbstractScrollArea.setFont(self, f)
     return
예제 #51
0
    def __init__(self, parent=None):
        super(EditorBase, self).__init__(parent)
        # linuxcnc defaults
        self.idle_line_reset = False
        # don't allow editing by default
        self.setReadOnly(True)
        # Set the default font
        self.font = QFont()
        self.font.setFamily('Courier')
        self.font.setFixedPitch(True)
        self.font.setPointSize(12)
        self.setFont(self.font)
        self.setMarginsFont(self.font)

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

        # Clickable margin 1 for showing markers
        self.setMarginSensitivity(1, False)
        # setting marker margin width to zero make the marker highlight line
        self.setMarginWidth(1, 0)
        #self.matginClicked.connect(self.on_margin_clicked)
        self.markerDefine(QsciScintilla.RightArrow,
                          self.ARROW_MARKER_NUM)
        self.setMarkerBackgroundColor(QColor("#ffe4e4"),
                                      self.ARROW_MARKER_NUM)

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

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

        # Set custom gcode lexer
        self.set_gcode_lexer()

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented
        # here: http://www.scintilla.org/ScintillaDoc.html)
        #self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        self.SendScintilla(QsciScintilla.SCI_SETSCROLLWIDTH,700)
        self.SendScintilla(QsciScintilla.SCI_SETSCROLLWIDTHTRACKING)

        # default gray background
        self.set_background_color('#C0C0C0')

        # not too small
        self.setMinimumSize(200, 100)
        self.filepath = None
예제 #52
0
 def setButtonSize(self):
     """
     Set the size of the changeOrder button
     """
     font = self.pushButton_changeOrder.font()
     fontMetrics = QFontMetrics(font)
     width = fontMetrics.width(self.pushButton_changeOrder.text()) + 25
     self.pushButton_changeOrder.setMinimumWidth(width)
     self.pushButton_changeOrder.setMaximumWidth(width)
     self.pushButton_changeOrder.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
예제 #53
0
 def __init__(self, ds):
     rowFM = QFontMetrics(ds.rowFont())
     self.splitFM = QFontMetrics(ds.splitFont())
     headerFM = QFontMetrics(ds.headerFont())
     self.rowHeight = rowFM.height() + CELL_MARGIN * 2
     self.splitHeight = self.splitFM.height() + CELL_MARGIN * 2
     self.headerHeight = headerFM.height() + CELL_MARGIN * 2
     spannedRowIndexes = set()
     for rowIndex in range(ds.rowCount()):
         extraRole = nonone(ds.data(rowIndex, 0, EXTRA_ROLE), 0)
         if extraRole & EXTRA_SPAN_ALL_COLUMNS:
             spannedRowIndexes.add(rowIndex)
     self.columns = []
     for colIndex in range(ds.columnCount()):
         col = ds.columnAtIndex(colIndex)
         sumWidth = 0
         maxWidth = 0
         # We need to have *at least* the width of the header.
         minWidth = headerFM.width(col.display) + CELL_MARGIN * 2
         for rowIndex in range(ds.rowCount()):
             if rowIndex in spannedRowIndexes:
                 continue
             data = ds.data(rowIndex, colIndex, Qt.DisplayRole)
             if data:
                 font = ds.data(rowIndex, colIndex, Qt.FontRole)
                 fm = QFontMetrics(font) if font is not None else rowFM
                 width = fm.width(data) + CELL_MARGIN * 2
                 width += ds.indentation(rowIndex, colIndex)
                 sumWidth += width
                 maxWidth = max(maxWidth, width)
             pixmap = ds.data(rowIndex, colIndex, Qt.DecorationRole)
             if pixmap is not None:
                 width = pixmap.width() + CELL_MARGIN * 2
                 maxWidth = max(maxWidth, width)
         avgWidth = sumWidth // ds.rowCount()
         maxWidth = max(maxWidth, minWidth)
         if col.cantTruncate: # if it's a "can't truncate" column, we make no concession
             minWidth = maxWidth
         cs = ColumnStats(colIndex, col, avgWidth, maxWidth, minWidth)
         self.columns.append(cs)
     self.maxWidth = sum(cs.maxWidth for cs in self.columns)
     self.minWidth = sum(cs.minWidth for cs in self.columns)
예제 #54
0
    def layout(self):
        time_fm = QFontMetrics(self.time.font())
        seconds_fm = QFontMetrics(self.seconds.font())

        x = self.rect.left()
        y = self.rect.top()

        self.time.setPos(x, y)
        self.seconds.setPos(x + time_fm.width("00:00") + 20,
                            y + time_fm.ascent() - seconds_fm.ascent())
        self.date.setPos(x, y + time_fm.ascent())
예제 #55
0
    def _scaleLenght(self):
        fmr = QFontMetrics(self._font).boundingRect(self._units)

        if self._orientation == Qt.Horizontal:
            w = fmr.width()+2
            lenght = self.geometry().width() - w
        else:
            h = fmr.height()+1
            lenght = self.geometry().height() - h

        return lenght
예제 #56
0
 def paintEvent(self, event):
     painter = QPainter(self)
     font_metrics = QFontMetrics(self.font())
     if font_metrics.width(self.text()) > self.contentsRect().width():
         label_width = self.size().width()
         fade_start = 1 - 50.0/label_width if label_width > 50 else 0.0
         gradient = QLinearGradient(0, 0, label_width, 0)
         gradient.setColorAt(fade_start, self.palette().color(self.foregroundRole()))
         gradient.setColorAt(1.0, Qt.transparent)
         painter.setPen(QPen(QBrush(gradient), 1.0))
     painter.drawText(self.contentsRect(), Qt.TextSingleLine | int(self.alignment()), self.text())
예제 #57
0
    def reshape(self):
        ''' Update the shape of the edge (redefined function) '''
        path = QPainterPath()
        # If there is a starting point, draw a line to the first curve point
        if self.start_point:
            path.moveTo(self.source_connection.center)
            path.lineTo(self.bezier[0])
        else:
            path.moveTo(self.source_connection.center)
        # Loop over the curve points:
        for group in self.bezier[1:]:
            path.cubicTo(*[point.center for point in group])

        # If there is an ending point, draw a line to it
        if self.end_point:
            path.lineTo(self.end_connection.center)

        end_point = path.currentPosition()
        arrowhead = self.angle_arrow(path)
        path.lineTo(arrowhead[0])
        path.moveTo(end_point)
        path.lineTo(arrowhead[1])
        path.moveTo(end_point)
        try:
            # Add the transition label, if any (none for the START edge)
            font = QFont('arial', pointSize=8)
            metrics = QFontMetrics(font)
            label = self.edge.get('label', '')
            lines = label.split('\n')
            width = metrics.width(max(lines)) # longest line
            height = metrics.height() * len(lines)
            # lp is the position of the center of the text
            pos = self.mapFromScene(*self.edge['lp'])
            if not self.text_label:
                self.text_label = QGraphicsTextItem(
                                 self.edge.get('label', ''), parent=self)
            self.text_label.setX(pos.x() - width / 2)
            self.text_label.setY(pos.y() - height / 2)
            self.text_label.setFont(font)
            # Make horizontal center alignment, as dot does
            self.text_label.setTextWidth(self.text_label.boundingRect().width())
            fmt = QTextBlockFormat()
            fmt.setAlignment(Qt.AlignHCenter)
            cursor = self.text_label.textCursor()
            cursor.select(QTextCursor.Document)
            cursor.mergeBlockFormat(fmt)
            cursor.clearSelection()
            self.text_label.setTextCursor(cursor)
            self.text_label.show()
        except KeyError:
            # no label
            pass
        self.setPath(path)
예제 #58
0
 def getRefRects(self):
     cursor = self.textCursor()
     f = self.font()
     f.setFixedPitch(True)
     f.setWeight(QFont.DemiBold)
     fm = QFontMetrics(f)
     refs = []
     for txt in re.finditer(Ref.RegEx, self.toPlainText()):
         cursor.setPosition(txt.start())
         r = self.cursorRect(cursor)
         r.setWidth(fm.width(txt.group(0)))
         refs.append(r)
     self.refRects = refs
예제 #59
0
 def width(self) -> int:
     """
         Calculate the width of the AlgorithmDataDesign needed for the widgets
     """
     font = self.lineEdit_name.font()
     fontMetrics = QFontMetrics(font)
     return max([self.radioButton_selected.size().width() ,\
         fontMetrics.width(self.lineEdit_name.text())  , \
         self.MyQtEnumComboBox_fieldRoll.minWidth() , \
         self.MyQtEnumComboBox_fieldsTypes.minWidth() , \
         self.pushButton_changeOrder.size().width() , \
         self.MyQtEnumComboBox_range.minWidth() , \
         self.MyQtEnumComboBox_normalizeMethod.minWidth()])