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 drawRectangles(self, qp): col = QColor(0, 0, 0) col.setNamedColor('#d4d4d4') qp.setPen(col) qp.setBrush(QColor(200, 0, 0)) qp.drawRect(10, 15, 90, 60) qp.setBrush(QColor(255, 80, 0, 160)) qp.drawRect(130, 15, 90, 60) qp.setBrush(QColor(25, 0, 90, 200)) qp.drawRect(250, 15, 90, 60)
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 __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 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))
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 interp(self, c0: QColor, c1: QColor, pct: int, cspace: Optional[QColor.Spec] = QColor.Spec.Rgb) -> QColor: if cspace is None: if pct == 100: return QColor(*c1.getRgb()) else: return QColor(*c0.getRgb()) out = QColor() if cspace == QColor.Spec.Rgb: col1 = Rgba(*c0.getRgb()) col2 = Rgba(*c1.getRgb()) comp = col1.get_pct_interp(col2, pct) out.setRgb(*comp) else: raise ValueError("Invalid colorspace") out = out.convertTo(c0.spec()) return out
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 clearCanvas(self): '''Clear canvas content. Returns: None ''' pixmap = self.pixmap() pixmap.fill(QColor(*self.backgroundColor)) self.setPixmap(pixmap)
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 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 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 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 __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, text, rect, parent=None): super().__init__(text, parent) self.setStyleSheet("color: white;") self.setGeometry(QRect(rect)) self.setAlignment(Qt.AlignmentFlag.AlignCenter) self.setWordWrap(True) self.font = QFont("Helvetica") self.font.setPixelSize(72) self.setFont(self.font) shadow = QGraphicsDropShadowEffect(self) shadow.setBlurRadius(40) shadow.setColor(QColor("black")) shadow.setOffset(3) self.setGraphicsEffect(shadow)
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 drawWidget(self, qp): MAX_CAPACITY = 700 OVER_CAPACITY = 750 font = QFont('Serif', 7, QFont.Weight.Light) qp.setFont(font) size = self.size() w = size.width() h = size.height() step = int(round(w / 10)) till = int(((w / OVER_CAPACITY) * self.value)) full = int(((w / OVER_CAPACITY) * MAX_CAPACITY)) if self.value >= MAX_CAPACITY: qp.setPen(QColor(255, 255, 255)) qp.setBrush(QColor(255, 255, 184)) qp.drawRect(0, 0, full, h) qp.setPen(QColor(255, 175, 175)) qp.setBrush(QColor(255, 175, 175)) qp.drawRect(full, 0, till - full, h) else: qp.setPen(QColor(255, 255, 255)) qp.setBrush(QColor(255, 255, 184)) qp.drawRect(0, 0, till, h) pen = QPen(QColor(20, 20, 20), 1, Qt.PenStyle.SolidLine) qp.setPen(pen) qp.setBrush(Qt.BrushStyle.NoBrush) qp.drawRect(0, 0, w - 1, h - 1) j = 0 for i in range(step, 10 * step, step): qp.drawLine(i, 0, i, 5) metrics = qp.fontMetrics() fw = metrics.horizontalAdvance(str(self.num[j])) x, y = int(i - fw / 2), int(h / 2) qp.drawText(x, y, str(self.num[j])) j = j + 1
def createTable(self): # # Define the max number of rows and the colomns. Lable the columns # with letters of the alphabet like spreadsheets since VisiCalc. # self.maxRows = 99 self.headerLabels = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ] self.tableWidget = QTableWidget() self.tableWidget.setRowCount(self.maxRows) self.tableWidget.setColumnCount(len(self.headerLabels)) self.tableWidget.setHorizontalHeaderLabels(self.headerLabels) # Pre-populate the cells in the spreadsheets with data, strings in # this example. # for row in range(0, self.maxRows): for col in range(0, len(self.headerLabels)): self.tableWidget.setItem( row, col, QTableWidgetItem("Cell {0}{1}".format( self.headerLabels[col], row + 1))) # # Set every other row a light green color to help readability. # if row % 2 != 0: self.tableWidget.item(row, col).setBackground( QColor(220, 255, 220)) self.tableWidget.move(0, 0) # # The next two function calls 'tighten up' the space around the text # items inserted into each cell. # self.tableWidget.resizeColumnsToContents() self.tableWidget.resizeRowsToContents() # Hook various events to their respective callbacks. # self.tableWidget.cellClicked.connect(self.cellClicked) self.tableWidget.cellChanged.connect(self.cellChanged) self.tableWidget.cellActivated.connect(self.cellActivated) self.tableWidget.cellEntered.connect(self.cellEntered) self.tableWidget.cellPressed.connect(self.cellPressed)
def mouseMoveEvent(self, event): if self.xCache == None: self.xCache = event.position().x() self.yCache = event.position().y() else: painter = QPainter(self.canvas) pen = painter.pen() pen.setWidth(self.strokeWidth) pen.setColor(QColor(*self.color)) pen.setStyle(self.strokeStyle) painter.setPen(pen) painter.drawLine(self.xCache, self.yCache, event.position().x(), event.position().y()) painter.end() self.setPixmap(self.canvas) self.xCache = event.position().x() self.yCache = event.position().y()