def create_diff_table(self, diffs): tbl = QTableWidget() tbl.setRowCount(len(diffs)) tbl.setColumnCount(3) tbl.setHorizontalHeaderItem(0, QTableWidgetItem('Field')) tbl.setHorizontalHeaderItem(1, QTableWidgetItem('Current')) tbl.setHorizontalHeaderItem(2, QTableWidgetItem('Previous')) from PyQt5.QtGui import QColor red = QColor() red.setRed(255) for row, diff in enumerate(diffs): tbl.setItem(row, 0, QTableWidgetItem(diff.field_name)) item1 = QTableWidgetItem(to_money(diff.current_amount)) item2 = QTableWidgetItem(to_money(diff.previous_amount)) if self._significant_diff(diff.current_amount, diff.previous_amount): item1.setForeground(red) item2.setForeground(red) tbl.setItem(row, 1, item1) tbl.setItem(row, 2, item2) tbl.verticalHeader().setVisible(False) tbl.resizeColumnsToContents() ht = tbl.rowHeight(0) * (tbl.rowCount() + 1) tbl.setFixedSize(tbl.horizontalHeader().length() + 20, ht) return tbl
def __init__(self, parent=None): super(GLWidget, self).__init__(parent) midnight = QTime(0, 0, 0) random.seed(midnight.secsTo(QTime.currentTime())) self.object = 0 self.xRot = 0 self.yRot = 0 self.zRot = 0 self.image = QImage() self.bubbles = [] self.lastPos = QPoint() self.trolltechGreen = QColor.fromCmykF(0.40, 0.0, 1.0, 0.0) self.trolltechPurple = QColor.fromCmykF(0.39, 0.39, 0.0, 0.0) self.animationTimer = QTimer() self.animationTimer.setSingleShot(False) self.animationTimer.timeout.connect(self.animate) self.animationTimer.start(25) self.setAutoFillBackground(False) self.setMinimumSize(200, 200) self.setWindowTitle("Overpainting a Scene")
def paintEvent(self, event): if self.highlightStart is not None and self.highlightEnd is not None: p = QPainter(self) opt = QStyleOptionSlider() self.initStyleOption(opt) gr = self.style().subControlRect(QStyle.CC_Slider, opt, QStyle.SC_SliderGroove, self) rectX, rectY, rectW, rectH = gr.getRect() startX = int( (rectW/(self.maximum() - self.minimum())) * self.highlightStart + rectX ) startY = (rectH - rectY) / 2 width = int( (rectW/(self.maximum() - self.minimum())) * self.highlightEnd + rectX ) - startX height = (rectH - startY) / 2 c = QColor(0, 152, 116) p.setBrush(c) c.setAlphaF(0.3) p.setPen(QPen(c, 1.0)) rectToPaint = QRect(startX, startY, width, height) p.drawRects(rectToPaint) super(HighlightedJumpSlider, self).paintEvent(event)
def __init__(self): super(Window, self).__init__() mainLayout = QGridLayout() self.glWidgets = [] for i in range(Window.NumRows): row = [] for j in range(Window.NumColumns): clearColor = QColor() clearColor.setHsv(((i * Window.NumColumns) + j) * 255 / (Window.NumRows * Window.NumColumns - 1), 255, 63) widget = GLWidget(None, None) widget.setClearColor(clearColor) widget.rotateBy(+42 * 16, +42 * 16, -21 * 16) mainLayout.addWidget(widget, i, j) widget.clicked.connect(self.setCurrentGlWidget) row.append(widget) self.glWidgets.append(row) self.setLayout(mainLayout) self.currentGlWidget = self.glWidgets[0][0] timer = QTimer(self) timer.timeout.connect(self.rotateOneStep) timer.start(20) self.setWindowTitle("Textures")
def paintEvent(self, event): if not self.isDisplayedWhenStopped() and not self.isRunning(): return width = min(self.width(), self.height()) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) outerRadius = (width-1) * 0.5 innerRadius = (width-1) * 0.5 * 0.38 capsuleHeight = outerRadius - innerRadius capsuleWidth = capsuleHeight * 0.23 if width > 32 else capsuleHeight * 0.35 capsuleRadius = capsuleWidth / 2 for i in range(12): color = QColor(self.color) color.setAlphaF(float(1.0 - float(i / 12.0))) p.setPen(Qt.NoPen) p.setBrush(color) p.save() p.translate(self.rect().center()) p.rotate(self._angle - float(i * 30.0)) p.drawRoundedRect(-capsuleWidth * 0.5, -(innerRadius + capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius) p.restore()
def colorValue(self, key, default = QColor()): if type(default) != QColor: default = QColor(default) name = self.mSettings.value(key, default.name()) if (not QColor.isValidColor(name)): return QColor() return QColor(name)
def setAlphaColorStr(self, color = "#ffffff", alpha = 100): '''通过字符串值设置半透明颜色''' alphaColor = QColor(color) alphaColor.setAlpha(alpha) red, green, blue, alpha = alphaColor.getRgb() self.setRed(red).setGreen(green).setBlue(blue).setAlpha(alpha) del alphaColor
def qUpper(self) : color = QColor() color.setHsv(self._sliders[0].upperValue(), self._sliders[1].upperValue(), self._sliders[2].upperValue()) #color.setRed(self._sliders[0].upperValue()) #color.setGreen(self._sliders[1].upperValue()) #color.setBlue(self._sliders[2].upperValue()) return color
def __init__(self, color): QIcon.__init__(self) qcolor = QColor() qcolor.setNamedColor(color) pixmap = QPixmap(20, 20) pixmap.fill(qcolor) self.addPixmap(pixmap)
def __init__(self, squareBounds): super().__init__() c = QColor(bConfig['invalidHoverColor']) c.setAlphaF(float(bConfig['weakEffectsAlpha'])) self.setBrush(QBrush(c)) self.setPen(QPen(Qt.NoPen)) self.setRect(squareBounds)
def drawRectangles(self, qp): color = QColor(0, 0, 0) color.setNamedColor('#646464') qp.setPen(color) qp.setBrush(QColor('black')) qp.drawRect(self.placementx1,self.placementx2, self.x1,self.x1)
class statusWidget(QWidget): def __init__(self): super(statusWidget,self).__init__() self.initUI() def initUI(self): self.green = QColor(0, 128, 0) self.red = QColor(128,0,0) self.setMinimumSize(100,200) lbl1 = QLabel('Pump',self) lbl1.move(10,0) lbl2 = QLabel('Valve', self) lbl2.move(10, 85) lbl3 = QLabel('Status 3', self) lbl3.move(10, 170) self.square1 = QFrame(self) self.square1.setGeometry(10,20,60,60) self.square1.setStyleSheet("QWidget { background-color: %s }" % self.green.name()) self.square2 = QFrame(self) self.square2.setGeometry(10,105,60,60) self.square2.setStyleSheet("QWidget { background-color: %s }" % self.red.name()) self.square3 = QFrame(self) self.square3.setGeometry(10,190,60,60) self.square3.setStyleSheet("QWidget { background-color: %s }" % self.red.name())
def initUI(self): col = QColor(10, 10, 100) self.btn1 = QPushButton('Color Dialog', self) self.btn1.move(20, 20) self.btn1.clicked.connect(self.showColorDialog) self.frm = QFrame(self) self.frm.setStyleSheet('QWidget {background-color: %s }' % col.name()) self.frm.setGeometry(130, 20, 100, 20) self.btn = QPushButton('input Dialog', self) self.btn.move(20, 50) self.btn.clicked.connect(self.showInputDialog) self.le = QLineEdit(self) self.le.move(130, 50) # vbox = QVBoxLayout() btn3 = QPushButton('Font Dialog', self) # btn3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) btn3.move(20, 80) # vbox.addWidget(btn3) btn3.clicked.connect(self.showFontDialog) self.lbl = QLabel('Knowledge only matters', self) self.lbl.move(110, 80) # vbox.addWidget(self.lbl) # self.setLayout(vbox) self.setGeometry(300, 300, 290, 150) self.setWindowTitle(' Dialog') self.show()
def __init__(self, parent=None): super(PWidgetGL, self).__init__(parent) self.object = 0 self.xRot = 500 self.yRot = 500 self.zRot = 0 self.coordLength = 3.0 self.lastPos = QPoint() self.rn = 0.0 self.Trn = 0.0 self.trolltechBlue = QColor.fromCmykF(1.0, 0.40, 0.0, 0.0) self.trolltechRed = QColor.fromCmykF(0.0, 1.0, 0.40, 0.0) self.trolltechGreen = QColor.fromCmykF(0.40, 0.0, 1.0, 0.0) self.trolltechBlack = QColor.fromCmykF(0.0, 0.0, 0.0, 1.0) self.timer = QTimer(self) self.timer.timeout.connect(self.animate) self.inited = False self.rcount = 0 self.tcount = 0 self.vcount = 0.0
def setData(self, index, value, role=Qt.EditRole): if role == Qt.EditRole and index.column() == self.ColumnID.Color: row = index.row() color = QColor(value["color"][0]) colorglobal=value["color"][1] fontsize,fontsizeglobal = value["fontsize"] linewidth,linewidthglobal = value["linewidth"] fontcolor = QColor(value["fontcolor"][0]) fontcolorglobal = value["fontcolor"][1] if color.isValid(): if not colorglobal: self._elements[row].color=color self.dataChanged.emit(index, index) else: for row,el in enumerate(self._elements): el.color=color ind=self.createIndex(row, self.ColumnID.Color, object=0) self.dataChanged.emit(ind, ind) if fontcolor.isValid(): if not fontcolorglobal: self._elements[row].fontcolor=fontcolor else: for row,el in enumerate(self._elements): el.fontcolor=fontcolor if not linewidthglobal: self._elements[row].linewidth=linewidth else: for row,el in enumerate(self._elements): el.linewidth=linewidth if not fontsizeglobal: self._elements[row].fontsize=fontsize else: for row,el in enumerate(self._elements): el.fontsize=fontsize return True if index.column()==self.ColumnID.Fix: try: value=float(value) self._elements[index.row()].isFixed=True row=index.row() self._elements[row].fixvalue="%.1f"%value self.dataChanged.emit(index,index) return True except: return False
def draw_board_rectangle(self, painter): col = QColor(0, 0, 0) col.setNamedColor('#d4d4d4') painter.setPen(col) painter.setBrush(QColor(200, 0, 0)) painter.drawRect(X_OFFSET, Y_OFFSET, 400, 400) pen = QPen(Qt.black, 2, Qt.SolidLine) painter.setPen(pen) for spot in [(x, x) for x in range(WIDTH + 1)]: left = ((spot[0] * SPACE) + X_OFFSET, Y_OFFSET) right = ((spot[0] * SPACE) + X_OFFSET, Y_OFFSET + (HEIGHT * SPACE)) up = (X_OFFSET, (spot[1] * SPACE) + Y_OFFSET) down = (X_OFFSET + (WIDTH * SPACE), (spot[1] * SPACE) + Y_OFFSET) painter.drawLine(left[0], left[1], right[0], right[1]) painter.drawLine(up[0], up[1], down[0], down[1]) for x in range(WIDTH): for y in range(HEIGHT): centerx, centery = self.get_center(x, y) if self.game.board.pieces[x][y].state in PLAYERS_STATES: if self.game.board.pieces[x][y].state == State.white: painter.setBrush(Qt.white) else: painter.setBrush(Qt.black) center = QPoint(centerx, centery) circle_diameter = int(SPACE / 2) - 5 painter.drawEllipse( center, circle_diameter, circle_diameter)
def _transform_hint_color(val): """Transformer for hint colors.""" log.config.debug("Transforming hint value {}".format(val)) def to_rgba(qcolor): """Convert a QColor to a rgba() value.""" return 'rgba({}, {}, {}, 0.8)'.format(qcolor.red(), qcolor.green(), qcolor.blue()) if val.startswith('-webkit-gradient'): pattern = re.compile(r'-webkit-gradient\(linear, left top, ' r'left bottom, ' r'color-stop\(0%, *([^)]*)\), ' r'color-stop\(100%, *([^)]*)\)\)') match = pattern.fullmatch(val) if match: log.config.debug('Color groups: {}'.format(match.groups())) start_color = QColor(match.group(1)) stop_color = QColor(match.group(2)) if not start_color.isValid() or not stop_color.isValid(): return None return ('qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 {}, ' 'stop:1 {})'.format(to_rgba(start_color), to_rgba(stop_color))) else: return None elif val.startswith('-'): # Custom CSS stuff? return None else: # Already transformed or a named color. return val
def createImage(self): """ Creates a new image by separating out the cyan, magenta, or yellow component, depending on the mask color specified in the constructor. The amount of the component found in each pixel of the image is used to determine how much of a user-selected ink is used for each pixel in the new image for the label widget. """ self.newImage = newImage = self.originalImage.copy() # Create CMY components for the ink being used. cyanInk = float(255 - QColor(self.paintColor).red()) / 255.0 magentaInk = float(255 - QColor(self.paintColor).green()) / 255.0 yellowInk = float(255 - QColor(self.paintColor).blue()) / 255.0 convert = self.convertMap[self.maskColor] for y in range(newImage.height()): for x in range(newImage.width()): p = self.originalImage.pixel(x, y) # Separate the source pixel into its cyan component. if self.inverted: amount = convert(p) else: amount = 255 - convert(p) newColor = QColor( 255 - min(int(amount * cyanInk), 255), 255 - min(int(amount * magentaInk), 255), 255 - min(int(amount * yellowInk), 255)) newImage.setPixel(x, y, newColor.rgb()) self.imageLabel.setPixmap(QPixmap.fromImage(newImage))
class ColorSwatchWidget(QLabel): def __init__(self, color=QColor(255, 255, 255, 255)): if isinstance(color, QColor): self.current_color = color else: # otherwise, it should be an rgb or rgba tuple if len(color) == 3: self.current_color = QColor(color[0], color[1], color[2], 255) else: self.current_color = QColor(color[0], color[1], color[2], color[3]) super(QLabel, self).__init__("") self.setMinimumSize(30, 30) self.reset_style_sheet() def reset_style_sheet(self): color_string = "rgb(" + str(self.current_color.red()) + ", " + \ str(self.current_color.green()) + ", " + \ str(self.current_color.blue()) + ")" self.setStyleSheet("QLabel { background-color : "+ color_string + "; " "border-style: outset;" "border-width: 2px;" "border-color: beige;}") def set_color(self, color): self.current_color = color def mousePressEvent(self, e): color_dialog = QColorDialog() color_dialog.exec_() self.current_color = color_dialog.selectedColor() self.reset_style_sheet() def value(self): return self.current_color
def _createBarcode(self): if self.barcode["value"] == "": return if self.barcode["type"] == BARCODE_ANY: logger.warning("Usando %s por defecto" % self.typeToName(BARCODE_128)) self.barcode["type"] = BARCODE_128 type_ = self.typeToName(self.barcode["type"]) value_ = self.barcode["value"] bg_ = self.barcode["bg"] fg_ = self.barcode["fg"] if not isinstance(self.barcode["bg"], str): bg_ = QColor(self.barcode["bg"]).name() if not isinstance(self.barcode["fg"], str): fg_ = QColor(self.barcode["fg"]).name() margin_ = self.barcode["margin"] / 10 bar_ = None render_options = { 'module_width': 0.2, 'module_height': 5, # 15 'text_distance': 1.0, # 5.0 'background': bg_.lower(), 'foreground': fg_.lower(), 'write_text': self.barcode["text"], 'font_size': 10, 'text': value_, 'quiet_zone': margin_, # 6.5 } try: import barcode from barcode.writer import ImageWriter from PIL.ImageQt import ImageQt barC = barcode.get_barcode_class(type_.lower()) bar_ = barC(u'%s' % value_, writer=ImageWriter()) b = bar_.render(render_options) qim = ImageQt(b) self.p = QPixmap.fromImage(qim) except Exception: print(traceback.format_exc()) self.barcode["valid"] = False self.p = None if self.p: # Escalar if self.barcode["scale"] != 1.0: wS_ = self.barcode["x"] * self.barcode["scale"] hS_ = self.barcode["y"] * self.barcode["scale"] self.p = self.p.scaled(wS_, hS_) self.barcode["x"] = self.p.width() self.barcode["y"] = self.p.height() # FALTA: res , cut y rotation self.barcode["valid"] = True else: self.barcode["valid"] = False
def test_alpha(self): c = QColor(Qt.red) c.setAlpha(128) self.assertEqual(QColorAlpha(Qt.red, 128), c) self.assertEqual(QColorAlpha('#ff0000', 128), c) self.assertEqual(QColorAlpha('#ff000080'), c) self.assertEqual(QColorAlpha(255, 0, 0, 128), c)
def start_GUI(self): frm = QFrame(self) col = QColor(0, 0, 0) frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) frm.setGeometry(0, 0, 800, 800) frm.show() self.gui_choise_server_client()
def __init__(self, squareBounds): super().__init__() c = QColor(bConfig['lastMoveColor']) c.setAlphaF(float(bConfig['effectsAlpha'])) self.setBrush(QBrush(c)) self.setPen(QPen(Qt.NoPen)) self.setRect(squareBounds)
def makeMap(self, width, height, n): ''' Generates the graphical map, from the game's map. Sets events and connects signals for the territories. ''' for i in range(n): self.coords.append([]) for j in range(n): ter_square = TerritorySquare(self, self.game.map.map[i][j]) self.coords[i].append(ter_square) square = self.coords[i][j] square.mouseReleaseEvent = self.showTerritoryDialog square.incomeChanged.emit(square.ter.get_income()) square.marketUpgr.emit(square.ter.buildings.market_lvl) square.fortUpgr.emit(square.ter.buildings.fort_lvl) x = 110 + i * (width + 1) y = 60 + j * (height + 1) square.setGeometry(x, y, width, height) if square.ter.owner: color = QColor(*square.ter.owner.color) else: color = QColor(127, 127, 127) bgcolor = "QWidget { background-color: %s }" square.setStyleSheet(bgcolor % color.name()) square.calcCenter()
def generateRandomColors(M=256, colormodel="hsv", clamp=None, zeroIsTransparent=False): """Generate a colortable with M entries. colormodel: currently only 'hsv' is supported clamp: A dictionary stating which parameters of the color in the colormodel are clamped to a certain value. For example: clamp = {'v': 1.0} will ensure that the value of any generated HSV color is 1.0. All other parameters (h,s in the example) are selected randomly to lie uniformly in the allowed range. """ r = numpy.random.random((M, 3)) if clamp is not None: for k, v in clamp.items(): idx = colormodel.index(k) r[:, idx] = v colors = [] if colormodel == "hsv": for i in range(M): if zeroIsTransparent and i == 0: colors.append(QColor(0, 0, 0, 0).rgba()) else: h, s, v = r[i, :] color = numpy.asarray(colorsys.hsv_to_rgb(h, s, v)) * 255 qColor = QColor(*color) colors.append(qColor.rgba()) return colors else: raise RuntimeError("unknown color model '%s'" % colormodel)
def paintEvent(self, event): # TODO: maybe use self.upm*(1+2*BufferHeight) for the denominator as in # fontView scale = self.height() / (self.upm * 1.2) x_offset = \ (self.width() - self.maxWidth * scale - self.padding * 2) / 2 if x_offset < 0: scale *= 1 + 2 * x_offset / (self.maxWidth * scale) x_offset = 0 painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.translate(self.padding, self.padding + (self.ascender * 1.2) * scale) painter.scale(scale, -scale) col = QColor(Qt.black) col.setAlphaF(.2) for glyph in self.glyphs: if self.alignRight: dist = self.maxWidth - glyph.width else: dist = 0 glyphPath = glyph.getRepresentation("defconQt.QPainterPath") painter.save() painter.translate(x_offset + dist, 0) painter.fillPath(glyphPath, col) painter.restore()
def __init__(self, size, *args, **kw): super(ClockBack,self).__init__(*args, **kw) self.size = size self.bbox = QRectF(0, 0, self.size, self.size) self._color = QColor(255,0,0,255) self._outline_color = QColor(255,0,0,255) self._alpha = 255 self._line_width = 3
def colorize_can_id(frame): if not frame.extended: return mask = 0b11111 priority = (frame.id >> 24) & mask col = QColor() col.setRgb(0xFF, 0xFF - (mask - priority) * 6, 0xFF) return col
def getElementStyle(element, base_name=None): """Lookup element color.""" style = ELEMENT_STYLE.get( base_name or element.base_name.upper(), DEFAULT_STYLE) color = QColor(style.color) if element.l == 0: color.setAlphaF(style.alpha) return color, style.width
def adjust_lightness(color, amount): r, g, b, a = color.getRgbF() hu, s, l = rgb_to_husl(r, g, b) l += amount c = QColor() r, g, b = husl_to_rgb(hu, s, l) c.setRgbF(min(r, 1), min(g, 1), min(b, 1)) return c
def paint_background(self, painter, x_offset, y_offset, width, height): old_brush = painter.brush() old_pen = painter.pen() width_factor = width / 3000 height_factor = height / 2000 start_green_zone = QPolygonF() start_green_zone.append(QPointF(width - (0 * width_factor + x_offset), 2000 * height_factor + y_offset)) start_green_zone.append(QPointF(width - (0 * width_factor + x_offset), 1350 * height_factor + y_offset)) start_green_zone.append(QPointF(width - (400 * width_factor + x_offset), 1350 * height_factor + y_offset)) start_green_zone.append(QPointF(width - (400 * width_factor + x_offset), 2000 * height_factor + y_offset)) painter.setPen(QPen(QColor(97, 153, 59))) painter.setBrush(QBrush(QColor(97, 153, 59))) painter.drawPolygon(start_green_zone) start_orange_zone = QPolygonF() start_orange_zone.append(QPointF(width - (2600 * width_factor + x_offset), 2000 * height_factor + y_offset)) start_orange_zone.append(QPointF(width - (3000 * width_factor + x_offset), 2000 * height_factor + y_offset)) start_orange_zone.append(QPointF(width - (3000 * width_factor + x_offset), 1350 * height_factor + y_offset)) start_orange_zone.append(QPointF(width - (2600 * width_factor + x_offset), 1350 * height_factor + y_offset)) painter.setPen(QPen(QColor(208, 93, 40))) painter.setBrush(QBrush(QColor(208, 93, 40))) painter.drawPolygon(start_orange_zone) construction_zone_green = QPolygonF() construction_zone_green.append(QPointF(width - (400 * width_factor + x_offset), 1820 * height_factor + y_offset)) construction_zone_green.append(QPointF(width - (400 * width_factor + x_offset), 2000 * height_factor + y_offset)) construction_zone_green.append(QPointF(width - (960 * width_factor + x_offset), 2000 * height_factor + y_offset)) construction_zone_green.append(QPointF(width - (960 * width_factor + x_offset), 1820 * height_factor + y_offset)) painter.setPen(QPen(QColor(97, 153, 59))) painter.setBrush(QBrush(QColor(0, 0, 0, 0))) painter.drawPolygon(construction_zone_green) construction_zone_orange = QPolygonF() construction_zone_orange.append(QPointF(width - (2040 * width_factor + x_offset), 1820 * height_factor + y_offset)) construction_zone_orange.append(QPointF(width - (2040 * width_factor + x_offset), 2000 * height_factor + y_offset)) construction_zone_orange.append(QPointF(width - (2600 * width_factor + x_offset), 2000 * height_factor + y_offset)) construction_zone_orange.append(QPointF(width - (2600 * width_factor + x_offset), 1820 * height_factor + y_offset)) painter.setPen(QPen(QColor(208, 93, 40))) painter.setBrush(QBrush(QColor(0, 0, 0, 0))) painter.drawPolygon(construction_zone_orange) white_line = QPolygonF() white_line.append(QPointF(width - (1120 * width_factor + x_offset), 2000 * height_factor + y_offset)) white_line.append(QPointF(width - (1140 * width_factor + x_offset), 2000 * height_factor + y_offset)) white_line.append(QPointF(width - (1140 * width_factor + x_offset), 1660 * height_factor + y_offset)) white_line.append(QPointF(width - (1490 * width_factor + x_offset), 1660 * height_factor + y_offset)) white_line.append(QPointF(width - (1490 * width_factor + x_offset), 1700 * height_factor + y_offset)) white_line.append(QPointF(width - (1510 * width_factor + x_offset), 1700 * height_factor + y_offset)) white_line.append(QPointF(width - (1510 * width_factor + x_offset), 1660 * height_factor + y_offset)) white_line.append(QPointF(width - (1860 * width_factor + x_offset), 1660 * height_factor + y_offset)) white_line.append(QPointF(width - (1860 * width_factor + x_offset), 2000 * height_factor + y_offset)) white_line.append(QPointF(width - (1880 * width_factor + x_offset), 2000 * height_factor + y_offset)) white_line.append(QPointF(width - (1880 * width_factor + x_offset), 1660 * height_factor + y_offset)) white_line.append(QPointF(width - (3000 * width_factor + x_offset), 1660 * height_factor + y_offset)) white_line.append(QPointF(width - (3000 * width_factor + x_offset), 1640 * height_factor + y_offset)) white_line.append(QPointF(width - (2400 * width_factor + x_offset), 1640 * height_factor + y_offset)) white_line.append(QPointF(width - (2400 * width_factor + x_offset), 1170 * height_factor + y_offset)) white_line.append(QPointF(width - (2700 * width_factor + x_offset), 1170 * height_factor + y_offset)) white_line.append(QPointF(width - (2700 * width_factor + x_offset), 1150 * height_factor + y_offset)) white_line.append(QPointF(width - (2400 * width_factor + x_offset), 1150 * height_factor + y_offset)) white_line.append(QPointF(width - (2400 * width_factor + x_offset), 320 * height_factor + y_offset)) white_line.append(QPointF(width - (2380 * width_factor + x_offset), 320 * height_factor + y_offset)) white_line.append(QPointF(width - (2380 * width_factor + x_offset), 1150 * height_factor + y_offset)) white_line.append(QPointF(width - (2150 * width_factor + x_offset), 1150 * height_factor + y_offset)) white_line.append(QPointF(width - (2150 * width_factor + x_offset), 1170 * height_factor + y_offset)) white_line.append(QPointF(width - (2380 * width_factor + x_offset), 1170 * height_factor + y_offset)) white_line.append(QPointF(width - (2380 * width_factor + x_offset), 1640 * height_factor + y_offset)) white_line.append(QPointF(width - (1510 * width_factor + x_offset), 1640 * height_factor + y_offset)) white_line.append(QPointF(width - (1510 * width_factor + x_offset), 1600 * height_factor + y_offset)) white_line.append(QPointF(width - (1490 * width_factor + x_offset), 1600 * height_factor + y_offset)) white_line.append(QPointF(width - (1490 * width_factor + x_offset), 1640 * height_factor + y_offset)) white_line.append(QPointF(width - (620 * width_factor + x_offset), 1640 * height_factor + y_offset)) white_line.append(QPointF(width - (620 * width_factor + x_offset), 1170 * height_factor + y_offset)) white_line.append(QPointF(width - (850 * width_factor + x_offset), 1170 * height_factor + y_offset)) white_line.append(QPointF(width - (850 * width_factor + x_offset), 1150 * height_factor + y_offset)) white_line.append(QPointF(width - (620 * width_factor + x_offset), 1150 * height_factor + y_offset)) white_line.append(QPointF(width - (620 * width_factor + x_offset), 320 * height_factor + y_offset)) white_line.append(QPointF(width - (600 * width_factor + x_offset), 320 * height_factor + y_offset)) white_line.append(QPointF(width - (600 * width_factor + x_offset), 1150 * height_factor + y_offset)) white_line.append(QPointF(width - (300 * width_factor + x_offset), 1150 * height_factor + y_offset)) white_line.append(QPointF(width - (300 * width_factor + x_offset), 1170 * height_factor + y_offset)) white_line.append(QPointF(width - (600 * width_factor + x_offset), 1170 * height_factor + y_offset)) white_line.append(QPointF(width - (600 * width_factor + x_offset), 1640 * height_factor + y_offset)) white_line.append(QPointF(width - (0 * width_factor + x_offset), 1640 * height_factor + y_offset)) white_line.append(QPointF(width - (0 * width_factor + x_offset), 1660 * height_factor + y_offset)) white_line.append(QPointF(width - (1120 * width_factor + x_offset), 1660 * height_factor + y_offset)) painter.setPen(QPen(QColor(255, 255, 255))) painter.setBrush(QBrush(QColor(255, 255, 255, 255))) painter.drawPolygon(white_line) painter.setPen(old_pen) painter.setBrush(old_brush)
def __init__(self, buffer_id, url): Buffer.__init__(self, buffer_id, url, True, QColor(0, 0, 0, 255)) self.add_widget(VideoPlayerWidget()) self.buffer_widget.play(url)
# # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! import blue as blue from PyQt5 import QtGui from PyQt5.QtCore import QPoint from PyQt5.QtGui import QPainter, QPen, QColor, QImage from PyQt5.QtWidgets import QLabel import GlobalConfig import TelloController global point point=[] lineColor =QColor(255, 0, 255) pointColor=QColor(0, 0, 255) pen=QPen() ''' 标定打点类 ''' class TQLable(QLabel): def mousePressEvent(self, ev: QtGui.QMouseEvent) -> None: super().mousePressEvent(ev) self.showHistoryPoint(ev) self.repaint() def paintEvent(self, a0: QtGui.QPaintEvent) -> None: global pen painter = QPainter(self)
def draw(self, qp): size = randint(10, 350) qp.setBrush(QColor('yellow')) qp.setPen(QColor('yellow')) qp.drawEllipse(self.x - (size // 2), self.y - (size // 2), size, size)
def __init__(self, parent=None): super(PieChart, self).__init__(parent) self._name = '' self._color = QColor()
def refresh_canvas(self): # Paint all pixels back to black self.canvas.painter.fillRect(0, 0, self.canvas.width, self.canvas.height, QColor('#000000')) # Update canvas self.canvas.update()
def drawing(self, qp): qp.setBrush(QColor('Yellow')) a = randint(1, 150) qp.drawEllipse(randint(151, 760), randint(151, 480), a, a)
def tab_indicator_color(self, idx): """Get the tab indicator color for the given index.""" try: return self.tab_data(idx, 'indicator-color') except KeyError: return QColor()
def __init__(self): super(Window, self).__init__() self.setGeometry(350, 250, 920, 500) self.setWindowTitle("2048 Cat") self.brushes = { 0: QBrush(QColor(0xcdc1b4)), 1: QBrush(QColor(0x999999)), 2: QBrush(QColor(0xeee4da)), 4: QBrush(QColor(0xede0c8)), 8: QBrush(QColor(0xf2b179)), 16: QBrush(QColor(0xf59563)), 32: QBrush(QColor(0xf67c5f)), 64: QBrush(QColor(0xf65e3b)), 128: QBrush(QColor(0xedcf72)), 256: QBrush(QColor(0xedcc61)), 512: QBrush(QColor(0xedc850)), 1024: QBrush(QColor(0xedc53f)), 2048: QBrush(QColor(0xedc22e)), } self.backgroundBrush = QBrush(QColor(0xbbada0)) self.resetRect = QRectF(290, 30, 100, 40) self.descriptionRect = QRectF(10, 30, 270, 40) self.infoFromSignal = [] self.conceptFromSignal = [] self.codeRackStatFromSignal = [] self.proposalsActivityFromSignal = {} self.structureDepictList = [] self.player1 = gamePlay() self.player1._signal1.connect(self.showInfo) self.player1._signal1.connect(self.update) self.player1.controller1.workspace1._signal2.connect(self.catchInfo) self.player1.controller1.workspace1._signal2.connect(self.update) self.player1.controller1.conceptweb1._signal3.connect( self.catchConcepts) self.player1.controller1.conceptweb1._signal3.connect(self.update) self.player1.controller1.coderack1._signal4.connect( self.catchCodeRackStat) self.player1.controller1.coderack1._signal4.connect(self.update) self.player1.controller1._signal5.connect(self.catchProposalsActivity) self.player1.controller1._signal5.connect(self.update) self.player1.controller1.workspace1._signal6.connect( self.catchDepictList) self.player1.controller1.workspace1._signal6.connect(self.update) self.player1.start()
# Copyright 2017-2022 Christian Karl (karlch) <karlch at protonmail dot com> # License: GNU GPL v3, see the "LICENSE" and "AUTHORS" files for details. """Integration tests related to editing images.""" from PyQt5.QtGui import QPixmap, QColor import pytest from vimiv.config import styles from vimiv.imutils import edit_handler WIDTH = 300 HEIGHT = 200 COLOR = QColor("#888888") @pytest.fixture() def edit(mocker, qtbot): mocker.patch("vimiv.api.signals") mocker.patch("vimiv.api.modes.Mode.close") mocker.patch.object(styles, "_style", styles.create_default()) handler = edit_handler.EditHandler() handler._init_manipulate() handler.pixmap = QPixmap(WIDTH, HEIGHT) handler.pixmap.fill(COLOR) yield handler @pytest.fixture()
class BubbleLabel(QWidget): BackgroundColor = QColor(195, 195, 195) BorderColor = QColor(150, 150, 150) def __init__(self, *args, **kwargs): text = kwargs.pop("text", "") super(BubbleLabel, self).__init__(*args, **kwargs) # 设置无边框置顶 self.setWindowFlags(Qt.Window | Qt.Tool | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.X11BypassWindowManagerHint) # 设置最小宽度和高度 self.setMinimumWidth(300) self.setMinimumHeight(100) self.setAttribute(Qt.WA_TranslucentBackground, True) layout = QVBoxLayout(self) # 左上右下的边距(下方16是因为包括了三角形) layout.setContentsMargins(8, 8, 8, 16) self.label = QLabel(self) layout.addWidget(self.label) self.setText(text) # 获取屏幕高宽 self._desktop = QApplication.instance().desktop() def setText(self, text): self.label.setText(text) def text(self): return self.label.text() def stop(self): self.hide() self.animationGroup.stop() self.close() def show(self): super(BubbleLabel, self).show() # 窗口开始位置 startPos = QPoint( self._desktop.screenGeometry().width() - self.width() - 100, self._desktop.availableGeometry().height() - self.height()) endPos = QPoint( self._desktop.screenGeometry().width() - self.width() - 100, self._desktop.availableGeometry().height() - self.height() * 3 - 5) # print(startPos, endPos) self.move(startPos) # 初始化动画 self.initAnimation(startPos, endPos) def initAnimation(self, startPos, endPos): # 透明度动画 opacityAnimation = QPropertyAnimation(self, b"opacity") opacityAnimation.setStartValue(1.0) opacityAnimation.setEndValue(0.0) # 设置动画曲线 opacityAnimation.setEasingCurve(QEasingCurve.InQuad) opacityAnimation.setDuration(4000) # 在4秒的时间内完成 # 往上移动动画 moveAnimation = QPropertyAnimation(self, b"pos") moveAnimation.setStartValue(startPos) moveAnimation.setEndValue(endPos) moveAnimation.setEasingCurve(QEasingCurve.InQuad) moveAnimation.setDuration(5000) # 在5秒的时间内完成 # 并行动画组(目的是让上面的两个动画同时进行) self.animationGroup = QParallelAnimationGroup(self) self.animationGroup.addAnimation(opacityAnimation) self.animationGroup.addAnimation(moveAnimation) self.animationGroup.finished.connect(self.close) # 动画结束时关闭窗口 self.animationGroup.start() def paintEvent(self, event): super(BubbleLabel, self).paintEvent(event) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # 抗锯齿 rectPath = QPainterPath() # 圆角矩形 triPath = QPainterPath() # 底部三角形 height = self.height() - 8 # 往上偏移8 rectPath.addRoundedRect(QRectF(0, 0, self.width(), height), 5, 5) x = self.width() / 5 * 4 triPath.moveTo(x, height) # 移动到底部横线4/5处 # 画三角形 triPath.lineTo(x + 6, height + 8) triPath.lineTo(x + 12, height) rectPath.addPath(triPath) # 添加三角形到之前的矩形上 # 边框画笔 painter.setPen( QPen(self.BorderColor, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) # 背景画刷 painter.setBrush(self.BackgroundColor) # 绘制形状 painter.drawPath(rectPath) # 三角形底边绘制一条线保证颜色与背景一样 painter.setPen( QPen(self.BackgroundColor, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(x, height, x + 12, height) def windowOpacity(self): return super(BubbleLabel, self).windowOpacity() def setWindowOpacity(self, opacity): super(BubbleLabel, self).setWindowOpacity(opacity) # 由于opacity属性不在QWidget中需要重新定义一个 opacity = pyqtProperty(float, windowOpacity, setWindowOpacity)
self.update() def scroll_to_end(self): self.scroll_offset = self.max_scroll_offset() self.update() def zoom_in(self): self.scale = min(10, self.scale + 0.2) self.update() def zoom_out(self): self.scale = max(1, self.scale - 0.2) self.update() def zoom_reset(self): self.update_scale() self.update() if __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) w = PdfViewerWidget(sys.argv[1], QColor(0, 0, 0, 255)) w.resize(1920, 1080) w.show() sys.exit(app.exec_())
def paintEvent(self, event): super().paintEvent(event) painter = QPainter() painter.begin(self) # background brushBG = QBrush(Qt.black, Qt.SolidPattern) if not common.AppSettings["ShowMask"]: brushBG.setColor(Qt.darkGray) brushBG.setStyle(Qt.Dense1Pattern) painter.setBackground(Qt.gray) else: brushBG.setColor(Qt.black) brushBG.setStyle(Qt.SolidPattern) painter.setBackground(Qt.black) painter.setBackgroundMode(Qt.OpaqueMode) painter.setBrush(brushBG) painter.setPen(Qt.NoPen) painter.drawRect(0, 0, self.width(), self.height()) # draw photo if not self.myPhoto.isNull(): # rotate and draw photo as specified by user transform = QTransform() transform.translate(self.myPhotoDestRect.center().x(), self.myPhotoDestRect.center().y()) transform.rotate(-self.myPhotoRotation) transform.translate(-self.myPhotoDestRect.center().x(), -self.myPhotoDestRect.center().y()) painter.setTransform(transform) painter.drawImage(self.myPhotoDestRect, self.myPhoto, self.myPhotoSrcRect) # draw it painter.resetTransform() # useful local vars centerPoint = QPoint(self.viewCenter[0], self.viewCenter[1]) destRect = QRect(0, 0, self.myPhotoDestRect.width(), self.myPhotoDestRect.height()) fontWidth = self.fontMetrics.width("X") # mask if common.AppSettings["ShowMask"]: maskPainter = QPainter() maskPainter.begin(self.mask) maskPainter.setBrush(QBrush(Qt.magenta, Qt.SolidPattern)) maskPainter.drawEllipse(self.viewCenter[0] - self.myPhotoRadius, self.viewCenter[1] - self.myPhotoRadius, self.myPhotoDiameter, self.myPhotoDiameter) maskPainter.end() painter.setCompositionMode(QPainter.CompositionMode_DestinationIn) painter.drawImage(0, 0, self.mask) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) # HUD if common.AppSettings["ShowHUD"]: painter.setBackgroundMode(Qt.TransparentMode) #painter.setBackground(Qt.black) painter.setBrush(Qt.NoBrush) painter.setFont(self.fontScaled) # draw UV grid if common.AppSettings["ShowUVGrid"]: painter.setPen(self.penText) # box tl = self.myPhotoTopLeft tr = (self.viewCenter[0] + self.myPhotoRadius, self.viewCenter[1] - self.myPhotoRadius) bl = (self.viewCenter[0] - self.myPhotoRadius, self.viewCenter[1] + self.myPhotoRadius) br = (self.viewCenter[0] + self.myPhotoRadius, self.viewCenter[1] + self.myPhotoRadius) painter.drawLine(tl[0], tl[1], tr[0], tr[1]) painter.drawLine(bl[0], bl[1], br[0], br[1]) painter.drawLine(tl[0], tl[1], bl[0], bl[1]) painter.drawLine(tr[0], tr[1], br[0], br[1]) # crosshairs painter.drawLine(tl[0], self.viewCenter[1], tr[0], self.viewCenter[1]) painter.drawLine(self.viewCenter[0], tr[1], self.viewCenter[0], br[1]) # labels destRect.setCoords(tl[0] + 4, tl[1] + 4, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "0") destRect.setCoords(tr[0] - (fontWidth+4), tr[1] + 4, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "1") destRect.setCoords(bl[0] + 3, bl[1] - (self.fontMetrics.height()+3), self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "1") destRect.setCoords(br[0] - (fontWidth+3), br[1] - (self.fontMetrics.height()+3), self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "1") # grid coordinates gpntrad = self.myPhotoRadius * 0.005 painter.setPen(self.penText) painter.setBrush(self.brushGrid) painter.setFont(self.fontScaled) for i in range(0, len(self.gridpoints)): point = self.gridpoints[i] u, v = self.gridUVs[i] t, p = self.gridskycoords[i] painter.drawEllipse(QPoint(point[0], point[1]), gpntrad, gpntrad) destRect.setCoords(point[0]+fontWidth/2, point[1]-self.fontMetrics.height(), self.width(), self.height()) textuv = "{0:.1f}u, {1:.1f}v".format(round(u,1), round(v,1)) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, textuv) destRect.setCoords(point[0]+fontWidth/2, point[1], self.width(), self.height()) textuv = "{0:d}°, {1:d}°".format(int(round(t)), int(round(p))) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, textuv) painter.setBrush(Qt.NoBrush) # draw lens warp if common.AppSettings["ShowLensWarp"]: # ideal lens longitudes along azimuth painter.setPen(self.penText) for i in range(0, int(len(self.compassTicks)/2), 3): p1 = QPoint(self.compassTicks[i][2], self.compassTicks[i][3]) p2 = QPoint(self.compassTicks[i+18][2], self.compassTicks[i+18][3]) # tick opposite 180 degrees painter.drawLine(p1, p2) # ideal lens latitudes along zenith for r, alt in self.lensIdealRadii: painter.drawEllipse(centerPoint, r, r) # actual/warped lens latitudes along zenith painter.setPen(self.penLens) for r, alt in self.lensRealRadii: painter.drawEllipse(centerPoint, r, r) destRect.setCoords(self.viewCenter[0] + r + 3, self.viewCenter[1] - (self.fontMetrics.height() + 3), self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "{0:d}°".format(int(alt))) # draw compass if common.AppSettings["ShowCompass"]: # compass ticks text shadows if common.AppSettings["ShowShadows"]: painter.setPen(self.penShadowText) for tick in self.compassTicks: destRect.setCoords(tick[4] + 1, tick[5] + 1, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(tick[6])+"°") # compass ticks text painter.setPen(self.penText) for tick in self.compassTicks: painter.drawLine(tick[0], tick[1], tick[2], tick[3]) destRect.setCoords(tick[4], tick[5], self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(tick[6])+"°") # photo radius #painter.drawEllipse(self.viewCenter[0] - self.myPhotoRadius, self.viewCenter[1] - self.myPhotoRadius, self.myPhotoDiameter, self.myPhotoDiameter) painter.drawEllipse(centerPoint, self.myPhotoRadius, self.myPhotoRadius) # cardinal directions destRect.setCoords(self.viewCenter[0] - self.myPhotoRadius - (fontWidth+4), self.viewCenter[1] - self.fontMetrics.height()/2, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "W") destRect.setCoords(self.viewCenter[0] + self.myPhotoRadius + 4, self.viewCenter[1] - self.fontMetrics.height()/2, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "E") destRect.setCoords(self.viewCenter[0] - fontWidth/2, self.viewCenter[1] - self.myPhotoRadius - (self.fontMetrics.height()+3), self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "S") destRect.setCoords(self.viewCenter[0] - fontWidth/2, self.viewCenter[1] + self.myPhotoRadius + 3, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "N") # draw sampling pattern if common.AppSettings["ShowSamples"]: painter.setPen(self.penText) for i, points in enumerate(self.sampleAreaVisible): painter.drawLine(QLine(points[0], points[1])) painter.drawLine(QLine(points[1], points[2])) painter.drawLine(QLine(points[2], points[3])) painter.drawLine(QLine(points[3], points[0])) for i in range(0, len(self.samplePoints)): p = self.samplePoints[i] painter.drawEllipse(QPoint(p[0],p[1]), ViewFisheye.SampleRadius, ViewFisheye.SampleRadius) painter.drawText(p[0] + ViewFisheye.SampleRadius, p[1], str(i)) # draw sun path if common.AppSettings["ShowSunPath"]: sunradius = self.myPhotoRadius * 0.1 # shadows painter.setPen(self.penShadowSun) if common.AppSettings["ShowShadows"]: painter.drawEllipse(QPoint(self.sunPositionVisible[0]+1, self.sunPositionVisible[1]+1), sunradius, sunradius) self.pathSun.translate(1.0, 1.0) painter.drawPath(self.pathSun) self.pathSun.translate(-1.0, -1.0) for i in range(0, self.pathSun.elementCount()): e = self.pathSun.elementAt(i) destRect.setCoords(e.x, e.y + self.fontMetrics.height()/2 + 1, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(self.sunPathPoints[i][2].hour)) # sun, path, hours painter.setPen(self.penSun) painter.drawEllipse(QPoint(self.sunPositionVisible[0], self.sunPositionVisible[1]), sunradius, sunradius) painter.drawPath(self.pathSun) for i in range(0, self.pathSun.elementCount()): e = self.pathSun.elementAt(i) destRect.setCoords(e.x, e.y + self.fontMetrics.height() / 2, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(self.sunPathPoints[i][2].hour)) # draw selected samples (ALWAYS) r = QRect() # shadows if common.AppSettings["ShowShadows"]: painter.setPen(self.penShadowSelected) for i in self.samplesSelected: x, y = self.samplePoints[i] painter.drawEllipse(QPoint(x+1, y+1), ViewFisheye.SampleRadius, ViewFisheye.SampleRadius) # samples for i in self.samplesSelected: painter.setPen(self.penSelected[i]) x, y = self.samplePoints[i] painter.drawEllipse(QPoint(x, y), ViewFisheye.SampleRadius, ViewFisheye.SampleRadius) # draw user's selection bounds if (abs(self.dragSelectRect.right()-self.dragSelectRect.left()) >= ViewFisheye.SelectionRectMin and abs(self.dragSelectRect.bottom()-self.dragSelectRect.top()) >= ViewFisheye.SelectionRectMin): painter.setPen(self.penSelectRect) painter.drawRect(self.dragSelectRect) # draw timestamp painter.setPen(self.penText) painter.setFont(self.fontFixed) destRect.setCoords(10, 10, self.width() / 2, 50) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(self.myPhotoTime)) # draw sky cover assessment destRect.setCoords(10, 25, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, self.skyCover.name + "/" + common.SkyCoverDesc[self.skyCover]) # draw photo rotation if self.myPhotoRotation != 0: destRect.setCoords(10, self.height()-25, self.width(), self.height()) painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "Rotation: " + str(self.myPhotoRotation) + "°") # where is the mouse relative to the center? # this is used as an optimization to only display information when mouse is in fisheye portion dx = self.coordsMouse[0] - self.viewCenter[0] dy = self.coordsMouse[1] - self.viewCenter[1] distance = math.sqrt((dx * dx) + (dy * dy)) # distance from mouse to view center # coordinates we are interested in #self.coordsMouse # x,y of this widget coordsxy = (-1, -1) # x,y over photo as scaled/rendered on this widget coordsXY = (-1, -1) # x,y over actual original photo on disk coordsUV = (-1, -1) # u,v coords of fisheye portion of photo w/ 0,0 top left and 1,1 bottom right coordsTP = (-1, -1) # theta,phi polar coordinates # text textxy = "-1, -1 xy" textXY = "-1, -1 xy" textUV = "-1, -1 uv" textTP = "-1, -1 θφ" textPX = "0 0 0 px" # compute all relevant information only when mouse is within fisheye portion of photo if distance < self.myPhotoRadius: coordsxy = (self.coordsMouse[0] - self.myPhotoDestRect.x(), self.coordsMouse[1] - self.myPhotoDestRect.y()) coordsXY = (int(coordsxy[0] / self.myPhotoDestRect.width() * self.myPhoto.width()), int(coordsxy[1] / self.myPhotoDestRect.height() * self.myPhoto.height())) coordsUV = ((self.coordsMouse[0] - self.myPhotoTopLeft[0]) / self.myPhotoDiameter, (self.coordsMouse[1] - self.myPhotoTopLeft[1]) / self.myPhotoDiameter) coordsTP = utility_angles.FisheyeUV2SkyCoord(coordsUV[0], coordsUV[1]) # text textxy = str(coordsxy[0]) + ", " + str(coordsxy[1]) + " xy" textXY = str(coordsXY[0]) + ", " + str(coordsXY[1]) + " xy" textUV = "{:.2f}".format(coordsUV[0]) + ", " + "{:.2f}".format(coordsUV[1]) + " uv" textTP = "{:.2f}".format(coordsTP[0]) + ", " + "{:.2f}".format(coordsTP[1]) + " θφ" # pixels colors pixreg = common.AppSettings["PixelRegion"] colorsRegion = np.zeros((pixreg, pixreg, 4)) colorFinal = colorsRegion[0,0] # RGBA of pixel under mouse of photo on disk # colorFinal = self.myPhoto.pixelColor(coordsXY[0], coordsXY[1]) if distance < self.myPhotoRadius: halfdim = int(pixreg / 2) rstart = coordsXY[1]-halfdim rstop = coordsXY[1]+halfdim+1 cstart = coordsXY[0]-halfdim cstop = coordsXY[0]+halfdim+1 if (rstart >= 0 and rstop<=self.myPhotoPixels.shape[0] and cstart >= 0 and cstop<=self.myPhotoPixels.shape[1]): colorsRegion = self.myPhotoPixels[rstart:rstop, cstart:cstop] colorFinal = colorsRegion[halfdim, halfdim] if pixreg > 1: # with pixel weighting colorFinal = utility_data.collectPixels([coordsXY], [pixreg], pixels=self.myPhotoPixels, weighting=common.PixelWeighting(common.AppSettings["PixelWeighting"]))[0] textPX = str(colorFinal[0]) + " " + str(colorFinal[1]) + " " + str(colorFinal[2]) + " px" # draw HUD text strings # x,y coords destRect.setCoords(0, 0, self.width() - 10, self.height()- 124) painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textxy) # X,Y coords destRect.setCoords(0, 0, self.width() - 10, self.height() - 114) painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textXY) # u,v coords destRect.setCoords(0, 0, self.width() - 10, self.height() - 104) painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textUV) # t,p coords destRect.setCoords(0, 0, self.width() - 10, self.height() - 94) painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textTP) # pixel color destRect.setCoords(0, 0, self.width() - 10, self.height() - 84) painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textPX) # compute pixel visualization coordinates circleX = self.width() - 10 - ViewFisheye.SelectedPixelBox - 10 - ViewFisheye.SelectedPixelBox - 10 - ViewFisheye.SelectedPixelBox circleY = self.height() - 10 - ViewFisheye.SelectedPixelBox pixelsX = self.width() - 10 - ViewFisheye.SelectedPixelBox - 10 - ViewFisheye.SelectedPixelBox pixelsY = self.height() - 10 - ViewFisheye.SelectedPixelBox pixelsWeightedX = self.width() - ViewFisheye.SelectedPixelBox - 10 pixelsWeightedY = self.height() - 10 - ViewFisheye.SelectedPixelBox # draw pixel visualization - fills pixreg = common.AppSettings["PixelRegion"] if distance < self.myPhotoRadius: painter.setPen(Qt.NoPen) # pixel region pixdim = ViewFisheye.SelectedPixelBox / pixreg for row in range(0, pixreg): for col in range(0, pixreg): color = colorsRegion[row, col] color = QColor(color[0], color[1], color[2]) painter.setBrush(QBrush(color, Qt.SolidPattern)) painter.drawRect(pixelsX + (col * pixdim), pixelsY + (row * pixdim), math.ceil(pixdim), math.ceil(pixdim)) # final pixel color color = QColor(colorFinal[0], colorFinal[1], colorFinal[2]) painter.setBrush(QBrush(color, Qt.SolidPattern)) cx = circleX + (coordsUV[0] * ViewFisheye.SelectedPixelBox) cy = circleY + (coordsUV[1] * ViewFisheye.SelectedPixelBox) painter.drawEllipse(cx - 5, cy - 5, 10, 10) painter.drawRect(pixelsWeightedX, pixelsWeightedY, ViewFisheye.SelectedPixelBox, ViewFisheye.SelectedPixelBox) # draw pixel visualization - outlines painter.setPen(self.penText) painter.setBrush(Qt.NoBrush) painter.drawEllipse(circleX, circleY, ViewFisheye.SelectedPixelBox, ViewFisheye.SelectedPixelBox) painter.drawRect(pixelsX, pixelsY, ViewFisheye.SelectedPixelBox, ViewFisheye.SelectedPixelBox) painter.drawRect(pixelsWeightedX, pixelsWeightedY, ViewFisheye.SelectedPixelBox, ViewFisheye.SelectedPixelBox) # raw data missing indicator # if (not self.rawAvailable): # painter.drawPixmap(pixelX + ViewFisheye.SelectedPixelBox / 2, # pixelY + ViewFisheye.SelectedPixelBox / 2, # self.iconWarning) # end draw painter.end()
def __init__(self): super().__init__() self.drawing = False self.lastPoint = QPoint() self.frameButtons = QFrame() self.crewPlace = False self.currentColor = QColor("Transparent") self.playerPins = [] self.colorList = [ Qt.red, Qt.blue, QColor(255, 165, 0), QColor(255, 255, 255), Qt.black, QColor(0, 255, 255), Qt.yellow, QColor(255, 192, 203), QColor(128, 0, 128), QColor(0, 255, 0), QColor(0, 128, 0), QColor(165, 42, 42) ] self.labelToMove = None # Map image self.mapLabel = QLabel() oldimage = QPixmap("./skeld_map.png") image = oldimage.scaled(1200, 1200, Qt.KeepAspectRatio, Qt.FastTransformation) self.mapLabel.setPixmap(image) self.savedPixmap = image # Buttons self.buttonBox = QGroupBox(self) self.colorLayout = QHBoxLayout(self.buttonBox) crewmateSelector = QPushButton("Place crewmate", self.buttonBox) crewmateSelector.clicked.connect(lambda: crewPlace.crewPlaceMode(self)) redSelector = QPushButton(self.buttonBox) redSelector.setStyleSheet("background-color: red") redSelector.clicked.connect(lambda: self.changeColor(Qt.red)) blueSelector = QPushButton(self.buttonBox) blueSelector.setStyleSheet("background-color: blue") blueSelector.clicked.connect(lambda: self.changeColor(Qt.blue)) orangeSelector = QPushButton(self.buttonBox) orangeSelector.setStyleSheet("background-color: orange") orangeSelector.clicked.connect( lambda: self.changeColor(QColor(255, 165, 0))) whiteSelector = QPushButton(self.buttonBox) whiteSelector.setStyleSheet("background-color: white") whiteSelector.clicked.connect( lambda: self.changeColor(QColor(255, 255, 255))) blackSelector = QPushButton(self.buttonBox) blackSelector.setStyleSheet("background-color: black") blackSelector.clicked.connect(lambda: self.changeColor(Qt.black)) cyanSelector = QPushButton(self.buttonBox) cyanSelector.setStyleSheet("background-color: cyan") cyanSelector.clicked.connect( lambda: self.changeColor(QColor(0, 255, 255))) yellowSelector = QPushButton(self.buttonBox) yellowSelector.setStyleSheet("background-color: yellow") yellowSelector.clicked.connect(lambda: self.changeColor(Qt.yellow)) pinkSelector = QPushButton(self.buttonBox) pinkSelector.setStyleSheet("background-color: pink") pinkSelector.clicked.connect( lambda: self.changeColor(QColor(255, 192, 203))) purpleSelector = QPushButton(self.buttonBox) purpleSelector.setStyleSheet("background-color: purple") purpleSelector.clicked.connect( lambda: self.changeColor(QColor(128, 0, 128))) limeSelector = QPushButton(self.buttonBox) limeSelector.setStyleSheet("background-color: lime") limeSelector.clicked.connect( lambda: self.changeColor(QColor(0, 255, 0))) greenSelector = QPushButton(self.buttonBox) greenSelector.setStyleSheet("background-color: green") greenSelector.clicked.connect( lambda: self.changeColor(QColor(0, 128, 0))) brownSelector = QPushButton(self.buttonBox) brownSelector.setStyleSheet("background-color: brown") brownSelector.clicked.connect( lambda: self.changeColor(QColor(165, 42, 42))) eraserSelector = QPushButton("Erase", self.buttonBox) eraserSelector.clicked.connect(lambda: self.erase()) self.colorLayout.addWidget(crewmateSelector) self.colorLayout.addWidget(redSelector) self.colorLayout.addWidget(blueSelector) self.colorLayout.addWidget(orangeSelector) self.colorLayout.addWidget(whiteSelector) self.colorLayout.addWidget(blackSelector) self.colorLayout.addWidget(cyanSelector) self.colorLayout.addWidget(yellowSelector) self.colorLayout.addWidget(pinkSelector) self.colorLayout.addWidget(purpleSelector) self.colorLayout.addWidget(limeSelector) self.colorLayout.addWidget(greenSelector) self.colorLayout.addWidget(brownSelector) self.colorLayout.addWidget(eraserSelector) self.buttonBox.setGeometry( QRect(0, self.mapLabel.pixmap().height(), self.mapLabel.pixmap().width(), 50)) # Window settings self.setGeometry( QRect(0, 0, self.mapLabel.pixmap().width(), self.mapLabel.pixmap().height() + self.buttonBox.height())) self.setFixedSize( self.mapLabel.pixmap().width(), self.mapLabel.pixmap().height() + self.buttonBox.height()) self.setWindowTitle("CrewMap | @author : Maxime Missichini") self.setWindowIcon(QIcon("./assets/icon.png")) self.show()
def clearChart(self): self.color = QColor(Qt.transparent) self.update() self.chartCleared.emit()
class FlowViewStyle(object): BackgroundColor = QColor() FineGridColor = QColor() CoarseGridColor = QColor() def __init__(self, jsonFile: str = "./DefaultStyle.json", jsonText: str = None): self.loadJsonFile(jsonFile) if (jsonText): self.loadJsonText(jsonText) #------------------------------------------------------------------------- def loadJsonFile(self, styleFile: str): file = QFile(styleFile) if (not file.open(QIODevice.ReadOnly)): print("Couldn't open file: {}".format(styleFile)) return self.loadJsonFromByteArray(file.readAll()) #------------------------------------------------------------------------- def setStyle(self, jsonText: str): self.style = FlowViewStyle(jsonText) self.StyleCollection.setFlowViewStyle(style) #------------------------------------------------------------------------- def loadJsonFromByteArray(self, byteArray: QByteArray): json = QJsonDocument(QJsonDocument.fromJson(byteArray)) topLevelObject = json.object() nodeStyleValues = topLevelObject["FlowViewStyle"] obj = nodeStyleValues.toObject() self.BackgroundColor = self.flowViewStyleReadColor( obj, "BackgroundColor") self.FineGridColor = self.flowViewStyleReadColor(obj, "FineGridColor") self.CoarseGridColor = self.flowViewStyleReadColor( obj, "CoarseGridColor") #------------------------------------------------------------------------- def flowViewStyleCheckUndefinedValue(self, v, variable): if (type(v) == QJsonValue.Undefined or type(v) == QJsonValue.Null): qWarning("Undefined value for parameter: ", variable) #------------------------------------------------------------------------- def flowViewStyleReadColor(self, values, variable) -> QColor: valuesRef = values[variable] self.flowViewStyleCheckUndefinedValue(valuesRef, variable) if (valuesRef.isArray()): colorArray = valuesRef.toArray() rgb = [] for it in colorArray: rgb.append(it.toDouble()) return QColor(rgb[0], rgb[1], rgb[2]) else: return QColor(valueRef.toString()) #------------------------------------------------------------------------- def loadJsonText(self, jsonText: str): self.loadJsonFromByteArray(jsonText)
def color(self, color): self._color = QColor(color)
def select_img_click(self): try: self.ImgsList.clear() self.Clear() # 得到图片所在文件夹dir_path self.dir_path = QtWidgets.QFileDialog.getExistingDirectory(self,'选择文件夹') # 存点和带点图片的文件夹 self.PointsPath = os.path.join(self.dir_path,'points') self.ImgWithPointsPath = os.path.join(self.dir_path,'ImgWithPoints') dir_list = os.listdir(self.dir_path) img_list = [] ## 将图片文件放到列表框中 for dir in dir_list: suffix_list = ['jpg','png','jpeg','bmp'] if dir.split('.')[-1].lower() in suffix_list: # print(dir) img_list.append(dir) self.ImgsList.addItem(dir) if len(img_list) > 0: # 图像文件索引字典 self.totalnum = len(img_list) self.img_index_dict = dict() self.file_index_dict = dict() for i,d in enumerate(img_list): self.img_index_dict[i] = d self.file_index_dict[d] = i # print(self.img_index_dict) # 查找当前已标记图像并显示为红色 self.MarkedImg_index_dict = dict() if(os.path.exists(self.PointsPath)): marked_list = os.listdir(self.PointsPath) for dir in marked_list: file = os.path.splitext(dir)[0] if file in self.file_index_dict: self.MarkedImg_index_dict[file] = 1 self.ImgsList.item(self.file_index_dict.get(file)).setForeground(QColor('red')) self.current_index = 0 # 当前的图像索引 # 当前图片文件路径 self.current_filename = os.path.join( self.dir_path,self.img_index_dict[self.current_index] ) # 实例化一个图像 self.Imgshow() # 当前文件名 self.current_text = self.img_index_dict[self.current_index].split('.')[0] self.ImgShow.update() # 设置ImgNamet控件文本内容 self.ImgName.setText(self.current_text) # 启用其他按钮 # self.markButton.setEnabled(True) self.preButton.setEnabled(True) self.nextButton.setEnabled(True) self.UndoButton.setEnabled(True) self.zoominButton.setEnabled(True) self.zoomoutButton.setEnabled(True) self.CancelButton.setEnabled(True) self.remarkButton.setEnabled(True) self.saveButton.setEnabled(True) # 判断当前图片是否已被标注 self.ismarked() # # 设置图片数量信息 self.ImgNum.setText("{}/{}".format(self.current_index+1,self.totalnum)) else: QtWidgets.QMessageBox.information( self,'提示','文件夹没有发现图片文件!', QtWidgets.QMessageBox.Ok ) except Exception as e: print(repr(e))
def on_update(self): def item_path( item ): # Recursively builds the path for an item eg 'parent_name/item_name' return item.text(0) if not item.parent() else item_path( item.parent()) + "/" + item.text(0) def remember_expanded_items(root): # Save the set of expanded items... so that address list updates don't annoyingly collapse # our tree list widget due to the update. This function recurses. Pass self.invisibleRootItem(). expanded_item_names = set() for i in range(0, root.childCount()): it = root.child(i) if it and it.childCount(): if it.isExpanded(): expanded_item_names.add(item_path(it)) expanded_item_names |= remember_expanded_items( it) # recurse return expanded_item_names def restore_expanded_items(root, expanded_item_names): # Recursively restore the expanded state saved previously. Pass self.invisibleRootItem(). for i in range(0, root.childCount()): it = root.child(i) if it and it.childCount(): restore_expanded_items( it, expanded_item_names) # recurse, do leaves first old = bool(it.isExpanded()) new = bool(item_path(it) in expanded_item_names) if old != new: it.setExpanded(new) self.wallet = self.parent.wallet had_item_count = self.topLevelItemCount() item = self.currentItem() current_address = item.data(0, Qt.UserRole) if item else None expanded_item_names = remember_expanded_items(self.invisibleRootItem()) self.clear() receiving_addresses = self.wallet.get_receiving_addresses() change_addresses = self.wallet.get_change_addresses() if self.parent.fx and self.parent.fx.get_fiat_address_config(): fx = self.parent.fx else: fx = None account_item = self sequences = [0, 1] if change_addresses else [0] items_to_re_select = [] for is_change in sequences: if len(sequences) > 1: name = _("Receiving") if not is_change else _("Change") seq_item = QTreeWidgetItem([name, '', '', '', '', '']) account_item.addChild(seq_item) if not is_change and not had_item_count: # first time we create this widget, auto-expand the default address list seq_item.setExpanded(True) expanded_item_names.add(item_path(seq_item)) else: seq_item = account_item used_item = QTreeWidgetItem([_("Used"), '', '', '', '', '']) used_flag = False addr_list = change_addresses if is_change else receiving_addresses for n, address in enumerate(addr_list): num = len(self.wallet.get_address_history(address)) is_used = self.wallet.is_used(address) balance = sum(self.wallet.get_addr_balance(address)) address_text = address.to_ui_string() label = self.wallet.labels.get(address.to_storage_string(), '') balance_text = self.parent.format_amount(balance, whitespaces=True) columns = [address_text, str(n), label, balance_text, str(num)] if fx: rate = fx.exchange_rate() fiat_balance = fx.value_str(balance, rate) columns.insert(4, fiat_balance) address_item = SortableTreeWidgetItem(columns) address_item.setTextAlignment(3, Qt.AlignRight) address_item.setFont(3, QFont(MONOSPACE_FONT)) if fx: address_item.setTextAlignment(4, Qt.AlignRight) address_item.setFont(4, QFont(MONOSPACE_FONT)) address_item.setFont(0, QFont(MONOSPACE_FONT)) address_item.setData(0, Qt.UserRole, address) address_item.setData(0, Qt.UserRole + 1, True) # label can be edited if self.wallet.is_frozen(address): address_item.setBackground(0, QColor('lightblue')) if self.wallet.is_beyond_limit(address, is_change): address_item.setBackground(0, QColor('red')) if is_used: if not used_flag: seq_item.insertChild(0, used_item) used_flag = True used_item.addChild(address_item) else: seq_item.addChild(address_item) if address == current_address: items_to_re_select.append(address_item) if items_to_re_select: # NB: Need to select the item at the end becasue internally Qt does some index magic # to pick out the selected item and the above code mutates the TreeList, invalidating indices # and other craziness, which might produce UI glitches. See #1042 self.setCurrentItem(items_to_re_select[-1]) # Now, at the very end, enforce previous UI state with respect to what was expanded or not. See #1042 restore_expanded_items(self.invisibleRootItem(), expanded_item_names)
def drawSquare(self, painter, x, y, type): color = QColor(self.colors[type]) painter.fillRect(x, y, self.square_width, self.square_height, color)
def highlightBlock(self, text): comments = [] def inComment(i): ''' checks if position i is inside a block comment ''' for c in comments: if c[0] <= i <= c[1]: return True fmKeyword = QTextCharFormat() fmKeyword.setFontWeight(QFont.Bold) fmKeyword.setForeground(QColor('#808')) fmComment = QTextCharFormat() fmComment.setForeground(QColor('#080')) fmLiteral = QTextCharFormat() fmLiteral.setForeground(QColor('#00F')) keywords = [ 'select', 'from', 'order\s+by', 'group\s+by', 'where', 'inner', 'left', 'right', 'outer', 'join', 'as', 'on', 'with', 'distinct', 'create', 'drop', 'procedure', 'table', 'truncate', 'function', 'where', 'asc', 'desc', 'case', 'when', 'else', 'and', 'or', 'like', 'round', 'count', 'sum', 'min', 'max', 'avg', 'updtae', 'insert', 'into', 'call', 'do', 'begin', 'end', 'then', 'if', 'in', 'not', 'between', 'having', 'union\s+all', 'union', 'except' ] rules = [] #check multi line comments self.setCurrentBlockState(0) startIndex = 0 if (self.previousBlockState() != 1): startIndex = text.find('/*') while startIndex >= 0: endIndex = text.find('*/', startIndex) if endIndex == -1: self.setCurrentBlockState(1) commentLength = len(text) - startIndex else: commentLength = endIndex - startIndex + 2 self.setFormat(startIndex, commentLength, fmComment) comments.append((startIndex, startIndex + commentLength)) startIndex = text.find('/*', startIndex + commentLength) # if the whole block is a comment - just skip the rest rules if len(comments) == 1: c = comments[0] if c[0] == 0 and c[1] == len(text): return for kw in keywords: rules.append(['\\b' + kw + '\\b', fmKeyword, False]) # literals rules.append(['\'.*?\'', fmLiteral, False]) rules.append(['".+?"', fmLiteral, False]) # one line comment rules.append(['--.+', fmComment, True]) for r in rules: (pattern, format, stop) = (r[0], r[1], r[2]) ml = re.finditer(pattern, text, re.I) i = 0 for m in ml: i += 1 if not inComment(m.start(0)): self.setFormat(m.start(0), len(m.group(0)), format) if i > 0 and stop: # do not apply other rules # for example in case of single line comments break
def draw_circles(self, qp): qp.setBrush(QColor(0, 0, 0, 0)) for color, data in self.circles: pen = QPen(QColor(*color), 5) qp.setPen(pen) qp.drawEllipse(*data)
PREF_AUTOSCAF_INDEX = 0 PREF_STARTUP_TOOL_INDEX = 0 PREF_ZOOM_SPEED = 20 #50 PREF_ZOOM_AFTER_HELIX_ADD = True PREF_SHOW_ICON_LABELS = True THE_FONT = None THE_FONT_SIZE = None if util.isMac(): THE_FONT = "Times" THE_FONT = "Arial" THE_FONT_SIZE = 10 elif util.isWindows(): THE_FONT = "Segoe UI" THE_FONT = "Calibri" THE_FONT = "Arial" THE_FONT_SIZE = 9 else: # linux THE_FONT = "DejaVu Sans" THE_FONT_SIZE = 9 BLUE_FILL = QColor(153, 204, 255) # 99ccff BLUE_STROKE = QColor(0, 102, 204) # 0066cc BLUISH_STROKE = QColor(0, 182, 250) # ORANGE_FILL = QColor(255, 204, 153) # ffcc99 ORANGE_STROKE = QColor(204, 102, 51) # cc6633 LIGHT_ORANGE_FILL = QColor(255, 234, 183) LIGHT_ORANGE_STROKE = QColor(234, 132, 81) GRAY_FILL = QColor(238, 238, 238) # eeeeee (was a1a1a1) GRAY_STROKE = QColor(102, 102, 102) # 666666 (was 424242)
def __init__(self, buffer_id, url): Buffer.__init__(self, buffer_id, url, False, QColor(0, 0, 0, 255)) self.add_widget(PdfViewerWidget(url, QColor(0, 0, 0, 255)))
def setupLayers(self): layers = [] op = self.topLevelOperatorView binct = [QColor(Qt.black), QColor(Qt.white)] binct[0] = 0 ct = create_default_16bit() ct[0] = 0 # Show the cached output, since it goes through a blocked cache if op.CachedOutput.ready(): outputSrc = LazyflowSource(op.CachedOutput) outputLayer = ColortableLayer(outputSrc, ct) outputLayer.name = "Final output" outputLayer.visible = False outputLayer.opacity = 1.0 outputLayer.setToolTip("Results of thresholding and size filter") layers.append(outputLayer) if op.InputChannelColors.ready(): input_channel_colors = [ QColor(r_g_b1[0], r_g_b1[1], r_g_b1[2]) for r_g_b1 in op.InputChannelColors.value ] else: input_channel_colors = list( map(QColor, self._defaultInputChannelColors)) for channel, channelProvider in enumerate(self._channelProviders): slot_drange = channelProvider.Output.meta.drange if slot_drange is not None: drange = slot_drange else: drange = (0.0, 1.0) channelSrc = LazyflowSource(channelProvider.Output) inputChannelLayer = AlphaModulatedLayer( channelSrc, tintColor=input_channel_colors[channel], range=drange, normalize=drange) inputChannelLayer.opacity = 0.5 inputChannelLayer.visible = True inputChannelLayer.name = "Input Channel " + str(channel) inputChannelLayer.setToolTip("Select input channel " + str(channel) + \ " if this prediction image contains the objects of interest.") layers.append(inputChannelLayer) if self._showDebug: #FIXME: We have to do that, because lazyflow doesn't have a way to make an operator partially ready curIndex = op.CurOperator.value if curIndex == 1: if op.BigRegions.ready(): lowThresholdSrc = LazyflowSource(op.BigRegions) lowThresholdLayer = ColortableLayer(lowThresholdSrc, binct) lowThresholdLayer.name = "After low threshold" lowThresholdLayer.visible = False lowThresholdLayer.opacity = 1.0 lowThresholdLayer.setToolTip( "Results of thresholding with the low pixel value threshold" ) layers.append(lowThresholdLayer) if op.FilteredSmallLabels.ready(): filteredSmallLabelsSrc = LazyflowSource( op.FilteredSmallLabels) #filteredSmallLabelsLayer = self.createStandardLayerFromSlot( op.FilteredSmallLabels ) filteredSmallLabelsLayer = ColortableLayer( filteredSmallLabelsSrc, binct) filteredSmallLabelsLayer.name = "After high threshold and size filter" filteredSmallLabelsLayer.visible = False filteredSmallLabelsLayer.opacity = 1.0 filteredSmallLabelsLayer.setToolTip( "Results of thresholding with the high pixel value threshold,\ followed by the size filter" ) layers.append(filteredSmallLabelsLayer) if op.SmallRegions.ready(): highThresholdSrc = LazyflowSource(op.SmallRegions) highThresholdLayer = ColortableLayer( highThresholdSrc, binct) highThresholdLayer.name = "After high threshold" highThresholdLayer.visible = False highThresholdLayer.opacity = 1.0 highThresholdLayer.setToolTip( "Results of thresholding with the high pixel value threshold" ) layers.append(highThresholdLayer) elif curIndex == 0: if op.BeforeSizeFilter.ready(): thSrc = LazyflowSource(op.BeforeSizeFilter) thLayer = ColortableLayer(thSrc, ct) thLayer.name = "Before size filter" thLayer.visible = False thLayer.opacity = 1.0 thLayer.setToolTip( "Results of thresholding before the size filter is applied" ) layers.append(thLayer) # Selected input channel, smoothed. if op.Smoothed.ready(): smoothedLayer = self.createStandardLayerFromSlot(op.Smoothed) smoothedLayer.name = "Smoothed input" smoothedLayer.visible = True smoothedLayer.opacity = 1.0 smoothedLayer.setToolTip( "Selected channel data, smoothed with a Gaussian with user-defined sigma" ) layers.append(smoothedLayer) # Show the raw input data rawSlot = self.topLevelOperatorView.RawInput if rawSlot.ready(): rawLayer = self.createStandardLayerFromSlot(rawSlot) rawLayer.name = "Raw data" rawLayer.visible = True rawLayer.opacity = 1.0 layers.append(rawLayer) return layers
def current_color(pixmap): image = pixmap.toImage() return QColor(image.pixel(0, 0))
def paintEvent(self, event): painter = QPainter(self) painter.fillRect(event.rect(), QColor(212, 212, 212))
class DyTableWidget(QTableWidget): highlightBackground = QColor('#FFD700') def __init__(self, parent=None, readOnly=False, index=True, floatCut=True, autoScroll=True, floatRound=2): """ @index: 是否要插入默认行索引(Org.) @floatRound: 小数点后格式化成几位, 只在@floatCut is True时有效 """ super().__init__(parent) self.setSortingEnabled(True) self.verticalHeader().setVisible(False) if readOnly: self.setEditTriggers(QTableWidget.NoEditTriggers) self.setSelectionBehavior(QAbstractItemView.SelectRows) self._role = Qt.DisplayRole if readOnly else Qt.EditRole self.__index = index # 原始插入的行索引 self._floatCut = floatCut self._floatRoundFormat = '%.{0}f'.format(floatRound) self._autoForegroundCol = None # 指定前景色关键列,如果此列对应的值改变时,将改变所对应行的前景色。包含'Org.'列 self._enableAutoScroll = autoScroll self.setColNames([]) self._initItemMenu() self._initRows() def _initRows(self): self._itemsMap = {} # 由行关键字建立的item的字典, {key: [item]} # mark self._markedItem = None self._markedItemOriginalBackground = None self._markedItemsOriginalForeground = [] # highlight, item is one of item in one row self._highlightedItems = [ ] # [[item, [highlightedItemsOriginalForeground], [highlightedItemsOriginalBackground]]] # find self._findItems = [] self._curFindItemPos = 0 def _clearHighlight(self): # reproduce highlighed items because during cancel highlight procedure element will be deleted from @self._highlightedItems highlightedItems = [item[0] for item in self._highlightedItems] for item in highlightedItems: self._highlight(item) def _clearVisualEffects(self): self._mark(self._markedItem) self._clearHighlight() def __getitem__(self, indices): row, col = indices item = self._getItem(row, col) if item is None: return None return DyCommon.toNumber(item.data(self._role)) def _getItem(self, row, col): # row if isinstance(row, str): item = None if row in self._itemsMap: item = self._itemsMap[row][0] if item is None: return None row = item.row() # column if isinstance(col, int): if self.__index: col += 1 else: col = self._getColPos(col) # get item try: item = self.item(row, col) except: item = None return item def _updateItemsMap(self, rowKey, col, item): if rowKey not in self._itemsMap: self._itemsMap[rowKey] = [] rowLen = len(self._itemsMap[rowKey]) for i in range(rowLen, col + 1): self._itemsMap[rowKey].append(None) self._itemsMap[rowKey][col] = item def _getColPos(self, colName): for i in range(self.columnCount()): item = self.horizontalHeaderItem(i) if colName == item.text(): return i return None def _updateItem(self, row, col, value): """ Update one item, @row and @col can be string or integer. It's gengeral function. @col is included Org. for @col is integer, i.e. it's absolute updating. """ if isinstance(row, str): self._updateItemByRowKey(row, col, value) else: self._updateItemByRowPos(row, col, value) def _updateItemByRowPos(self, row, col, value): if isinstance(col, str): colPos = self._getColPos(col) if colPos is None: # insert a new column with column name colPos = self.columnCount() item = QTableWidgetItem(col) self.setHorizontalHeaderItem(colPos, item) col = colPos # now we take it by positions self._updateItemByPos(row, col, value) def _getColPosWithCreation(self, colName): colPos = self._getColPos(col) if colPos is None: # insert a new column with column name colPos = self.columnCount() item = QTableWidgetItem(col) self.setHorizontalHeaderItem(colPos, item) return colPos def _setAutoRowForeground(self, item): if self._autoForegroundCol is None: return # ignore 'Org.' column if self.__index and item.column() == 0: return # get forground of reference item row = item.row() refItem = self.item(row, self._autoForegroundCol) if not refItem: return # set forground same as reference item item.setForeground(refItem.foreground()) # we still need to go through row if value of reference item changed if item.column() == self._autoForegroundCol: # get foreground for row color = self.getForegroundOverride(item.data(self._role)) if color is None: if item.background() == Qt.white: # for qdarkstyle color = Qt.black else: color = Qt.white # no foreground changed if item.foreground() == color: return for i in range(self.columnCount()): if self.__index and i == 0: continue item = self.item(row, i) if item: item.setForeground(color) def _setItemData(self, item, value): """ 设置Item的值和相应的格式 string值将会保持原始格式 """ assert value is None or isinstance(value, float) or isinstance( value, int) or isinstance(value, str), 'type(value) is {0}'.format( type(value)) # set data if isinstance(value, float): if not np.isnan(value): if self._floatCut: value = self._floatRoundFormat % value else: value = None item.setData(self._role, value) # set auto row color self._setAutoRowForeground(item) if self._enableAutoScroll: self.scrollToItem(item) def _setItemDataFast(self, item, value): """ 快速设置Item的值 string值将会保持原始格式 """ assert value is None or isinstance(value, float) or isinstance( value, int) or isinstance(value, str), 'type(value) is {0}'.format( type(value)) # set data if isinstance(value, float): if not np.isnan(value): if self._floatCut: value = self._floatRoundFormat % value else: value = None item.setData(self._role, value) def _newItemByRowKey(self, rowKey, col, value): if rowKey in self._itemsMap: row = self._itemsMap[rowKey][0].row() else: row = self.rowCount() if isinstance(col, str): col = self._getColPosWithCreation(col) # now we take it by positions item = self._updateItemByPos(row, col, value) # update to items map self._updateItemsMap(rowKey, col, item) def _updateItemByRowKey(self, rowKey, col, value): isExistingItem = False if rowKey in self._itemsMap: if isinstance(col, str): colPos = self._getColPos(col) else: colPos = col if colPos is not None: if colPos < len(self._itemsMap[rowKey]): if self._itemsMap[rowKey][ colPos] is not None: # item existing self._setItemData(self._itemsMap[rowKey][colPos], value) isExistingItem = True if not isExistingItem: self._newItemByRowKey(rowKey, col, value) def _updateItemByPos(self, row, col, value): # get item if existing item = self.item(row, col) # new item if item is None: # enlarge rowCount = self.rowCount() colCount = self.columnCount() if row >= rowCount: self.setRowCount(row + 1) if col >= colCount: self.setColumnCount(col + 1) # add new item item = DyTableWidgetItem(self._role) self.setItem(row, col, item) # Should call @setItem firstly, then set data self._setItemData(item, value) return item def _update(self, indices, value): """ Update one row by @indices is row key or row position, @value is [x, x, x, ...] or one item by @indices is (row key or row position, column name or column position), @value is x. position is from 0. """ if isinstance(indices, tuple): row, col = indices else: row, col = indices, None # add one row # update Org. if self.__index: if isinstance(row, str): # row key if row not in self._itemsMap: # first updating self._updateItem(row, 0, self.rowCount() + 1) else: if not self.item(row, 0): # first updating self._updateItem(row, 0, row + 1) # value is row No. from 1 offset = 1 # offset for column else: offset = 0 # offset for column if col is None: # row for col, v in enumerate(value, offset): self._updateItem(row, col, v) else: # one item self._updateItem(row, (col + offset) if isinstance(col, int) else col, value) def __setitem__(self, indices, value): """ add one row like obj[x] = [v,v,..] add one like obj[x,y] = v """ self.setSortingEnabled(False) self._update(indices, value) self.resizeColumnsToContents() self.resizeRowsToContents() self.setSortingEnabled(True) def addColNames(self, names): colStart = self.columnCount() self.setColumnCount(colStart + len(names)) for col, name in enumerate(names, colStart): colItem = self.horizontalHeaderItem(col) if colItem is None: colItem = QTableWidgetItem(col) self.setHorizontalHeaderItem(col, colItem) colItem.setText(name) #self.resizeColumnsToContents() def hasIndex(self): return self.__index def addColName(self, col, name): if self.__index: col += 1 if col >= self.columnCount(): self.setColumnCount(col + 1) colItem = self.horizontalHeaderItem(col) if colItem is None: colItem = QTableWidgetItem(col) self.setHorizontalHeaderItem(col, colItem) colItem.setText(name) #self.resizeColumnsToContents() def setHeaderForeground(self, color): """ 只能设置整个header http://stackoverflow.com/questions/36196988/color-individual-horizontal-headers-of-qtablewidget-in-pyqt @color: string, like 'red' """ self.horizontalHeader().setStyleSheet('color:' + color) def setColName(self, col, name): if self.__index: col += 1 colItem = self.horizontalHeaderItem(col) if colItem: colItem.setText(name) self.resizeColumnsToContents() def setColNames(self, names=None): """ @names:[name1, name2] """ if names is None: return if self.__index: newNames = ['Org.'] + names else: newNames = names self.setColumnCount(len(newNames)) self.setHorizontalHeaderLabels(newNames) self.resizeColumnsToContents() def setItemForeground(self, row, col, color): if self.__index: col += 1 try: self.item(row, col).setForeground(color) except Exception as ex: pass def setItemBackground(self, row, col, color): if self.__index: col += 1 try: self.item(row, col).setBackground(color) except Exception as ex: pass def setRowForeground(self, row, color): try: colCount = self.columnCount() start, end = (1, colCount) if self.__index else (0, colCount) for col in range(start, end): self.item(row, col).setForeground(color) except Exception as ex: pass def setRowBackground(self, row, color): try: colCount = self.columnCount() start, end = (1, colCount) if self.__index else (0, colCount) for col in range(start, end): self.item(row, col).setBackground(color) except Exception as ex: pass def append(self, rows, header=None, autoForegroundColName=None): """ @rows: [[x,x,x],[x,x,x],...] @header: [x,x,x] """ self.setSortingEnabled(False) if header: self.setColNames(header) if autoForegroundColName: self.setAutoForegroundCol(autoForegroundColName) rowCount = self.rowCount() self.setRowCount(rowCount + len(rows)) for rowIndex, rowData in enumerate(rows, rowCount): self._update(rowIndex, rowData) self.resizeColumnsToContents() self.resizeRowsToContents() self.setSortingEnabled(True) def appendRow(self, row, new=False, disableSorting=True): """ @row: [x,x,x] @return: row position of added row(starting from 0) """ if disableSorting: self.setSortingEnabled(False) if new: self.clearAllRows() rowCount = self.rowCount() self._update(rowCount, row) self.resizeColumnsToContents() self.resizeRowsToContents() if disableSorting: self.setSortingEnabled(True) return rowCount def setAutoForegroundCol(self, colName): self._autoForegroundCol = self._getColPos(colName) def getAutoForegroundColName(self): if self._autoForegroundCol is None: return None autoForegroundCol = self._autoForegroundCol - 1 if self.__index else self._autoForegroundCol return self.getColName(autoForegroundCol) def _autoScrollAct(self): self._enableAutoScroll = not self._enableAutoScroll if self._enableAutoScroll: self._autoScrollAction.setText('关闭自动滚动') else: self._autoScrollAction.setText('开启自动滚动') def _visibleMarkAct(self): if self._markedItem is not None: self.scrollToItem(self._markedItem) def _isInHighlight(self, item): row = item.row() for highlightedItems in self._highlightedItems: if highlightedItems[0].row() == row: return True return False def _setMark(self): row = self._markedItem.row() markBg = QColor(Qt.yellow) self.setRowBackground(row, markBg) for col in range(self.columnCount()): if self.__index and col == 0: self._markedItemsOriginalForeground.append(None) continue item = self.item(row, col) fg = item.foreground().color() # only change qdarkstyle default foreground if fg == QColor(0, 0, 0) or fg == QColor(192, 192, 192): item.setForeground(QColor(0, 0, 0)) # for qdarkstyle default foreground if fg == QColor(0, 0, 0): fg = QColor(192, 192, 192) # save self._markedItemsOriginalForeground.append(fg) def _setHighlight(self, item): row = item.row() highlightedItemsForeground = [] highlightedItemsBackground = [] self._highlightedItems.append( [item, highlightedItemsForeground, highlightedItemsBackground]) for col in range(self.columnCount()): if self.__index and col == 0: highlightedItemsForeground.append(None) highlightedItemsBackground.append(None) continue item = self.item(row, col) fg = item.foreground().color() bg = item.background() # only change qdarkstyle default foreground if fg == QColor(0, 0, 0) or fg == QColor(192, 192, 192): item.setForeground(QColor(0, 0, 0)) # for qdarkstyle default foreground if fg == QColor(0, 0, 0): fg = QColor(192, 192, 192) item.setBackground(self.highlightBackground) # save highlightedItemsForeground.append(fg) highlightedItemsBackground.append(bg) def _resetMark(self): row = self._markedItem.row() self.setRowBackground(row, self._markedItemOriginalBackground) for col in range(self.columnCount()): if self.__index and col == 0: continue item = self.item(row, col) # 如果标记后添加列,可能会导致超出 if col < len(self._markedItemsOriginalForeground): item.setForeground(self._markedItemsOriginalForeground[col]) def _resetHighlight(self, highlightItem): row = highlightItem[0].row() for col in range(self.columnCount()): if self.__index and col == 0: continue item = self.item(row, col) # 如果标记后添加列,可能会导致超出 if col < len(highlightItem[1]): item.setForeground(highlightItem[1][col]) # 如果标记后添加列,可能会导致超出 if col < len(highlightItem[2]): item.setBackground(highlightItem[2][col]) def markByData(self, colName, itemData): """ @colName: 指定item所在的列名 @itemData: item的数据 """ col = self._getColPos(colName) if col is None: return for row in range(self.rowCount()): if self[row, col] == itemData: item = self.item(row, col) self._mark(item) break def _highlightSameItemContent(self, item, clearHightlight=True): """ @clearHightlight: 是否清除先前的高亮 """ if item is None: return if clearHightlight: self._clearHighlight() text = item.text() col = item.column() for row in range(self.rowCount()): item = self.item(row, col) if item.text() == text: self._highlight(item, withCancel=False) def _highlight(self, item, withCancel=True): """ @withCancel: True-对已经高亮的item高亮,则清除该高亮 """ if item is None: return row = item.row() if self._markedItem is not None and self._markedItem.row() == row: return # 取消鼠标所在行的高亮 cancelHighlight = False for i, highlightedItem in enumerate(self._highlightedItems): if highlightedItem[0].row() == row: # 已经高亮过了 if not withCancel: return self._resetHighlight(highlightedItem) cancelHighlight = True break if cancelHighlight: del self._highlightedItems[i] return # highlight self._setHighlight(item) def _mark(self, item): if item is None: return if self._isInHighlight(item): return # 取消鼠标所在行的标记 if self._markedItem is not None and self._markedItem.row() == item.row( ): self._resetMark() self._markedItem = None self._markedItemsOriginalForeground = [] return # unmark previous if self._markedItem is not None: self._resetMark() self._markedItem = None self._markedItemsOriginalForeground = [] # save for new mark self._markedItemOriginalBackground = item.background() self._markedItem = item self._setMark() def _markAct(self): item = self.itemAt(self._rightClickPoint) self._mark(item) def _highlightAct(self): item = self.itemAt(self._rightClickPoint) self._highlight(item) def _highlightSameItemContentAct(self): item = self.itemAt(self._rightClickPoint) clearAction, notClearAction = self._highlightSameItemContentActions if notClearAction.isChecked(): notClearAction.setChecked(False) clearHighlight = False else: clearAction.setChecked(False) clearHighlight = True self._highlightSameItemContent(item, clearHighlight) def _initItemMenu(self): """ 初始化Item右键菜单 """ self._itemMenu = QMenu(self) self._tableCountAction = QAction('', self) self._itemMenu.addAction(self._tableCountAction) self._itemMenu.addSeparator() self._autoScrollAction = QAction( '关闭自动滚动' if self._enableAutoScroll else '开启自动滚动', self) self._autoScrollAction.triggered.connect(self._autoScrollAct) self._itemMenu.addAction(self._autoScrollAction) self._markAction = QAction('标记', self) self._markAction.triggered.connect(self._markAct) self._itemMenu.addAction(self._markAction) self._visibleMarkAction = QAction('定位到标记', self) self._visibleMarkAction.triggered.connect(self._visibleMarkAct) self._itemMenu.addAction(self._visibleMarkAction) # item只有一种状态,要不是标记,要不就是高亮 self._highlightAction = QAction('高亮', self) self._highlightAction.triggered.connect(self._highlightAct) self._itemMenu.addAction(self._highlightAction) # 高亮所有同列相同内容的item menu = self._itemMenu.addMenu('高亮同列相同内容的表项') self._highlightSameItemContentActions = [ QAction('清除先前高亮', self), QAction('保留先前高亮', self) ] for action in self._highlightSameItemContentActions: action.triggered.connect(self._highlightSameItemContentAct) action.setCheckable(True) menu.addAction(action) action = QAction('查找...', self) action.triggered.connect(self._findAct) self._itemMenu.addAction(action) def _findAct(self): data = {} if DySingleEditDlg(data, '查找', '要查找的内容').exec_(): text = str(data['data']) self._findItems = self.findItems(text, Qt.MatchContains) self._curFindItemPos = 0 if self._findItems: self.scrollToItem(self._findItems[self._curFindItemPos]) self.setCurrentItem(self._findItems[self._curFindItemPos]) else: QMessageBox.warning(self, '警告', '没有找到要查找的内容!') def keyPressEvent(self, event): if event.key() == Qt.Key_F3: if not self._findItems: QMessageBox.warning(self, '警告', '没有找到要查找的内容!') return self._curFindItemPos += 1 self._curFindItemPos = self._curFindItemPos % len(self._findItems) self.scrollToItem(self._findItems[self._curFindItemPos]) self.setCurrentItem(self._findItems[self._curFindItemPos]) def contextMenuEvent(self, event): """ Item右键点击事件 """ self._rightClickPoint = event.pos() item = self.itemAt(self._rightClickPoint) self._tableCountAction.setText('行: {0}, 列: {1}'.format( self.rowCount(), self.columnCount())) if item is None: self._markAction.setEnabled(False) self._highlightAction.setEnabled(False) else: itemState = 0 # 0: not marked or highlighted, 1: marked, 2: highlighted if self._markedItem is not None and self._markedItem.row( ) == item.row(): itemState = 1 else: for highlightedItem in self._highlightedItems: if highlightedItem[0].row() == item.row(): itemState = 2 if itemState == 0: self._markAction.setText('标记') self._markAction.setEnabled(True) self._highlightAction.setText('高亮') self._highlightAction.setEnabled(True) elif itemState == 1: self._markAction.setText('取消标记') self._markAction.setEnabled(True) self._highlightAction.setEnabled(False) else: self._highlightAction.setText('取消高亮') self._highlightAction.setEnabled(True) self._markAction.setEnabled(False) # at last, set visible mark action if self._markedItem is not None: self._visibleMarkAction.setText('定位标记') self._visibleMarkAction.setEnabled(True) else: self._visibleMarkAction.setEnabled(False) self._itemMenu.popup(QCursor.pos()) def removeRow(self, row): """ remove row, which can be by index or key """ self.setSortingEnabled(False) if isinstance(row, int): # remove by index # find item in map delRowKey = None for rowKey, items in self._itemsMap.items(): if items[0].row() == row: delRowKey = rowKey break # remove from map if delRowKey is not None: del self._itemsMap[delRowKey] # remove from table widget super().removeRow(row) else: # remove by key # remove from map if row in self._itemsMap: delRow = self._itemsMap[row][0].row() del self._itemsMap[row] # remove from table widget super().removeRow(delRow) self.setSortingEnabled(True) def removeAll(self): rowCount = self.rowCount() for _ in range(rowCount): self.removeRow(0) def getAll(self): """ 以列表方式返回table的所有值,Org.列除外 """ tableItems = [] for row in range(self.rowCount()): rowItems = [] colCount = (self.columnCount() - 1) if self.__index else self.columnCount() for col in range(colCount): rowItems.append(self[row, col]) tableItems.append(rowItems) return tableItems def getHighlights(self): """ 以列表方式返回table所有高亮的值,Org.列除外 """ # get sorted highlighed rows highlightedRows = [item[0].row() for item in self._highlightedItems] highlightedRows.sort() tableItems = [] for row in highlightedRows: rowItems = [] colCount = (self.columnCount() - 1) if self.__index else self.columnCount() for col in range(colCount): rowItems.append(self[row, col]) tableItems.append(rowItems) return tableItems def toDataFrame(self): colNames = self.getColNames() rows = self.getAll() df = pd.DataFrame(rows, columns=colNames) return df def getColNames(self): colNames = [] for col in range(self.columnCount()): headerItem = self.horizontalHeaderItem(col) colName = headerItem.text() if colName == 'Org.': continue colNames.append(colName) return colNames if colNames else None def getColName(self, col): if self.__index: col += 1 headerItem = self.horizontalHeaderItem(col) if headerItem: return headerItem.text() return None def getColumnsData(self, colNames): """ 以列表方式返回指定列名的所有值 @colNames: [colName] @return: [[data]] """ # get postions of column names colPos = [self._getColPos(x) for x in colNames] colPos = [((x - 1) if self.__index else x) for x in colPos] tableItems = [] for row in range(self.rowCount()): rowItems = [] for col in colPos: rowItems.append(self[row, col]) tableItems.append(rowItems) return tableItems def appendColumns(self, columnNames, columnsData): """ @columnNames: [column name] @columnsData: [[column data]] """ self.setSortingEnabled(False) # adjust start column postion for appended columns colStart = (self.columnCount() - 1) if self.__index else self.columnCount() # append column names for col, name in enumerate(columnNames, colStart): self.addColName(col, name) # append columns data for row, rowData in enumerate(columnsData): for col, data in enumerate(rowData, colStart): self._update((row, col), data) self.resizeColumnsToContents() self.resizeRowsToContents() # 重新设置标记 self._renewMark() # 重新设置高亮 self._renewHighlight() self.setSortingEnabled(True) def _updateAutoForegroundColForeground(self, row): item = self.item(row, self._autoForegroundCol) if item is None: return try: value = float(item.data(self._role)) except Exception as ex: value = 0 # if referenced item doesn't have value or not number, think it as default 0. if value > 0: color = Qt.red elif value < 0: color = Qt.darkGreen else: if item.background() == Qt.white: # for qdarkstyle color = Qt.black else: color = QColor('#C0C0C0') item.setForeground(color) def updateAutoForegroundCol(self, colAbs): """ @colAbs: 更新自动前景色关键列,包含'Org.' column """ if isinstance(colAbs, str): self._autoForegroundCol = self._getColPos(colAbs) else: self._autoForegroundCol = colAbs if self._autoForegroundCol is None: return for row in range(self.rowCount()): # upate foreground of auto foreground column item self._updateAutoForegroundColForeground(row) refItem = self.item(row, self._autoForegroundCol) if refItem is None: continue for col in range(self.columnCount()): if self.__index and col == 0: # ignore 'Org.' column continue item = self.item(row, col) if item is None: continue item.setForeground(refItem.foreground()) def getForegroundOverride(self, value): """ 可由子类重载,这样可以根据不同的值设置不同的前景色 """ try: value = float(value) if value > 0: color = Qt.red elif value < 0: color = Qt.darkGreen else: color = None # default except Exception as ex: color = None return color def _getForeground(self, rowData, autoForegroundCol, item): # 如果@rowData的item个数小于等于@autoForegroundCol # 支持row数据比header少的状况 try: value = rowData[autoForegroundCol] color = self.getForegroundOverride(value) except Exception as ex: color = None if color is None: if item.background() == Qt.white: color = Qt.black else: # for qdarkstyle color = QColor(192, 192, 192) return color def _updateOrg(self, row): if not self.__index: return item = self.item(row, 0) if item is None: item = DyTableWidgetItem(self._role) self.setItem(row, 0, item) item.setData(self._role, row + 1) def clearAllRows(self): self._clearVisualEffects() self.setRowCount(0) self._initRows() def fastAppendRows(self, rows, autoForegroundColName=None, new=False): """ 快速批量添加行数据,忽略细节 调用之前,必须先设置header @new: 新建还是添加 """ self.setSortingEnabled(False) if new: self._clearVisualEffects() self.setRowCount(len(rows)) rowStart = 0 self._initRows() else: rowStart = self.rowCount() self.setRowCount(rowStart + len(rows)) if autoForegroundColName is not None: self._autoForegroundCol = self._getColPos(autoForegroundColName) # column position in input raw data(@rows) if self._autoForegroundCol is not None: autoForegroundCol = self._autoForegroundCol - 1 if self.__index else self._autoForegroundCol offset = 1 if self.__index else 0 item = None for row, rowData in enumerate(rows, rowStart): self._updateOrg(row) for col, value in enumerate(rowData, offset): # create new if not existing item = self.item(row, col) if item is None: item = DyTableWidgetItem(self._role) self.setItem(row, col, item) # set item data self._setItemDataFast(item, value) # set foreground if autoForegroundColName is not None and self._autoForegroundCol is not None: if col == offset: # only get auto foreground when begining of row color = self._getForeground(rowData, autoForegroundCol, item) item.setForeground(color) self.resizeColumnsToContents() self.resizeRowsToContents() self.setSortingEnabled(True) if self._enableAutoScroll and item is not None: self.scrollToItem(item) def fastAppendColumns(self, columnNames, columnsData): """ 快速批量添加列数据,忽略细节 @columnNames: [column name] @columnsData: [[column data]] """ self.setSortingEnabled(False) # adjust start column postion for appended columns colStart = self.columnCount() # append column names self.addColNames(columnNames) # append columns data for row, rowData in enumerate(columnsData): for col, value in enumerate(rowData, colStart): # create new if not existing item = self.item(row, col) if item is None: item = DyTableWidgetItem(self._role) self.setItem(row, col, item) # set item data self._setItemDataFast(item, value) # get item of auto foreground if self._autoForegroundCol is None: continue refItem = self.item(row, self._autoForegroundCol) if not refItem: continue # set forground same as reference item item.setForeground(refItem.foreground()) self.resizeColumnsToContents() self.resizeRowsToContents() # 重新设置标记 self._renewMark() # 重新设置高亮 self._renewHighlight() self.setSortingEnabled(True) def _renewMark(self): """ 重新设置标记 """ markedItem = self._markedItem # 先取消标记 self._mark(markedItem) # 设置标记 self._mark(markedItem) def _renewHighlight(self): """ 重新设置高亮 """ # reproduce highlighed items because during cancel highlight procedure element will be deleted from @self._highlightedItems highlightedItems = [item[0] for item in self._highlightedItems] for item in highlightedItems: # 先取消高亮 self._highlight(item) # 设置高亮 self._highlight(item) def setItemsForeground(self, rowKeys, colors): """ @rowKeys: [rowKey] or [row number] @colors: ((text, color)) or [[text, color]] """ for key in rowKeys: for col in range(self.columnCount()): item = self._getItem(key, col) if item is None: continue itemData = item.data(self._role) for text, color in colors: if isinstance(itemData, str) and text in itemData: item.setForeground(color) break def filter(self, filter, highlight=False): """ 根据filter表达式选取行数据,filter表达式是对列进行操作。对应的列为x[0], x[1], ... @return: 过滤出来的数据列表 """ # 取消高亮 self._clearHighlight() tableItems = [] for row in range(self.rowCount()): rowItems = [] colCount = (self.columnCount() - 1) if self.__index else self.columnCount() for col in range(colCount): rowItems.append(self[row, col]) # execute filter try: x = rowItems if not eval(filter): # some of elements are None continue except Exception as ex: continue if highlight: self._highlight(self.item(row, col)) tableItems.append(rowItems) return tableItems def org(self, row): if self.__index: return self[row, 'Org.'] return None def addColumnOperateColumns(self, exp): """ 根据exp表达式进行列运算(类似于Pandas),并添加列到table widget x代表table widget对应的DataFrame """ newColumnData = [] for row in range(self.rowCount()): rowItems = [] colCount = (self.columnCount() - 1) if self.__index else self.columnCount() for col in range(colCount): rowItems.append(self[row, col]) # execute exp x = rowItems try: value = eval(exp) except: value = None newColumnData.append([value]) # get column name x = self.getColNames() try: p = re.compile('x\[\d+\]') elements = p.findall(exp) elements_ = [] for v in elements: elements_.append('[' + eval(v) + ']') expFormat = p.sub('{}', exp) newColumnName = expFormat.format(*elements_) except: newColumnName = exp # add columns into table widget self.fastAppendColumns([newColumnName], newColumnData)
def Button(parent=None): btn = PathButton(parent) btn.setIsDownColor(QColor()) btn.setFocusPolicy(Qt.NoFocus) btn.setSize(QSize(26, 26)) return btn
def _updateGuiFromOperator(self): op = self.topLevelOperatorView # check if the data is 2D. If so, hide the z-dependent spinboxes data_has_z_axis = True if self.topLevelOperatorView.InputImage.ready(): tShape = self.topLevelOperatorView.InputImage.meta.getTaggedShape() if not 'z' in tShape or tShape['z'] == 1: data_has_z_axis = False self._drawer.sigmaSpinBox_Z.setVisible(data_has_z_axis) numChannels = 0 if op.InputImage.ready(): # Channel channelIndex = op.InputImage.meta.axistags.index('c') numChannels = op.InputImage.meta.shape[channelIndex] if op.InputChannelColors.ready(): input_channel_colors = [ QColor(r_g_b[0], r_g_b[1], r_g_b[2]) for r_g_b in op.InputChannelColors.value ] else: if self._defaultInputChannelColors is None: self._defaultInputChannelColors = colortables.default16_new[1:] input_channel_colors = list( map(QColor, self._defaultInputChannelColors)) self._drawer.inputChannelComboBox.clear() self._drawer.coreChannelComboBox.clear() for ichannel in range(numChannels): # make an icon pm = QPixmap(16, 16) pm.fill(input_channel_colors[ichannel]) self._drawer.inputChannelComboBox.insertItem( ichannel, QIcon(pm), str(ichannel)) self._drawer.coreChannelComboBox.insertItem( ichannel, QIcon(pm), str(ichannel)) self._drawer.inputChannelComboBox.setCurrentIndex(op.Channel.value) self._drawer.coreChannelComboBox.setCurrentIndex(op.CoreChannel.value) # Sigmas sigmaDict = self.topLevelOperatorView.SmootherSigma.value for axiskey, spinBox in list(self._sigmaSpinBoxes.items()): spinBox.setValue(sigmaDict[axiskey]) # Thresholds self._drawer.lowThresholdSpinBox.setValue(op.LowThreshold.value) self._drawer.highThresholdSpinBox.setValue(op.HighThreshold.value) self._drawer.lambdaSpinBoxGC.setValue(op.Beta.value) # Size filters self._drawer.minSizeSpinBox.setValue(op.MinSize.value) self._drawer.maxSizeSpinBox.setValue(op.MaxSize.value) # Operator method = op.CurOperator.value # There isn't a 1-to-1 correspondence between the combo widget and ThresholdingMethod # Methods 0,1,2 are 1-to-1, but method 3 means "two-level, but don't merge cores." method_combo_index = {0: 0, 1: 1, 2: 2, 3: 1}[method] self._drawer.methodComboBox.setCurrentIndex(method_combo_index) self._drawer.preserveIdentitiesCheckbox.setChecked( op.CurOperator.value == 3) self._enableMethodSpecificControls()