def __init__(self): CG = self.ColorGroup CR = self.ColorRole self._brush = {} self._brush[CG.Active] = { CR.Background: QBrush(QColor.fromRgb(240, 240, 240)), CR.Base: QBrush(Qt.white), CR.Frame: QBrush(Qt.black), CR.Edge: QBrush(Qt.black), CR.Text: QBrush(Qt.black) } self._brush[CG.Selected] = { CR.Background: QBrush(Qt.white), CR.Base: QBrush(QColor.fromRgb(247, 247, 255)), CR.Frame: QBrush(QColor.fromRgb(0, 0, 200)), CR.Edge: QBrush(QColor.fromRgb(0, 0, 200)), CR.Text: QBrush(Qt.black) } self._brush[CG.Disabled] = {} self._brush[CG.Inactive] = {} # Copy Active group to other ones for key in self._brush[CG.Active]: self._brush[CG.Disabled][key] = QBrush(self._brush[CG.Active][key]) self._brush[CG.Inactive][key] = QBrush(self._brush[CG.Active][key]) self._current_color_group = CG.Active
def fill(self): # display the name of the selected node if self.guiSelection: node = self.guiSelection[0] if isinstance(node, nodes.BallastSystem): self._bs = node if self._bs is None: return tw = self.ui.tableWidget partial = QColor.fromRgb(*254*np.array(ds.COLOR_SELECT)) full = QColor.fromRgb(*254*np.array(ds.COLOR_WATER)) empty = QColor.fromRgb(254,254,254) self._filling_table = True self._cbFrozen.clear() for i,t in enumerate(self._bs._tanks): rows = i tw.setRowCount(rows + 1) tw.setVerticalHeaderItem(rows, QtWidgets.QTableWidgetItem(t.name)) item = QtWidgets.QTableWidgetItem('{:.1f}'.format(t.max)) item.setFlags(QtCore.Qt.ItemIsEditable) tw.setItem(rows, 0, item) item = QtWidgets.QTableWidgetItem('{:.1f}'.format(t.pct)) if t.pct >= 99.9: item.setBackground(QBrush(full)) item.setTextColor(empty) elif t.pct > 0.1: item.setBackground(QBrush(partial)) else: item.setBackground(QBrush(empty)) tw.setItem(rows, 1, item) item = QtWidgets.QCheckBox() self._cbFrozen.append(item) item.setChecked(t.frozen) item.stateChanged.connect(self.tankFrozenChanged) tw.setCellWidget (rows, 2, item) for j in range(3): item = QtWidgets.QTableWidgetItem('{:.3f}'.format(t.position[j])) item.setFlags(QtCore.Qt.ItemIsEditable) tw.setItem(rows, 3+j, item) self._filling_table = False
def data(self, index, role=Qt.DisplayRole): if not index.isValid() or not (0 <= index.row() < len(self.domains)): return None domain = self.domains[index.row()] column = index.column() if role == Qt.DisplayRole: if column == ID: return domain.id elif column == NAME: return domain.name if domain.name is not None else '--' elif column == COLOR: return '' if domain.color is not None else '+' elif column == COLORLABEL: return str(domain.color) if domain.color is not None else '--' elif column == MASK: return None elif column == HIGHLIGHT: return None elif role == Qt.ToolTipRole: if column == NAME: return 'Double-click to edit' elif column in (COLOR, COLORLABEL): return 'Double-click to edit \nRight-click to clear' elif column in (MASK, HIGHLIGHT): return 'Click to toggle' elif role == Qt.TextAlignmentRole: if column in (MASK, HIGHLIGHT, COLOR): return int(Qt.AlignCenter | Qt.AlignVCenter) else: return int(Qt.AlignLeft | Qt.AlignVCenter) elif role == Qt.BackgroundColorRole: if column == COLOR: if isinstance(domain.color, tuple): return QColor.fromRgb(*domain.color) elif isinstance(domain.color, str): return QColor.fromRgb( *openmc.plots._SVG_COLORS[domain.color]) elif role == Qt.CheckStateRole: if column == MASK: return Qt.Checked if domain.masked else Qt.Unchecked elif column == HIGHLIGHT: return Qt.Checked if domain.highlighted else Qt.Unchecked return None
def particulasTabla(self, particulas): labels = ['Id', 'origen', 'destino', 'velocidad', 'color', 'distancia'] self.ui.tblParticulas.clear() self.ui.tblParticulas.setColumnCount(6) self.ui.tblParticulas.setRowCount(len(particulas)) self.ui.tblParticulas.setHorizontalHeaderLabels(labels) row = 0 for particula in particulas: idx = QTableWidgetItem(str(particula.id)) origen = QTableWidgetItem('(' + str(particula.origen.x) + ',' + str(particula.origen.y) + ')') destino = QTableWidgetItem('(' + str(particula.destino.x) + ',' + str(particula.destino.y) + ')') velocidad = QTableWidgetItem(str(particula.velocidad)) color = QTableWidgetItem("") color.setBackground( QBrush( QColor.fromRgb(particula.color.r, particula.color.g, particula.color.b))) distancia = QTableWidgetItem(str(particula.distancia)) self.ui.tblParticulas.setItem(row, 0, idx) self.ui.tblParticulas.setItem(row, 1, origen) self.ui.tblParticulas.setItem(row, 2, destino) self.ui.tblParticulas.setItem(row, 3, velocidad) self.ui.tblParticulas.setItem(row, 4, color) self.ui.tblParticulas.setItem(row, 5, distancia) row += 1 self.ui.tblParticulas.horizontalHeader().setSectionResizeMode( QHeaderView.ResizeToContents)
def __init__(self, console): super(type(self), self).__init__() self.bar = QRoundProgressBar(console) self.bar.setFixedSize(300, 300) self.bar.setDataPenWidth(0) self.bar.setOutlinePenWidth(0) self.bar.setDonutThicknessRatio(0.92) self.bar.setDecimals(0) self.bar.setNullPosition(90) self.bar.setBarStyle(QRoundProgressBar.StyleDonut) self.bar.setDataColors([(0., QColor.fromRgb(65, 105, 225))]) self.bar.setRange(0, 29) self.setWindowTitle(f'{console.ptt_id} 驗證碼') lay = QVBoxLayout() lay.addWidget(self.bar) self.setLayout(lay) self.console = console self.timer_thread = None self.call_close = False self.logger = Logger('Progress', Logger.INFO) self.setWindowIcon(util.load_icon(config.icon_small)) self.update_otp()
def fill_results_table_with(self, summary): rows = -1 factor = 0.3 color = QColor.fromRgb(255 - 100 * factor, 255 - 100 * factor, 255) for b in summary: mode = b['mode'] name = b['node'] + ' mode:' + str(mode) try: node = self.guiScene[b['node']] except: continue rows += 1 self.ui.tableWidget.setRowCount(rows+1) self.ui.tableWidget.setVerticalHeaderItem(rows, QtWidgets.QTableWidgetItem(name)) self.ui.tableWidget.setItem(rows, 1, QtWidgets.QTableWidgetItem('{:e}'.format(node.inertia))) if mode>2: self.ui.tableWidget.setItem(rows, 2, QtWidgets.QTableWidgetItem('{:e}'.format(node.inertia_radii[mode-3]))) self.ui.tableWidget.item(rows, 2).setBackground(QBrush(color)) else: self.ui.tableWidget.item(rows, 1).setBackground(QBrush(color)) self.ui.tableWidget.setItem(rows, 2, QtWidgets.QTableWidgetItem('n/a')) self.ui.tableWidget.setItem(rows, 3, QtWidgets.QTableWidgetItem('{:.3e}'.format(b['total_inertia']))) self.ui.tableWidget.setItem(rows, 4, QtWidgets.QTableWidgetItem('{:.3e}'.format(b['stiffness']))) self.ui.tableWidget.setItem(rows, 5, QtWidgets.QTableWidgetItem(b['unconstrained'])) self.ui.tableWidget.setItem(rows, 6, QtWidgets.QTableWidgetItem(b['noinertia']))
def paintEvent(self, e: QEvent): """ Call when Qt renderer engine estimate that is needed :param e: the event """ qp = QPainter(self) qp.drawImage(0, 0, self._buffer) qp.setBrush(QColor.fromRgb(255, 255, 0, 180)) qp.drawEllipse(QPoint(self.mouseX, self.mouseY), 5, 5)
def _formatiraj(self, r, g, b, stil=''): #_boja = QColor() _boja = QColor.fromRgb(r, g, b, 255) _format = QTextCharFormat() _format.setForeground(_boja) if 'bold' in stil: _format.setFontWeight(QFont.Bold) if 'italic' in stil: _format.setFontItalic(True) return _format
def writeInNodeList(self, new=[]): if len(self.result) < 1: self.lw_selectedNodes.clear() index = 0 # print(len(self.result)) for i in new: self.lw_selectedNodes.addItem(i.name) color = i.wireColor self.lw_selectedNodes.item(index).setBackground( QColor.fromRgb(color.r, color.g, color.b)) if ((color.r + color.g + color.b) / 3) > 127.5: self.lw_selectedNodes.item(index).setForeground( QColor.fromRgb(60, 60, 60)) else: self.lw_selectedNodes.item(index).setForeground( QColor.fromRgb(240, 240, 240)) index += 1
def paintEvent(self, e: QEvent): """ Call when Qt renderer engine estimate that is needed :param e: the event """ ratio = self.ratio if self.scaleToWindow else 1 qp = QPainter(self) qp.drawImage( 0, 0, self._buffer.scaled(self.sessionWidth * ratio, self.sessionHeight * ratio, aspectMode=Qt.KeepAspectRatio)) qp.setBrush(QColor.fromRgb(255, 255, 0, 180)) qp.drawEllipse(QPoint(self.mouseX * ratio, self.mouseY * ratio), 5, 5)
def _writeFrame(self, surface: QImage): w = self.stream.width h = self.stream.height surface = surface.scaled(w, h) if self.scale else surface.copy() # Draw the mouse pointer. Render mouse clicks? p = QPainter(surface) p.setBrush(QColor.fromRgb(255, 255, 0, 180)) (x, y) = self.mouse p.drawEllipse(x, y, 5, 5) p.end() # Output frame. frame = av.VideoFrame.from_image(ImageQt.fromqimage(surface)) for packet in self.stream.encode(frame): if self.progress: self.progress() self.mp4.mux(packet)
def writeFrame(self): w = self.stream.width h = self.stream.height surface = self.imageHandler.screen.scaled( w, h) if self.scale else self.imageHandler.screen.copy() # Draw the mouse pointer. Render mouse clicks? p = QPainter(surface) p.setBrush(QColor.fromRgb(255, 255, 0, 180)) (x, y) = self.mouse p.drawEllipse(x, y, 5, 5) p.end() # Output frame. frame = av.VideoFrame.from_ndarray(qimage2ndarray.rgb_view(surface)) for packet in self.stream.encode(frame): if self.progress: self.progress() self.mp4.mux(packet)
def activate_modeshape(self): if not self._shapes_calculated: return i = self.ui.horizontalSlider.sliderPosition() scale = self.ui.sliderSize.sliderPosition() + 1 scale = 1.05**(scale - 30) # print('Activating mode-shape {} with scale {}'.format(i, scale)) omega = self.omega[i] self.ui.lblPeriod.setText('{:.2f} s'.format(2 * np.pi / omega)) self.ui.lblRads.setText('{:.2f} rad/s'.format(omega)) shape = self.shapes[:, i] n_frames = 100 t_modeshape = 5 dofs = DAVE.frequency_domain.generate_modeshape_dofs( self.d0, shape, scale, n_frames, scene=self.guiScene) t = np.linspace(0, t_modeshape, n_frames) self.gui.animation_start(t, dofs, True, self.d0, do_not_reset_time=True) # update exitation row in table for i, d in enumerate(shape): self.ui.tableWidget.setItem( i, 0, QtWidgets.QTableWidgetItem('{:.2f}'.format(d))) cell = self.ui.tableWidget.item(i, 0) if cell is None: continue m = np.max(np.abs(shape)) if m > 0 and abs(d) > 0: factor = 0.5 + 0.5 * abs(d) / m else: factor = 0 color = QColor.fromRgb(255 - 100 * factor, 255 - 100 * factor, 255) cell.setBackground(QBrush(color))
def Event_AppendToList(self): maya_cmds.undoInfo(stateWithoutFlush=False) try: selection = maya_cmds.ls(selection=True) maya_cmds.select(hierarchy=True) transforms = maya_cmds.ls(selection=True, transforms=True) transforms.sort(key=lambda s: s.lower()) if self.window.Check_IgnoreInstances.isChecked(): for i in xrange(len(transforms)): if '|' in transforms[ i] and not self.window.List_IdenticalNames.findItems( transforms[i], Qt.MatchExactly): transformParents = maya_cmds.listRelatives( transforms[i], path=True, allParents=True) if (len(transformParents) if transformParents is not None else 0) <= 1: self.window.List_IdenticalNames.addItem( transforms[i]) else: for i in xrange(len(transforms)): if '|' in transforms[ i] and not self.window.List_IdenticalNames.findItems( transforms[i], Qt.MatchExactly): transformParents = maya_cmds.listRelatives( transforms[i], path=True, allParents=True) if (len(transformParents) if transformParents is not None else 0) <= 1: self.window.List_IdenticalNames.addItem( transforms[i]) else: transformWidget = QListWidgetItem(transforms[i]) transformWidget.setTextColor( QColor.fromRgb(255, 64, 64)) self.window.List_IdenticalNames.addItem( transformWidget) self.window.Label_IdenticalNamesCount.setText( str(self.window.List_IdenticalNames.count())) maya_cmds.select(selection) except Exception as e: print >> stderr, str(e) maya_cmds.undoInfo(stateWithoutFlush=True)
def paintEvent(self, event: QPaintEvent): if self._get_state_cb is None: print( "GraphEditor: state callback is not specified. Ignoring paint event." ) return state = self._get_state_cb() painter = QPainter(self) painter.fillRect(self.rect(), QColor.fromRgb(58, 58, 58)) for node_id, node in state.items(): if node_id == self._selected_node_id: state = NodeUiState.Selected elif node_id == self._focused_node_id: state = NodeUiState.Focused else: state = NodeUiState.Normal draw_node(node, state, painter)
def addMod(self): allowed = mxs.readvalue(mxs.StringStream('Skin')) if mxs.classOf(mxs.modPanel.getCurrentObject()) == allowed: try: node = mxs.selection[0] mod = mxs.modPanel.getCurrentObject() modID = mxs.modPanel.getModifierIndex(mxs.selection[0], mod) if [node, mod, modID] in self.skinMeshes: pass else: self.skinMeshes.append([node, mod, modID]) self.lw_skiin.addItem("{} > {} > ID:{}".format( mxs.selection[0].name, mod, modID)) self.lw_skiin.item(self.lw_skiin.count() - 1).setBackground( QColor.fromRgb(60, 60, 60)) except: pass # print("Error") else: pass
def rgb_to_qcolor(color: int): """Convert an RDP color (0xRRGGBB) to a QColor.""" bpp = 16 # TODO: check BPP from capabilities if bpp in [24, 32]: return QColor(color) if bpp == 16: t = color & 0x1F t = (t << 3) + t // 4 b = min(t, 255) t = (color >> 5) & 0x3F t = (t << 2) + t // 4 // 2 g = min(t, 255) t = (color >> 11) & 0x1F t = (t << 3) + t // 4 r = min(t, 255) elif bpp == 15: pass elif bpp == 8: # TODO: Support palettized mode. pass return QColor.fromRgb(r, g, b)
def testRepr(self): c = QColor.fromRgb(1, 2, 3, 4) s = c.spec() self.assertEqual(repr(s), repr(QColor.Rgb))
def decode_color(color: int) -> QColor: r = (color >> 16) & 0xFF g = (color >> 8) & 0xFF b = (color >> 0) & 0xFF a = (color >> 24) & 0xFF return QColor.fromRgb(r, g, b, a)
def __init__(self, parent): super().__init__(parent) self.setStyleSheet(""" QToolBar { spacing: 5px; } QToolBar::separator { } """) # Check here for icon names # https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html#names self._bold_action = QIcon.fromTheme("format-text-bold") self.addAction(self._bold_action, "bold").setShortcut(QKeySequence.Bold) self._ital_action = QIcon.fromTheme("format-text-italic") self.addAction(self._ital_action, "italic").setShortcut(QKeySequence.Italic) self._under_action = QIcon.fromTheme("format-text-underline") self.addAction(self._under_action, "underline").setShortcut(QKeySequence.Underline) self._strk_action = QIcon.fromTheme("format-text-strikethrough") self.addAction(self._strk_action, "strikethrough") self.addSeparator() self._justl_action = QIcon.fromTheme("format-justify-left") self.addAction(self._justl_action, "left") self._justc_action = QIcon.fromTheme("format-justify-center") self.addAction(self._justc_action, "center") self._justr_action = QIcon.fromTheme("format-justify-right") self.addAction(self._justr_action, "right") self.addSeparator() self._bullet_action = QIcon.fromTheme("format-list-unordered") self.addAction(self._bullet_action, "bullet") self._number_action = QIcon.fromTheme("format-list-ordered") self.addAction(self._number_action, "numbered") self.addSeparator() # the following convert regular text items into special text items self._code_action = QIcon.fromTheme("format-text-code") self.addAction(self._code_action, "source code") self._check_action = QIcon.fromTheme("checkbox") self.addAction(self._check_action, "check") self.addSeparator() self.current_fg_color = QColor.fromRgb(0x000000) self.current_bg_color = QColor.fromRgb(0xffffff) self.foregnd_button = FontColorButton( QIcon.fromTheme("format-text-color"), "set text color") self.foregnd_button.set_color_display(self.current_fg_color) self.addWidget(self.foregnd_button) self.backgnd_button = FontColorButton(QIcon.fromTheme("color-fill"), "set text highlight color") self.backgnd_button.set_color_display(self.current_bg_color) self.foregnd_select_button = QPushButton( QIcon.fromTheme("color-management"), "") self.foregnd_select_button.setToolTip( "Select a new text foreground color") self.addWidget(self.foregnd_select_button) self.foregnd_select_button.setMaximumWidth(30) self.backgnd_select_button = QPushButton( QIcon.fromTheme("color-management"), "") self.backgnd_select_button.setToolTip( "Select a new text highlight color") self.addWidget(self.backgnd_button) self.backgnd_select_button.setMaximumWidth(30) self.addWidget(self.backgnd_select_button) self.addSeparator() # Configure font family and size input self.family_label = QLabel("Font") self.family_label.setMaximumWidth(40) self.addWidget(self.family_label) self.family_menu = QComboBox() self.family_menu.setMaximumWidth(180) self._fonts = {} # dict for fast lookups for i, each in enumerate(QFontDatabase().families()): font = self.family_menu.font() font.setFamily(each) font.setPointSize(12) self.family_menu.addItem(each) self._fonts[each] = i self.family_menu.setItemData(i, font, Qt.FontRole) self.addWidget(self.family_menu) self.size_label = QLabel("Size") self.size_label.setMaximumWidth(40) self.addWidget(self.size_label) self.size_input = QLineEdit("12") self.size_input.setValidator(FontSizeValidator()) self.size_input.setMaximumWidth(40) self.addWidget(self.size_input) # connect signals self.actionTriggered.connect(self._dispatch_event) self.foregnd_button.pressed.connect( lambda: G_FORMAT_SIGNALLER.foreground_colored.emit( self.current_fg_color)) self.backgnd_button.pressed.connect( lambda: G_FORMAT_SIGNALLER.background_colored.emit( self.current_bg_color)) self.foregnd_select_button.pressed.connect(self._select_fg_color) self.backgnd_select_button.pressed.connect(self._select_bg_color) G_FORMAT_SIGNALLER.active_font_changed.connect( self._feedback_font_size) self.size_input.returnPressed.connect(self._update_font_size) self.family_menu.activated[str].connect( lambda x: G_FORMAT_SIGNALLER.family_formatted.emit(x))
class Canvas(QWidget): content_changed = Signal() _background_color = QColor.fromRgb(0, 0, 0) _foreground_color = QColor.fromRgb(255, 255, 255) def __init__(self, parent, w, h, pen_width, scale): super().__init__(parent) self.w = w self.h = h self.scaled_w = scale * w self.scaled_h = scale * h self.scale = scale # Set size self.setFixedSize(self.scaled_w, self.scaled_h) # Create image self.small_image = QImage(self.w, self.h, QImage.Format_RGB32) self.small_image.fill(self._background_color) self.large_image = QImage(self.scaled_w, self.scaled_h, QImage.Format_RGB32) self.large_image.fill(self._background_color) # Create pen self.pen = QPen() self.pen.setColor(self._foreground_color) self.pen.setJoinStyle(Qt.RoundJoin) self.pen.setCapStyle(Qt.RoundCap) self.pen.setWidthF(scale * pen_width) # There is currently no path self.currentPath = None self.content_changed.connect(self.repaint) def _get_painter(self, paintee): painter = QPainter(paintee) painter.setPen(self.pen) painter.setRenderHint(QPainter.Antialiasing, True) return painter def _derive_small_image(self, large_image=None): if large_image is None: large_image = self.large_image # Downsample image self.small_image = large_image.scaled(self.w, self.h, mode=Qt.SmoothTransformation) self.content_changed.emit() def _current_path_updated(self, terminate_path=False): # Determine whether to draw on the large image directly or whether to make a temporary copy paintee = self.large_image if terminate_path else self.large_image.copy( ) # Draw path on the large image of choice painter = self._get_painter(paintee) if self.currentPath.elementCount() != 1: painter.drawPath(self.currentPath) else: painter.drawPoint(self.currentPath.elementAt(0)) painter.end() # Optionally terminate the path if terminate_path: self.currentPath = None # Downsample image self._derive_small_image(paintee) def _clear_image(self): self.large_image.fill(self._background_color) self._derive_small_image() def get_content(self): return np.asarray(self.small_image.constBits()).reshape( (self.h, self.w, -1)) def set_content(self, image_rgb): for row in range(image_rgb.shape[0]): for col in range(image_rgb.shape[1]): self.small_image.setPixel(col, row, image_rgb[row, col]) self.large_image = self.small_image.scaled( self.scaled_w, self.scaled_h, mode=Qt.SmoothTransformation) self._derive_small_image() self.content_changed.emit() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: # Create new path self.currentPath = QPainterPath() self.currentPath.moveTo(event.pos()) self._current_path_updated() def mouseMoveEvent(self, event): if (event.buttons() & Qt.LeftButton) and self.currentPath is not None: # Add point to current path self.currentPath.lineTo(event.pos()) self._current_path_updated() def mouseReleaseEvent(self, event): if (event.button() == Qt.LeftButton) and self.currentPath is not None: # Add terminal point to current path self.currentPath.lineTo(event.pos()) self._current_path_updated(terminate_path=True) elif event.button() == Qt.RightButton: self._clear_image() def paintEvent(self, event): paint_rect = event.rect() # Only paint the surface that needs painting painter = self._get_painter(self) # Draw image painter.scale(self.scale, self.scale) painter.drawImage(paint_rect, self.small_image, paint_rect) painter.end() painter = self._get_painter(self) #if self.currentPath is not None: # painter.drawPath(self.currentPath) @Slot() def repaint(self): super().repaint()
class GridDisplay(GameDisplay): background_colour = QColor.fromRgb(0x009E0B) line_colour = QColor.fromRgb(0x000000) player1_colour = QColor.fromRgb(0x000000) player2_colour = QColor.fromRgb(0xFFFFFF) def __init__(self, start_state: GridGameState): super().__init__(start_state) self.start_state: GridGameState = start_state self.spaces = [] # self.spaces[i][j] holds row i, column j self.column_dividers = [] self.row_dividers = [] self.column_labels = [] self.row_labels = [] self.text_x = self.text_y = 0 ui = self.ui = Ui_GridControls() ui.setupUi(self) scene = QGraphicsScene() ui.game_display.setScene(scene) scene.setBackgroundBrush(self.background_colour) self.player1_icon = self.create_icon(self.player1_colour) self.player2_icon = self.create_icon(self.player2_colour) ui.black_count_pixmap.setText('') ui.white_count_pixmap.setText('') ui.black_count.setText('') ui.white_count.setText('') for _ in range(start_state.board_height - 1): self.row_dividers.append(scene.addLine(0, 0, 1, 1)) for _ in range(start_state.board_width - 1): self.column_dividers.append(scene.addLine(0, 0, 1, 1)) for i in range(start_state.board_height): self.row_labels.append(scene.addSimpleText(f'{i + 1}')) for j in range(start_state.board_width): self.column_labels.append(scene.addSimpleText(chr(65 + j))) self.to_move = scene.addEllipse(0, 0, 1, 1, brush=self.get_player_brush( self.start_state.X_PLAYER)) self.to_move.setVisible(False) self.move_text = ui.move_text for i in range(self.start_state.board_height): row: typing.List[QGraphicsItem] = [] self.spaces.append(row) for j in range(self.start_state.board_width): piece = GraphicsPieceItem(i, j, self) scene.addItem(piece) piece.setBrush(self.background_colour) piece.setPen(self.background_colour) row.append(piece) self.debug_message = '' def resizeEvent(self, event: QResizeEvent): super().resizeEvent(event) game_display = self.ui.game_display view_size = game_display.contentsRect() width = view_size.width() height = view_size.height() extra_columns = 0 margin = 1 if self.show_coordinates else 0 cell_size = min( width // (self.start_state.board_width + extra_columns + margin), height // (self.start_state.board_height + margin)) size = cell_size * self.start_state.board_width x0 = (width - cell_size * (self.start_state.board_width + extra_columns + margin)) // 2 y0 = (height - cell_size * (self.start_state.board_height + margin)) // 2 x0 += margin * cell_size y0 += margin * cell_size font = QFont(self.default_font) font_size = max(1, int(cell_size // 2)) font.setPointSize(font_size) for i in range(self.start_state.board_height - 1): r = cell_size * (i + 1) self.row_dividers[i].setLine(x0, y0 + r, x0 + size, y0 + r) for i in range(self.start_state.board_width - 1): r = cell_size * (i + 1) self.column_dividers[i].setLine(x0 + r, y0, x0 + r, y0 + size) for i, label in enumerate(self.row_labels): r = cell_size * (2 * i + 1) // 2 label.setFont(font) text_x = x0 - cell_size // 2 text_y = y0 + r center_text_item(label, text_x, text_y) for i, label in enumerate(self.column_labels): r = cell_size * (2 * i + 1) // 2 label.setFont(font) center_text_item(label, x0 + r, y0 - cell_size // 2) font_size = max(1, int(cell_size * extra_columns // 6)) font.setPointSize(font_size) self.text_x = x0 + size + cell_size * extra_columns // 2 self.text_y = (y0 + cell_size * self.start_state.board_height // 2 + cell_size * extra_columns // 5) self.update_move_text() for i, row in enumerate(self.spaces): for j, piece in enumerate(row): x = x0 + j * cell_size + cell_size // 8 y = y0 + i * cell_size + cell_size // 8 piece.setRect(x, y, cell_size * 3 // 4, cell_size * 3 // 4) self.scene().setSceneRect(0, 0, width, height) def scene(self) -> QGraphicsScene: return self.ui.game_display.scene() @staticmethod def create_icon(player_colour: QColor) -> QPixmap: size = 200 icon = QPixmap(size, size) icon.fill(Qt.transparent) painter = QPainter(icon) try: painter.setBrush(player_colour) pen = QPen() pen.setWidth(3) painter.setPen(pen) painter.drawEllipse(1, 1, size - 2, size - 2) finally: painter.end() return icon def update_board(self, state: GameState): assert isinstance(state, GridGameState) self.current_state = state self.valid_moves = self.current_state.get_valid_moves() is_ended = self.current_state.is_ended() spaces = self.current_state.get_spaces() for i in range(self.current_state.board_height): for j in range(self.current_state.board_width): player = spaces[i][j] piece = self.spaces[i][j] if player == self.current_state.NO_PLAYER: if is_ended: piece.setVisible(False) else: piece.setVisible(True) piece.setBrush(self.background_colour) piece.setPen(self.background_colour) else: piece.setVisible(True) piece.setBrush(self.get_player_brush(player)) piece.setPen(self.line_colour) piece.setOpacity(1) self.ui.player_pixmap.setVisible(True) for label in itertools.chain(self.row_labels, self.column_labels): label.setVisible(self.show_coordinates) if is_ended: if self.current_state.is_win(self.current_state.X_PLAYER): self.update_move_text('wins') self.ui.player_pixmap.setPixmap(self.player1_icon) elif self.current_state.is_win(self.current_state.O_PLAYER): self.update_move_text('wins') self.to_move.setBrush( self.get_player_brush(self.current_state.O_PLAYER)) else: self.update_move_text('draw') self.ui.player_pixmap.clear() else: self.update_move_text(self.choose_active_text()) active_player = self.current_state.get_active_player() self.ui.player_pixmap.setPixmap( self.get_player_icon(active_player)) def get_player_brush(self, player): return QBrush(self.player1_colour if player == self.start_state.X_PLAYER else self.player2_colour) def get_player_icon(self, player: int) -> QPixmap: return (self.player1_icon if player == self.start_state.X_PLAYER else self.player2_icon) def update_move_text(self, text: str = None): if self.debug_message: self.move_text.setText(self.debug_message) elif text is not None: self.move_text.setText(text) def on_hover_enter(self, piece_item: GraphicsPieceItem): if self.is_piece_played(piece_item): return if not self.can_move(): return move = self.calculate_move(piece_item.row, piece_item.column) is_valid = self.valid_moves[move] if not is_valid: return piece_item.setBrush( self.get_player_brush(self.current_state.get_active_player())) piece_item.setPen(self.line_colour) piece_item.setOpacity(0.5) def on_hover_leave(self, piece_item: GraphicsPieceItem): if self.is_piece_played(piece_item): return piece_item.setBrush(self.background_colour) piece_item.setPen(self.background_colour) piece_item.setOpacity(1) def on_click(self, piece_item: GraphicsPieceItem): if not self.can_move(): return move = self.calculate_move(piece_item.row, piece_item.column) is_valid = self.valid_moves[move] if is_valid: self.make_move(move) def calculate_move(self, row, column): move = row * self.start_state.board_width + column return move def is_piece_played(self, piece_item): current_spaces = self.current_state.get_spaces() hovered_player = current_spaces[piece_item.row][piece_item.column] return hovered_player != self.start_state.NO_PLAYER def close(self): super().close() scene = self.ui.game_display.scene() if scene is not None: scene.clear()
def highlightBlock(self, text): # Highlight keywords keywords = ["(?<=\\W\\()\\w+(?=[ *&]*\\))","\\w+ (?=.*\\)$)","^ +\\w+ (?=[*&_A-Za-z0-9\\[\\] ]+;)","^\w+","\\bin_addr\\b","\\bssize_t\\b","\\bsocklen_t\\b","\\bsa_family_t\\b","\\b__int32_t\\b","\\b__int8_t\\b","\\b__int16_t\\b","\\b__uint32_t\\b","\\b__uint8_t\\b","\\b__uint16_t\\b","\\bpid_t\\b","\\bcode\\b","\\bLPSTR\\b","\\bSIZE_T\\b","\\bLPVOID\\b","\\bDWORD\\b","\\bclock_t\\b","\\bthis\\b","\\bUINT\\b","\\bHANDLE\\b","\\blonglong\\b","\\bushort\\b","\\bFILE\\b","\\bulong\\b","\\bbyte\\b","\\bfalse\\b","\\btrue\\b","\\buint\\b","\\bsize_t\\b","\\bundefined\\d*\\b","\\bchar\\b", "\\bclass\\b", "\\bconst\\b", "\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b","\\bfriend\\b", "\\binline\\b", "\\bint\\b","\\blong\\b", "\\bnamespace\\b", "\\boperator\\b","\\bprivate\\b", "\\bprotected\\b", "\\bpublic\\b","\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b","\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b","\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b","\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b","\\bvoid\\b", "\\bvolatile\\b", "\\bbool\\b"] keyword_format = QTextCharFormat() keyword_format.setForeground(getThemeColor(enums.ThemeColor.KeywordColor)) for keyword in keywords: for match in re.finditer(keyword, text): self.setFormat(match.start(), match.end() - match.start(), keyword_format) # Highlight flow words flow_words = ["\\breturn\\b","\\bif\\b","\\belse\\b","\\bswitch\\b","\\bcase\\b","\\bwhile\\b","\\bfor\\b","\\bdo\\b","\\bgoto\\b"] flow_format = QTextCharFormat() flow_format.setForeground(getThemeColor(enums.ThemeColor.TokenHighlightColor)) for flow in flow_words: for match in re.finditer(flow, text): self.setFormat(match.start(), match.end() - match.start(), flow_format) # Highlight functions function_format = QTextCharFormat() function_format.setForeground(getThemeColor(enums.ThemeColor.CodeSymbolColor)) function_pattern = "\\b\\w+(?=\\()" for match in re.finditer(function_pattern, text): self.setFormat(match.start(), match.end() - match.start(), function_format) # Highlight comments comment_format = QTextCharFormat() comment_format.setForeground(getThemeColor(enums.ThemeColor.CommentColor)) comment_pattern = "\/\/.*$" for match in re.finditer(comment_pattern, text): self.setFormat(match.start(), match.end() - match.start(), comment_format) multi_comment_pattern = "(?s)\\/\\*.*?\\*\\/" for match in re.finditer(multi_comment_pattern, text): self.setFormat(match.start(), match.end() - match.start(), comment_format) # Highlight string constants const_format = QTextCharFormat() const_format.setForeground(getThemeColor(enums.ThemeColor.StringColor)) string_consts = "\"(.*?)\"" for match in re.finditer(string_consts, text): self.setFormat(match.start(), match.end() - match.start(), const_format) # Highlight numeric constants num_const_format = QTextCharFormat() num_const_format.setForeground(getThemeColor(enums.ThemeColor.NumberColor)) num_consts = "\\b\\d+\\b" for match in re.finditer(num_consts, text): self.setFormat(match.start(), match.end() - match.start(), num_const_format) hex_const = "0x[0-9a-f]+\\b" for match in re.finditer(hex_const, text): self.setFormat(match.start(), match.end() - match.start(), num_const_format) # Highlight data data_format = QTextCharFormat() data_format.setForeground(getThemeColor(enums.ThemeColor.DataSymbolColor)) data_consts = "\\b(PTR)?_?DAT_[0-9a-zA-Z]+\\b" for match in re.finditer(data_consts, text): self.setFormat(match.start(), match.end() - match.start(), data_format) # Highlight CPP Class paths cpp_format = QTextCharFormat() cpp_format.setForeground(getThemeColor(enums.ThemeColor.NameSpaceColor)) cpp_path = "\\b\\w*(?=::)" for match in re.finditer(cpp_path, text): self.setFormat(match.start(), match.end() - match.start(), cpp_format) # Params params_format = QTextCharFormat() params_format.setForeground(getThemeColor(enums.ThemeColor.FieldNameColor)) for arg in self.args: params_pattern = "\\b" + arg + "\\b" for match in re.finditer(params_pattern, text): self.setFormat(match.start(), match.end() - match.start(), params_format) # Highlight selection if self.selected: selection_format = QTextCharFormat() #selection_format.setBackground(getThemeColor(enums.ThemeColor.Highlight)) selection_format.setBackground(QColor.fromRgb(121,195,231)) selection_format.setForeground(QColor.fromRgb(42,42,42)) try: selection_pattern = self.selected for match in re.finditer(selection_pattern, text): self.setFormat(match.start(), match.end() - match.start(), selection_format) except: pass
def value_color(self): return QColor.fromRgb(0xFFA140)
from PySide2.QtGui import QPainter, QColor from python.platform import Node class NodeUiState(enum.Enum): Normal = 0 Focused = 1 Selected = 2 node_header_height = 50 node_knob_height = 40 node_width = 200 normal_color = QColor.fromRgb(50, 120, 30) focused_color = QColor.fromRgb(50, 120, 60) selected_color = QColor.fromRgb(60, 120, 130) def draw_node(node: Node, node_state: NodeUiState, painter: QPainter): node_rect = QRect(node.metadata['PositionX'], node.metadata['PositionY'], node_width, node_header_height) if node_state == NodeUiState.Selected: color = selected_color elif node_state == NodeUiState.Focused: color = focused_color else: color = normal_color
starPath = QPainterPath() starPath.moveTo(28, 15) for i in range(5): starPath.lineTo(14 + 14 * math.cos(0.8 * i * math.pi), 15 + 14 * math.sin(0.8 * i * math.pi)) starPath.closeSubpath() star = QImage(30, 30, QImage.Format_ARGB32) star.fill(Qt.transparent) painter = QPainter(star) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QColor.fromRgb(0xf6, 0xa6, 0x25)) painter.setBrush(painter.pen().color()) painter.drawPath(starPath) series2.setBrush(star) series2.setPen(QColor(Qt.transparent)) chartView = QtCharts.QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) chart.addSeries(series0) chart.addSeries(series1) chart.addSeries(series2) chart.setTitle("Simple scatterchart example") chart.createDefaultAxes()
def interpolate(start: QColor, end: QColor, ratio: float) -> QColor: """Interpolate between two colors""" r = int(ratio * start.red() + (1 - ratio) * end.red()) g = int(ratio * start.green() + (1 - ratio) * end.green()) b = int(ratio * start.blue() + (1 - ratio) * end.blue()) return QColor.fromRgb(r, g, b)
def value_color(self): return QColor.fromRgb(0x58D858)