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 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 __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 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 data(self, index, role): """Handles how the the items are displayed in the table using roles.""" if index.isValid(): # data is the text displayed for every index in the table data = self.data[index.row()][index.column()] if role == Qt.ItemDataRole.DisplayRole: return data # Demonstrates how to set bold text for a specific column if role == Qt.ItemDataRole.FontRole and index.column() == 0: bold_font = QFont() bold_font.setBold(True) return bold_font # Demonstrates how to set the background color in order to highlight # specific cells that contain desired values if role == Qt.ItemDataRole.BackgroundRole and "Brown Trout" in data: blue_bg = QBrush(QColor("#6EEEF8")) return blue_bg
def data(self, index, role): """Return the data values at the specific index based upon the given role.""" if index.isValid(): # data is the text displayed for every index in the table data = self._data[index.row()][index.column()] if role == Qt.ItemDataRole.DisplayRole \ or role == Qt.ItemDataRole.EditRole: # Use values from _headers to set the text for # each table's last row if index.row() == len(self._data) - 1 and index.column() == 0: if "Money In" in self._headers: return "Total Income" if "Money Out" in self._headers: return "Total Expenses" if "Money Left Over" in self._headers: return "Income Minus Expenses" if index.column() == 1: total = 0.0 for item in self._data: value = float(item[1].replace("$", "")) total += value if index.row() == len(self._data) - 1: return f"${total:.2f}" self.values_edited.emit( ) # Initialize the values in the beginning return data if role == Qt.ItemDataRole.TextAlignmentRole and index.column() == 1: return Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter if role == Qt.ItemDataRole.BackgroundRole and index.row() == len( self._data) - 1: grey_bg = QBrush(QColor("#C5CDD4")) return grey_bg
def get_masked_image(path, size=64, overlay_text=""): """ Returns a pixmap from an image file masked with a smooth circle. The returned pixmap will have a size of *size* × *size* pixels. :param str path: Path to image file. :param int size: Target size. Will be the diameter of the masked image. :param str overlay_text: Overlay text. This will be shown in white sans-serif on top of the image. :return: Masked image with overlay text. :rtype: QPixmap """ with open(path, "rb") as f: imgdata = f.read() imgtype = path.split(".")[-1] # Load image and convert to 32-bit ARGB (adds an alpha channel): image = QImage.fromData(imgdata, imgtype) image.convertToFormat(QImage.Format.Format_ARGB32) # Crop image to a square: imgsize = min(image.width(), image.height()) width = (image.width() - imgsize) / 2 height = (image.height() - imgsize) / 2 rect = QRect( round(width), round(height), imgsize, imgsize, ) image = image.copy(rect) # Create the output image with the same dimensions and an alpha channel # and make it completely transparent: out_img = QImage(imgsize, imgsize, QImage.Format.Format_ARGB32) out_img.fill(Qt.GlobalColor.transparent) # Create a texture brush and paint a circle with the original image onto # the output image: brush = QBrush(image) # Create texture brush painter = QPainter(out_img) # Paint the output image painter.setBrush(brush) # Use the image texture brush painter.setPen(Qt.PenStyle.NoPen) # Don't draw an outline painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) # Use AA painter.drawEllipse(0, 0, imgsize, imgsize) # Actually draw the circle if overlay_text: # draw text font = QtGui.QFont("Arial Rounded MT Bold") font.setPointSize(imgsize * 0.4) painter.setFont(font) painter.setPen(Qt.GlobalColor.white) painter.drawText(QRect(0, 0, imgsize, imgsize), Qt.AlignmentFlag.AlignCenter, overlay_text) painter.end() # We are done (segfault if you forget this) # Convert the image to a pixmap and rescale it. Take pixel ratio into # account to get a sharp image on retina displays: pr = QtWidgets.QApplication.instance().devicePixelRatio() pm = QPixmap.fromImage(out_img) pm.setDevicePixelRatio(pr) size = int(pr * size) pm = pm.scaled( size, size, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation, ) return pm
TEXTPADDING = 20 QUFONT = QFont() QUFONT.setPixelSize(70) QUMARGIN = 50 NAMEHEIGHT = 50 NAMEFONT = QFont() NAMEFONT.setPixelSize(20) NAMEPEN = QPen(WHITE) SCOREFONT = QFont() SCOREFONT.setPixelSize(50) SCOREPEN = QPen(WHITE) HOLEPEN = QPen(RED) HIGHLIGHTPEN = QPen(BLUE) HIGHLIGHTBRUSH = QBrush(WHITE) CORRECTBRUSH = QBrush(GREEN) INCORRECTBRUSH = QBrush(RED) LIGHTPEN = QPen(GREY) LIGHTBRUSH = QBrush(RED) BORDERWIDTH = 10 BORDERPEN = QPen(BLACK) BORDERPEN.setWidth(BORDERWIDTH) DIVIDERBRUSH = QBrush(WHITE) DIVIDERWIDTH = 20 FILLBRUSH = QBrush(BLUE) SCOREHEIGHT = 0.15
def paint(self, painter: 'QPainter', option: QStyleOptionViewItem, index: 'QModelIndex'): """Highlight dates in red - TODO clean this up a bit, put stuff at class level - TODO could do this for all cell delegates so focus rect is same - and no text shifting happens """ date_color = self.color painter.save() parent = self.parent options = QStyleOptionViewItem(option) self.initStyleOption(options, index) # otherwise text draws twice options.text = '' style = QApplication.style( ) if options.widget is None else options.widget.style() ctx = QAbstractTextDocumentLayout.PaintContext() if index.row() == self.parent.data_model.current_row: # yellow selected row ctx.palette.setColor(QPalette.ColorRole.Text, QColor('black')) color = self.color_hl_bg_mouseover if option.state & QStyle.StateFlag.State_MouseOver else self.color_hl_bg options.palette.setColor(QPalette.ColorRole.Highlight, QColor(color)) elif option.state & QStyle.StateFlag.State_MouseOver and not option.state & QStyle.StateFlag.State_HasFocus: # mouse hover, but not active row ctx.palette.setColor(QPalette.ColorRole.Text, QColor(self.color_mouseover_text)) options.backgroundBrush = QBrush(QColor(self.color_mouseover_bg)) date_color = self.color_mouseover_text_date else: # not selected or hovered, just normal cell in column ctx.palette.setColor( QPalette.ColorRole.Text, option.palette.color(QPalette.ColorGroup.Active, QPalette.ColorRole.Text)) # need to set background color before drawing row style.drawControl(QStyle.ControlElement.CE_ItemViewItem, options, painter) if option.state & QStyle.StateFlag.State_HasFocus: pen = painter.pen() pen.setColor(QColor('red')) pen.setWidth(self.border_width) painter.setPen(pen) rect = option.rect.adjusted(1, 1, -1, -1) # rect = option.rect painter.drawRect(rect) textRect = style.subElementRect(QStyle.SubElement.SE_ItemViewItemText, options) # shift text up 4 pixels so don't have to shift with red focus box # this matches super().paint alignment if index.column() != 0: textRect.adjust(-1, -4, 0, 0) # this sets the html doc text in the correct place, but modifies location of painter, call close to last painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) # regex replace font color for dates, set to html text = index.data() res = re.sub(self.date_expr, rf'<font color="{date_color}">\1</font>', text) \ .replace('\n', '<br>') self.doc.setHtml(res) # define max width textDoc can occupy, eg word wrap self.doc.setTextWidth(options.rect.width()) self.doc.documentLayout().draw(painter, ctx) painter.restore()
def __init__(self, buffer, view_info): super(View, self).__init__() self.buffer = buffer # Init widget attributes. if get_emacs_func_cache_result("eaf-emacs-running-in-wayland-native", []): self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.BypassWindowManagerHint) elif get_emacs_func_cache_result( "eaf-emacs-not-use-reparent-technology", []): self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint | Qt.WindowType.NoDropShadowWindowHint) else: self.setWindowFlags(Qt.WindowType.FramelessWindowHint) self.setAttribute(Qt.WidgetAttribute.WA_X11DoNotAcceptFocus, True) self.setContentsMargins(0, 0, 0, 0) self.installEventFilter(self) # Init attributes. self.view_info = view_info (self.buffer_id, self.emacs_xid, self.x, self.y, self.width, self.height) = view_info.split(":") self.x = int(self.x) self.y = int(self.y) self.width = int(self.width) self.height = int(self.height) # Build QGraphicsView. self.layout = QVBoxLayout(self) self.layout.setSpacing(0) self.layout.setContentsMargins(0, 0, 0, 0) self.graphics_view = QGraphicsView(buffer, self) # Remove border from QGraphicsView. self.graphics_view.setHorizontalScrollBarPolicy( Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.graphics_view.setVerticalScrollBarPolicy( Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.graphics_view.setRenderHints( QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform | QPainter.RenderHint.TextAntialiasing) self.graphics_view.setFrameStyle(QFrame.Shape.NoFrame) # Fill background color. self.graphics_view.setBackgroundBrush(QBrush(buffer.background_color)) # Add graphics view. self.layout.addWidget(self.graphics_view) # NOTE: show function must start before resize to trigger *first* resizeEvent after show. self.show() # Resize after show to trigger fit view operation. self.resize(self.width, self.height) self.buffer.aspect_ratio_change.connect(self.adjust_aspect_ratio)
def generate_itemGroup(self, xs, ys, label, type): gItemGroup = QGraphicsItemGroup() pointBbx = QRectF() pointBbx.setSize(QSizeF(self.gView.labelSize, self.gView.labelSize)) textLabel = QGraphicsTextItem(label) if len(xs) == 1: pointBbx.moveCenter(QPointF(xs[0], ys[0])) textLabel.setPos(xs[0] - (textLabel.boundingRect().width() / 2), ys[0] - (textLabel.boundingRect().height() / 2)) pointShape = QGraphicsEllipseItem(pointBbx) shapeColor = Qt.GlobalColor.white textColor = Qt.GlobalColor.black tooltip = 'P{}:{}' elif len(xs) == 2: pointBbx.moveCenter(QPointF(xs[1], ys[1])) textLabel.setPos(xs[1] - (textLabel.boundingRect().width() / 2), ys[1] - (textLabel.boundingRect().height() / 2)) r, g, b = np.random.choice(range(256), size=3) line_item = QGraphicsLineItem(xs[0], ys[0], xs[1], ys[1]) line_item.setPen( QPen(QColor(r, g, b, 128), self.gView.labelSize / 6)) gItemGroup.addToGroup(line_item) # line_end = QGraphicsEllipseItem(xs[1], ys[1], # int(self.gView.labelSize/3), int(self.gView.labelSize/3)) # line_end.setPen(QPen(QColor(r, g, b), 0.5)) # line_end.setBrush(QBrush(QColor(r, g, b))) # gItemGroup.addToGroup(line_end) pointShape = QGraphicsEllipseItem(pointBbx) shapeColor = QColor(r, g, b, 128) textColor = Qt.GlobalColor.black tooltip = 'L{}:{}' # textLabel.setRotation(np.arctan((ys[1] - ys[0])/(xs[1] - xs[0]))*(180/3.14)) else: pointBbx.moveCenter(QPointF(np.mean(xs), np.mean(ys))) textLabel.setPos( np.mean(xs) - (textLabel.boundingRect().width() / 2), np.mean(ys) - (textLabel.boundingRect().height() / 2)) points = [QPointF(x, y) for x, y in zip(xs, ys)] polygon = QPolygonF(points) r, g, b = np.random.choice(range(256), size=3) zone_item = QGraphicsPolygonItem(polygon) zone_item.setPen(QPen(QColor(r, g, b), self.gView.labelSize / 10)) zone_item.setBrush(QBrush(QColor(r, g, b, 40))) gItemGroup.addToGroup(zone_item) pointShape = QGraphicsRectItem(pointBbx) shapeColor = Qt.GlobalColor.darkBlue textColor = Qt.GlobalColor.white tooltip = 'Z{}:{}' pointShape.setPen(QPen(Qt.GlobalColor.white, 0.5)) pointShape.setBrush(QBrush(shapeColor)) # self.gView.scene().addEllipse(pointBbx, QPen(Qt.white, 0.5), QBrush(Qt.black)) gItemGroup.setToolTip(tooltip.format(label, type)) gItemGroup.addToGroup(pointShape) labelFont = QFont() labelFont.setPointSize(round(self.gView.labelSize / 2)) labelFont.setBold(True) textLabel.setFont(labelFont) textLabel.setDefaultTextColor(textColor) gItemGroup.addToGroup(textLabel) return gItemGroup
def drawBrushes(self, qp): brush = QBrush(Qt.BrushStyle.SolidPattern) qp.setBrush(brush) qp.drawRect(10, 15, 90, 60) brush.setStyle(Qt.BrushStyle.Dense1Pattern) qp.setBrush(brush) qp.drawRect(130, 15, 90, 60) brush.setStyle(Qt.BrushStyle.Dense2Pattern) qp.setBrush(brush) qp.drawRect(250, 15, 90, 60) brush.setStyle(Qt.BrushStyle.DiagCrossPattern) qp.setBrush(brush) qp.drawRect(10, 105, 90, 60) brush.setStyle(Qt.BrushStyle.Dense5Pattern) qp.setBrush(brush) qp.drawRect(130, 105, 90, 60) brush.setStyle(Qt.BrushStyle.Dense6Pattern) qp.setBrush(brush) qp.drawRect(250, 105, 90, 60) brush.setStyle(Qt.BrushStyle.HorPattern) qp.setBrush(brush) qp.drawRect(10, 195, 90, 60) brush.setStyle(Qt.BrushStyle.VerPattern) qp.setBrush(brush) qp.drawRect(130, 195, 90, 60) brush.setStyle(Qt.BrushStyle.BDiagPattern) qp.setBrush(brush) qp.drawRect(250, 195, 90, 60)