def get_list_from_file(filepath): # gets the the colors of the image (pixelcount (r, g, b)) # converts the tuple to a QColor and appends it to a new list # which is in turn converted into a tuple and returned gc.collect() img = Image.open(filepath) # if you set it to lower than the amount of colors in a picture the # function returns none; # if the amount is too high the performance takes a hit colorlist = img.convert("RGB").getcolors(maxcolors=1000000) qcolorlist = [] # picture has no alpha channel if len(colorlist[0][1]) == 3: for count_color in colorlist: r, g, b = count_color[1] qcolorlist.append((count_color[0], QColor.fromRgb(r, g, b))) # picture has alpha channel elif len(colorlist[0][1]) == 4: for count_color in colorlist: r, g, b, a = count_color[1] qcolorlist.append( (count_color[0], QColor.fromRgb(r, g, b, alpha=a)) ) qcolorlist = tuple(qcolorlist) # deleting isnt necessary but I want to free it before collection # but I also havent locked at how del or the gc works so heyyyyy del colorlist gc.collect() return qcolorlist
def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # function that changes a layer's color # copied from https://gis.stackexchange.com/questions/284057/how-to-change-layer-symbology-in-qgis-3-with-qgsfeaturerendererv2 # more information https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html#single-symbol-renderer def change_color(layer, rgb): # get the symbols single_symbol_renderer = layer.renderer() symbol = single_symbol_renderer.symbol() symbol.setColor(rgb) # more efficient than refreshing the whole canvas, which requires a redraw of ALL layers layer.triggerRepaint() # update legend for layer self.iface.layerTreeView().refreshLayerSymbology(layer.id()) # get the current layer active_layer = self.iface.activeLayer() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: if self.dlg.redRadioButton.isChecked(): print("selected red") change_color(active_layer, QColor.fromRgb(255, 0, 0)) elif self.dlg.greenRadioButton.isChecked(): print("selected green") change_color(active_layer, QColor.fromRgb(0, 255, 0)) elif self.dlg.blueRadioButton.isChecked(): print("selected blue") change_color(active_layer, QColor.fromRgb(0, 0, 255))
def __init__(self, tasks=()): super().__init__() self.tasks = tasks self.formula = None self.axis_pen = QPen() self.func_pen = QPen() self.coords_pen = QPen() self.square_pen = QPen() self.last_coords = QPoint(0, 0) self.setMouseTracking(True) self.axis_pen.setWidth(3) self.func_pen.setWidth(3) self.axis_pen.setColor(QColor.fromRgb(config.AXIS_COLOR)) self.func_pen.setColor(QColor.fromRgb(config.FUNCTION_COLOR)) self.coords_pen.setColor(QColor.fromRgb(config.GRID_COLOR)) self.square_pen.setColor( QColor.fromRgb(config.HIGHLIGHTED_SQUARE_COLOR)) self.padding = 0 self.panelWidth = 200 self.tracking = False self.task_number = 0 self.steps_count = WIDTH self.init_vars() self.init_UI()
def configure_area(self, x_title='Index', x_unit='', y_title='Values', y_unit=''): """ Configure the plot to: Show a X,Y grid. Sets the colors to a white background theme. Sets the axis range and labels. :param x_title: The x axis label. :param x_unit: The unit names of the x values. :param y_title: The y axis label. :param y_unit: The unit names of the y axis. """ self.plotWidget.showGrid(True, True) # Colors: self.plotWidget.setBackgroundBrush( QBrush(QColor.fromRgb(255, 255, 255))) self.plotWidget.getAxis('left').setPen(QPen(QColor.fromRgb(0, 0, 0))) self.plotWidget.getAxis('bottom').setPen(QPen(QColor.fromRgb(0, 0, 0))) self.plotWidget.getAxis('left').setPen(QPen(QColor.fromRgb(0, 0, 0))) self.plotWidget.getAxis('bottom').setPen(QPen(QColor.fromRgb(0, 0, 0))) # Axis: self.plotWidget.setXRange(0, self.qnt_points) self.plotWidget.setYRange(self.__y_range[0], self.__y_range[1]) self.plotWidget.setLabel('bottom', x_title, units=x_unit) self.plotWidget.setLabel('left', y_title, units=y_unit)
def mousePressEvent(self, event): if event.button() == Qt.MiddleButton: self.offset = event.globalPos() - self.frameGeometry().topLeft() ## print(self.offset) elif event.button() == Qt.LeftButton: position = QPoint(event.pos().x(), event.pos().y()) color = QColor.fromRgb(self.local_image.pixel(position)) self.fgcolor = color ## print(color.redF(), color.greenF(), color.blueF(), color.alphaF()) # print values from a QColor if krita: self.updateKritaForeGroundColor(color) self.drawGUI() self.update() # Refresh the drawn colors. elif event.button() == Qt.RightButton: position = QPoint(event.pos().x(), event.pos().y()) color = QColor.fromRgb(self.local_image.pixel(position)) self.bgcolor = color ## print(color.redF(), color.greenF(), color.blueF(), color.alphaF()) # print values from a QColor if krita: self.updateKritaBackGroundColor(color) self.drawGUI() self.update() # Refresh the drawn colors. elif event.buttons() == Qt.XButton1: QApplication.beep() # Do something here... Change a texture/mask/page, call a function, etc.... elif event.buttons() == Qt.XButton2: QApplication.beep()
def update_target_colors(self, src_tar_map, binsz): # 根据 hue范围进行变色 for k, v in src_tar_map.items(): for idx, tc in enumerate(self._dom_colors): hsl = transfer_lab.rgb2hue_opencv( transfer_lab.lab2rgb_opencv(tc)) h360 = hsl[0] * 2 if h360 >= k * binsz and h360 <= (k + 1) * binsz: tar_h360 = v * binsz delta = tar_h360 - k * binsz h360 += delta hsl[0] = int(h360 / 2) self._tar_colors[idx] = transfer_lab.rgb2lab_opencv( transfer_lab.hue2rgb_opencv(hsl)) for idx, w in enumerate(self.layout_widgets(self.tar_color_layout)): p = w.widget().palette() r, g, b = transfer_lab.lab2rgb_opencv(self._tar_colors[idx]) p.setColor(w.widget().backgroundRole(), QColor.fromRgb(r, g, b)) w.widget().setPalette(p) w.widget().setStyleSheet("background-color: %s" % (QColor.fromRgb(r, g, b).name())) self.update_image() pass
def paintEvent(self, event): super().paintEvent(event) height = max(self.height() // IMG_SIZE, 1) width = max(self.width() // IMG_SIZE, 1) self.scrollbar.setMaximum(len(self.uids) // width) self.scrollbar.setPageStep(1) painter = QtGui.QPainter(self) for i in range(0, width): for j in range(0, height): x = i * IMG_SIZE y = j * IMG_SIZE index = i + (j + self.scrollbar.value()) * width if index < len(self.uids): if index == self.selected_index: painter.fillRect(x, y, IMG_SIZE, IMG_SIZE, QColor.fromRgb(0xCCE8FF)) image = self.get_image(self.uids[index]) painter.drawImage(x + IMG_SIZE / 2 - image.width() / 2, y + IMG_SIZE / 2 - image.height() / 2, image) if index == self.selected_index: painter.setPen(QColor.fromRgb(0x99D1FF)) painter.drawRect(x, y, IMG_SIZE - 1, IMG_SIZE - 1) painter.end()
def get_quantize(filepath, maximal_colors): # TODO not DRY need to refactor one other day in the distant future # quantizes the image and converts it back to rgb because this is the only # format where you can call getcolors() and the it goes through the process # to make a QColor-list because the original way isnt compatiple with # the quantization. img = Image.open(filepath) img = img.quantize(colors=maximal_colors) colorlist = img.convert("RGB").getcolors(maxcolors=maximal_colors) qcolorlist = [] # picture has no alpha channel if len(colorlist[0][1]) == 3: for count_color in colorlist: r, g, b = count_color[1] qcolorlist.append(QColor.fromRgb(r, g, b)) # picture has alpha channel elif len(colorlist[0][1]) == 4: for count_color in colorlist: r, g, b, a = count_color[1] qcolorlist.append( (QColor.fromRgb(r, g, b, alpha=a)) ) del colorlist gc.collect() return qcolorlist
def paintEvent( self, event ): #draws the regions around the truck and change their colors green to red if there is any car in the region painter = QPainter(self) painter.setPen(QPen(Qt.black, 3, Qt.DashLine)) painter.setBrush( QBrush(QColor.fromRgb(0, 255, 0, 100), Qt.SolidPattern) ) #fromRgb(int r, int g, int b, int a = 255) a=alpha-chanel->transperancy painter.drawRect(460, 635, 100, 165) # sagalt 530, 635, 100, 165 painter.drawRect(300, 635, 100, 165) # solalt 370, 635, 100, 165 painter.drawRect(300, 535, 130, 96) # ustsol 370,535, 130, 96 painter.drawRect(435, 535, 130, 96) # ustsag 505, 535, 130, 96 qp = QPainter(self) #change colors for rect in self.rectObjArray: if (rect.x() <= 565 and rect.x() >= 170 and rect.y() <= 735 and rect.y() >= 535): qp.setPen(QPen(Qt.black, 3, Qt.DashLine)) qp.setBrush(QColor(200, 0, 0)) qp.drawRect(rect) else: qp.setPen(QPen(Qt.black, 3, Qt.DashLine)) qp.setBrush(QBrush(QColor.fromRgb(0, 255, 0), Qt.SolidPattern)) qp.drawRect(rect)
def mousePressEvent(self, event: 'QGraphicsSceneMouseEvent') -> None: try: for element in self.active_elements: element.setBrush(QBrush(QColor.fromRgb(240, 240, 250))) except Exception as exception: print('error with a brush in mousePressEvent in MainScene:', exception) try: if event.button() == 2: current_x, current_y = event.scenePos().x( ), event.scenePos().y() for rect, object_rect in self.parent.rectangles: try: if rect.x1 <= current_x <= rect.x2 and \ rect.y1 <= current_y <= rect.y2: try: context_menu = QMenu() history = context_menu.addAction('history') action = context_menu.exec(QCursor().pos()) if action == history: rect.widget = QWidget() rect.widget.setWindowTitle( 'Biography of {}'.format( rect.name)) layout = QHBoxLayout() label = QLabel() label.setText(rect.description) layout.addWidget(label) rect.widget.setLayout(layout) rect.widget.setGeometry( QCursor().pos().x(), QCursor().pos().y(), 500, 200) rect.widget.show() except Exception as exception: print(exception) except Exception as exception: print(exception) elif event.button() == 1: current_x, current_y = event.scenePos().x( ), event.scenePos().y() for _event, event_object in self.parent.events: if _event.x1 <= current_x <= _event.x2 and _event.y1 <= current_y <= _event.y2: for _rect, object_rect in self.parent.rectangles: year_from = int(_rect.years.split()[0]) year_to = int(_rect.years.split()[2]) if year_from <= int(_event.years) <= year_to: object_rect.setBrush( QBrush(QColor.fromRgb(200, 200, 240))) self.active_elements.append(object_rect) pass except Exception as e: print(e) print('finished')
def legSelected(self, legIdx): print("Leg:{} selected".format(legIdx)) for idx in range(len(self.legs)): leg = self.legs[idx] if idx is legIdx: leg.set_color(QColor.fromRgb(127, 127, 0)) else: leg.set_color(QColor.fromRgb(127, 127, 127))
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setBrush(QColor.fromRgb(255, 255, 0)) painter.setPen(QColor.fromRgb(255, 255, 0)) for i in self.list: painter.drawEllipse(*i) painter.end()
def get_color_by_string(color_string, inverse = False): color_re = re.compile(r'\d+') rgb = color_re.findall(color_string) color = None if inverse: color = QColor.fromRgb(255 - int(rgb[0]), 255 - int(rgb[1]), 255 - int(rgb[2])) if not inverse: color = QColor.fromRgb(int(rgb[0]), int(rgb[1]),int(rgb[2])) return color
def __init__(self, parent=None): QWidget.__init__(self, parent) cparser = PuddleConfig() get_color = lambda key, default: QColor.fromRgb(*cparser.get( 'extendedtags', key, default, True)) add = get_color('add', [0, 255, 0]) edit = get_color('edit', [255, 255, 0]) remove = get_color('remove', [255, 0, 0]) get_color = lambda key, default: QColor.fromRgb(*cparser.get( 'table', key, default, True)) preview = get_color('preview_color', [192, 255, 192]) selection_default = QPalette().color( QPalette.ColorRole.Mid).getRgb()[:-1] selection = get_color('selected_color', selection_default) colors = (add, edit, remove, preview, selection) text = translate( "Colour Settings", '<p>Below are the backgrounds used for various controls in puddletag. <br /> Double click the desired action to change its colour.</p>' ) label = QLabel(text) self.listbox = QTableWidget(0, 1, self) self.listbox.setEditTriggers( QAbstractItemView.EditTrigger.NoEditTriggers) header = self.listbox.horizontalHeader() self.listbox.setSortingEnabled(False) header.setVisible(True) header.setStretchLastSection(True) self.listbox.setHorizontalHeaderLabels(['Action']) self.listbox.setRowCount(len(colors)) titles = [ (translate("Colour Settings", 'Row selected in file-view.'), selection), (translate("Colour Settings", 'Row colour for files with previews.'), preview), (translate("Colour Settings", 'Field added in Extended Tags.'), add), (translate("Colour Settings", 'Field edited in Extended Tags.'), edit), (translate("Colour Settings", 'Field removed in Extended Tags.'), remove), ] for i, z in enumerate(titles): self.listbox.setItem(i, 0, StatusWidgetItem(*z)) vbox = QVBoxLayout() vbox.addWidget(label) vbox.addWidget(self.listbox) self.setLayout(vbox) self.listbox.cellDoubleClicked.connect(self.edit)
def __init__(self, parent=None): super(GameArea, self).__init__(parent) self.__ui = Ui_GameArea() self.__ui.setupUi(self) self.__ratio = self.RATIO_WITH_SHIPLIST self.__scaleFactor = 1 self.controller = Controller() self.controller._accept = self.__accept self.controller._decline = self.__decline self.__gameModel = None self.__shipList = { "boat": ShipListItem(length=1, name="boat", count=4), "destroyer": ShipListItem(length=2, name="destroyer", count=3), "cruiser": ShipListItem(length=3, name="cruiser", count=2), "battleship": ShipListItem(length=4, name="battleship", count=1), } # resources self.__cellImages = {"intact": None, "hit": None, "miss": None} self.__sprites = {"explosion": None, "splash": None} self.__originalTileSize = 0 self.tileSize = 0 self.__shipListImage = QImage() self.__counterImage = QImage() # drawing items self.__placedShips = [] self.__field = [QGraphicsPixmapItem() for _ in range(100)] self.__letters = [QGraphicsTextItem() for _ in range(10)] self.__numbers = [QGraphicsTextItem() for _ in range(10)] for i in range(10): self.__letters[i].setDefaultTextColor(QColor.fromRgb(0, 0, 0)) self.__numbers[i].setDefaultTextColor(QColor.fromRgb(0, 0, 0)) self.__spriteAnimations = [] self.__shipListItem = QGraphicsPixmapItem() self.__ghostShip = QGraphicsPixmapItem( ) # data: 0 - rotation; 1 - ShipListItem self.__placer = QGraphicsRectItem() self.__dragShip = False self.__targetPixmap = None self.__targets = [] self.__scanEffect = None # prepare Qt objects self.__scene = QGraphicsScene() self.__loadResources() self.__initGraphicsView() self.__adjustedToSize = 0
def variableColor(variable): if variable.type == 'Real': return QColor.fromRgb(0, 0, 127) elif variable.type in ['Integer', 'Enumeration']: return QColor.fromRgb(255, 127, 0) elif variable.type == 'Boolean': return QColor.fromRgb(255, 0, 255) elif variable.type == 'String': return QColor.fromRgb(0, 128, 0) else: return QColor.fromRgb(0, 0, 0)
def drawInWorld(self, qPainter): pen = qPainter.pen() pen.setColor(QColor.fromRgb(255, 0, 0)) qPainter.setPen(pen) # draw convex hull if None != self.polygon: qPainter.drawPolyline(self.polygon) pen.setColor(QColor.fromRgb(0, 0, 255)) qPainter.setPen(pen)
def fromJson(self, json): self._backgroundColor = QColor.fromRgb(json["backgroundColor"]["r"], json["backgroundColor"]["g"], json["backgroundColor"]["b"]) self._cartColor = QColor.fromRgb(json["cartColor"]["r"], json["cartColor"]["g"], json["cartColor"]["b"]) self._cartWidth = json["cartWidth"] self._poleColor = QColor.fromRgb(json["poleColor"]["r"], json["poleColor"]["g"], json["poleColor"]["b"]) self._showAngleTolerance = json["showAngleTolerance"]
def applySettings(self, control=None): cparser = PuddleConfig() x = lambda c: c.getRgb()[:-1] colors = [x(self.listbox.item(z, 0).background().color()) for z in range(self.listbox.rowCount())] cparser.set('table', 'selected_color', colors[0]) cparser.set('table', 'preview_color', colors[1]) cparser.set('extendedtags', 'add', colors[2]) cparser.set('extendedtags', 'edit', colors[3]) cparser.set('extendedtags', 'remove', colors[4]) control.model().selectionBackground = QColor.fromRgb(*colors[0]) control.model().previewBackground = QColor.fromRgb(*colors[1])
def change_teeth(self, idx): teeth = self.data_manager.get_all_teeth(True) self.tooth1 = teeth[0] self.tooth2 = teeth[idx] self.tooth1.outline_pen = QPen(QColor.fromRgb(255, 0, 0)) self.tooth2.outline_pen = QPen(QColor.fromRgb(0, 255, 0)) self.scene.clear() self.tooth1.draw(self.scene, True, False, False) self.tooth2.draw(self.scene, True, False, False) self._focus_view() self.align_step = 0
def drawInWorld(self, qPainter): pen = qPainter.pen() pen.setColor(QColor.fromRgb(255, 0, 0)) qPainter.setPen(pen) if None is not self.polygon: qPainter.drawPolyline(self.polygon) pen.setColor(QColor.fromRgb(0, 255, 0)) qPainter.setPen(pen) if None is not self.holePolygon: qPainter.drawPolyline(self.holePolygon) if len(self.lineSeg) == 2: qPainter.drawLine(QLineF(self.lineSeg[0], self.lineSeg[1])) pen.setColor(QColor.fromRgb(0, 0, 255)) qPainter.setPen(pen)
def read_settings(self): settings = QSettings(self.appctx.ORG, self.appctx.APPLICATION) # Read Header Settings settings.beginGroup("display/header") default_font = QFont("sans-serif", pointSize=12, weight=QFont.Bold, italic=False) self.header_font = QFont( settings.value("font", defaultValue=default_font)) settings.endGroup() # Read Index Settings settings.beginGroup("display/index") default_font = QFont("sans-serif", pointSize=10, weight=QFont.Normal, italic=False) self.index_font = QFont( settings.value("font", defaultValue=default_font)) settings.endGroup() # Read Data Settings settings.beginGroup("display/data") # Font default_font = QFont("sans-serif", pointSize=10, weight=QFont.Normal, italic=False) self.data_font = QFont( settings.value("font", defaultValue=default_font)) # Colors self.data_bgcolor_unknown = QColor( settings.value("bgcolor_unknown", defaultValue=QColor.fromRgb(255, 255, 255))) self.data_bgcolor_binary = QColor( settings.value("bgcolor_binary", defaultValue=QColor.fromRgb(255, 204, 153))) self.data_bgcolor_categorical = QColor( settings.value("bgcolor_categorical", defaultValue=QColor.fromRgb(153, 204, 255))) self.data_bgcolor_continuous = QColor( settings.value("bgcolor_continuous", defaultValue=QColor.fromRgb(204, 153, 255))) # Float Precision self.data_float_precision = settings.value("float_precision", defaultValue=3) settings.endGroup()
def draw_pieces(self, painter): """draw the prices on the board""" brush_color = QColor.fromRgb(200, 200, 200) images = [QImage(WHITE_PIECE), QImage(BLACK_PIECE), QImage(WHITE_KING), QImage(BLACK_KING), QImage(BLACK_SQUARE)] idx = 0 i = 0 y = 1 while i < 2: for row in range(0, len(self.boardArray)): for col in range(0, len(self.boardArray[0])): #painter.save() col_transformation = col * self.square_width() row_transformation = row * self.square_height() ## Todo victoire quand bloquer if self.boardArray[row][col] == 2: brush_color = self.color_brush_white(row, col, i) idx = 0 elif self.boardArray[row][col] == 1: brush_color = Qt.black idx = 4 elif self.boardArray[row][col] == 3: brush_color = self.color_brush_black(row, col, i) idx = 1 elif self.boardArray[row][col] == 4: brush_color = self.color_brush_white(row, col, i) idx = 2 elif self.boardArray[row][col] == 5: brush_color = self.color_brush_black(row, col, i) idx = 3 elif self.boardArray[row][col] == 6: brush_color = QColor.fromRgb(128, 128, 128) if self.boardArray[row][col] != 0: painter.setPen(brush_color) if brush_color == Qt.white or brush_color == QColor.fromRgb(255, 0, 255): y = 2 # Todo draw some the pieces as eclipses radius_width = (self.square_width() / 10 * 8) / 2 radius_height = (self.square_height() / 10 * 8) / 2 center = QPoint(col_transformation + (self.square_width() / 2), row_transformation + (self.square_height() / 2)) if idx != 4: painter.drawEllipse(center, radius_width, radius_height) self.image = images[idx].scaled(radius_width * 2, radius_height * 2) painter.drawImage(center.x() - radius_width, center.y() - radius_height, self.image) #painter.restore() self.update() i += y
def draw_event(self, event, min_x, max_x, min_y, max_y, pen=QPen(Qt.black, 3, Qt.SolidLine), brush=QBrush(QColor.fromRgb(250, 240, 240))): object_event = self.scene.addRect(event.x1, event.y1, event.x2 - event.x1, event.y2 - event.y1, pen, brush) text = event.description.split() pre = 0 result_text = event.name + '\n\n' for word in text: if pre + len(word) > 50: pre = 0 result_text += '\n' pre += len(word) + 1 result_text += word + ' ' object_event.setToolTip(result_text) self.events.append((event, object_event)) text_event = QGraphicsTextItem(str(event.years)) text_event.setPos(event.x1 + 5, event.y1 + 5) font = QFont() font.setBold(False) font.setPixelSize(25) text_event.setFont(font) text_event.setFont(font) self.scene.addItem(text_event)
def paint(self, painter, option, widget): if self.scene().mode == 1: self.setOpacity(1 if self.model_item.logging_active else 0.3) painter.setOpacity(constants.SELECTION_OPACITY) if self.hover_active or self.isSelected(): painter.setBrush(constants.SELECTION_COLOR) elif not self.is_valid(): painter.setBrush(QColor(255, 0, 0, 150)) else: painter.setBrush(QColor.fromRgb(204, 204, 204, 255)) height = self.number.boundingRect().height() if self.model_item.type != ConditionType.ELSE: height += self.desc.boundingRect().height() painter.drawRect(QRectF(0, 0, self.boundingRect().width(), height)) painter.setBrush(Qt.NoBrush) painter.drawRect(self.boundingRect()) if self.drag_over: self.paint_drop_indicator(painter)
def Setup(self): self.setLayout(self.layout) p = QPalette() p.setColor(QPalette.Background, QColor.fromRgb(29, 29, 29)) self.setAutoFillBackground(True) self.setPalette(p)
def _addAirspaceLayer(self, group, layerName): """Adds the airspace layer to the project""" fields = [ QgsField('name', QVariant.String), QgsField('airspace_class', QVariant.String), QgsField('floor', QVariant.Int), QgsField('ceiling', QVariant.Int) ] layer = self.createVectorLayer(layerName, 'Polygon', fields) # Colour layer.renderer().symbol().setColor(QColor.fromRgb(0x00, 0xff, 0x00)) # Labeling settings = QgsPalLayerSettings() settings.fieldName = """coalesce(\"name\", 'No Name') || ' - ' || 'FL' || \"floor\" || ' to ' || 'FL' || \"ceiling\" || ' (Class ' || \"airspace_class\" || ')'""" settings.isExpression = True settings.placement = QgsPalLayerSettings.PerimeterCurved layer.setLabeling(QgsVectorLayerSimpleLabeling(settings)) layer.setLabelsEnabled(True) layer.triggerRepaint() self.addLayerToGroup(layer, group) return layer
def drawCoord(self, qPainter): # pen = QtGui.QPen() pen = qPainter.pen() color = QColor.fromRgb(200, 200, 200) pen.setColor(color) qPainter.setPen(pen) qPainter.drawLines(self.axisLines)
def get_vectorLayer(self): """Get model grid contour as a layer for QGIS""" vectorlayer = QgsVectorLayer("Linestring?crs=EPSG:4326", "Bounding box", "memory") segment = ogr.Geometry(ogr.wkbLineString) for X, Y in zip(self.lon[0, :], self.lat[0, :]): segment.AddPoint(X, Y) for X, Y in zip(self.lon[:, -1], self.lat[:, -1]): segment.AddPoint(X, Y) for X, Y in zip(self.lon[-1, ::-1], self.lat[-1, ::-1]): segment.AddPoint(X, Y) for X, Y in zip(self.lon[::-1, 0], self.lat[::-1, 0]): segment.AddPoint(X, Y) geom = QgsGeometry.fromWkt(segment.ExportToWkt()) feature = QgsFeature() feature.setGeometry(geom) pr = vectorlayer.dataProvider() pr.addAttributes([QgsField("id", QVariant.Int)]) vectorlayer.updateFields() feature.setAttributes([int(0)]) pr.addFeature(feature) vectorlayer.renderer().symbol().setWidth(0.7) vectorlayer.renderer().symbol().setColor(QColor.fromRgb(0, 137, 0)) proyecto = QgsProject.instance() proyecto.addMapLayer(vectorlayer)
def _addRestrictedLayer(self, group, layerName): """Adds the Restricted airspaces to the project""" fields = [ QgsField('name', QVariant.String), QgsField('height', QVariant.String), ] layer = self.createVectorLayer(layerName, 'Polygon', fields) # Colour layer.renderer().symbol().setColor( QColor.fromRgb(0xff, 0x60, 0x60, 0x80)) # Labeling settings = QgsPalLayerSettings() settings.fieldName = '"name" || \'\\n0ft\\n\' || "height"' settings.isExpression = True settings.placement = QgsPalLayerSettings.AroundPoint layer.setLabeling(QgsVectorLayerSimpleLabeling(settings)) layer.setLabelsEnabled(True) layer.triggerRepaint() self.addLayerToGroup(layer, group) return layer
def __init__(self, parent=None): super(PlayList, self).__init__() self.parent = parent self.setParent(self.parent.parent) self.setObjectName("PlayList") self.musicList = [] self.currentRow = -1 self.allRow = 0 self.itemColor = QBrush(QColor.fromRgb(95, 95, 99)) with open('QSS/playList.qss', 'r') as f: self.setStyleSheet(f.read()) self.resize(574, 477) self.hide() self.setButtons() self.setLabels() self.setTables() self.setLayouts()
def showspots(self): """Display spots in a list""" self.listWidget.clear() for i in self.spots: mode_selection = self.comboBox_mode.currentText() if mode_selection == "-FT*" and i["mode"][:2] == "FT": continue if (mode_selection == "All" or mode_selection == "-FT*" or i["mode"] == mode_selection): band_selection = self.comboBox_band.currentText() if (band_selection == "All" or self.getband( i["frequency"].split(".")[0]) == band_selection): spot = (f"{i['spotTime'].split('T')[1][0:5]} " f"{i['activator'].rjust(10)} " f"{i['reference'].ljust(7)} " f"{i['frequency'].split('.')[0].rjust(6)} " f"{i['mode']}") self.listWidget.addItem(spot) if spot[5:] == self.lastclicked[5:]: founditem = self.listWidget.findItems( spot[5:], QtCore.Qt.MatchFlag.MatchContains, # pylint: disable=no-member ) founditem[0].setSelected(True) if i["activator"] in self.workedlist: founditem = self.listWidget.findItems( i["activator"], QtCore.Qt.MatchFlag.MatchContains, # pylint: disable=no-member ) founditem[0].setBackground( QBrush(QColor.fromRgb(0, 128, 0)))
def _parse_qcolor_html(color_spec): digits = color_spec[1:] if color_spec.startswith('#') else color_spec if len(digits) not in [6, 8]: raise ValueError('Invalid length for HTML format') components = [int(digits[i:i+2], 16) for i in range(0, len(digits), 2)] return QColor.fromRgb(*components)
def _add_task_to_table(self, row, task): self._ignore_cell_changed = True self.setItem(row, self._dict_header['id'], QTableWidgetItem(str(task.identifier))) self.item(row, self._dict_header['id']) \ .setTextAlignment(Qt.AlignCenter) self.setItem(row, self._dict_header['name'], QTableWidgetItem(str(task.name))) combo = QComboBox() items = [task_type for task_type in Task.task_types_names] combo.addItems(items) combo.setCurrentIndex(combo.findText(task.task_type)) combo.currentIndexChanged.connect( lambda x: self._cell_changed(row, self._dict_header['task_type'])) self.setCellWidget(row, self._dict_header['task_type'], combo) item = QTableWidgetItem(task.abort_on_miss and 'Yes' or 'No') item.setFlags( Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable) item.setCheckState(task.abort_on_miss and Qt.Checked or Qt.Unchecked) self.setItem(row, self._dict_header['abort'], item) self.setItem(row, self._dict_header['list_activation_dates'], QTableWidgetItem( ', '.join(map(str, task.list_activation_dates)))) self.item(row, self._dict_header['list_activation_dates']) \ .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) for i in ['activation_date', 'period', 'deadline', 'wcet', 'base_cpi', 'n_instr', 'mix', 'acet', 'et_stddev', 'preemption_cost']: self.setItem(row, self._dict_header[i], QTableWidgetItem(str(task.__dict__[i]))) self.item(row, self._dict_header[i]) \ .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) stack_item = QTableWidgetItem(str(task.stack_file)) stack_item.setFlags(stack_item.flags() ^ (Qt.ItemIsEditable)) self.setItem(row, self._dict_header['sdp'], stack_item) combo = QComboBox() combo.currentIndexChanged.connect( lambda x: self._cell_changed(row, self._dict_header['followed'])) self.setCellWidget(row, self._dict_header['followed'], combo) for col in range(len(self._custom_fields)): key = self._custom_fields[col] if key in task.data and task.data[key] is not None: item = QTableWidgetItem(str(task.data[key])) else: item = QTableWidgetItem('') item.setBackgroundColor(QColor.fromRgb(200, 255, 200)) self.setItem(row, col + len(self._header), item) self._ignore_cell_changed = False self._show_period(task, row)
def _redraw(self, tooth, normalize=True): self.scene.clear() img = self.image.copy() if normalize: img = (img / img.max()) * 255 # Draw sampled positions to image if self.show_sampled_positions and tooth is not None: resolution_level = self.active_shape_model.get_current_level() assert isinstance(resolution_level, ResolutionLevel) all_sample_positions = [] Sampler.sample(tooth, img, resolution_level.landmark_model.m, False, all_sample_positions) for point_sample_positions in all_sample_positions: for x, y in point_sample_positions: img[y, x] = 255 # Draw image qimg = toQImage(img.astype(np.uint8)) self.scene.addPixmap(QPixmap.fromImage(qimg)) # Draw initial positions if self.cached_init_poses is None: self.cached_init_poses = self.initial_pose_model.find(self.radiograph_image) for pose in self.cached_init_poses: position, scale, rotation = InitialPoseModel.downsample_pose(pose, self.current_sampling_level) self.scene.addEllipse(position[0] - 2, position[1] - 2, 4, 4, pen=QPen(QColor.fromRgb(0, 0, 255)), brush=QBrush(QColor.fromRgb(0, 0, 255))) # Draw tooth from active shape model if tooth is not None: tooth.outline_pen = QPen(QColor(255, 0, 0)) tooth.draw(self.scene, True, True) # Set generated scene into the view self._focus_view((qimg.width(), qimg.height()))
def paintEvent(self, event): super(TextLineNumArea, self).paintEvent(event) # draw background painter = QPainter(self) painter.fillRect( self._width - 2, 0, self._width, self._height, QColor.fromRgb(192, 226, 192, 255) ) painter.fillRect( 0, 0, self._width - 2, self._height, QColor.fromRgb(0, 127, 85, 226) ) # calc range for blocks blck_height = (self._height + self.v_scroll().maximum()) / self.block_cnt() blck_start = int( self.v_scroll().value() / blck_height ) blck_end = blck_start + int( self._height / blck_height ) + 1 if blck_end > self.block_cnt(): blck_end = self.block_cnt() # draw line numbers painter.setPen(Qt.white) painter.setFont(self._font) for line in range(blck_start, blck_end): x = 0 y = (line * self.line_interval) - self.v_scroll().value() w = self._width - 4 h = self.line_interval painter.drawText ( x, y + 4, w, h, Qt.AlignRight, str(line) )
def _redraw(self, normalize=False): self.scene.clear() img = self.image.copy() if normalize: img = (img / img.max()) * 255 # Draw image qimg = toQImage(img.astype(np.uint8)) self.scene.addPixmap(QPixmap.fromImage(qimg)) # Add jaws divider self.scene.addLine(QLineF(0, self.y_line, self.image.shape[1], self.y_line), pen=QPen(QColor.fromRgb(255, 0, 0))) self.scene.addLine(QLineF(0, self.y_top_line, self.image.shape[1], self.y_top_line), pen=QPen(QColor.fromRgb(255, 0, 0))) self.scene.addLine(QLineF(0, self.y_lower_line, self.image.shape[1], self.y_lower_line), pen=QPen(QColor.fromRgb(255, 0, 0))) # Add image center self.scene.addEllipse(self.image.shape[0]/2 - self.landmark_size, self.image.shape[1]/2 - self.landmark_size, self.landmark_size * 2, self.landmark_size * 2, pen=QPen(QColor.fromRgb(255, 0, 0)), brush=QBrush(QColor.fromRgb(255, 0, 0))) # Draw Hough lines if self.lines is not None: #for x1,y1,x2,y2 in self.lines[0]: for i, line_param in enumerate(self.lines): rho,theta = line_param a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 200*(-b)) y1 = int(y0 + 200*(a)) x2 = int(x0 - 200*(-b)) y2 = int(y0 - 200*(a)) self.scene.addLine(QLineF(x1, y1, x2, y2), pen=QPen(QColor.fromRgb(0, 255, 0)))
def paintEvent(self, event): painter = QPainter(self) if len(self.m_histogram) == 0: painter.fillRect(0, 0, self.width(), self.height(), QColor.fromRgb(0, 0, 0)) return barWidth = self.width() / float(len(self.m_histogram)) for i, value in enumerate(self.m_histogram): h = value * height() # Draw the level. painter.fillRect(barWidth * i, height() - h, barWidth * (i + 1), height(), Qt.red) # Clear the rest of the control. painter.fillRect(barWidth * i, 0, barWidth * (i + 1), height() - h, Qt.black)
def __init__(self, data_manager): super(TrainerDialog, self).__init__() self.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) self.scene = QGraphicsScene() self.scene.setBackgroundBrush(QBrush(QColor.fromRgb(50, 50, 50))) self.graphicsView.setScene(self.scene) self.alignButton.clicked.connect(self.make_step) self.trainButton.clicked.connect(self.train) assert isinstance(data_manager, DataManager) self.data_manager = data_manager self.change_teeth(1) teeth = data_manager.get_all_teeth(False) self.choiceSlider.setRange(1, len(teeth) - 1) self.choiceSlider.valueChanged.connect(self.change_teeth)
def _parse_qcolor_arrayish(color_spec): if len(color_spec) < 3 or len(color_spec) > 4: raise ValueError('Expecting an array of length 3 or 4') if len(set(type(x) for x in color_spec)) > 1: raise ValueError('All components must have the same type') comp_type = type(color_spec[0]) if comp_type == int: if not all(0 <= x <= 255 for x in color_spec): raise ValueError('Integer components must be in the [0..255] range') return QColor.fromRgb(*color_spec) elif comp_type == float: if not all(0.0 <= x <= 1.0 for x in color_spec): raise ValueError('Float components must be in the [0.0..1.0] range') return QColor.fromRgbF(*color_spec) raise ValueError('Only int and float components are supported')
def _show_training_result(self): mean_tooth = Tooth(to_landmarks_format(self.pca.mean)) test_tooth = self.data_manager.get_tooth(0, 0, True) test_tooth.align(mean_tooth) tooth_data = test_tooth.landmarks.flatten() projection = self.pca.project(tooth_data) reconstructed_data = self.pca.reconstruct(projection) shapes = [self.pca.mean, tooth_data, reconstructed_data] colors = [[255, 0, 0], [0, 255, 255], [255, 255, 0]] self.scene.clear() for i, shape in enumerate(shapes): tooth = Tooth(to_landmarks_format(shape)) r, g, b = colors[i] tooth.outline_pen = QPen(QColor.fromRgb(r, g, b)) tooth.outline_pen.setWidthF(0.02) tooth.draw(self.scene, True, False, False) self._focus_view() self.compCountLabel.setText(str(len(self.pca.eigen_values)))
def visualize_data(window, data_manager, search_results): # Scene where everything will be drawn scene = QGraphicsScene() reference_radiograph = data_manager.left_out_radiograph reference_image = reference_radiograph.image reference_teeth = data_manager.get_all_teeth_from_radiograph(reference_radiograph) # Draw reference image first qimg = toQImage(reference_image.astype(np.uint8)) scene.addPixmap(QPixmap.fromImage(qimg)) for tooth in reference_teeth: assert isinstance(tooth, Tooth) tooth.outline_pen = QPen(QColor.fromRgb(0, 0, 255)) tooth.draw(scene) if search_results is not None: for tooth in search_results: assert isinstance(tooth, Tooth) tooth.draw(scene) window.set_scene(scene)
MAX_RECENT_FILE_NR = 10 ZOOM_TICKS = 10 PIXELS_PER_PATH = 5000 SPECTRUM_BUFFER_SIZE = 10 ** 5 SNIFF_BUFFER_SIZE = 5 * 10 ** 7 PAUSE_TRESHOLD = 10 RECT_BIT_WIDTH = 10 BIT_SCENE_HEIGHT = 100 TRANSPARENT_COLOR = QColor(Qt.transparent) LINECOLOR = QColor.fromRgb(225, 225, 225) BGCOLOR = QColor.fromRgb(55, 53, 53) AXISCOLOR = QColor.fromRgb(200, 200, 200, 100) ARROWCOLOR = QColor.fromRgb(204, 120, 50) SEND_INDICATOR_COLOR = QColor("darkblue") # overwritten by system color (bin/urh) # ROI-SELECTION COLORS SELECTION_COLOR = QColor("darkblue") # overwritten by system color (bin/urh) NOISE_COLOR = QColor("red") SELECTION_OPACITY = 0.8 NOISE_OPACITY = 0.4 # SEPARATION COLORS ONES_AREA_COLOR = QColor.fromRgb(0, 128, 128) ZEROS_AREA_COLOR = QColor.fromRgb(90, 9, 148)