def __init__(self, logger, opts): QGraphicsScene.__init__(self) self.logger, self.opts = logger, opts self.pages = [] self.chapters = [] self.chapter_layout = None self.current_screen = None self.current_page = 0 self.link_map = {} self.chapter_map = {} self.history = History() self.last_search = iter([]) if not opts.white_background: self.setBackgroundBrush(QBrush(QColor(0xee, 0xee, 0xee)))
def rasterize_svg(self, elem, width=0, height=0, format='PNG'): view_box = elem.get('viewBox', elem.get('viewbox', None)) sizes = None logger = self.oeb.logger if view_box is not None: try: box = [ float(x) for x in [_f for _f in re.split('[, ]', view_box) if _f] ] sizes = [box[2] - box[0], box[3] - box[1]] except (TypeError, ValueError, IndexError): logger.warn( 'SVG image has invalid viewBox="%s", ignoring the viewBox' % view_box) else: for image in elem.xpath( 'descendant::*[local-name()="image" and ' '@height and contains(@height, "%")]'): logger.info( 'Found SVG image height in %, trying to convert...') try: h = float(image.get('height').replace('%', '')) / 100. image.set('height', str(h * sizes[1])) except: logger.exception( 'Failed to convert percentage height:', image.get('height')) data = QByteArray(xml2str(elem, with_tail=False)) svg = QSvgRenderer(data) size = svg.defaultSize() if size.width() == 100 and size.height() == 100 and sizes: size.setWidth(sizes[0]) size.setHeight(sizes[1]) if width or height: size.scale(width, height, Qt.KeepAspectRatio) logger.info('Rasterizing %r to %dx%d' % (elem, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) painter.end() array = QByteArray() buffer = QBuffer(array) buffer.open(QIODevice.WriteOnly) image.save(buffer, format) return str(array)
def get_pixel_map(): ' Get the order of pixels in QImage (RGBA or BGRA usually) ' global _qimage_pixel_map if _qimage_pixel_map is None: i = QImage(1, 1, QImage.Format_ARGB32) i.fill(QColor(0, 1, 2, 3)) raw = bytearray(i.constBits().asstring(4)) _qimage_pixel_map = { c: raw.index(x) for c, x in zip('RGBA', b'\x00\x01\x02\x03') } _qimage_pixel_map = ''.join( sorted(_qimage_pixel_map, key=_qimage_pixel_map.get)) return _qimage_pixel_map
def create_icon(text, palette=None, sz=32, divider=2): if palette is None: palette = QApplication.palette() img = QImage(sz, sz, QImage.Format_ARGB32) img.fill(Qt.transparent) p = QPainter(img) p.setRenderHints(p.TextAntialiasing | p.Antialiasing) qDrawShadeRect(p, img.rect(), palette, fill=QColor('#ffffff'), lineWidth=1, midLineWidth=1) f = p.font() f.setFamily('Liberation Sans'), f.setPixelSize(sz // divider), f.setBold(True) p.setFont(f), p.setPen(Qt.black) p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text) p.end() return QIcon(QPixmap.fromImage(img))
def set_color(self): r, g, b = gprefs['cover_grid_color'] tex = gprefs['cover_grid_texture'] pal = self.palette() pal.setColor(QPalette.ColorRole.Base, QColor(r, g, b)) self.setPalette(pal) ss = '' if tex: from calibre.gui2.preferences.texture_chooser import texture_path path = texture_path(tex) if path: path = os.path.abspath(path).replace(os.sep, '/') ss += 'background-image: url({});'.format(path) ss += 'background-attachment: fixed;' pm = QPixmap(path) if not pm.isNull(): val = pm.scaled(1, 1).toImage().pixel(0, 0) r, g, b = qRed(val), qGreen(val), qBlue(val) dark = max(r, g, b) < 115 col = '#eee' if dark else '#111' ss += 'color: {};'.format(col) self.delegate.highlight_color = QColor(col) self.setStyleSheet('QListView {{ {} }}'.format(ss))
def add_borders_to_image(img, left=0, top=0, right=0, bottom=0, border_color='#ffffff'): img = image_from_data(img) if not (left > 0 or right > 0 or top > 0 or bottom > 0): return img canvas = QImage(img.width() + left + right, img.height() + top + bottom, QImage.Format_RGB32) canvas.fill(QColor(border_color)) overlay_image(img, canvas, left, top) return canvas
def __init__(self, doc): QSyntaxHighlighter.__init__(self, doc) self.colors = {} self.colors['doctype'] = QColor(192, 192, 192) self.colors['entity'] = QColor(128, 128, 128) self.colors['tag'] = QColor(136, 18, 128) self.colors['comment'] = QColor(35, 110, 37) self.colors['attrname'] = QColor(153, 69, 0) self.colors['attrval'] = QColor(36, 36, 170)
def paintEvent(self, event): QWidget.paintEvent(self, event) pmap = self._pixmap if pmap.isNull(): return w, h = pmap.width(), pmap.height() ow, oh = w, h cw, ch = self.rect().width(), self.rect().height() scaled, nw, nh = fit_image(w, h, cw, ch) if scaled: pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) w, h = pmap.width(), pmap.height() x = int(abs(cw - w) / 2.) y = int(abs(ch - h) / 2.) target = QRect(x, y, w, h) p = QPainter(self) p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) p.drawPixmap(target, pmap) if self.draw_border: pen = QPen() pen.setWidth(self.BORDER_WIDTH) p.setPen(pen) p.drawRect(target) if self.show_size: sztgt = target.adjusted(0, 0, 0, -4) f = p.font() f.setBold(True) p.setFont(f) sz = u'\u00a0%d x %d\u00a0' % (ow, oh) flags = Qt.AlignBottom | Qt.AlignRight | Qt.TextSingleLine szrect = p.boundingRect(sztgt, flags, sz) p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200)) p.setPen(QPen(QColor(255, 255, 255))) p.drawText(sztgt, flags, sz) p.end()
def paintEvent(self, event): canvas_size = self.rect() width = self.current_pixmap_size.width() extrax = canvas_size.width() - width if extrax < 0: extrax = 0 x = int(extrax // 2) height = self.current_pixmap_size.height() extray = canvas_size.height() - height if extray < 0: extray = 0 y = int(extray // 2) target = QRect(x, y, width, height) p = QPainter(self) p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() spmap = self.pixmap.scaled(target.size() * dpr, Qt.KeepAspectRatio, Qt.SmoothTransformation) spmap.setDevicePixelRatio(dpr) p.drawPixmap(target, spmap) if gprefs['bd_overlay_cover_size']: sztgt = target.adjusted(0, 0, 0, -4) f = p.font() f.setBold(True) p.setFont(f) sz = '\u00a0%d x %d\u00a0' % (self.pixmap.width(), self.pixmap.height()) flags = Qt.AlignBottom | Qt.AlignRight | Qt.TextSingleLine szrect = p.boundingRect(sztgt, flags, sz) p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200)) p.setPen(QPen(QColor(255, 255, 255))) p.drawText(sztgt, flags, sz) p.end()
def generarTablaPer(self): # habilito botones self.cambiarEstadoBoton(self.botonCalPert, True) self.cambiarEstadoBoton(self.botonNewPert, True) # guardo el numero de las actividades self.numActividades = int(self.spinNumPert.text()) # limpiar tabla self.tablaActividades.clear() # numero de filas self.tablaActividades.setRowCount(self.numActividades) # numero de columnas self.tablaActividades.setColumnCount(18) # ponemos los titulos de la columna self.listColumnas = [ " Actividad ", " Detalle ", " Predecesores ", " To ", " Tn ", " Tp ", " D i,j ", " O i,j ", " Ti0 ", " Ti1 ", " Tj0 ", " Tj1 ", " MT i,j ", " MI i,j ", " Fecha Inicio temprano ", " Fecha Inicio tardío ", " Fecha Fin temprano ", " Fecha Fin tardío " ] # insertar columnas for i in range(18): item = QTableWidgetItem(self.listColumnas[i]) item.setBackground(QtGui.QColor(21, 30, 61)) item.setForeground(QBrush(QColor(255, 223, 0))) self.tablaActividades.setHorizontalHeaderItem(i, item) # insertat celdas for j in range(self.numActividades): for k in range(18): item = QTableWidgetItem("") self.tablaActividades.setItem(j, k, item) self.tablaActividades.resizeColumnsToContents() # lista de actividades self.listadeActividades = [] # poner las letras del abecedario self.letras = list(map(chr, range(65, 91))) # Lista de A - Z for i in range(self.numActividades): celda = QTableWidgetItem(self.letras[i]) self.listadeActividades.append(self.letras[i]) # celda.setTextAlignment(Qt.AlignHCenter) self.tablaActividades.setItem(i, 0, celda) self.show_popup_InformacionP( "Guía", "Los precedesores de las actividades deben ser ingresados separados por comas, asi A,B\nPara las actividades sin predecesores debe ingresar N/A" )
def __InitData(self): # self.__size = QSize(480,460) # self.__size = QSize(280, 280) self.__size = QSize(600, 600) self.__board = QPixmap(self.__size) # 新建QPixmap作为画板,宽350px,高250px self.__board.fill(Qt.black) # 用白色填充画板 self.__IsEmpty = True # 默认为空画板 self.EraserMode = False # 默认为禁用橡皮擦模式 self.__lastPos = QPoint(0, 0) self.__currentPos = QPoint(0, 0) self.__painter = QPainter() self.__painter.setRenderHints(QPainter.Antialiasing, True) self.__thickness = 60 # 默认画笔粗细为20px self.__penColor = QColor("white") # 设置默认画笔颜色为黑色 self.__colorList = QColor.colorNames() # 获取颜色列表
def __fillColorList(self, comboBox): index_black = 0 index = 0 for color in self.__colorList: if color == "black": index_black = index index += 1 pix = QPixmap(70, 20) pix.fill(QColor(color)) comboBox.addItem(QIcon(pix), None) comboBox.setIconSize(QSize(70, 20)) comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents) comboBox.setCurrentIndex(index_black)
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.PenStyle.NoPen)) self.setCursor(Qt.CursorShape.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)
def dark_palette(): p = QPalette() dark_color = QColor(45,45,45) disabled_color = QColor(127,127,127) text_color = QColor('#eee') p.setColor(p.Window, dark_color) p.setColor(p.WindowText, text_color) p.setColor(p.Base, QColor(18,18,18)) p.setColor(p.AlternateBase, dark_color) p.setColor(p.ToolTipBase, dark_color) p.setColor(p.ToolTipText, text_color) p.setColor(p.Text, text_color) p.setColor(p.Disabled, p.Text, disabled_color) p.setColor(p.Button, dark_color) p.setColor(p.ButtonText, text_color) p.setColor(p.Disabled, p.ButtonText, disabled_color) p.setColor(p.BrightText, Qt.red) p.setColor(p.Link, dark_link_color) p.setColor(p.Highlight, dark_link_color) p.setColor(p.HighlightedText, Qt.black) p.setColor(p.Disabled, p.HighlightedText, disabled_color) return p
def draw_sized_text(img, dw, line, top, left_margin, right_margin, auto_reduce_font): from PyQt5.Qt import QPainter, Qt, QRect, QColor total_margin = left_margin + right_margin if img.size[0] - total_margin <= 0: total_margin = 0 left_margin = 0 right_margin = 0 p = QPainter(img.img) p.setRenderHint(p.TextAntialiasing) pen = p.pen() pen.setColor(QColor(dw.fill_color)) p.setPen(pen) flags = line._align try: if auto_reduce_font: line_width = img.size[0] - total_margin initial_font_size = line.font.pixelSize() text = line.text while True: f = line.font p.setFont(f) br = p.boundingRect( 0, 0, line_width, 100, flags | Qt.TextSingleLine, text) if br.width() < line_width: break oversize_factor = br.width() / line_width if oversize_factor > 10: f.setPixelSize(f.pixelSize() - 8) elif oversize_factor > 5: f.setPixelSize(f.pixelSize() - 4) elif oversize_factor > 3: f.setPixelSize(f.pixelSize() - 2) else: f.setPixelSize(f.pixelSize() - 1) if f.pixelSize() < 6: # Enough is enough, clearly cannot fit on one line! # Abort the font reduction process f.setPixelSize(initial_font_size) line.text = '*** TEXT TOO LARGE TO AUTO-FIT ***' break p.setFont(line.font) br = p.drawText(QRect( left_margin, top, img.size[0] - left_margin - right_margin, img.size[1] - top), flags | Qt.TextWordWrap, line.text) return br.bottom() finally: p.end()
def add_experiment(self, exp, refresh_table=True): # add experiment to plots self.plots.add(exp.enumerate_plots()) self.experiments[exp.name] = exp # ensure it has a style assigned, even if it has no plots if len(exp.style) == 0: (exp.style_order, exp.style) = next(self.plots.style_generator) # add experiment to table (table, table_args) = (self.table, self.table_args) header = table.horizontalHeader() # disable sorting to prevent bug when adding items. will be restored by refresh_table. self.prev_sort = (header.sortIndicatorSection(), header.sortIndicatorOrder()) # save state table.setSortingEnabled(False) # new row row = table.rowCount() table.insertRow(row) # create icon (label with unicode symbol) with the plot color. u'\u2611 \u2610' icon = self.set_table_cell(row, 0, u'\u2611') icon.setForeground(QColor(exp.style.get('color', '#808080'))) # store experiment name with icon, to be retrieved later in table_click icon.setData(Qt.UserRole, 'hide') icon.setData(Qt.UserRole + 1, exp.name) # experiment name label = self.set_table_cell(row, 1, exp.name) label.setData(Qt.UserRole, 'select') label.setData(Qt.UserRole + 1, exp.name) # print a row of argument values for this experiment for arg_name in exp.meta.keys(): if not arg_name.startswith('_'): if arg_name not in table_args: # a new argument name, add a column col = table.columnCount() table.setColumnCount(col + 1) table.setHorizontalHeaderItem(col, QtWidgets.QTableWidgetItem(arg_name)) #, QtWidgets.QTableWidgetItem.Type table_args[arg_name] = col else: col = table_args[arg_name] self.set_table_cell(row, col, exp.meta.get(arg_name, '')) if refresh_table: self.refresh_table()
def in_table(): # is exists table in document ? c = QTextCursor(doc.text) c.movePosition(QTextCursor.Start) _in_table = False while c.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor): if doc.in_table(): _in_table = True doc.background_color("blue") cc = doc._text_edit_cursor cell = cc.currentTable().cellAt(cc).format() clr = cell.background().color().name() self.assertEqual(clr, QColor("blue").name()) break return _in_table
def paintEvent(self, QPaintEvent): pen = QPen() pen.setWidth(self.__circle_width) painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(pen) # Paint line to origin painter.drawPath(self.line_path) # Paint circle q = QColor(Qt.white) painter.setBrush(q) painter.drawEllipse(self.__handle_pos, self.__radius, self.__radius) painter.end()
def __init__(self, parent, qml=''): """初始化widget. :param parent: 显示窗口 :param qml: 具体加载的qml 默认为 'GUI/py_ui/toast.qml' """ self.toast = QtQuickWidgets.QQuickWidget(parent) # 设置为透明和允许显示 self.toast.setClearColor(QColor(Qt.transparent)) self.toast.setAttribute(Qt.WA_AlwaysStackOnTop) self.parent = parent if not qml: qml = './py_ui/toast.qml' self.toast.setSource(QUrl(qml)) # widget是透明的,可以先设置状态 self.show()
def color(self, val): val = unicode_type(val or '') col = QColor(val) orig = self._color if col.isValid(): self._color = val self.setText(val) p = QPixmap(self.iconSize()) p.fill(col) self.setIcon(QIcon(p)) else: self._color = None self.setText(self.choose_text) self.setIcon(QIcon()) if orig != col: self.color_changed.emit(self._color)
def __init__(self, text, rect, right_align=False, color_role=QPalette.WindowText, swatch=None, is_overriden=False): self.rect, self.text = rect, text self.right_align = right_align self.is_overriden = is_overriden self.color_role = color_role self.override_color = None self.swatch = swatch if swatch is not None: self.swatch = QColor(swatch[0], swatch[1], swatch[2], int(255 * swatch[3]))
def set_ui(self): self.setWindowTitle('Register') self.setObjectName('register') self.resize(self.w, self.h) self.top_wi.setObjectName('top') self.top_wi.resize(930 * self.xr, 95 * self.yr) self.logo_la.setObjectName('logo') self.logo_la.resize(65 * self.xr, 65 * self.zr) self.logo_la.move(29 * self.xr, 16 * self.yr) effect = QGraphicsDropShadowEffect() effect.setOffset(10, 10) effect.setColor(QColor(0, 0, 0, 80)) effect.setBlurRadius(20) self.ind_wi.setObjectName('login') self.ind_wi.resize(327 * self.xr, 388 * self.yr) self.ind_wi.move(300 * self.xr, 150 * self.yr) self.ind_wi.setGraphicsEffect(effect) self.register_but.setObjectName('button') self.register_but.move(64 * self.xr, 315 * self.yr) self.register_but.resize(202 * self.xr, 45 * self.yr) self.register_but.setText('注册新用户') self.register_but.clicked.connect(self.register) self.imp_la.setObjectName('imp_label') self.imp_la.resize(100 * self.zr, 100 * self.zr) self.imp_la.move(115 * self.xr + 100 * (self.xr - self.zr) / 2, 15 * self.yr) self.imp_la.setStyleSheet('border-radius:{}px;'.format(self.zr * 49)) self.account_le.setObjectName('input') self.account_le.setTextMargins(20, 0, 0, 0) self.account_le.resize(213 * self.xr, 45 * self.yr) self.account_le.move(59 * self.xr, 126 * self.yr) self.account_le.setPlaceholderText('账号') self.psw_le.setObjectName('input') self.psw_le.setTextMargins(20, 0, 0, 0) self.psw_le.resize(213 * self.xr, 45 * self.yr) self.psw_le.move(59 * self.xr, 181 * self.yr) self.psw_le.setPlaceholderText('密码') self.psw_le.setEchoMode(QLineEdit.Password) self.name_le.setObjectName('input') self.name_le.setTextMargins(20, 0, 0, 0) self.name_le.resize(213 * self.xr, 45 * self.yr) self.name_le.move(59 * self.xr, 236 * self.yr) self.name_le.setPlaceholderText('昵称') self.ind_wi.setStyleSheet('#input{border-radius:' + str(self.zr * 20) + 'px;}' + '#button{border-radius:' + str(self.zr * 20) + 'px;' + 'font-size:' + str(int(self.zr * 18)) + 'px;}')
def __init__(self, parent): QStackedWidget.__init__(self, parent) self.permanent_message = '' self.temporary_message = TemporaryMessage(1, '', 'info', monotonic()) self.msg = Message(self, parent.sb_background) self.addWidget(self.msg) self.setFocusPolicy(Qt.NoFocus) self.msg.setFocusPolicy(Qt.NoFocus) self.search = SearchPanel(self) self.search.edit.abort_search.connect(self.hide_search) self.search.edit.editingFinished.connect(self.hide_search) self.addWidget(self.search) self.update_timer = t = QTimer(self) self.fg_color = color('status bar foreground', None) if self.fg_color: self.fg_color = QColor(self.fg_color) t.setSingleShot(True), t.setInterval(100), t.timeout.connect(self.update_message)
def quantize_image(img, max_colors=256, dither=True, palette=''): ''' Quantize the image to contain a maximum of `max_colors` colors. By default a palette is chosen automatically, if you want to use a fixed palette, then pass in a list of color names in the `palette` variable. If you, specify a palette `max_colors` is ignored. Note that it is possible for the actual number of colors used to be less than max_colors. :param max_colors: Max. number of colors in the auto-generated palette. Must be between 2 and 256. :param dither: Whether to use dithering or not. dithering is almost always a good thing. :param palette: Use a manually specified palette instead. For example: palette='red green blue #eee' ''' img = image_from_data(img) if img.hasAlphaChannel(): img = blend_image(img) if palette and isinstance(palette, basestring): palette = palette.split() return imageops.quantize(img, max_colors, dither, [QColor(x).rgb() for x in palette])
def change_color(self, which, reset=False): if reset: setattr(self, 'current_%s_color'%which, None) else: initial = getattr(self, 'current_%s_color'%which) if initial: initial = QColor(initial) else: initial = Qt.black if which == 'text' else Qt.white title = (_('Choose text color') if which == 'text' else _('Choose background color')) col = QColorDialog.getColor(initial, self, title, QColorDialog.ShowAlphaChannel) if col.isValid(): name = unicode(col.name()) setattr(self, 'current_%s_color'%which, name) self.update_sample_colors()
def format_text(self, formatting): if self.syntax != 'html': return if formatting.startswith('justify_'): return self.smarts.set_text_alignment( self, formatting.partition('_')[-1]) color = 'currentColor' if formatting in {'color', 'background-color'}: color = QColorDialog.getColor( QColor(Qt.GlobalColor.black if formatting == 'color' else Qt.GlobalColor.white), self, _('Choose color'), QColorDialog.ColorDialogOption.ShowAlphaChannel) if not color.isValid(): return r, g, b, a = color.getRgb() if a == 255: color = 'rgb(%d, %d, %d)' % (r, g, b) else: color = 'rgba(%d, %d, %d, %.2g)' % (r, g, b, a / 255) prefix, suffix = { 'bold': ('<b>', '</b>'), 'italic': ('<i>', '</i>'), 'underline': ('<u>', '</u>'), 'strikethrough': ('<strike>', '</strike>'), 'superscript': ('<sup>', '</sup>'), 'subscript': ('<sub>', '</sub>'), 'color': ('<span style="color: %s">' % color, '</span>'), 'background-color': ('<span style="background-color: %s">' % color, '</span>'), }[formatting] left, right = self.get_range_inside_tag() c = self.textCursor() c.setPosition(left) c.setPosition(right, QTextCursor.MoveMode.KeepAnchor) prev_text = unicode_type(c.selectedText()).rstrip('\0') c.insertText(prefix + prev_text + suffix) if prev_text: right = c.position() c.setPosition(left) c.setPosition(right, QTextCursor.MoveMode.KeepAnchor) else: c.setPosition(c.position() - len(suffix)) self.setTextCursor(c)
def create_icon(text, palette=None, sz=None, divider=2, fill='white'): if isinstance(fill, str): fill = QColor(fill) sz = sz or int(math.ceil(tprefs['toolbar_icon_size'] * QApplication.instance().devicePixelRatio())) if palette is None: palette = QApplication.palette() img = QImage(sz, sz, QImage.Format_ARGB32) img.fill(Qt.transparent) p = QPainter(img) p.setRenderHints(p.TextAntialiasing | p.Antialiasing) if fill is not None: qDrawShadeRect(p, img.rect(), palette, fill=fill, lineWidth=1, midLineWidth=1) f = p.font() f.setFamily('Liberation Sans'), f.setPixelSize(int(sz // divider)), f.setBold(True) p.setFont(f), p.setPen(Qt.black) p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text) p.end() return QIcon(QPixmap.fromImage(img))
def __InitData(self, sizeX, sizeY): self.__size = QSize(sizeX, sizeY) self.__board = QPixmap( self.__size) #Make a new QPixmap as paint board,350px * 250px self.__board.fill(Qt.white) #Fill the paint board with white self.__IsEmpty = True #board is empty by default self.EraserMode = False #eraser mode is disabled by default self.__lastPos = None self.__currentPos = QPoint(0, 0) self.__painter = QPainter() self.__thickness = 1 #default pen thickness is 1 self.__penColor = QColor("black") #default color is black self.__colorList = QColor.colorNames() #get the list of colors
def fillFlagCB(self, cur_flag_id=None): """Заполняем combobox данными о флагах""" con = sqlite3.connect(self.data_base) cur = con.cursor() flags = cur.execute( f'SELECT id, title, red, green, blue FROM flags WHERE category = {self.category_id}' ) index = 0 for id_, title, r, g, b in flags: self.cbFlags.addItem(FlagIcon(QColor(r, g, b)), title, userData=id_) if cur_flag_id is not None and id_ == cur_flag_id: self.cbFlags.setCurrentIndex(index) index += 1 self.cbFlags.addItem('Без флага', userData=None) if cur_flag_id is None: self.cbFlags.setCurrentIndex(index)
def __InitData(self): self.__size = QSize(1600,1200) self.__board = QPixmap(self.__size) #新建QPixmap作为画板,宽350px,高250px self.__board.fill(Qt.white) #用白色填充画板 self.__IsEmpty = True #默认为空画板 self.EraserMode = False #默认为禁用橡皮擦模式 self.__lastPos = QPoint(0,0) self.__currentPos = QPoint(0,0) self.__painter = QPainter() self.__thickness = 10 #默认画笔粗细为10px self.__penColor = QColor("black") #设置默认画笔颜色为黑色 self.__colorList = QColor.colorNames() #获取颜色列表