def data(self, index, role=None):
     row = index.row()
     column = index.column()
     if role == Qt.DisplayRole:
         if column == 0:
             return row + 1
         elif column == 1:
             return self.players[row].name
         elif column == 2:
             return self.players[row].club
         elif column == 3:
             if self.players[row].allPass != 0:
                 return str(self.players[row].correctPass /
                            self.players[row].allPass * 100)[:6]
             else:
                 return 0
     elif role == Qt.TextAlignmentRole:
         if column != 1:
             return Qt.AlignCenter
     elif role == Qt.BackgroundRole:
         if row == 0:
             return QBrush(QColor(255, 180, 180))
         elif row == 1:
             return QBrush(Qt.darkYellow)
         elif row == 2:
             return QBrush(Qt.green)
Beispiel #2
0
 def __init__(self, develop=False):
     self.drawn_once = False
     self.develop = develop
     self.title_font = f = QFont()
     f.setPointSize(self.TITLE_SIZE)
     f.setBold(True)
     self.title_height = QFontMetrics(f).lineSpacing() + 2
     self.body_font = f = QFont()
     f.setPointSize(self.BODY_SIZE)
     self.line_height = QFontMetrics(f).lineSpacing()
     self.total_height = max(self.LOGO_SIZE,
                             self.title_height + 3 * self.line_height)
     self.num_font = f = QFont()
     f.setPixelSize(self.total_height)
     f.setItalic(True), f.setBold(True)
     f = QFontMetrics(f)
     self.num_ch = unicode_type(max(3, numeric_version[0]))
     self.footer_font = f = QFont()
     f.setPointSize(self.FOOTER_SIZE)
     f.setItalic(True)
     self.dpr = QApplication.instance().devicePixelRatio()
     self.pmap = QPixmap(I('library.png', allow_user_override=False))
     self.pmap.setDevicePixelRatio(self.dpr)
     self.pmap = self.pmap.scaled(int(self.dpr * self.LOGO_SIZE),
                                  int(self.dpr * self.LOGO_SIZE),
                                  transformMode=Qt.SmoothTransformation)
     self.light_brush = QBrush(QColor('#F6F3E9'))
     self.dark_brush = QBrush(QColor('#39322B'))
     pmap = QPixmap(int(self.WIDTH * self.dpr),
                    int(self.total_height * self.dpr))
     pmap.setDevicePixelRatio(self.dpr)
     pmap.fill(Qt.transparent)
     QSplashScreen.__init__(self, pmap)
     self.setWindowTitle(__appname__)
Beispiel #3
0
class Link(QGraphicsRectItem):
    inactive_brush = QBrush(QColor(0xff, 0xff, 0xff, 0xff))
    active_brush = QBrush(QColor(0x00, 0x00, 0x00, 0x59))

    def __init__(self, parent, start, stop, refobj, slot):
        QGraphicsRectItem.__init__(self, start, 0, stop - start, parent.height,
                                   parent)
        self.refobj = refobj
        self.slot = slot
        self.brush = self.__class__.inactive_brush
        self.setPen(QPen(Qt.NoPen))
        self.setCursor(Qt.PointingHandCursor)
        self.setAcceptHoverEvents(True)

    def hoverEnterEvent(self, event):
        self.brush = self.__class__.active_brush
        self.parentItem().update()

    def hoverLeaveEvent(self, event):
        self.brush = self.__class__.inactive_brush
        self.parentItem().update()

    def mousePressEvent(self, event):
        self.hoverLeaveEvent(None)
        self.slot(self.refobj)
Beispiel #4
0
 def create_square_graphs(self):
     a = 0
     b = 0
     for i in range(self.map.get_height()):
         self.graphSquares[i] = [None] * self.map.get_width()
         for j in range(self.map.get_width()):
             squar = QGraphicsRectItem(b*50, a*50, 50, 50)
             if a == 2 and b == 1:
                 color = QColor(124,252,0)
                 brush = QBrush(color)
                 squar.setBrush(brush)
                 b += 1
             elif not self.objects[i][j].is_obstacle:
                 color = QColor(20,20,20)
                 brush = QBrush(color)
                 squar.setBrush(brush)
                 b += 1
             else:
                 color = QColor(211,211,211)
                 brush = QBrush(color)
                 squar.setBrush(brush)
                 b += 1
             self.graphSquares[i][j] = squar
         a += 1
         b = 0
     return self.graphSquares
Beispiel #5
0
    def set_style(self, style):
        pf = PF(style=style)
        self.styles = {}
        self.normal = self.base_fmt()
        self.background_color = pf.style.background_color
        self.color = 'black'

        for ttype, ndef in pf.style:
            fmt = self.base_fmt()
            fmt.setProperty(fmt.UserProperty, str(ttype))
            if ndef['color']:
                fmt.setForeground(QBrush(QColor('#%s'%ndef['color'])))
                fmt.setUnderlineColor(QColor('#%s'%ndef['color']))
                if ttype == Generic.Output:
                    self.color = '#%s'%ndef['color']
            if ndef['bold']:
                fmt.setFontWeight(QFont.Bold)
            if ndef['italic']:
                fmt.setFontItalic(True)
            if ndef['underline']:
                fmt.setFontUnderline(True)
            if ndef['bgcolor']:
                fmt.setBackground(QBrush(QColor('#%s'%ndef['bgcolor'])))
            if ndef['border']:
                pass  # No support for borders

            self.styles[ttype] = fmt
Beispiel #6
0
class Background(QWidget):  # {{{

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.bcol = QColor(*gprefs['cover_grid_color'])
        self.btex = gprefs['cover_grid_texture']
        self.update_brush()
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

    def update_brush(self):
        self.brush = QBrush(self.bcol)
        if self.btex:
            from calibre.gui2.preferences.texture_chooser import texture_path
            path = texture_path(self.btex)
            if path:
                p = QPixmap(path)
                try:
                    dpr = self.devicePixelRatioF()
                except AttributeError:
                    dpr = self.devicePixelRatio()
                p.setDevicePixelRatio(dpr)
                self.brush.setTexture(p)
        self.update()

    def sizeHint(self):
        return QSize(200, 120)

    def paintEvent(self, ev):
        painter = QPainter(self)
        painter.fillRect(ev.rect(), self.brush)
        painter.end()
Beispiel #7
0
class Background(QWidget):  # {{{

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.bcol = QColor(*gprefs['cover_grid_color'])
        self.btex = gprefs['cover_grid_texture']
        self.update_brush()
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

    def update_brush(self):
        self.brush = QBrush(self.bcol)
        if self.btex:
            from calibre.gui2.preferences.texture_chooser import texture_path
            path = texture_path(self.btex)
            if path:
                self.brush.setTexture(QPixmap(path))
        self.update()

    def sizeHint(self):
        return QSize(200, 120)

    def paintEvent(self, ev):
        painter = QPainter(self)
        painter.fillRect(ev.rect(), self.brush)
        painter.end()
 def getProblems(self):
     self.remindLabel.setVisible(False)
     self.recommendLabel.setVisible(False)
     self.newrecord.setVisible(False)
     self.table.setVisible(True)
     self.aboutcontent.setVisible(False)
     print('heregetproblem')
     self.connection = sqlite3.connect("database/oj.db")
     Data = self.connection.execute(
         "SELECT id,name,level,tags,AC,ACrate FROM problem Order By id")
     self.connection.commit()
     Data = Data.fetchall()
     row = len(Data)  #取得记录个数,用于设置表格的行数
     vol = len(Data[0])  #取得字段数,用于设置表格的列数
     print(row)
     print(vol)
     self.table.setRowCount(row)
     self.table.setColumnCount(vol)
     self.table.setHorizontalHeaderLabels(
         ['编号', '题目名字', '题目等级', '题目标签', 'AC人数', 'AC率'])
     self.table.verticalHeader().setVisible(False)
     #        self.table.horizontalHeader().setVisible(False)
     self.table.horizontalHeader().setFixedHeight(25)
     for index in range(self.table.columnCount()):
         headItem = self.table.horizontalHeaderItem(index)
         #            headItem.setBackground(QBrush(QColor(28, 28, 28)))
         headItem.setFont(QFont("song", 9, QFont.Bold))
         headItem.setForeground(QBrush(QColor(137, 199, 161)))
         headItem.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
     self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
     self.table.setColumnWidth(0, 40)
     self.table.setColumnWidth(1, 80)
     self.table.setColumnWidth(2, 90)
     self.table.setColumnWidth(3, 230)
     self.table.setColumnWidth(4, 50)
     self.table.setColumnWidth(5, 85)
     self.table.setRowHeight(0, 30)
     self.table.setRowHeight(1, 30)
     self.table.setRowHeight(2, 30)
     self.table.setRowHeight(3, 30)
     self.table.setRowHeight(4, 30)
     self.table.setRowHeight(5, 30)
     self.table.setRowHeight(6, 30)
     self.table.setRowHeight(7, 30)
     self.table.setRowHeight(8, 30)
     self.table.setRowHeight(9, 30)
     for i in range(row):
         if i % 2 == 0:
             for j in range(vol):
                 temp_data = Data[i][j]  #临时记录,不能直接插入表格
                 data = QTableWidgetItem(str(temp_data))  #转换后可插入表格
                 data.setBackground(QBrush(QColor(245, 245, 244)))
                 self.table.setItem(i, j, data)
         else:
             for j in range(vol):
                 temp_data = Data[i][j]  #临时记录,不能直接插入表格
                 data = QTableWidgetItem(str(temp_data))  #转换后可插入表格
                 data.setBackground(QBrush(QColor(254, 254, 254)))
                 self.table.setItem(i, j, data)
Beispiel #9
0
 def update_brush(self):
     self.brush = QBrush(self.bcol)
     if self.btex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(self.btex)
         if path:
             self.brush.setTexture(QPixmap(path))
     self.update()
Beispiel #10
0
    def __call__(self, painter, rect, color_theme, title_block, subtitle_block, footer_block):
        painter.fillRect(rect, self.color1)
        top = title_block.position.y + 2
        extra_spacing = subtitle_block.line_spacing // 2 if subtitle_block.line_spacing else title_block.line_spacing // 3
        height = title_block.height + subtitle_block.height + extra_spacing + title_block.leading
        right = rect.right() - self.hmargin
        width = right - self.hmargin

        # Draw main banner
        p = main = QPainterPath(QPointF(self.hmargin, top))
        draw_curved_line(p, rect.width() - 2 * self.hmargin, 0, 0.1, -0.1, 0.9, -0.1)
        deltax = self.GRADE * height
        p.lineTo(right + deltax, top + height)
        right_corner = p.currentPosition()
        draw_curved_line(p, - width - 2 * deltax, 0, 0.1, 0.05, 0.9, 0.05)
        left_corner = p.currentPosition()
        p.closeSubpath()

        # Draw fold rectangles
        rwidth = self.fold_width
        yfrac = 0.1
        width23 = int(0.67 * rwidth)
        rtop = top + height * yfrac

        def draw_fold(x, m=1, corner=left_corner):
            ans = p = QPainterPath(QPointF(x, rtop))
            draw_curved_line(p, rwidth*m, 0, 0.1, 0.1*m, 0.5, -0.2*m)
            fold_upper = p.currentPosition()
            p.lineTo(p.currentPosition() + QPointF(-deltax*m, height))
            fold_corner = p.currentPosition()
            draw_curved_line(p, -rwidth*m, 0, 0.2, -0.1*m, 0.8, -0.1*m)
            draw_curved_line(p, deltax*m, -height, 0.2, 0.1*m, 0.8, 0.1*m)
            p = inner_fold = QPainterPath(corner)
            dp = fold_corner - p.currentPosition()
            draw_curved_line(p, dp.x(), dp.y(), 0.5, 0.3*m, 1, 0*m)
            p.lineTo(fold_upper), p.closeSubpath()
            return ans, inner_fold

        left_fold, left_inner = draw_fold(self.hmargin - width23)
        right_fold, right_inner = draw_fold(right + width23, m=-1, corner=right_corner)

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        pen = QPen(self.ccolor2)
        pen.setWidth(3)
        pen.setJoinStyle(Qt.RoundJoin)
        painter.setPen(pen)
        for r in (left_fold, right_fold):
            painter.fillPath(r, QBrush(self.color2))
            painter.drawPath(r)
        for r in (left_inner, right_inner):
            painter.fillPath(r, QBrush(self.color2.darker()))
            painter.drawPath(r)
        painter.fillPath(main, QBrush(self.color2))
        painter.drawPath(main)
        painter.restore()
        return self.ccolor2, self.ccolor2, self.ccolor1
 def addbutton(self):
     self.connection = sqlite3.connect("database/oj.db")
     f = open(r'database/username.txt')
     username = f.read()
     f.close()
     topTen = self.connection.execute(
         "SELECT user1,user2,user3,user4,user5,user6,user7,user8,user9,user10 FROM secondrecommend WHERE username = '******'"
         % username)
     #        print(topTen)
     self.connection.commit()
     #        print(Data)
     topTen = topTen.fetchall()
     self.table.setRowCount(10)
     self.table.setColumnCount(6)
     self.table.setHorizontalHeaderLabels(
         ['编号', '题目名字', '题目等级', '题目标签', 'AC率', 'AC人数'])
     self.table.verticalHeader().setVisible(False)
     self.table.horizontalHeader().setFixedHeight(25)
     for index in range(self.table.columnCount()):
         headItem = self.table.horizontalHeaderItem(index)
         headItem.setFont(QFont("song", 9, QFont.Bold))
         headItem.setForeground(QBrush(QColor(137, 199, 161)))
         headItem.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
     self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
     self.table.setColumnWidth(0, 40)
     self.table.setColumnWidth(1, 120)
     self.table.setColumnWidth(2, 90)
     self.table.setColumnWidth(3, 186)
     self.table.setColumnWidth(4, 98)
     self.table.setColumnWidth(5, 60)
     self.table.setRowHeight(0, 38)
     self.table.setRowHeight(1, 38)
     self.table.setRowHeight(2, 38)
     self.table.setRowHeight(3, 38)
     self.table.setRowHeight(4, 38)
     self.table.setRowHeight(5, 38)
     self.table.setRowHeight(6, 38)
     self.table.setRowHeight(7, 38)
     self.table.setRowHeight(8, 38)
     self.table.setRowHeight(9, 38)
     for i in range(10):
         Data = self.connection.execute(
             "SELECT id,name,level,tags,ACrate,AC FROM problem where id = '%s'"
             % topTen[0][i])
         Data = Data.fetchall()
         if i % 2 == 0:
             for j in range(6):
                 temp_data = Data[0][j]  #临时记录,不能直接插入表格
                 data = QTableWidgetItem(str(temp_data))  #转换后可插入表格
                 data.setBackground(QBrush(QColor(245, 245, 244)))
                 self.table.setItem(i, j, data)
         else:
             for j in range(6):
                 temp_data = Data[0][j]  #临时记录,不能直接插入表格
                 data = QTableWidgetItem(str(temp_data))  #转换后可插入表格
                 data.setBackground(QBrush(QColor(254, 254, 254)))
                 self.table.setItem(i, j, data)
Beispiel #12
0
 def data(self, index, role):
     if not index.isValid():
         return None
     row, col = index.row(), index.column()
     if row < 0 or row >= self.rowCount():
         return None
     display_plugin = self.display_plugins[row]
     if role in [Qt.DisplayRole, Qt.UserRole]:
         if col == 0:
             return display_plugin.name
         if col == 1:
             if display_plugin.donation_link:
                 return _('PayPal')
         if col == 2:
             return self._get_status(display_plugin)
         if col == 3:
             return self._get_display_version(
                 display_plugin.installed_version)
         if col == 4:
             return self._get_display_version(
                 display_plugin.available_version)
         if col == 5:
             if role == Qt.UserRole:
                 return self._get_display_release_date(
                     display_plugin.release_date, 'yyyyMMdd')
             else:
                 return self._get_display_release_date(
                     display_plugin.release_date)
         if col == 6:
             return self._get_display_version(
                 display_plugin.calibre_required_version)
         if col == 7:
             return display_plugin.author
     elif role == Qt.DecorationRole:
         if col == 0:
             return self._get_status_icon(display_plugin)
         if col == 1:
             if display_plugin.donation_link:
                 return QIcon(I('donate.png'))
     elif role == Qt.ToolTipRole:
         if col == 1 and display_plugin.donation_link:
             return _(
                 'This plugin is FREE but you can reward the developer for their effort\n'
                 'by donating to them via PayPal.\n\n'
                 'Right-click and choose Donate to reward: '
             ) + display_plugin.author
         else:
             return self._get_status_tooltip(display_plugin)
     elif role == Qt.ForegroundRole:
         if col != 1:  # Never change colour of the donation column
             if display_plugin.is_deprecated:
                 return QBrush(Qt.blue)
             if display_plugin.is_disabled():
                 return QBrush(Qt.gray)
     return None
Beispiel #13
0
 def makeQPixmap(self, width, height):
     data = numpy.zeros((width, height), float)
     data[...] = (numpy.arange(width) / (width - 1.))[:, numpy.newaxis]
     # make brush image -- diag background, with colormap on top
     img = QPixmap(width, height)
     painter = QPainter(img)
     painter.fillRect(0, 0, width, height, QBrush(QColor("white")))
     painter.fillRect(0, 0, width, height, QBrush(Qt.BDiagPattern))
     painter.drawImage(0, 0, self.colorize(data))
     painter.end()
     return img
Beispiel #14
0
    def __init__(self, registers):
        super().__init__(len(registers), len(QRegistersWidget.HEADERS))
        self.registers = registers
        self.labels = None
        self.values = None
        self.old_background = None
        self.old_foreground = None
        self.black = QBrush(QColor("#000000"))
        self.change = QBrush(QColor("#c0c000"))
        self.mono = QFont("Cascadia Code PL", 16)

        self.init_ui()
Beispiel #15
0
def read_color(col):
    if QColor.isValidColor(col):
        return QBrush(QColor(col))
    if col.startswith('rgb('):
        r, g, b = map(int, (x.strip() for x in col[4:-1].split(',')))
        return QBrush(QColor(r, g, b))
    try:
        r, g, b = col[0:2], col[2:4], col[4:6]
        r, g, b = int(r, 16), int(g, 16), int(b, 16)
        return QBrush(QColor(r, g, b))
    except Exception:
        pass
    def headerData(self, section: int, orientation: Qt.Orientation, role: int = Qt.DisplayRole):
        # BackgroundRole most likely will be overriden by a widget palette and a general application style
        if role == Qt.BackgroundRole:
            return QBrush(Qt.blue)

        if role == Qt.ForegroundRole:
            return QBrush(Qt.red)

        if role == Qt.DisplayRole and orientation == Qt.Horizontal and section < len(self.headers):
            return self.headers[section]
        else:
            return super().headerData(section, orientation, role)
Beispiel #17
0
def full(p, xmax, ymax):
    p.drawRect(0, 0, xmax, ymax)
    p.drawPolyline(QPoint(0, 0), QPoint(xmax, 0), QPoint(xmax, ymax),
                    QPoint(0, ymax), QPoint(0, 0))
    pp = QPainterPath()
    pp.addRect(0, 0, xmax, ymax)
    p.drawPath(pp)
    p.save()
    for i in range(3):
        col = [0, 0, 0, 200]
        col[i] = 255
        p.setOpacity(0.3)
        p.fillRect(0, 0, xmax/10, xmax/10, QBrush(QColor(*col)))
        p.setOpacity(1)
        p.drawRect(0, 0, xmax/10, xmax/10)
        p.translate(xmax/10, xmax/10)
        p.scale(1, 1.5)
    p.restore()

    # p.scale(2, 2)
    # p.rotate(45)
    p.drawPixmap(0, 0, xmax/4, xmax/4, QPixmap(I('library.png')))
    p.drawRect(0, 0, xmax/4, xmax/4)

    f = p.font()
    f.setPointSize(20)
    # f.setLetterSpacing(f.PercentageSpacing, 200)
    f.setUnderline(True)
    # f.setOverline(True)
    # f.setStrikeOut(True)
    f.setFamily('Calibri')
    p.setFont(f)
    # p.setPen(QColor(0, 0, 255))
    # p.scale(2, 2)
    # p.rotate(45)
    p.drawText(QPoint(xmax/3.9, 30), 'Some—text not By’s ū --- Д AV ff ff')

    b = QBrush(Qt.HorPattern)
    b.setColor(QColor(Qt.blue))
    pix = QPixmap(I('lt.png'))
    w = xmax/4
    p.fillRect(0, ymax/3, w, w, b)
    p.fillRect(xmax/3, ymax/3, w, w, QBrush(pix))
    x, y = 2*xmax/3, ymax/3
    p.drawTiledPixmap(QRectF(x, y, w, w), pix, QPointF(10, 10))

    x, y = 1, ymax/1.9
    g = QLinearGradient(QPointF(x, y), QPointF(x+w, y+w))
    g.setColorAt(0, QColor('#00f'))
    g.setColorAt(1, QColor('#fff'))
    p.fillRect(x, y, w, w, QBrush(g))
Beispiel #18
0
 def update_brush(self):
     self.brush = QBrush(self.bcol)
     if self.btex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(self.btex)
         if path:
             p = QPixmap(path)
             try:
                 dpr = self.devicePixelRatioF()
             except AttributeError:
                 dpr = self.devicePixelRatio()
             p.setDevicePixelRatio(dpr)
             self.brush.setTexture(p)
     self.update()
Beispiel #19
0
    def __init__(self, gui):
        QWidget.__init__(self, gui)
        self.setObjectName('jobs_pointer')
        self.setVisible(False)
        self.resize(100, 80)
        self.animation = QPropertyAnimation(self, "geometry", self)
        self.animation.setDuration(750)
        self.animation.setLoopCount(2)
        self.animation.setEasingCurve(QEasingCurve.Linear)
        self.animation.finished.connect(self.hide)

        taily, heady = 0, 55
        self.arrow_path = QPainterPath(QPointF(40, taily))
        self.arrow_path.lineTo(40, heady)
        self.arrow_path.lineTo(20, heady)
        self.arrow_path.lineTo(50, self.height())
        self.arrow_path.lineTo(80, heady)
        self.arrow_path.lineTo(60, heady)
        self.arrow_path.lineTo(60, taily)
        self.arrow_path.closeSubpath()

        c = self.palette().color(QPalette.Active, QPalette.WindowText)
        self.color = QColor(c)
        self.color.setAlpha(100)
        self.brush = QBrush(self.color, Qt.SolidPattern)
Beispiel #20
0
 def corner():
     b = QBrush(self.ccolor1)
     p.fillPath(path, b)
     p.rotate(90), p.translate(100, -100), p.scale(1, -1), p.translate(
         -103, -97)
     p.fillPath(path, b)
     p.setWorldTransform(QTransform())
Beispiel #21
0
 def drawContents(self, painter):
     painter.setBackgroundMode(Qt.OpaqueMode)
     painter.setBackground(QBrush(QColor(0xee, 0xee, 0xee)))
     painter.setPen(Qt.black)
     painter.setRenderHint(painter.TextAntialiasing, True)
     painter.drawText(self.rect().adjusted(5, 5, -5, -5), Qt.AlignLeft,
                      self.message())
Beispiel #22
0
 def data(self, index, role):
     if not index.isValid():
         return None
     if index.internalId() == 0:
         if role == Qt.DisplayRole:
             category = self.categories[index.row()]
             return (_("%(plugin_type)s %(plugins)s")%
                     dict(plugin_type=category, plugins=_('plugins')))
     else:
         plugin = self.index_to_plugin(index)
         disabled = is_disabled(plugin)
         if role == Qt.DisplayRole:
             ver = '.'.join(map(str, plugin.version))
             desc = '\n'.join(textwrap.wrap(plugin.description, 100))
             ans='%s (%s) %s %s\n%s'%(plugin.name, ver, _('by'), plugin.author, desc)
             c = plugin_customization(plugin)
             if c and not disabled:
                 ans += _('\nCustomization: ')+c
             if disabled:
                 ans += _('\n\nThis plugin has been disabled')
             return (ans)
         if role == Qt.DecorationRole:
             return self.disabled_icon if disabled else self.icon
         if role == Qt.ForegroundRole and disabled:
             return (QBrush(Qt.gray))
         if role == Qt.UserRole:
             return plugin
     return None
Beispiel #23
0
 def __init__(self, right=False, parent=None, show_open_in_editor=False):
     PlainTextEdit.__init__(self, parent)
     self.setFrameStyle(0)
     self.show_open_in_editor = show_open_in_editor
     self.side_margin = 0
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     self.customContextMenuRequested.connect(self.show_context_menu)
     self.setFocusPolicy(Qt.NoFocus)
     self.right = right
     self.setReadOnly(True)
     self.setLineWrapMode(self.WidgetWidth)
     font = self.font()
     ff = tprefs['editor_font_family']
     if ff is None:
         ff = default_font_family()
     font.setFamily(ff)
     font.setPointSize(tprefs['editor_font_size'])
     self.setFont(font)
     self.calculate_metrics()
     self.setTabStopWidth(tprefs['editor_tab_stop_width'] * self.space_width)
     font = self.heading_font = QFont(self.font())
     font.setPointSize(int(tprefs['editor_font_size'] * 1.5))
     font.setBold(True)
     theme = get_theme(tprefs['editor_theme'])
     pal = self.palette()
     pal.setColor(pal.Base, theme_color(theme, 'Normal', 'bg'))
     pal.setColor(pal.AlternateBase, theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'Normal', 'fg'))
     pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg'))
     pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.viewport().setCursor(Qt.ArrowCursor)
     self.line_number_area = LineNumbers(self)
     self.blockCountChanged[int].connect(self.update_line_number_area_width)
     self.updateRequest.connect(self.update_line_number_area)
     self.line_number_palette = pal = QPalette()
     pal.setColor(pal.Base, theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(pal.BrightText, theme_color(theme, 'LineNrC', 'fg'))
     self.line_number_map = LineNumberMap()
     self.search_header_pos = 0
     self.changes, self.headers, self.images = [], [], OrderedDict()
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff), self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.diff_backgrounds = {
         'replace' : theme_color(theme, 'DiffReplace', 'bg'),
         'insert'  : theme_color(theme, 'DiffInsert', 'bg'),
         'delete'  : theme_color(theme, 'DiffDelete', 'bg'),
         'replacereplace': theme_color(theme, 'DiffReplaceReplace', 'bg'),
         'boundary': QBrush(theme_color(theme, 'Normal', 'fg'), Qt.Dense7Pattern),
     }
     self.diff_foregrounds = {
         'replace' : theme_color(theme, 'DiffReplace', 'fg'),
         'insert'  : theme_color(theme, 'DiffInsert', 'fg'),
         'delete'  : theme_color(theme, 'DiffDelete', 'fg'),
         'boundary': QColor(0, 0, 0, 0),
     }
     for x in ('replacereplace', 'insert', 'delete'):
         f = QTextCharFormat()
         f.setBackground(self.diff_backgrounds[x])
         setattr(self, '%s_format' % x, f)
Beispiel #24
0
def draw_snake_spinner(painter, rect, angle, light, dark):
    painter.setRenderHint(QPainter.Antialiasing)

    if rect.width() > rect.height():
        delta = (rect.width() - rect.height()) // 2
        rect = rect.adjusted(delta, 0, -delta, 0)
    elif rect.height() > rect.width():
        delta = (rect.height() - rect.width()) // 2
        rect = rect.adjusted(0, delta, 0, -delta)
    disc_width = max(4, rect.width() // 10)

    drawing_rect = QRect(rect.x() + disc_width, rect.y() + disc_width, rect.width() - 2 * disc_width, rect.height() - 2 *disc_width)
    try:
        angle_for_width = math.degrees(math.atan2(1.3 * disc_width, drawing_rect.width()))
    except ZeroDivisionError:
        angle_for_width = 5

    gradient = QConicalGradient(drawing_rect.center(), angle - angle_for_width)
    gradient.setColorAt(1, light)
    gradient.setColorAt(0, dark)

    painter.setPen(QPen(light, disc_width))
    painter.drawArc(drawing_rect, 0, 360 * 16)
    pen = QPen(QBrush(gradient), disc_width)
    pen.setCapStyle(Qt.RoundCap)
    painter.setPen(pen)
    painter.drawArc(drawing_rect, angle * 16, (360 - 2 * angle_for_width) * 16)
Beispiel #25
0
 def __init__(self, develop=False):
     self.drawn_once = False
     self.develop = develop
     self.title_font = f = QFont()
     f.setPointSize(self.TITLE_SIZE)
     f.setBold(True)
     self.title_height = QFontMetrics(f).lineSpacing() + 2
     self.body_font = f = QFont()
     f.setPointSize(self.BODY_SIZE)
     self.line_height = QFontMetrics(f).lineSpacing()
     self.total_height = max(self.LOGO_SIZE, self.title_height + 3 * self.line_height)
     self.num_font = f = QFont()
     f.setPixelSize(self.total_height)
     f.setItalic(True), f.setBold(True)
     f = QFontMetrics(f)
     self.num_ch = str(max(3, numeric_version[0]))
     self.footer_font = f = QFont()
     f.setPointSize(self.FOOTER_SIZE)
     f.setItalic(True)
     self.dpr = QApplication.instance().devicePixelRatio()
     self.pmap = QPixmap(I('library.png', allow_user_override=False))
     self.pmap.setDevicePixelRatio(self.dpr)
     self.pmap = self.pmap.scaled(int(self.dpr * self.LOGO_SIZE), int(self.dpr * self.LOGO_SIZE), transformMode=Qt.SmoothTransformation)
     self.light_brush = QBrush(QColor('#F6F3E9'))
     self.dark_brush = QBrush(QColor('#39322B'))
     pmap = QPixmap(int(self.WIDTH * self.dpr), int(self.WIDTH * self.dpr))
     pmap.setDevicePixelRatio(self.dpr)
     pmap.fill(Qt.transparent)
     QSplashScreen.__init__(self, pmap)
     self.setWindowTitle(__appname__)
Beispiel #26
0
 def draw_text(self, style, painter, option, widget, index, item):
     tr = style.subElementRect(style.SE_ItemViewItemText, option, widget)
     text = index.data(Qt.DisplayRole)
     hover = option.state & style.State_MouseOver
     if hover or gprefs['tag_browser_show_counts']:
         count = unicode_type(index.data(COUNT_ROLE))
         width = painter.fontMetrics().boundingRect(count).width()
         r = QRect(tr)
         r.setRight(r.right() - 1), r.setLeft(r.right() - width - 4)
         self.paint_text(painter, r, Qt.AlignCenter | Qt.TextSingleLine, count, hover)
         tr.setRight(r.left() - 1)
     else:
         tr.setRight(tr.right() - 1)
     is_rating = item.type == TagTreeItem.TAG and not self.rating_pat.sub('', text)
     if is_rating:
         painter.setFont(self.rating_font)
     flags = Qt.AlignVCenter | Qt.AlignLeft | Qt.TextSingleLine
     lr = QRect(tr)
     lr.setRight(lr.right() * 2)
     br = painter.boundingRect(lr, flags, text)
     if br.width() > tr.width():
         g = QLinearGradient(tr.topLeft(), tr.topRight())
         c = option.palette.color(QPalette.WindowText)
         g.setColorAt(0, c), g.setColorAt(0.8, c)
         c = QColor(c)
         c.setAlpha(0)
         g.setColorAt(1, c)
         pen = QPen()
         pen.setBrush(QBrush(g))
         painter.setPen(pen)
     self.paint_text(painter, tr, flags, text, hover)
Beispiel #27
0
 def do_insert_link(self, *args):
     link, name, is_image = self.ask_link()
     if not link:
         return
     url = self.parse_link(link)
     if url.isValid():
         url = unicode_type(url.toString(NO_URL_FORMATTING))
         self.focus_self()
         with self.editing_cursor() as c:
             if is_image:
                 c.insertImage(url)
             else:
                 name = name or url
                 fmt = QTextCharFormat()
                 fmt.setAnchor(True)
                 fmt.setAnchorHref(url)
                 fmt.setFontUnderline(True)
                 fmt.setForeground(QBrush(QColor('blue')))
                 prev_fmt = c.charFormat()
                 c.mergeCharFormat(fmt)
                 c.insertText(url)
                 c.setCharFormat(prev_fmt)
     else:
         error_dialog(self, _('Invalid URL'),
                      _('The url %r is invalid') % link, show=True)
    def do_insert_link(self, *args):
        link, name, is_image = self.ask_link()
        if not link:
            return
        url = self.parse_link(link)
        if url.isValid():
            url = unicode_type(url.toString(NO_URL_FORMATTING))
            self.focus_self()
            with self.editing_cursor() as c:
                if is_image:
                    c.insertImage(url)
                else:
                    oldfmt = QTextCharFormat(c.charFormat())
                    fmt = QTextCharFormat()
                    fmt.setAnchor(True)
                    fmt.setAnchorHref(url)
                    fmt.setForeground(QBrush(self.palette().color(QPalette.Link)))
                    if name or not c.hasSelection():
                        c.mergeCharFormat(fmt)
                        c.insertText(name or url)
                    else:
                        pos, anchor = c.position(), c.anchor()
                        start, end = min(pos, anchor), max(pos, anchor)
                        for i in range(start, end):
                            cur = self.textCursor()
                            cur.setPosition(i), cur.setPosition(i + 1, c.KeepAnchor)
                            cur.mergeCharFormat(fmt)
                    c.setPosition(c.position())
                    c.setCharFormat(oldfmt)

        else:
            error_dialog(self, _('Invalid URL'),
                         _('The url %r is invalid') % link, show=True)
Beispiel #29
0
 def do_test(self):
     selections = []
     self.match_locs = []
     if self.regex_valid():
         text = unicode_type(self.preview.toPlainText())
         regex = unicode_type(self.regex.text())
         cursor = QTextCursor(self.preview.document())
         extsel = QTextEdit.ExtraSelection()
         extsel.cursor = cursor
         extsel.format.setBackground(QBrush(Qt.yellow))
         try:
             for match in compile_regular_expression(regex).finditer(text):
                 es = QTextEdit.ExtraSelection(extsel)
                 es.cursor.setPosition(match.start(),
                                       QTextCursor.MoveAnchor)
                 es.cursor.setPosition(match.end(), QTextCursor.KeepAnchor)
                 selections.append(es)
                 self.match_locs.append((match.start(), match.end()))
         except:
             pass
     self.preview.setExtraSelections(selections)
     if self.match_locs:
         self.next.setEnabled(True)
         self.previous.setEnabled(True)
     self.occurrences.setText(unicode_type(len(self.match_locs)))
Beispiel #30
0
 def __init__(self,
              font_loader,
              canvas,
              logger,
              opts,
              ruby_tags,
              link_activated,
              width=0,
              height=0):
     if hasattr(canvas, 'canvaswidth'):
         width, height = canvas.canvaswidth, canvas.canvasheight
     _Canvas.__init__(self,
                      font_loader,
                      logger,
                      opts,
                      width=width,
                      height=height)
     self.block_id = canvas.id
     self.ruby_tags = ruby_tags
     self.link_activated = link_activated
     self.text_width = width
     fg = canvas.framecolor
     bg = canvas.bgcolor
     if not opts.visual_debug and canvas.framemode != 'none':
         self.setPen(Pen(fg, canvas.framewidth))
     self.setBrush(QBrush(Color(bg)))
     self.items = []
     for po in canvas:
         obj = po.object
         item = object_factory(self, obj, respect_max_y=True)
         if item:
             self.items.append((item, po.x1, po.y1))
Beispiel #31
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.__parent = parent
     self.__board = QPixmap(QSize(440, 440))
     self.__board.fill(Qt.transparent)
     self.__board_old = self.__board.copy()
     self.__board_old_old = self.__board.copy()
     self.__board_before_dots = self.__board.copy()
     self.__thickness = 10  # 默认画笔粗细为10px
     self.__penColor = QColor(0, 0, 0, 128)
     self.__painter = QPainter()
     self.__pen = QPen(self.__penColor, self.__thickness)
     self.__pen_seg = QPen(QColor(0, 0, 0, 128))
     self.__brush = QBrush(QColor(0, 0, 0, 128))
     self.__pen.setCapStyle(Qt.RoundCap)
     #self.__painter.setPen(self.__pen)
     self.__lastPos = QPoint(0, 0)  # 上一次鼠标位置
     self.__currentPos = QPoint(0, 0)  # 当前的鼠标位置
     self.__points = []  # dots模式的点集
     self.__mouse_pressed = False
     self.__can_undo = False
     self.__has_seg = False
     self.__mode = 1
     self.__ERASE = 0
     self.__LINE = 1
     self.__RECT = 2
     self.__CIRCLE = 3
     self.__DOTS = 4
     self.__transparent = False
     self.__trans_board = self.__board.copy()
     self.__trans_board.fill(Qt.transparent)
Beispiel #32
0
def draw_snake_spinner(painter, rect, angle, light, dark):
    painter.setRenderHint(QPainter.Antialiasing)

    if rect.width() > rect.height():
        delta = (rect.width() - rect.height()) // 2
        rect = rect.adjusted(delta, 0, -delta, 0)
    elif rect.height() > rect.width():
        delta = (rect.height() - rect.width()) // 2
        rect = rect.adjusted(0, delta, 0, -delta)
    disc_width = max(3, min(rect.width() // 10, 8))

    drawing_rect = QRect(rect.x() + disc_width,
                         rect.y() + disc_width,
                         rect.width() - 2 * disc_width,
                         rect.height() - 2 * disc_width)

    gap = 60  # degrees
    gradient = QConicalGradient(drawing_rect.center(), angle - gap // 2)
    gradient.setColorAt((360 - gap // 2) / 360.0, light)
    gradient.setColorAt(0, dark)

    pen = QPen(QBrush(gradient), disc_width)
    pen.setCapStyle(Qt.RoundCap)
    painter.setPen(pen)
    painter.drawArc(drawing_rect, angle * 16, (360 - gap) * 16)
Beispiel #33
0
    def hline(self):
        """
        Insert horizontal line
        """
        # Tag HR is not correctly displayed  in QTextview
        cur_char_fmt = self._text_edit_cursor.charFormat()
        cur_block_fmt = self._text_edit_cursor.blockFormat()
        if bool(self._text_edit_cursor.currentTable()):
            self._text_edit_cursor.insertBlock(cur_block_fmt, cur_char_fmt)

        block_fmt = QTextBlockFormat()
        block_fmt.setTopMargin(5)
        block_fmt.setBottomMargin(5)
        block_fmt.setAlignment(Qt.AlignLeft)
        block_fmt.setBackground(QBrush(QColor("#C1C1C1")))

        char_format = QTextCharFormat()
        char_format.setFont(QFont("Arial", 1))

        self._text_edit_cursor.insertBlock(block_fmt, char_format)
        self._text_edit_cursor.insertText(" ")

        self._text_edit_cursor.insertBlock(cur_block_fmt, cur_char_fmt)

        self.change(self._text_edit_cursor)
Beispiel #34
0
 def update_brush(self):
     self.brush = QBrush(self.bcol)
     if self.btex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(self.btex)
         if path:
             self.brush.setTexture(QPixmap(path))
     self.update()
Beispiel #35
0
 def update_brush(self):
     self.brush = QBrush(self.bcol)
     if self.btex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(self.btex)
         if path:
             p = QPixmap(path)
             try:
                 dpr = self.devicePixelRatioF()
             except AttributeError:
                 dpr = self.devicePixelRatio()
             p.setDevicePixelRatio(dpr)
             self.brush.setTexture(p)
     self.update()
Beispiel #36
0
class SplashScreen(QSplashScreen):

    TITLE_SIZE = 20  # pt
    BODY_SIZE = 12  # pt
    FOOTER_SIZE = 9  # pt
    LOGO_SIZE = 96  # px
    WIDTH = 550  # px

    def __init__(self, develop=False):
        self.drawn_once = False
        self.develop = develop
        self.title_font = f = QFont()
        f.setPointSize(self.TITLE_SIZE)
        f.setBold(True)
        self.title_height = QFontMetrics(f).lineSpacing() + 2
        self.body_font = f = QFont()
        f.setPointSize(self.BODY_SIZE)
        self.line_height = QFontMetrics(f).lineSpacing()
        self.total_height = max(self.LOGO_SIZE, self.title_height + 3 * self.line_height)
        self.num_font = f = QFont()
        f.setPixelSize(self.total_height)
        f.setItalic(True), f.setBold(True)
        f = QFontMetrics(f)
        self.num_ch = str(max(3, numeric_version[0]))
        self.footer_font = f = QFont()
        f.setPointSize(self.FOOTER_SIZE)
        f.setItalic(True)
        self.dpr = QApplication.instance().devicePixelRatio()
        self.pmap = QPixmap(I('library.png', allow_user_override=False))
        self.pmap.setDevicePixelRatio(self.dpr)
        self.pmap = self.pmap.scaled(int(self.dpr * self.LOGO_SIZE), int(self.dpr * self.LOGO_SIZE), transformMode=Qt.SmoothTransformation)
        self.light_brush = QBrush(QColor('#F6F3E9'))
        self.dark_brush = QBrush(QColor('#39322B'))
        pmap = QPixmap(int(self.WIDTH * self.dpr), int(self.WIDTH * self.dpr))
        pmap.setDevicePixelRatio(self.dpr)
        pmap.fill(Qt.transparent)
        QSplashScreen.__init__(self, pmap)
        self.setWindowTitle(__appname__)

    def drawContents(self, painter):
        self.drawn_once = True
        painter.save()
        painter.setRenderHint(painter.TextAntialiasing, True)
        painter.setRenderHint(painter.Antialiasing, True)
        pw = self.LOGO_SIZE
        height = max(pw, self.total_height)
        width = self.width()

        # Draw frame
        y = (self.height() - height) // 2
        bottom = y + height
        painter.fillRect(0, y, width, height, self.light_brush)
        painter.fillRect(0, y, width, self.title_height, self.dark_brush)
        painter.fillRect(0, y, pw, height, self.dark_brush)
        dy = (height - self.LOGO_SIZE) // 2
        painter.drawPixmap(0, y + dy, self.pmap)

        # Draw number
        painter.setFont(self.num_font)
        num_width = painter.boundingRect(0, 0, 0, 0, Qt.AlignCenter | Qt.TextSingleLine, self.num_ch).width() + 12
        num_x = width - num_width
        painter.setPen(QPen(QColor('#d6b865')))
        painter.drawText(num_x, y, num_width, height, Qt.AlignCenter | Qt.TextSingleLine, self.num_ch)

        # Draw title
        x = pw + 10
        width -= num_width + 5 + x
        painter.setFont(self.title_font)
        painter.drawText(x, y, width, self.title_height, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, "CALIBRE")

        # Draw starting up message
        y += self.title_height + 5
        painter.setPen(QPen(self.dark_brush.color()))
        painter.setFont(self.body_font)
        br = painter.drawText(x, y, width, self.line_height, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, _(
            'Starting up, please wait...'))
        starting_up_bottom = br.bottom()

        # Draw footer
        m = self.message()
        if m and m.strip():
            painter.setFont(self.footer_font)
            b = max(starting_up_bottom + 5, bottom - self.line_height)
            painter.drawText(x, b, width, self.line_height, Qt.AlignLeft | Qt.AlignTop | Qt.TextSingleLine, m)

        painter.restore()

    def show_message(self, msg):
        self.showMessage(msg)
        self.wait_for_draw()

    def wait_for_draw(self):
        # Without this the splash screen is not painted on linux and windows
        self.drawn_once = False
        st = monotonic()
        while not self.drawn_once and (monotonic() - st < 0.1):
            QApplication.instance().processEvents()

    def keyPressEvent(self, ev):
        if not self.develop:
            return QSplashScreen.keyPressEvent(self, ev)
        ev.accept()
        QApplication.instance().quit()