def initUI(self): self.col = QColor(0, 0, 0) redb = QPushButton('Red', self) redb.setCheckable(True) redb.move(10, 10) redb.clicked[bool].connect(self.setColor) greenb = QPushButton('Green', self) greenb.setCheckable(True) greenb.move(10, 60) greenb.clicked[bool].connect(self.setColor) blueb = QPushButton('Blue', self) blueb.setCheckable(True) blueb.move(10, 110) blueb.clicked[bool].connect(self.setColor) self.square = QFrame(self) self.square.setGeometry(150, 20, 100, 100) self.square.setStyleSheet("QWidget { background-color: %s }" % self.col.name()) self.setGeometry(300, 300, 300, 250) self.setWindowTitle('Toggle button') self.show()
def dark_palette(): p = QPalette() disabled_color = QColor(127, 127, 127) p.setColor(QPalette.ColorRole.Window, dark_color) p.setColor(QPalette.ColorRole.WindowText, dark_text_color) p.setColor(QPalette.ColorRole.Base, QColor(18, 18, 18)) p.setColor(QPalette.ColorRole.AlternateBase, dark_color) p.setColor(QPalette.ColorRole.ToolTipBase, dark_color) p.setColor(QPalette.ColorRole.ToolTipText, dark_text_color) p.setColor(QPalette.ColorRole.Text, dark_text_color) p.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Text, disabled_color) p.setColor(QPalette.ColorRole.Button, dark_color) p.setColor(QPalette.ColorRole.ButtonText, dark_text_color) p.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.ButtonText, disabled_color) p.setColor(QPalette.ColorRole.BrightText, Qt.GlobalColor.red) p.setColor(QPalette.ColorRole.Link, dark_link_color) p.setColor(QPalette.ColorRole.Highlight, QColor(0x0b, 0x45, 0xc4)) p.setColor(QPalette.ColorRole.HighlightedText, dark_text_color) p.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.HighlightedText, disabled_color) return p
def getIcon(path): pixmap = QPixmap(path) mask = pixmap.createMaskFromColor(QColor('blue'), QtCore.Qt.MaskMode.MaskOutColor) pixmap.fill((QColor(color))) pixmap.setMask(mask) return QtGui.QIcon(pixmap)
def setupColors(self): self.color = self.primaryColor self.backgroundColor = self.secondaryColor self.animation = QVariantAnimation( startValue=QColor(*self.primaryColor), endValue=QColor(*self.secondaryColor), valueChanged=self.onHover, duration=400) self.borderColor = self.primaryColor
def paint_background(self, painter): br = 12 # border_radius bw = 1 # border_width c = QColor('#fdfd96') p = QPainterPath() p.addRoundedRect(QRectF(self.rect()), br, br) painter.fillPath(p, c) p.addRoundedRect( QRectF(self.rect()).adjusted(bw, bw, -bw, -bw), br, br) painter.fillPath(p, QColor('black'))
def __init__(self, parent): QStyledItemDelegate.__init__(self, parent) pal = parent.palette() self.frames = RotatingIcon(frames=NUM_FRAMES, icon_size=ICON_SIZE).frames self.frame_number = 0 self.dark = pal.color(QPalette.ColorRole.Text) self.light = pal.color(QPalette.ColorRole.Base) self.highlighted_text = QColor( color('tab tree current foreground', Qt.GlobalColor.white)) self.current_background = QBrush( QColor(color('tab tree current background', Qt.GlobalColor.black)))
def __init__(self) -> None: super().__init__() self._initialized = False # type: bool self._light_position = Vector(0, 0, 0) # type: Vector self._background_color = QColor(128, 128, 128) # type: QColor self._viewport_width = 0 # type: int self._viewport_height = 0 # type: int self._window_width = 0 # type: int self._window_height = 0 # type: int self._batches = [] # type: List[RenderBatch] self._named_batches = {} # type: Dict[str, RenderBatch] self._quad_buffer = None # type: QOpenGLBuffer
def __init__(self, parent: 'TableView', df: pd.DataFrame = None): super().__init__(parent) self._df = pd.DataFrame() self._df_orig = pd.DataFrame() self._df_pre_dyn_filter = None self._resort = lambda: None # Null resort functon self._cols = [] self.view = parent self.table_widget = self.view.parent # sketch - could also be dlgs.TableDialog self.formats = parent.formats self.highlight_funcs = parent.highlight_funcs self.m_display = {} # type: Dict[str, Dict[int, Any]] self.m_color_bg = {} # type: Dict[str, Dict[int, Any]] self.m_color_text = {} # type: Dict[str, Dict[int, Any]] self.current_row = -1 self.highlight_rows = True self.selection_color = QColor(cf.config['color']['bg']['yellowrow']) self.display_color = True self.color_enabled = False self.set_queue() self._queue_locked = False self.alignments = {} self.block_resort_style = False if not df is None: self.set_df(df=df)
def drawPolygon(self, polygons): for polygon in polygons: xy = [] for p in polygon[:-1]: x = self.evaluate(p.getX() + self.widget.width() / 2) y = self.evaluate(-p.getY() + self.widget.height() / 2) xy.append(QPoint(x, y)) self.setBrush(QColor(polygon[-1][0])) if self.widget.camera.controler.mode: self.setPen(QColor(polygon[-1][0])) else: self.setPen(QColor('white')) super().drawPolygon(QPolygon(xy)) self.setPen(QColor('white'))
def set_color(style_vals: List[Tuple[str]], i: int) -> Union[QColor, str]: """Convert list of tuples of colors to single color value - may only have background-color, not color Parameters ---------- style_vals : List[Tuple[str]] list of [('background-color', '#E4E4E4'),] i : int either first or last background-color/color tuple Returns ------- Union[QColor, str] single color QColor val or str eg '#E4E4E4' """ try: # style_vals can be [] sometimes? if style_vals: color = style_vals[i][1] color_out = color if not color == '' else None return QColor(color_out) if as_qt and not color_out is None else color_out except Exception: log.warning(f'Failed to get style from: {style_vals}') return None
def paintEvent(self, ev): p = QPainter(self) c = color('tab tree background', None) if c: p.fillRect(ev.rect(), QColor(c)) p.end() QWidget.paintEvent(self, ev)
def initUI(self): col = QColor(0, 0, 0) self.btn = QPushButton('Dialog', self) self.btn.move(20, 20) self.btn.clicked.connect(self.showDialog) self.frm = QFrame(self) self.frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.frm.setGeometry(130, 22, 200, 200) self.setGeometry(300, 300, 450, 350) self.setWindowTitle('Color dialog') self.show()
def update_statusbar(self, msg: str = None, warn: bool = False, success: bool = False, log_: bool = False, *args) -> None: """Statusbar shows temporary messages that disappear on any context event""" if not msg is None: # allow warn or success status to be passed with msg as dict if isinstance(msg, dict): warn = msg.get('warn', False) success = msg.get('success', False) msg = msg.get('msg', None) # kinda sketch if log_: log.info(msg) bar = self.statusBar() self.prev_status = bar.currentMessage() bar.showMessage(msg) msg_lower = msg.lower() if warn or 'warn' in msg_lower or 'error' in msg_lower: color = '#ff5454' # '#fa7070' elif success or 'success' in msg_lower: color = '#70ff94' else: color = 'white' palette = bar.palette() palette.setColor(QPalette.ColorRole.WindowText, QColor(color)) bar.setPalette(palette) self.app.processEvents()
def _setUniformValueDirect(self, uniform: int, value: Union[Vector, Matrix, Color, List[float], List[List[float]], float, int]) -> None: if type(value) is Matrix: cast(QOpenGLShaderProgram, self._shader_program).setUniformValue(uniform, self._matrixToQMatrix4x4( cast(Matrix, value))) elif type(value) is Vector: value = cast(Vector, value) cast(QOpenGLShaderProgram, self._shader_program).setUniformValue(uniform, QVector3D(value.x, value.y, value.z)) elif type(value) is Color: value = cast(Color, value) cast(QOpenGLShaderProgram, self._shader_program).setUniformValue(uniform, QColor(round(value.r * 255), round(value.g * 255), round(value.b * 255), round(value.a * 255))) elif type(value) is list and type(cast(List[List[float]], value)[0]) is list and len( cast(List[List[float]], value)[0]) == 4: value = cast(List[List[float]], value) cast(QOpenGLShaderProgram, self._shader_program).setUniformValue(uniform, self._matrixToQMatrix4x4(Matrix(value))) elif type(value) is list and len(cast(List[float], value)) == 4: value = cast(List[float], value) cast(QOpenGLShaderProgram, self._shader_program).setUniformValue(uniform, QVector4D(value[0], value[1], value[2], value[3])) elif type(value) is list and type(cast(List[List[float]], value)[0]) is list and len(cast(List[List[float]], value)[0]) == 2: value = cast(List[List[float]], value) cast(QOpenGLShaderProgram, self._shader_program).setUniformValueArray(uniform, [QVector2D(i[0], i[1]) for i in value]) elif type(value) is list and len(cast(List[float], value)) == 2: value = cast(List[float], value) cast(QOpenGLShaderProgram, self._shader_program).setUniformValue(uniform, QVector2D(value[0], value[1])) elif type(value) is list and len(cast(List[float], value)) == 3: value = cast(List[float], value) cast(QOpenGLShaderProgram, self._shader_program).setUniformValue(uniform, QVector3D(value[0], value[1], value[2])) else: cast(QOpenGLShaderProgram, self._shader_program).setUniformValue(uniform, cast(Union[float, int], value))
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.col = QColor(0, 0, 0) redb = QPushButton('Red', self) redb.setCheckable(True) redb.move(10, 10) redb.clicked[bool].connect(self.setColor) greenb = QPushButton('Green', self) greenb.setCheckable(True) greenb.move(10, 60) greenb.clicked[bool].connect(self.setColor) blueb = QPushButton('Blue', self) blueb.setCheckable(True) blueb.move(10, 110) blueb.clicked[bool].connect(self.setColor) self.square = QFrame(self) self.square.setGeometry(150, 20, 100, 100) self.square.setStyleSheet("QWidget { background-color: %s }" % self.col.name()) self.setGeometry(300, 300, 300, 250) self.setWindowTitle('Toggle button') self.show() def setColor(self, pressed): source = self.sender() if pressed: val = 255 else: val = 0 if source.text() == "Red": self.col.setRed(val) elif source.text() == "Green": self.col.setGreen(val) else: self.col.setBlue(val) self.square.setStyleSheet("QFrame { background-color: %s }" % self.col.name())
def update_message(self): tm = self.temporary_message col = self.fg_color bold = False is_permanent = True if tm.text and (tm.timeout == 0 or monotonic() - tm.start_time < tm.timeout): text = tm.text if tm.type == 'error': col, bold = QColor('red'), True elif tm.type == 'success': col, bold = QColor('green'), True self.update_timer.start() is_permanent = False else: text = self.permanent_message self.update_timer.stop() self.msg.set_message(text, col, bold, is_permanent)
def mousePressEvent(self, event): if event.buttons() == Qt.MouseButton.LeftButton and (self.parent().parent().drawLineAction.isChecked() \ or self.parent().parent().obsTb.line_newRecButton.isChecked()) and self.gLineItem == None: self.setMouseTracking(True) p1 = self.mapToScene(int(event.position().x()), int(event.position().y())) self.gLineItem = self.scene().addLine(QLineF(p1, p1)) r, g, b = np.random.choice(range(256), size=3) self.gLineItem.setPen(QPen(QColor(0, 0, 0), self.labelSize / 7)) # self.gLineItem.setOpacity(0.25) elif event.buttons() == Qt.MouseButton.LeftButton and (self.parent().parent().maskGenAction.isChecked() \ or self.parent().parent().obsTb.zone_newRecButton.isChecked()): self.setMouseTracking(True) p_clicked = self.mapToScene(int(event.position().x()), int(event.position().y())) if self.gPolyItem == None: self.currentPoly = QPolygonF([p_clicked]) self.gPolyItem = self.scene().addPolygon(self.currentPoly) r, g, b = np.random.choice(range(256), size=3) self.gPolyItem.setPen( QPen(QColor(r, g, b), self.labelSize / 10)) self.gPolyItem.setBrush(QBrush(QColor(r, g, b, 40))) else: self.currentPoly.append(p_clicked) self.gPolyItem.setPolygon(self.currentPoly) elif event.buttons() == Qt.MouseButton.LeftButton and self.parent( ).parent().drawPointAction.isChecked(): p = self.mapToScene(event.x(), event.y()) pointBbx = QRectF() pointBbx.setSize(QSizeF(self.labelSize, self.labelSize)) pointBbx.moveCenter(p) gPointItem = self.scene().addEllipse( pointBbx, QPen(Qt.GlobalColor.white, 0.5), QBrush(Qt.GlobalColor.black)) self.unsavedPoints.append(gPointItem) self.scene().parent().drawPointAction.setChecked(False) self.unsetCursor() elif event.buttons() == Qt.MouseButton.LeftButton: #RightButton: self.parent().parent().play()
def changeBrighteness(self, value): #TODO: Reset the value of brightness, remember the original values # as going back to 0, i.e. keep track of original image's values #TODO: modify values based on original image if (value < -255 | value > 255): return self.image for row_pixel in range(self.image.width()): for col_pixel in range(self.image.height()): current_val = QColor(self.image.pixel(row_pixel, col_pixel)) red = current_val.red() green = current_val.green() blue = current_val.blue() new_red = red + value new_green = green + value new_blue = blue + value # Set the new RGB values for the current pixel if new_red > 255: red = 255 elif new_red < 0: red = 0 else: red = new_red if new_green > 255: green = 255 elif new_green < 0: green = 0 else: green = new_green if new_blue > 255: blue = 255 elif new_blue < 0: blue = 0 else: blue = new_blue new_value = qRgb(red, green, blue) self.image.setPixel(row_pixel, col_pixel, new_value) self.setPixmap(QPixmap().fromImage(self.image))
def headerData(self, section, orientation, role): """Specify the data displayed in the header given the role, section, and orientation of each item.""" if role == Qt.ItemDataRole.DisplayRole: if orientation == Qt.Orientation.Horizontal: return self._headers[section] if role == Qt.ItemDataRole.BackgroundRole: blue_bg = QBrush(QColor("#6EEEF8")) return blue_bg
def changeHue(self): for row_pixel in range(self.image.width()): for col_pixel in range(self.image.height()): current_val = QColor(self.image.pixel(row_pixel, col_pixel)) hue = current_val.hue() current_val.setHsv(hue, current_val.saturation(), current_val.value(), current_val.alpha()) self.image.setPixelColor(row_pixel, col_pixel, current_val) self.setPixmap(QPixmap().fromImage(self.image))
def paintEvent(self, ev): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.TextAntialiasing) f = painter.font() f.setBold(True) f.setPixelSize(self.height() - 1) painter.setFont(f) painter.setPen(QColor('red' if self.is_enabled else 'green')) painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, 'Z') painter.end()
def clearCanvas(self): '''Clear canvas content. Returns: None ''' pixmap = self.pixmap() pixmap.fill(QColor(*self.backgroundColor)) self.setPixmap(pixmap)
class ColorImage(QQuickPaintedItem): def __init__(self, parent=None): super().__init__(parent) self._source = QUrl() self._color = QColor() self._svg_data = b"" self._renderer = None sourceChanged = pyqtSignal() colorChanged = pyqtSignal() def _updateSVG(self) -> None: if not self._source or self._source.toLocalFile() == "": return try: with open(self._source.toLocalFile(), "rb") as f: self._svg_data = f.read() except FileNotFoundError: Logger.log( "w", f"Unable to find image located at {self._source.toLocalFile()}" ) return self._svg_data = self._svg_data.replace( b"<svg ", b"<svg fill=\"%s\" " % self._color.name().encode("utf-8")) self._renderer = QSvgRenderer(self._svg_data) self.update() def setSource(self, source: QUrl) -> None: if self._source != source: self._source = source self.sourceChanged.emit() self._updateSVG() @pyqtProperty(QUrl, fset=setSource, notify=sourceChanged) def source(self) -> QUrl: return self._source def setColor(self, color: QColor) -> None: if self._color != color: self._color = color self.colorChanged.emit() self._updateSVG() @pyqtProperty(QColor, fset=setColor, notify=colorChanged) def color(self) -> QColor: return self._color def paint(self, painter: QPainter) -> None: pixel_ratio = Application.getInstance().getMainWindow( ).effectiveDevicePixelRatio() painter.scale(1 / pixel_ratio, 1 / pixel_ratio) if self._renderer: self._renderer.render(painter)
def RGBAtuple_to_RGBAQColor(tup): if not isinstance(tup, tuple): raise TypeError(f'Invalid argument type {type(tup)}, expected tuple') if len(tup) < 3: raise ValueError( f'Missing RGBA values in tuple, {tup}, expected at least 3') qcolor = QColor(*tup) return qcolor
def __init__(self, parent = None): super().__init__(parent) # FIXME: As of time of writing, you can not reference flags by name in QT6 # You can find the list of flags by value here https://doc.qt.io/qt-6/qquickitem.html#Flag-enum # This flag is QQuickItem::ItemHasContents self.setFlag(QQuickItem.Flag(8)) self._arrow_size = 0 self._color = QColor(255, 255, 255, 255) self._target = QPoint(0,0) self._border_width = 0 self._border_color = QColor(0, 0, 0, 255) self._geometry = None self._material = None self._node = None self._border_geometry = None self._border_material = None self._border_node = None
def __init__(self, parent, sb_background): QWidget.__init__(self, parent) self.is_permanent = False self.is_address = False self.is_secure = False self.static_text = None self.current_key = None self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.sb_background = QColor( color(sb_background, self.palette().color(QPalette.ColorRole.Window)))
def add_widget(self, widget): ''' Add widget.''' # Init background color before addWidget. if not hasattr(self, "background_color"): self.background_color = QColor(self.theme_background_color) self.buffer_widget = widget self.addWidget(self.buffer_widget) self.buffer_widget.installEventFilter(self) self.buffer_widget.buffer = self
def paintEvent(self, ev): if not self.static_text or not self.static_text.text(): return p = QPainter(self) p.setRenderHint(QPainter.RenderHint.TextAntialiasing) # If text is too long too fit, fade it out at the end self.static_text.setTextWidth(self.rect().width()) sz = self.static_text.size() r = self.rect() p.drawStaticText(0, int(r.height() - sz.height()) // 2, self.static_text) if sz.width() > r.width(): g = QLinearGradient(QPointF(self.rect().topLeft()), QPointF(self.rect().topRight())) c = QColor(self.sb_background) c.setAlpha(0) g.setColorAt(0, c) g.setColorAt(0.8, c) g.setColorAt(1.0, self.sb_background) p.fillRect(self.rect(), QBrush(g)) p.end()
def convertToSepia(self): """Convert image to sepia filter.""" #TODO: Sepia #704214 rgb(112, 66, 20) #TODO: optimize speed that the image converts, or add to thread if self.image.isNull() == False: for row_pixel in range(self.image.width()): for col_pixel in range(self.image.height()): current_val = QColor(self.image.pixel( row_pixel, col_pixel)) # Calculate r, g, b values for current pixel red = current_val.red() green = current_val.green() blue = current_val.blue() new_red = int(0.393 * red + 0.769 * green + 0.189 * blue) new_green = int(0.349 * red + 0.686 * green + 0.168 * blue) new_blue = int(0.272 * red + 0.534 * green + 0.131 * blue) # Set the new RGB values for the current pixel if new_red > 255: red = 255 else: red = new_red if new_green > 255: green = 255 else: green = new_green if new_blue > 255: blue = 255 else: blue = new_blue new_value = qRgb(red, green, blue) self.image.setPixel(row_pixel, col_pixel, new_value) self.setPixmap(QPixmap().fromImage(self.image)) self.repaint()
def changeContrast(self, contrast): """Change the contrast of the pixels in the image. Contrast is the difference between max and min pixel intensity.""" for row_pixel in range(self.image.width()): for col_pixel in range(self.image.height()): # Calculate a contrast correction factor factor = float(259 * (contrast + 255) / (255 * (259 - contrast))) current_val = QColor(self.image.pixel(row_pixel, col_pixel)) red = current_val.red() green = current_val.green() blue = current_val.blue() new_red = factor * (red - 128) + 128 new_green = factor * (green - 128) + 128 new_blue = factor * (blue - 128) + 128 new_value = qRgb(new_red, new_green, new_blue) self.image.setPixel(row_pixel, col_pixel, new_value) self.setPixmap(QPixmap().fromImage(self.image))