def setColorText(self, text): text = str(text).upper().replace('#', '') color = QColor('#' + text) if not color.isValid(): return self.box.setStyleSheet('background-color: #' + text + '; border: 1px solid black;') self.edit.setText(text) self.color = color return True
def txformat(color, style=''): """Return a QTextCharFormat with the given attributes. """ _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: _format.setFontItalic(True) return _format
class QColorGetTest(unittest.TestCase): def setUp(self): self.color = QColor(20, 40, 60, 80) def testGetRgb(self): self.assertEqual(self.color.getRgb(), (20, 40, 60, 80)) def testGetHslF(self): hls = colorsys.rgb_to_hls(20.0/255, 40.0/255, 60.0/255) hsla = hls[0], hls[2], hls[1], self.color.alphaF() for x, y in zip(self.color.getHslF(), hsla): # Due to rounding problems self.assert_(x - y < 1/100000.0) def testGetHsv(self): hsv = colorsys.rgb_to_hsv(20.0/255, 40.0/255, 60.0/255) hsva = int(hsv[0]*360.0), int(hsv[1]*255), int(hsv[2]*256), self.color.alpha() self.assertEqual(self.color.getHsv(), hsva) def testGetCmyk(self): # not supported by colorsys self.assertEqual(self.color.getCmyk(), (170, 85, 0, 195, 80)) def testGetCmykF(self): # not supported by colorsys for x, y in zip(self.color.getCmykF(), (170/255.0, 85/255.0, 0, 195/255.0, 80/255.0)): self.assert_(x - y < 1/10000.0)
def setUp(self): self.original = QColor.fromCmykF(0.2, 0.3, 0.4, 0.5, 0.6)
def paint(self, painter): """ :param QPainter painter: :return: """ if self.selected: painter.setPen(self._config.disasm_view_operand_select_color) painter.setBrush(self._config.disasm_view_operand_select_color) painter.drawRect(self.x, self.y, self.width, self.height) else: # should we highlight ourselves? if self.infodock.should_highlight_operand(self): painter.setPen( self._config.disasm_view_operand_highlight_color) painter.setBrush( self._config.disasm_view_operand_highlight_color) painter.drawRect(self.x, self.y, self.width, self.height) x = self.x if self._branch_target or self._branch_targets: if self._is_target_func: painter.setPen(self._config.disasm_view_target_addr_color) else: painter.setPen(self._config.disasm_view_antitarget_addr_color) else: if self.disasm_view.show_variable and self.variable is not None: # show-variable is enabled and this operand has a linked variable fallback = True if self.infodock.induction_variable_analysis is not None: r = self.infodock.induction_variable_analysis.variables.get( self.variable.ident, None) if r is not None and r.expr.__class__.__name__ == "InductionExpr": painter.setPen(Qt.darkYellow) fallback = False if fallback: painter.setPen(QColor(0xff, 0x14, 0x93)) else: painter.setPen(QColor(0, 0, 0x80)) painter.drawText(x, self.y + self._config.disasm_font_ascent, self._label) x += self._label_width # draw additional branch targets if self._branch_targets_text: painter.setPen(Qt.darkYellow) x += self.BRANCH_TARGETS_SPACING painter.drawText( x, self.y + self._config.disasm_font_ascent, self._branch_targets_text, ) x += self._branch_targets_text_width if self.variable is not None and self.disasm_view.show_variable_identifier: x += self.VARIABLE_IDENT_SPACING painter.setPen(Qt.darkGreen) painter.drawText(x, self.y + self._config.disasm_font_ascent, self._variable_ident) x += self._variable_ident_width # restores the color painter.setPen(QColor(0, 0, 0x80))
def colorChanged(self, color: QColor, hue: float, sat: float, bright: float) -> None: self.labColor.setStyleSheet("QLabel{background:%s;}" % color.name())
def __init__(self, parent=None): super(Form, self).__init__(parent) self.setWindowTitle("Backend Discord-GUI") self.changeStyle('fusion') palette = QPalette() palette.setColor(QPalette.Window, QColor(53, 53, 53)) palette.setColor(QPalette.WindowText, Qt.white) palette.setColor(QPalette.Text, Qt.white) palette.setColor(QPalette.Button, QColor(60, 60, 60)) palette.setColor(QPalette.ButtonText, Qt.white) palette.setColor(QPalette.Base, QColor(40, 40, 40)) palette.setColor(QPalette.ToolTipBase, QColor(60, 60, 60)) palette.setColor(QPalette.ToolTipText, Qt.white) palette.setColor(QPalette.PlaceholderText, QColor(100, 60, 60)) palette.setColor(QPalette.BrightText, Qt.white) palette.setColor(QPalette.Highlight, QColor(106, 13, 173)) palette.setColor(QPalette.HighlightedText, Qt.white) mainLayout = QVBoxLayout() hMainLayout = QHBoxLayout() passwordLayout = QHBoxLayout() self.username = QLineEdit(self) self.QUserLabel = QLabel("Username") self.username.setStyleSheet( "QToolTop { border: 0px; border-radius: 3px }") self.QUserLabel.setFont(QFont("Copperplate", 12)) self.password = QLineEdit(self) self.QPasswordLabel = QLabel("Password") self.password.setStyleSheet( "QToolTip { border: 0px; border-radius: 3px }") self.QPasswordLabel.setFont(QFont("Copperplate", 12)) self.showhideButton = QPushButton("Show") self.showhideButton.setCheckable(True) self.showhideButton.setChecked(False) self.showhideButton.clicked.connect(lambda: self.show_hide()) self.password.setEchoMode(QLineEdit.Password) passwordLayout.addWidget(self.QPasswordLabel) passwordLayout.addWidget(self.password) passwordLayout.addWidget(self.showhideButton) self.btn_Submit = QPushButton("Login") shortcut = QShortcut(QKeySequence("Return"), self.btn_Submit) shortcut.activated.connect(lambda: self.do_nothing()) shortcut.setEnabled(True) self.btn_SignUp = QPushButton("Sign Up") self.btn_SignUp.clicked.connect(lambda: window.openSignUp()) layout = QFormLayout() layout.addRow(self.QUserLabel, self.username) layout.addRow(passwordLayout) layout.addRow(self.btn_Submit) layout.addRow(self.btn_SignUp) Label = QLabel("Welcome To The\nBackend Discord-GUI Development") Label.setFont(QFont("Copperplate", 15, QFont.Bold)) Label.setAlignment(Qt.AlignCenter) mainLayout.addSpacing(80) mainLayout.addWidget(Label) mainLayout.addLayout(layout) mainLayout.addSpacing(100) hMainLayout.addSpacing(125) hMainLayout.addLayout(mainLayout) hMainLayout.addSpacing(125) self.setLayout(hMainLayout) QApplication.setPalette(palette)
def paint(self, painter, option, index): if index.column() == NUT_PERCENT_COL: progress_bar_option = QStyleOptionProgressBar() progress_bar_option.rect = option.rect progress_bar_option.minimum = 0 progress_bar_option.maximum = 100 progress_bar_option.textVisible = True progress = index.data(role=Qt.DisplayRole) p = QPalette() if progress is None: # A bug in the progress bar for the fusion style causes a thin vertical strip # of the progress bar chunk to be painted to the left of a progress bar with # less than 1% progess while drawn in a table view. # This strip is normally covered by the table's grid lines, but I have them disabled. # My workaround to display a completely empty progress bar without the strip # is to fill the progress bar and simply turn the color to white progress_bar_option.progress = 100 progress_bar_option.text = "No data" p.setColor(QPalette.Highlight, QColor(Qt.white)) p.setColor(QPalette.HighlightedText, Qt.darkGray) progress_bar_option.palette = p elif progress == -1: progress_bar_option.progress = 100 progress_bar_option.text = "None set" p.setColor(QPalette.Highlight, QColor(Qt.white)) p.setColor(QPalette.HighlightedText, Qt.darkGray) progress_bar_option.palette = p elif round(progress) == 0: progress_bar_option.progress = 100 progress_bar_option.text = "0%" p.setColor(QPalette.Highlight, QColor(Qt.white)) p.setColor(QPalette.HighlightedText, QColor(Qt.black)) progress_bar_option.palette = p elif 0 < round(progress) < 100: rounded_string = '{number:.{digits}f}%'.format(number=progress, digits=0) progress_bar_option.progress = round(progress) progress_bar_option.text = rounded_string elif 100 <= round(progress): rounded_string = '{number:.{digits}f}%'.format(number=progress, digits=0) progress_bar_option.progress = 100 progress_bar_option.text = rounded_string #p.setColor(QPalette.Highlight, QColor(247, 202, 202)) #progress_bar_option.palette = p #QApplication.style().drawControl(QStyle.CE_ProgressBar, progress_bar_option, painter) QStyleFactory.create('fusion').drawControl(QStyle.CE_ProgressBar, progress_bar_option, painter) else: QStyledItemDelegate.paint(self, painter, option, index)
def __init__(self, color: QColor = QColor('green')): super().__init__() self.color = color
def __init__(self, targetImage=None, axeSize=500, layer=None, parent=None): super().__init__(layer=layer, targetImage=targetImage, parent=parent) self.options = None pushButton1 = QPushButton(' Undo ') pushButton1.adjustSize() pushButton2 = QPushButton(' Redo ') pushButton2.adjustSize() pushButton1.clicked.connect(self.undo) pushButton2.clicked.connect(self.redo) spacingSlider = QSlider(Qt.Horizontal) spacingSlider.setObjectName('spacingSlider') spacingSlider.setRange(1,60) spacingSlider.setTickPosition(QSlider.TicksBelow) spacingSlider.setSliderPosition(10) spacingSlider.sliderReleased.connect(self.parent().label.brushUpdate) self.spacingSlider = spacingSlider jitterSlider = QSlider(Qt.Horizontal) jitterSlider.setObjectName('jitterSlider') jitterSlider.setRange(0, 100) jitterSlider.setTickPosition(QSlider.TicksBelow) jitterSlider.setSliderPosition(0) jitterSlider.sliderReleased.connect(self.parent().label.brushUpdate) self.jitterSlider = jitterSlider orientationSlider = QSlider(Qt.Horizontal) orientationSlider.setObjectName('orientationSlider') orientationSlider.setRange(0, 360) orientationSlider.setTickPosition(QSlider.TicksBelow) orientationSlider.setSliderPosition(180) orientationSlider.sliderReleased.connect(self.parent().label.brushUpdate) self.orientationSlider = orientationSlider # sample self.sample = QLabel() #self.sample.setMinimumSize(200, 100) pxmp = QPixmap(250,100) pxmp.fill(QColor(255, 255, 255, 255)) self.sample.setPixmap(pxmp) qpp = QPainterPath() qpp.moveTo(QPointF(20, 50)) qpp.cubicTo(QPointF(80, 25), QPointF(145, 70), QPointF(230, 60)) # c1, c2, endPoint self.samplePoly = qpp.toFillPolygon(QTransform()) # we want an unclosed polygon self.samplePoly.removeLast() # layout l = QVBoxLayout() l.setAlignment(Qt.AlignTop) hl = QHBoxLayout() hl.setAlignment(Qt.AlignHCenter) hl.addWidget(pushButton1) hl.addWidget(pushButton2) l.addLayout(hl) l.addWidget(QLabel('Brush Dynamics')) hl1 = QHBoxLayout() hl1.addWidget(QLabel('Spacing')) hl1.addWidget(spacingSlider) l.addLayout(hl1) hl2 = QHBoxLayout() hl2.addWidget(QLabel('Jitter')) hl2.addWidget(jitterSlider) l.addLayout(hl2) hl3 = QHBoxLayout() hl3.addWidget(QLabel('Orientation')) hl3.addWidget(self.orientationSlider) l.addLayout(hl3) l.addWidget(self.sample) self.setLayout(l) self.adjustSize() self.setDefaults() self.setWhatsThis( """ <b>Drawing :</b><br> Choose a brush family, flow, hardness and opacity. """ ) # end of setWhatsThis
class ColorList: """ A list of colors and a way to generate a next color and texture combination. Attributes: colors (:obj:`list`): List of colors used. """ colors = [ QColor(0, 0, 0), QColor(170, 0, 0), QColor(0, 85, 0), QColor(170, 85, 0), QColor(0, 170, 0), QColor(170, 170, 0), QColor(0, 255, 0), QColor(170, 255, 0), QColor(0, 0, 127), QColor(170, 0, 127), QColor(0, 85, 127), QColor(170, 85, 127), QColor(0, 170, 127), QColor(170, 170, 127), QColor(0, 255, 127), QColor(170, 255, 127), QColor(0, 0, 255), QColor(170, 0, 255), QColor(0, 85, 255), QColor(170, 85, 255), QColor(0, 170, 255), QColor(170, 170, 255), QColor(0, 255, 255), QColor(170, 255, 255), QColor(85, 0, 0), QColor(255, 0, 0), QColor(85, 85, 0), QColor(255, 85, 0), QColor(85, 170, 0), QColor(255, 170, 0), QColor(85, 255, 0), QColor(255, 255, 0), QColor(85, 0, 127), QColor(255, 0, 127), QColor(85, 85, 127), QColor(255, 85, 127), QColor(85, 170, 127), QColor(255, 170, 127), QColor(85, 255, 127), QColor(255, 255, 127), QColor(85, 0, 255), QColor(255, 0, 255), QColor(85, 85, 255), QColor(255, 85, 255), QColor(85, 170, 255), QColor(255, 170, 255), QColor(85, 255, 255), QColor(255, 255, 255) ] @classmethod def get_next_color_and_texture(cls, new_id, option): """ Sets the color and texture for a polygon option. Args: new_id (int): The new id for the polygon display option. option (:obj:`PolygonOption`): The polygon display option to set. """ num_colors = len(cls.colors) option.color = cls.colors[new_id % num_colors] option.texture = PolygonTexture( (int(option.texture) + int(new_id / num_colors)) % len(PolygonTexture))
class nDisplayMonitor(QAbstractTableModel): ''' This will monitor the status of the nDisplay nodes, in particular regarding sync. It polls the listener at the specified rate and the UI should update with this info. ''' ColorWarning = QColor(0x70, 0x40, 0x00) ColorNormal = QColor(0x3d, 0x3d, 0x3d) def __init__(self, parent): QAbstractTableModel.__init__(self, parent) self.polling_period_ms = 1000 self.devicedatas = OrderedDict( ) # ordered so that we can map row indices to devices self.timer = QTimer(self) self.timer.timeout.connect(self.poll_sync_status) headerdata = [ ('Node', 'The cluster name of this device'), ('Host', 'The URL of the remote PC'), ('Connected', 'If we are connected to the listner of this device'), ('Driver', 'GPU driver version'), ('FlipMode', 'Current presentation mode. Only available once the render node process is running. Expects "Hardware Composed: Independent Flip"' ), ('Gpus', 'Informs if GPUs are synced.'), ('Displays', 'Detected displays and whether they are in sync or not'), ('Fps', 'Sync Frame Rate'), ('HouseSync', 'Presence of an external sync signal connected to the remote Quadro Sync card' ), ('SyncSource', 'The source of the GPU sync signal'), ('Mosaics', 'Display grids and their resolutions'), ('Taskbar', 'Whether the taskbar is set to auto hide or always on top. It is recommended to be consistent across the cluster' ), ('InFocus', 'Whether nDisplay instance window is in Focus. It is recommended to be in focus.' ), ('ExeFlags', 'It is recommended to disable fullscreen opimizations on the unreal executable. Only available once the render node process is running. Expects "DISABLEDXMAXIMIZEDWINDOWEDMODE"' ), ] self.colnames = [hd[0] for hd in headerdata] self.tooltips = [hd[1] for hd in headerdata] def color_for_column(self, colname, value, data): ''' Returns the background color for the given cell ''' if data['Connected'].lower() == 'no': if colname == 'Connected': return self.ColorWarning return self.ColorNormal if colname == 'FlipMode': good_string = 'Hardware Composed: Independent Flip' return self.ColorNormal if good_string in value else self.ColorWarning if colname == 'Gpus': return self.ColorNormal if 'Synced' in value and 'Free' not in value else self.ColorWarning if colname == 'InFocus': return self.ColorNormal if 'yes' in value else self.ColorWarning if colname == 'ExeFlags': good_string = 'DISABLEDXMAXIMIZEDWINDOWEDMODE' return self.ColorNormal if good_string in value else self.ColorWarning if colname == 'Displays': is_normal = ('Slave' in value or 'Master' in value) and 'Unsynced' not in value return self.ColorNormal if is_normal else self.ColorWarning return self.ColorNormal def reset_device_data(self, device, data): ''' Sets device data to unconnected state ''' for colname in self.colnames: data[colname] = 'n/a' data['Host'] = str(device.ip_address) data['Node'] = device.name data[ 'Connected'] = 'yes' if device.unreal_client.is_connected else 'no' # extra data not in columns data['TimeLastFlipGlitch'] = time.time() def added_device(self, device): ''' Called by the plugin when a new nDisplay device has been added. ''' data = {} self.reset_device_data(device, data) self.devicedatas[device.device_hash] = { 'device': device, 'data': data, 'time_last_update': 0, 'stale': True } # notify the UI of the change self.layoutChanged.emit() # start/continue polling since there is at least one device if not self.timer.isActive(): self.timer.start(self.polling_period_ms) def removed_device(self, device): ''' Called by the plugin when an nDisplay device has been removed. ''' self.devicedatas.pop(device.device_hash) # notify the UI of the change self.layoutChanged.emit() # turn off the timer if there are no devices left if not self.devicedatas: self.timer.stop() def handle_stale_device(self, devicedata, deviceIdx): '''Detects if the device is stale, and resets the data if so as to not mislead the user ''' # if already flagged as stale, no need to do anything if devicedata['stale']: return # check if it has been too long time_elapsed_since_last_update = time.time( ) - devicedata['time_last_update'] timeout_factor = 4 if time_elapsed_since_last_update < timeout_factor * self.polling_period_ms * 1e-3: return # if we're here, it has been too long since the last update self.reset_device_data(devicedata['device'], devicedata['data']) devicedata['stale'] = True # notify the UI row = deviceIdx + 1 self.dataChanged.emit(self.createIndex(row, 1), self.createIndex(row, len( self.colnames))) # [Qt.EditRole] def handle_connection_change(self, devicedata, deviceIdx): ''' Detects if device connection changed and notifies the UI if a disconnection happens. ''' device = devicedata['device'] data = devicedata['data'] is_connected = device.unreal_client.is_connected was_connected = True if data['Connected'] == 'yes' else False data['Connected'] = 'yes' if is_connected else 'no' if was_connected != is_connected: if not is_connected: self.reset_device_data(device, data) row = deviceIdx + 1 self.dataChanged.emit(self.createIndex(row, 1), self.createIndex(row, len(self.colnames))) def poll_sync_status(self): ''' Polls sync status for all nDisplay devices ''' for deviceIdx, devicedata in enumerate(self.devicedatas.values()): device = devicedata['device'] # detect connection changes (a disconnection invalidates data) self.handle_connection_change(devicedata, deviceIdx) # detect stale devices self.handle_stale_device(devicedata, deviceIdx) # no point in continuing of not connected to listener if not device.unreal_client.is_connected: continue # create message try: program_id = device.program_start_queue.running_puuids_named( 'unreal')[-1] except IndexError: program_id = '00000000-0000-0000-0000-000000000000' _, msg = message_protocol.create_get_sync_status_message( program_id) # send get sync status message device.unreal_client.send_message(msg) def devicedata_from_device(self, device): ''' Retrieves the devicedata and index for given device ''' for deviceIdx, hash_devicedata in enumerate(self.devicedatas.items()): device_hash, devicedata = hash_devicedata[0], hash_devicedata[1] if device_hash == device.device_hash: return (deviceIdx, devicedata) raise KeyError def populate_sync_data(self, devicedata, message): ''' Populates model data with message contents, which comes from 'get sync data' command. ''' data = devicedata['data'] device = devicedata['device'] # # Sync Topology # syncStatus = message['syncStatus'] syncTopos = syncStatus['syncTopos'] # Build Gpus, informing which Gpus in each Sync group are in sync Gpus = [] for syncTopo in syncTopos: gpu_sync_oks = [gpu['bIsSynced'] for gpu in syncTopo['syncGpus']] gpu_sync_yesno = map(lambda x: "Synced" if x else 'Free', gpu_sync_oks) Gpus.append('%s' % (', '.join(gpu_sync_yesno))) data['Gpus'] = '\n'.join(Gpus) # Build Displays, informing which Display in each Sync group are in sync. Displays = [] bpc_strings = {1: 6, 2: 8, 3: 10, 4: 12, 5: 16} for syncTopo in syncTopos: display_sync_states = [ f"{syncDisplay['syncState']}({bpc_strings.get(syncDisplay['bpc'], '??')}bpc)" for syncDisplay in syncTopo['syncDisplays'] ] Displays.append(', '.join(display_sync_states)) data['Displays'] = '\n'.join(Displays) # Build Fps refreshRates = [ f"{syncTopo['syncStatusParams']['refreshRate']*1e-4:.3f}" for syncTopo in syncTopos ] data['Fps'] = '\n'.join(refreshRates) # Build House Sync house_fpss = [ syncTopo['syncStatusParams']['houseSyncIncoming'] * 1e-4 for syncTopo in syncTopos ] house_syncs = [ syncTopo['syncStatusParams']['bHouseSync'] for syncTopo in syncTopos ] house_sync_fpss = map(lambda x: f"{x[1]:.3f}" if x[0] else 'no', zip(house_syncs, house_fpss)) data['HouseSync'] = '\n'.join(house_sync_fpss) # Build Sync Source source_str = {0: 'Vsync', 1: 'House'} sync_sources = [ syncTopo['syncControlParams']['source'] for syncTopo in syncTopos ] sync_sources = [ source_str.get(sync_source, 'Unknown') for sync_source in sync_sources ] bInternalSlaves = [ syncTopo['syncStatusParams']['bInternalSlave'] for syncTopo in syncTopos ] sync_slaves = [] for i in range(len(sync_sources)): if bInternalSlaves[i] and sync_sources[i] == 'Vsync': sync_slaves.append('Vsync(daisy)') else: sync_slaves.append(sync_sources[i]) data['SyncSource'] = '\n'.join(sync_slaves) # # Mosaic Topology # mosaicTopos = syncStatus['mosaicTopos'] mosaicTopoLines = [] for mosaicTopo in mosaicTopos: displaySettings = mosaicTopo['displaySettings'] width_per_display = displaySettings['width'] height_per_display = displaySettings['height'] width = mosaicTopo['columns'] * width_per_display height = mosaicTopo['rows'] * height_per_display # Ignoring displaySettings['freq'] because it seems to be fixed and ignores sync frequency. line = f"{width}x{height} {displaySettings['bpp']}bpp" mosaicTopoLines.append(line) data['Mosaics'] = '\n'.join(mosaicTopoLines) # Build FlipMode. # flip_history = syncStatus['flipModeHistory'] if len(flip_history) > 0: data['FlipMode'] = flip_history[-1] # Detect FlipMode glitches if len(set(flip_history)) > 1: data['FlipMode'] = 'GLITCH!' data['TimeLastFlipGlitch'] = time.time() # Write time since last glitch if data['FlipMode'] != 'n/a': time_since_flip_glitch = time.time() - data['TimeLastFlipGlitch'] # Let the user know for 1 minute that there was a glitch in the flip mode if time_since_flip_glitch < 1 * 60: data['FlipMode'] = data['FlipMode'].split( '\n')[0] + '\n' + str(int(time_since_flip_glitch)) # Window in focus or not data['InFocus'] = 'no' for prog in device.program_start_queue.running_programs_named( 'unreal'): if prog.pid and prog.pid == syncStatus['pidInFocus']: data['InFocus'] = 'yes' break # Show Exe flags (like Disable Fullscreen Optimization) data['ExeFlags'] = '\n'.join( [layer for layer in syncStatus['programLayers'][1:]]) # Driver version driver = syncStatus['driverVersion'] data['Driver'] = f'{int(driver/100)}.{driver % 100}' # Taskbar visibility data['Taskbar'] = syncStatus['taskbar'] def on_get_sync_status(self, device, message): ''' Called when the listener has sent a message with the sync status ''' # check ack try: if message['bAck'] == False: return except KeyError: LOGGER.error( f"Error parsing 'get sync status' looking for 'bAck' flag") return # ok, we expect this to be a valid message, let's parse and update the model. deviceIdx, devicedata = self.devicedata_from_device(device) devicedata['time_last_update'] = time.time() devicedata['stale'] = False try: self.populate_sync_data(devicedata=devicedata, message=message) except KeyError: LOGGER.error( f"Error parsing 'get sync status' message and populating model data\n\n=== Traceback BEGIN ===\n{traceback.format_exc()}=== Traceback END ===\n" ) return row = deviceIdx + 1 self.dataChanged.emit(self.createIndex(row, 1), self.createIndex(row, len(self.colnames))) #~ QAbstractTableModel interface begin def rowCount(self, parent=QModelIndex()): return len(self.devicedatas) def columnCount(self, parent=QModelIndex()): return len(self.colnames) def headerData(self, section, orientation, role): if role == Qt.DisplayRole: if orientation == Qt.Horizontal: return self.colnames[section] else: return "{}".format(section) if role == Qt.ToolTipRole: return self.tooltips[section] return None def data(self, index, role=Qt.DisplayRole): column = index.column() row = index.row() # get column name colname = self.colnames[column] # grab device data from ordered dict _, devicedata = list(self.devicedatas.items())[ row] # returns key, value. Where key is the device_hash. data = devicedata['data'] value = data[colname] if role == Qt.DisplayRole: return value elif role == Qt.BackgroundRole: return self.color_for_column(colname=colname, value=value, data=data) elif role == Qt.TextAlignmentRole: return Qt.AlignRight return None @QtCore.Slot() def btnForceFocus_clicked(self): ''' Forces focus on the nDisplay window if not already in focus ''' for devicedata in self.devicedatas.values(): device = devicedata['device'] data = devicedata['data'] if data['InFocus'] != 'yes': device.force_focus() @QtCore.Slot() def btnFixExeFlags_clicked(self): ''' Tries to force the correct UE4Editor.exe flags ''' for devicedata in self.devicedatas.values(): device = devicedata['device'] data = devicedata['data'] good_string = 'DISABLEDXMAXIMIZEDWINDOWEDMODE' if good_string not in data['ExeFlags']: device.fix_exe_flags() @QtCore.Slot() def btnSoftKill_clicked(self): ''' Kills the cluster by sending a message to the master. ''' devices = [ devicedata['device'] for devicedata in self.devicedatas.values() ] if len(devices): try: devices[0].__class__.soft_kill_cluster(devices) except: LOGGER.warning("Could not soft kill cluster")
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()
widget = QWidget() widget.setLayout(layout) # Set the central widget of the Window. Widget will expand # to take up all the space in the window by default. self.setCentralWidget(widget) # tag::appStyle[] app = QApplication(sys.argv) app.setStyle("Fusion") # end::appStyle[] darkPalette = app.palette() darkPalette.setColor(QPalette.Window, QColor(53, 53, 53)) darkPalette.setColor(QPalette.WindowText, Qt.white) darkPalette.setColor(QPalette.Disabled, QPalette.WindowText, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Base, QColor(42, 42, 42)) darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66)) darkPalette.setColor(QPalette.ToolTipBase, Qt.white) darkPalette.setColor(QPalette.ToolTipText, Qt.white) darkPalette.setColor(QPalette.Text, Qt.white) darkPalette.setColor(QPalette.Disabled, QPalette.Text, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35)) darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20)) darkPalette.setColor(QPalette.Button, QColor(53, 53, 53)) darkPalette.setColor(QPalette.ButtonText, Qt.white) darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(127, 127, 127))
class DigitalCircle(QQuickPaintedItem): def __init__(self, parent=None): QQuickPaintedItem.__init__(self, parent) self._oroborusFlag = True self._cycleFlag = True self._radius = 100 self._borderOffset = 15 self._digitsList = [] self._scale = 0 self._posX = 0 self._posY = 0 self._speedRatio = 1.0 self._timerInterval = 25 * self._speedRatio self._animationIndex = 0 self._timer = QTimer() QObject.connect(self._timer, SIGNAL('timeout()'), self, SLOT('requestSpecialUpdate()')) self._dotColor = QColor(Qt.green) self._lineWidth = 1 self._lineColor = QColor(Qt.black) @Slot(result='QString') def exportJson(self): from PySide2.QtCore import QJsonDocument, QByteArray, QJsonArray jDoc = QJsonDocument() jObj = dict() if self._oroborusFlag == False: jObj["oroborusFlag"] = self._oroborusFlag if self._cycleFlag == False: jObj["cycleFlag"] = self._cycleFlag if self._radius != 100: jObj["radius"] = self._radius if self._speedRatio != 1.0: jObj["speedRatio"] = self._speedRatio if self._lineWidth != 1: jObj["lineWidth"] = self._lineWidth digitsArray = QJsonArray() for d in self._digitsList: digitsArray.append(int(d)) jObj["digits"] = digitsArray jObj["scale"] = self._scale if self._dotColor != QColor(Qt.green): jObj["dotColor"] = self._dotColor.name() if self._lineColor != QColor(Qt.black): jObj["lineColor"] = self._lineColor.name() jDoc.setObject(jObj) jsonString = jDoc.toJson(QJsonDocument.Compact).data().decode() return jsonString @Slot('QString') def importJson(self, jsonString): import json jObj = json.loads(jsonString) if "oroborusFlag" in jObj: self._oroborusFlag = jObj["oroborusFlag"] else: self._oroborusFlag = True if "cycleFlag" in jObj: self._cycleFlag = jObj["cycleFlag"] else: self._cycleFlag = True if "radius" in jObj: self._radius = jObj["radius"] else: self._radius = 100 if "speedRatio" in jObj: self._speedRatio = jObj["speedRatio"] else: self._speedRatio = 1.0 if "lineWidth" in jObj: self._lineWidth = jObj["lineWidth"] else: self._lineWidth = 1 if "dotColor" in jObj: self._dotColor = QColor(jObj["dotColor"]) else: self._dotColor = QColor(Qt.green) if "lineColor" in jObj: self._lineColor = QColor(jObj["lineColor"]) else: self._lineColor = QColor(Qt.green) try: self._digitsList = jObj["digits"] self._scale = int(jObj["scale"]) except: print("failed to load digits: ", jObj) self.update() @Slot(float) def setSpeedRatio(self, newRate): self._speedRatio = newRate self._timerInterval = 25 * self._speedRatio self._timer.setInterval(self._timerInterval) @Slot('QColor') def setDotColor(self, newColor): self._dotColor = newColor @Slot('QColor') def setLineColor(self, newColor): self._lineColor = newColor @Slot(int) def setLineWidth(self, newLineWidth): self._lineWidth = newLineWidth @Slot('QVariant', int, bool, bool) def set(self, digitsList, scale, cycleFlag, oroborusFlag): if type(digitsList) is QJSValue: digitsList = digitsList.toVariant() self._digitsList = digitsList self._scale = scale self._cycleFlag = cycleFlag self._oroborusFlag = oroborusFlag self.update() def paint(self, painter): brushBackup = painter.brush() self.paintWithoutNotation(painter) self.drawNotation(painter) painter.setBrush(brushBackup) def paintWithoutNotation(self, painter): brushBackup = painter.brush() penBackup = painter.pen() localPen = QPen(self._lineColor) localPen.setWidth(self._lineWidth) painter.setPen(localPen) painter.drawEllipse(self._borderOffset, self._borderOffset, self._radius * 2, self._radius * 2) if self._scale == 0 or len(self._digitsList) == 0: return for i in range(1, len(self._digitsList)): prevDigit = self._digitsList[i - 1] currentDigit = self._digitsList[i] self.drawLine(painter, prevDigit, currentDigit) if self._cycleFlag: firstDigit = self._digitsList[0] lastDigit = self._digitsList[-1] self.drawLine(painter, lastDigit, firstDigit) painter.setBrush(self._dotColor) painter.drawEllipse( self._radius - self._posX + self._borderOffset - 10 / 2, self._radius - self._posY + self._borderOffset - 10 / 2, 10, 10) painter.setBrush(brushBackup) painter.setPen(penBackup) def drawLine(self, painter, start, end): scale = self._scale radius = self._radius if self._oroborusFlag == True: scale -= 1 degree1 = (scale - start) * 360.0 / scale y1 = radius * cos(degree1 * 3.14159265 / 180.0) x1 = radius * sin(degree1 * 3.14159265 / 180.0) degree2 = (scale - end) * 360.0 / scale y2 = radius * cos(degree2 * 3.14159265 / 180.0) x2 = radius * sin(degree2 * 3.14159265 / 180.0) radius += self._borderOffset painter.drawLine(radius - x1, radius - y1, radius - x2, radius - y2) def drawNotation(self, painter): if len(self._digitsList) == 0: return scale = self._scale radius = self._radius if self._oroborusFlag == True: scale -= 1 for i in range(0, scale): degree = (scale - i) * 360.0 / scale x = radius * sin(degree * 3.14159265 / 180.0) y = radius * cos(degree * 3.14159265 / 180.0) xWide = (radius + 12) * sin(degree * 3.14159265 / 180.0) yWide = (radius + 12) * cos(degree * 3.14159265 / 180.0) painter.drawEllipse(radius - x + self._borderOffset, radius - y + self._borderOffset, 3, 3) if self._digitsList[0] == i or self._digitsList[-1] == i: if self._digitsList[0] == i: painter.setBrush(Qt.white) else: painter.setBrush(Qt.black) painter.drawEllipse(radius - x + self._borderOffset - 10 / 2, radius - y + self._borderOffset - 10 / 2, 10, 10) if i == 0 and self._oroborusFlag == True: digitText = str(scale) else: digitText = str(i) painter.drawText(radius - xWide + self._borderOffset - 12 / 2, radius - yWide + self._borderOffset - 12 / 2, 20, 20, 0, digitText) def tracePositions(self, x1, y1, x2, y2, steps): result = [] deltaX = x2 - x1 deltaY = y2 - y1 stepX = deltaX / steps stepY = deltaY / steps for s in range(0, steps): anotherPosition = [x1 + stepX * s, y1 + stepY * s] result.append(anotherPosition) return result def prepareAnimation(self): scale = self._scale radius = self._radius if self._oroborusFlag == True: scale -= 1 stepsBetweenNodes = 20 digitsPositions = [] for digit in self._digitsList: degree = (scale - digit) * 360.0 / scale x = radius * sin(degree * 3.14159265 / 180.0) y = radius * cos(degree * 3.14159265 / 180.0) anotherPosition = [x, y] digitsPositions.append(anotherPosition) traces = [] for i in range(0, len(digitsPositions) - 1): x1 = digitsPositions[i][0] y1 = digitsPositions[i][1] x2 = digitsPositions[i + 1][0] y2 = digitsPositions[i + 1][1] anotherTrace = self.tracePositions(x1, y1, x2, y2, stepsBetweenNodes) traces.extend(anotherTrace) x1 = digitsPositions[-1][0] y1 = digitsPositions[-1][1] x2 = digitsPositions[0][0] y2 = digitsPositions[0][1] anotherTrace = self.tracePositions(x1, y1, x2, y2, stepsBetweenNodes) traces.extend(anotherTrace) self._animationTrace = traces @Slot() def startAnimation(self): if len(self._digitsList) == 0: return self.prepareAnimation() self._timer.setInterval(self._timerInterval) self._timer.start() @Slot() def requestSpecialUpdate(self): self.requestSpecialUpdateSafe() self.update() @Slot() def requestSpecialUpdateSafe(self): newX = self._animationTrace[self._animationIndex][0] newY = self._animationTrace[self._animationIndex][1] self._posX = newX self._posY = newY self._animationIndex += 1 if self._animationIndex >= len(self._animationTrace): self._animationIndex = 0 @Slot() def stopAnimation(self): self._timer.stop() self.resetAnimation() @Slot() def pauseAnimation(self): self._timer.stop() @Slot(result='bool') def animationIsRunning(self): return self._timer.isActive() @Slot() def resetAnimation(self): self._animationIndex = 0 @Slot(int) def setRadius(self, newRadius): self._radius = newRadius self.update() def getRadius(self): return self._radius def setBorderOffset(self, newBorderOffset): self._borderOffset = newBorderOffset self.update() def getBorderOffset(self): return self._borderOffset radius = Property(int, getRadius, setRadius) borderOffset = Property(int, getBorderOffset, setBorderOffset)
def double_click_data(self, item): if self.in_task: # make the data unfinished self.current_task.mark_as_unfinished(item.text()) # remove the visual highlight item.setBackground(QBrush(QColor("#ffffff")))
from PySide2.QtWidgets import * from PySide2.QtCore import Slot, Qt from PySide2.QtGui import QPalette, QColor app = QApplication([]) app.setStyle('Fusion') default_palette = QPalette() # Style needed for palette to work # Dark Palette (found on github, couldn't track the original author) dark_palette = QPalette() dark_palette.setColor(QPalette.Window, QColor(53, 53, 53)) dark_palette.setColor(QPalette.WindowText, Qt.white) dark_palette.setColor(QPalette.Base, QColor(25, 25, 25)) dark_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) dark_palette.setColor(QPalette.ToolTipBase, Qt.white) dark_palette.setColor(QPalette.ToolTipText, Qt.white) dark_palette.setColor(QPalette.Text, Qt.white) dark_palette.setColor(QPalette.Button, QColor(53, 53, 53)) dark_palette.setColor(QPalette.ButtonText, Qt.white) dark_palette.setColor(QPalette.BrightText, Qt.red) dark_palette.setColor(QPalette.Link, QColor(42, 130, 218)) dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218)) dark_palette.setColor(QPalette.HighlightedText, Qt.black) window = QWidget() layout = QGridLayout() # Make a few Dials and buttons: for i in range(0, 4): Dial = QDial() Button = QPushButton('Button ' + str(i)) Dial.setNotchesVisible(True) layout.addWidget(Button, 0, i)
def setUp(self): self.color = QColor(20, 40, 60, 80)
from PySide2.QtGui import QColor import os CURRENT_DIR = os.getcwd() RESOURCES_PATH = os.path.join(CURRENT_DIR, 'Resources') IMAGE_FOLDERS_PATH = os.path.join(CURRENT_DIR, 'Images') DATA_PATH = os.path.join(CURRENT_DIR, 'data.csv') LABELS_PATH = os.path.join(CURRENT_DIR, 'labels.txt') ICON_PATH = os.path.join(RESOURCES_PATH, 'logo.ico') CHECKED_PATH = os.path.join(RESOURCES_PATH, 'checked.png') UNCHECKED_PATH = os.path.join(RESOURCES_PATH, 'unchecked.png') TOP_BAR = 'rgba(70,70,70,255)' LABEL = 'rgba(200,200,200,255)' LABEL_DARK = 'rgba(20,20,20,255)' ACCENT = 'rgba(237,182,234,255)' BG = 'rgba(30,30,30,255)' BG_L1 = 'rgba(40,40,40,255)' BG_L2 = 'rgba(50,50,50,255)' ACCENT_QC = QColor(237,182,234,255) ACCENT_LOW_OPACITY_QC = QColor(237,182,234,40) ACCENT_VLOW_OPACITY_QC = QColor(237,182,234,25) LABEL_QC = QColor(200,200,200,255) LABEL_LOW_OPACITY_QC = QColor(200,200,200,70) BG_L2_QC = QColor(50,50,50,255)
def testStrFunction(self): c = QColor('red') c2 = eval(c.__str__()) self.assertEqual(c, c2)
def _create_line_indicator(self, addr, item_map, color=Qt.yellow, show_frontier=False, z=None, z_frontier=None): """ Generate a cursor at a given address. """ pos_x = self._get_pos_from_addr(addr) if pos_x is None: return pen = QPen(color) brush = QBrush(color) height = self.height tri_width = 7 tri_height = 4 pos_x = int(pos_x - tri_width / 2) # Center drawing center = pos_x + int(tri_width / 2) pos_y = 0 frontier_width = int(0.15 * max(self.width, self.height)) if show_frontier: # Draw frontier gradients r = QRectF(center - frontier_width, pos_y, frontier_width, height) bg = QLinearGradient(r.topLeft(), r.topRight()) color = Qt.red top_color = QColor(color) top_color.setAlpha(0) bg.setColorAt(0, top_color) bottom_color = QColor(color) bottom_color.setAlpha(180) bg.setColorAt(1, bottom_color) i = QGraphicsRectItem(r, parent=self) i.setPen(Qt.NoPen) i.setBrush(bg) if z_frontier is not None: i.setZValue(z_frontier) item_map.append(i) r = QRectF(center, pos_y, frontier_width, height) bg = QLinearGradient(r.topLeft(), r.topRight()) color = Qt.blue top_color = QColor(color) bg.setColorAt(0, top_color) bottom_color = QColor(color) bottom_color.setAlpha(0) bg.setColorAt(1, bottom_color) i = QGraphicsRectItem(r, parent=self) i.setPen(Qt.NoPen) i.setBrush(bg) if z_frontier is not None: i.setZValue(z_frontier) item_map.append(i) # Draw line i = QGraphicsLineItem(center, 0, center, height, parent=self) i.setPen(pen) if z is not None: i.setZValue(z) item_map.append(i) # Draw top and bottom triangles t = QPolygonF() t.append(QPointF(pos_x, pos_y)) t.append(QPointF(pos_x + tri_width - 1, pos_y)) t.append(QPointF(center, pos_y + tri_height - 1)) t.append(QPointF(pos_x, pos_y)) pos_y += height - 1 b = QPolygonF() b.append(QPointF(pos_x, pos_y)) b.append(QPointF(center, pos_y - tri_height + 1)) b.append(QPointF(pos_x + tri_width - 1, pos_y)) b.append(QPointF(pos_x, pos_y)) for i in [QGraphicsPolygonItem(t, parent=self), QGraphicsPolygonItem(b, parent=self)]: i.setPen(pen) i.setBrush(brush) if z is not None: i.setZValue(z) item_map.append(i)
def updateSample(self): pxmp = self.sample.pixmap() pxmp.fill(QColor(0,0,0,0)) brushFamily.brushStrokePoly(pxmp, self.samplePoly, self.layer.brushDict) self.sample.repaint()
def drawForeground(self, painter, rect): """Draws all connections and borders around selected items.""" # DRAW CONNECTIONS for ni in self.all_node_instances: for o in ni.outputs: for cpi in o.connected_port_instances: path = self.connection_path(o.gate.get_scene_center_pos(), cpi.gate.get_scene_center_pos()) w = path.boundingRect().width() h = path.boundingRect().height() gradient = QRadialGradient(path.boundingRect().center(), pythagoras(w, h) / 2) pen = Design.flow_theme.get_flow_conn_pen_inst(o.type_) c = pen.color() # highlight hovered connections if self.hovered_port_inst_gate == o.gate or self.hovered_port_inst_gate is cpi.gate: c = QColor('#c5c5c5') pen.setWidth(5) c_r = c.red() c_g = c.green() c_b = c.blue() gradient.setColorAt(0.0, QColor(c_r, c_g, c_b, 255)) gradient.setColorAt(0.75, QColor(c_r, c_g, c_b, 200)) gradient.setColorAt(0.95, QColor(c_r, c_g, c_b, 0)) gradient.setColorAt(1.0, QColor(c_r, c_g, c_b, 0)) pen.setBrush(gradient) painter.setPen(pen) painter.drawPath(path) # DRAW CURRENTLY DRAGGED CONNECTION if self.dragging_connection: pen = QPen('#101520') pen.setWidth(3) pen.setStyle(Qt.DotLine) painter.setPen(pen) gate_pos = self.gate_selected.get_scene_center_pos() if self.gate_selected.parent_port_instance.direction == 'output': painter.drawPath( self.connection_path(gate_pos, self.last_mouse_move_pos) ) else: painter.drawPath( self.connection_path(self.last_mouse_move_pos, gate_pos) ) # DRAW SELECTED NIs BORDER for ni in self.selected_node_instances(): pen = QPen(QColor('#245d75')) pen.setWidth(3) painter.setPen(pen) painter.setBrush(Qt.NoBrush) size_factor = 1.2 x = ni.pos().x() - ni.boundingRect().width() / 2 * size_factor y = ni.pos().y() - ni.boundingRect().height() / 2 * size_factor w = ni.boundingRect().width() * size_factor h = ni.boundingRect().height() * size_factor painter.drawRoundedRect(x, y, w, h, 10, 10) # DRAW SELECTED DRAWINGS BORDER for p_o in self.selected_drawings(): pen = QPen(QColor('#a3cc3b')) pen.setWidth(2) painter.setPen(pen) painter.setBrush(Qt.NoBrush) size_factor = 1.05 x = p_o.pos().x() - p_o.width / 2 * size_factor y = p_o.pos().y() - p_o.height / 2 * size_factor w = p_o.width * size_factor h = p_o.height * size_factor painter.drawRoundedRect(x, y, w, h, 6, 6) painter.drawEllipse(p_o.pos().x(), p_o.pos().y(), 2, 2)
def __init__(self, parent=None): super(SignUpForm, self).__init__(parent) self.checkedPass = 0 self.setWindowTitle("Backend Discord-GUI") self.changeStyle('fusion') palette = QPalette() palette.setColor(QPalette.Window, QColor(53, 53, 53)) palette.setColor(QPalette.WindowText, Qt.white) palette.setColor(QPalette.Text, Qt.white) palette.setColor(QPalette.Button, QColor(60, 60, 60)) palette.setColor(QPalette.ButtonText, Qt.white) palette.setColor(QPalette.Base, QColor(40, 40, 40)) palette.setColor(QPalette.ToolTipBase, QColor(60, 60, 60)) palette.setColor(QPalette.ToolTipText, Qt.white) palette.setColor(QPalette.PlaceholderText, QColor(100, 60, 60)) palette.setColor(QPalette.BrightText, Qt.white) palette.setColor(QPalette.Highlight, QColor(106, 13, 173)) palette.setColor(QPalette.HighlightedText, Qt.white) mainLayout = QVBoxLayout() hMainLayout = QHBoxLayout() passwordLayout = QHBoxLayout() entryBG = QPalette() gradient = QGradient() gradient.setColorAt(0.0, QColor(30, 30, 30)) gradient.setColorAt(0.4, QColor(30, 30, 30)) gradient.setColorAt(1.0, QColor(70, 70, 70)) gradient.setSpread(QGradient.RepeatSpread) entryBG.setBrush(QPalette.Button, QBrush(gradient)) self.name = QLineEdit(self) self.name.setFixedHeight(24) self.name.setToolTip("Max 64 Characters") self.name.setStyleSheet( "QToolTip { border: 0px; border-radius: 3px; }") self.name.setPalette(entryBG) self.QNameLabel = QLabel("Full Name") self.QNameLabel.setFont(QFont("Copperplate", 12)) self.name.setMaxLength(64) self.email = QLineEdit(self) self.email.setFixedHeight(24) self.email.setToolTip( "Max 128 Characters, Example - [email protected]") self.email.setStyleSheet( "QToolTip { border: 0px; border-radius: 3px }") self.email.setPalette(entryBG) self.QEmailLabel = QLabel("Email") self.QEmailLabel.setFont(QFont("Copperplate", 12)) self.email.setMaxLength(128) self.username = QLineEdit(self) self.username.setFixedHeight(24) self.username.setToolTip("Max 16 Characters") self.username.setStyleSheet( "QToolTip { border: 0px; border-radius: 3px }") self.username.setPalette(entryBG) self.QUserLabel = QLabel("Username") self.QUserLabel.setFont(QFont("Copperplate", 12)) self.username.setMaxLength(16) self.password = QLineEdit(self) self.password.setFixedHeight(24) self.password.setToolTip( "Max 32 Characters, Must Include = Uppercase Letter,\nNumber and Special Character" ) self.password.setStyleSheet( "QToolTip { border: 0px; border-radius: 3px }") self.password.setPalette(entryBG) self.QPasswordLabel = QLabel("Password ") self.password.setMaxLength(32) self.QPasswordLabel.setFont(QFont("Copperplate", 12)) self.showhideButton = QPushButton("Show") self.showhideButton.setCheckable(True) self.showhideButton.setChecked(False) self.showhideButton.clicked.connect(lambda: self.show_hide()) self.password.setEchoMode(QLineEdit.Password) passwordLayout.addWidget(self.QPasswordLabel) passwordLayout.addWidget(self.password) passwordLayout.addWidget(self.showhideButton) self.btn_SignUp = QPushButton("Sign Up") self.btn_SignUp.clicked.connect(lambda: self.signUpWindow()) shortcut = QShortcut(QKeySequence("Return"), self.btn_SignUp) shortcut.activated.connect(lambda: self.signUpWindow()) shortcut.setEnabled(True) self.btn_cancel = QPushButton("Cancel") self.btn_cancel.clicked.connect(lambda: self.cancel()) layout = QFormLayout() layout.addRow(self.QNameLabel, self.name) layout.addRow(self.QEmailLabel, self.email) layout.addRow(self.QUserLabel, self.username) layout.addRow(passwordLayout) layout.addRow(self.btn_SignUp) layout.addRow(self.btn_cancel) Label = QLabel("Sign Up To The\nBackend Discord-GUI Development") Label.setFont(QFont("Copperplate", 15, QFont.Bold)) Label.setAlignment(Qt.AlignCenter) mainLayout.addSpacing(40) mainLayout.addWidget(Label) mainLayout.addLayout(layout) mainLayout.addSpacing(60) hMainLayout.addSpacing(115) hMainLayout.addLayout(mainLayout) hMainLayout.addSpacing(115) self.setLayout(hMainLayout) QApplication.setPalette(palette)
def testReduceRGB(self): self.reduceColor(QColor.fromRgbF(0.1, 0.2, 0.3, 0.4))
class DetailedView(QWidget): title_text_size = 18 content_text_size = 14 border_color = QColor(112,112,112) back_color = QColor(255,255,255) visible_widgets = [] def __init__(self, title="", content="", _parent=None): super(DetailedView, self).__init__(overview.Overview.get_instance()) self._parent = _parent self.widget_resolution = overview.Overview.get_instance().frameGeometry() QCoreApplication.instance() # init self.layout = QVBoxLayout() self.lable_title = QLabel(title) self.lable_content = QLabel(content) # font title_font = self.lable_title.font() title_font.setPixelSize(self.title_text_size) content_font = self.lable_content.font() content_font.setPixelSize(self.content_text_size) self.lable_title.setFont(title_font) self.lable_content.setFont(content_font) # layout self.layout.addWidget(self.lable_title) self.layout.addWidget(self.lable_content) self.setLayout(self.layout) # flags self.setMouseTracking(True) def calc_min_size(self): # width if self.lable_title.sizeHint().width() > self.lable_content.sizeHint().width(): self.setMinimumWidth(self.lable_title.sizeHint().width() + (self.layout.margin() * 2)) else: self.setMinimumWidth(self.lable_content.sizeHint().width() + (self.layout.margin() * 2)) # height height = self.lable_title.sizeHint().height() height += self.lable_content.sizeHint().height() self.setMinimumHeight(height + (self.layout.margin() * 2)) def set_title(self, title): """ set title :param title: str :return: """ self.lable_title.setText(title) self.calc_min_size() def set_content(self, content): """ set content :param content: str :return: """ self.lable_content.setText(content) self.calc_min_size() def move_to_mouse(self): """ moves self to mouse and show :return: """ # turn if out of dekstop pos = self.cursor().pos() pos = overview.Overview.get_instance().mapFromGlobal(pos) if pos.x() + self.rect().width() > self.widget_resolution.width(): pos.setX(pos.x()-self.rect().width()) if pos.y() + self.rect().height() > self.widget_resolution.height(): pos.setY(pos.y()-self.rect().height()) #move self.move(pos) # if self.isVisible(): # if not self.isActiveWindow(): # # back to foreground # self.activateWindow() # else: DetailedView.close_all() DetailedView.add_to_visible(self) self.show() def ask_close(self): """ parent can ask for close :return: """ if not self.mouse_is_over_parent(): DetailedView.remove_visible(self) self.close() def close(self): DetailedView.remove_visible(self) super().close() def mouse_is_over_parent(self): """ returns if mouse if over _parent :return: bool """ mouse_pos = self._parent.mapFromGlobal(QCursor.pos()) margin = 1 return mouse_pos.x() > margin and mouse_pos.y() > margin and mouse_pos.x() < self._parent.rect().width() - margin and mouse_pos.y() < self._parent.rect().height() - margin def mouseMoveEvent(self, event:QMouseEvent): """ mouse move event :param event: :return: """ if self.mouse_is_over_parent(): self.move_to_mouse() else: self.close() def deleteLater(self): DetailedView.remove_visible(self) super().deleteLater() def mousePressEvent(self, event:QMouseEvent): """ redirect mouse press to _parent :param event: :return: """ self._parent.mousePressEvent(event) def paintEvent(self, event:QPaintEvent): """ draws background :param event: :return: None """ custom_painter = QPainter(self) custom_painter.fillRect(self.rect(), self.back_color) custom_painter.setPen(self.border_color) custom_painter.drawRect(0,0, self.rect().width()-1, self.rect().height()-1) def resizeEvent(self, event:QResizeEvent): self.widget_resolution = overview.Overview.get_instance().frameGeometry() super().resizeEvent(event) @staticmethod def add_to_visible(detailed_view): if not detailed_view in DetailedView.visible_widgets: DetailedView.visible_widgets.append(detailed_view) @staticmethod def remove_visible(detailed_view): if detailed_view in DetailedView.visible_widgets: DetailedView.visible_widgets.remove(detailed_view) @staticmethod def close_all(): for detailed_view in DetailedView.visible_widgets: detailed_view.ask_close()
def testReduceHsv(self): self.reduceColor(QColor.fromHsvF(0.1, 0.2, 0.3, 0.4))
def change_data(self): for i in range(10, 50): self._model.setData(self._model.index(i, 1), QColor(Qt.blue), Qt.BackgroundRole)
def setRandColor(self): self.setColor(QColor(qrand() % 256, qrand() % 256, qrand() % 256))
def fill_selection(option, painter): colour = QColor("lightblue") colour.setAlpha(100) painter.fillRect(option.rect, colour)
def updateColor(self, color: QColor, value: float, percent: float) -> None: item: ColorPanelBar = self.sender() index: int = self.__items.index(item) if index is 0: # 获取当前HSB处的颜色值 self.__items[1].topColor = color self.__items[2].topColor = color self.__items[1].borderColor = color self.__items[2].borderColor = color elif index is 1: self.__items[2].topColor = color self.__items[2].borderColor = color elif index is 2: self.__items[1].topColor = color self.__items[1].borderColor = color elif index == 3: self.__items[6].percent = 100 - percent elif index == 4: self.__items[7].percent = 100 - percent elif index == 5: self.__items[8].percent = 100 - percent elif index == 6: self.__items[3].percent = 100 - percent elif index == 7: self.__items[4].percent = 100 - percent elif index == 8: self.__items[5].percent = 100 - percent # 如果是HSB变化则CMY和RGB变化 if index < 3: hue: float = self.__items[0].percent / 100 sat: float = self.__items[1].percent / 100 bright: float = self.__items[2].percent / 100 # 组合HSB当前值,然后转为CMY和RGB计算百分比进行设置 color: QColor = QColor.fromHsvF(hue, sat, bright) percentRed: float = color.redF() * 100 percentGreen: float = color.greenF() * 100 percentBlue: float = color.blueF() * 100 self.__items[3].percent = 100 - percentRed self.__items[4].percent = 100 - percentGreen self.__items[5].percent = 100 - percentBlue self.__items[6].percent = percentRed self.__items[7].percent = percentGreen self.__items[8].percent = percentBlue # 根据百分比获取颜色值 red: float = self.__items[6].percent / 100 green: float = self.__items[7].percent / 100 blue: float = self.__items[8].percent / 100 currentColor: QColor = QColor.fromRgbF(red, green, blue) self.colorChanged.emit(currentColor, self.__items[0].value, self.__items[1].percent, self.__items[2].percent) # 如果是CMY或者RGB变化则HSB变化 if index >= 3: # hue活出现负数=白色,要矫正 percentHue: float = currentColor.hueF() * 100 if percentHue < 0: percentHue = 0 percentSat: float = currentColor.saturationF() * 100 percentBright: float = currentColor.lightnessF() * 100 # 计算当前值所占百分比 self.__items[0].percent = percentHue self.__items[1].percent = percentSat self.__items[2].percent = percentBright self.__items[1].topColor = currentColor self.__items[2].topColor = currentColor self.__items[1].borderColor = currentColor self.__items[2].borderColor = currentColor
def testReduceCMYK(self): self.reduceColor(QColor.fromCmykF(0.1, 0.2, 0.3, 0.4, 0.5))
customPlot.resize(800, 600) customPlot.setWindowTitle('Parametric Curves Demo') # pass the data to the curves; we know t (i in loop above) is ascending, so set alreadySorted=true (saves an extra internal sort): fermatSpiral1 = QCPCurve(customPlot.xAxis, customPlot.yAxis) fermatSpiral1.setData(dataSpiral1X, dataSpiral1Y) fermatSpiral2 = QCPCurve(customPlot.xAxis, customPlot.yAxis) fermatSpiral2.setData(dataSpiral2X, dataSpiral2Y) deltoidRadial = QCPCurve(customPlot.xAxis, customPlot.yAxis) deltoidRadial.setData(dataDeltoidX, dataDeltoidY) # color the curves: fermatSpiral1.setPen(QPen(Qt.blue)) fermatSpiral1.setBrush(QBrush(QColor(0, 0, 255, 20))) fermatSpiral2.setPen(QPen(QColor(255, 120, 0))) fermatSpiral2.setBrush(QBrush(QColor(255, 120, 0, 30))) radialGrad = QRadialGradient(QPointF(310, 180), 200) radialGrad.setColorAt(0, QColor(170, 20, 240, 100)) radialGrad.setColorAt(0.5, QColor(20, 10, 255, 40)) radialGrad.setColorAt(1, QColor(120, 20, 240, 10)) deltoidRadial.setPen(QPen(QColor(170, 20, 240))) deltoidRadial.setBrush(QBrush(radialGrad)) # set some basic customPlot config: customPlot.setInteractions(QCP.iRangeDrag | QCP.iRangeZoom | QCP.iSelectPlottables) customPlot.axisRect().setupFullAxesBox() customPlot.rescaleAxes()
def testQColorToTuple(self): c = QColor(0, 0, 255) c.setRgb(1, 2, 3) self.assertEqual((1, 2, 3, 255), c.toTuple())
def __init__(self, parent=None): QQuickPaintedItem.__init__(self, parent) self._name = u'' self._color = QColor()
def setUp(self): self.original = QColor.fromHsvF(0.2, 0.3, 0.4, 0.5)
if __name__ == '__main__': # Create the Qt Application app = QApplication(sys.argv) customPlot = QCustomPlot() customPlot.resize(800, 600) customPlot.setWindowTitle('Date Demo') # set locale to english, so we get english month names: customPlot.setLocale(QLocale(QLocale.English, QLocale.UnitedKingdom)) # seconds of current time, we'll use it as starting point in time for data: now = QDateTime.currentDateTime().toTime_t() # create multiple graphs: for gi in range(0, 5): customPlot.addGraph() color = QColor(20 + 200 / 4.0 * gi, 70 * (1.6 - gi / 4.0), 150, 150) customPlot.graph().setLineStyle(QCPGraph.lsLine) customPlot.graph().setPen(QPen(color.lighter(200))) customPlot.graph().setBrush(QBrush(color)) timeDataX = [0.0] * 250 timeDataY = [0.0] * 250 # generate random walk data: for i in range(0, 250): timeDataX[i] = now + 24 * 3600 * i if i == 0: timeDataY[i] = (float(i) / 50.0 + 1) * uniform(-0.5, 0.5) else: timeDataY[i] = math.fabs(timeDataY[i - 1]) * ( 1 + 0.02 / 4.0 * (4 - gi)) + (float(i) / 50.0 + 1) * uniform(-0.5, 0.5) customPlot.graph().setData(timeDataX, timeDataY)
def testRepr(self): c = QColor.fromRgb(1, 2, 3, 4) s = c.spec() self.assertEqual(repr(s), repr(QColor.Rgb))
def initForm(self): self.navLabel11.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Left self.navLabel12.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Left self.navLabel13.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Left self.navLabel21.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Right self.navLabel22.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Right self.navLabel23.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Right self.navLabel31.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Top self.navLabel32.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Top self.navLabel33.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Top self.navLabel41.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Bottom self.navLabel42.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Bottom self.navLabel43.arrowPosition = NavLabel.ArrowPosition.ArrowPosition_Bottom self.navLabel12.background = QColor(255, 107, 107) self.navLabel13.background = QColor(24, 189, 155) self.navLabel21.background = QColor(225, 102, 255) self.navLabel22.background = QColor(45, 62, 80) self.navLabel23.background = QColor(210, 84, 0) self.navLabel32.background = QColor(255, 107, 107) self.navLabel33.background = QColor(24, 189, 155) self.navLabel41.background = QColor(225, 102, 255) self.navLabel42.background = QColor(45, 62, 80) self.navLabel43.background = QColor(210, 84, 0) self.navLabel51.borderRadius = 0 self.navLabel52.borderRadius = 0 self.navLabel53.borderRadius = 0 self.navLabel51.background = QColor(80, 80, 80) self.navLabel52.background = QColor(80, 80, 80) self.navLabel53.background = QColor(80, 80, 80) self.navLabel52.showTriangle = True self.navLabel53.showTriangle = True self.navLabel53.showArrow = False
def testReprFunction(self): c = QColor(100, 120, 200) c2 = eval(c.__repr__()) self.assertEqual(c, c2)
def paint(self, painter, option, widget=None): painter.setRenderHint(QPainter.Antialiasing) brush = QBrush(QColor(100, 100, 100, 150)) # QBrush(QColor('#3B9CD9')) painter.setBrush(brush) std_pen = QPen( QColor(30, 43, 48) ) # QColor(30, 43, 48) # used for header title and minimal std dark border std_pen.setWidthF(1.5) # painter.setPen(std_pen) if self.parent_node.design_style == 'extended': if GlobalStorage.storage['design style'] == 'dark std': c = self.parent_node.color # main rect body_gradient = QRadialGradient( self.boundingRect().topLeft(), self.flow.pythagoras(self.height, self.width)) body_gradient.setColorAt( 0, QColor(c.red() / 10 + 100, c.green() / 10 + 100, c.blue() / 10 + 100, 200)) body_gradient.setColorAt( 1, QColor(c.red() / 10 + 100, c.green() / 10 + 100, c.blue() / 10 + 100, 0)) painter.setBrush(body_gradient) painter.setPen(Qt.NoPen) painter.drawRoundedRect(self.boundingRect(), 12, 12) header_gradient = QLinearGradient( self.get_header_rect().topRight(), self.get_header_rect().bottomLeft()) header_gradient.setColorAt( 0, QColor(c.red(), c.green(), c.blue(), 255)) header_gradient.setColorAt( 1, QColor(c.red(), c.green(), c.blue(), 0)) painter.setBrush(header_gradient) painter.setPen(Qt.NoPen) painter.drawRoundedRect(self.get_header_rect(), 12, 12) elif GlobalStorage.storage['design style'] == 'dark tron': # main rect c = QColor('#212224') painter.setBrush(c) pen = QPen(self.parent_node.color) pen.setWidth(2) painter.setPen(pen) body_path = self.get_extended_body_path_TRON_DESIGN(10) painter.drawPath(body_path) # painter.drawRoundedRect(self.boundingRect(), 12, 12) c = self.parent_node.color header_gradient = QLinearGradient( self.get_header_rect().topRight(), self.get_header_rect().bottomLeft()) header_gradient.setColorAt( 0, QColor(c.red(), c.green(), c.blue(), 255)) header_gradient.setColorAt( 0.5, QColor(c.red(), c.green(), c.blue(), 100)) header_gradient.setColorAt( 1, QColor(c.red(), c.green(), c.blue(), 0)) painter.setBrush(header_gradient) header_path = self.get_extended_header_path_TRON_DESIGN(10) painter.drawPath(header_path) painter.setFont(self.display_name_font) painter.setPen(std_pen) painter.drawText(self.get_title_rect(), Qt.AlignVCenter | Qt.AlignLeft, self.parent_node.title) painter.setBrush(Qt.NoBrush) painter.setPen(QPen(Qt.white, 1)) # painter.drawRect(self.get_header_rect()) elif self.parent_node.design_style == 'minimalistic': path = QPainterPath() path.moveTo(-self.width / 2, 0) if GlobalStorage.storage['design style'] == 'dark std': path.cubicTo(-self.width / 2, -self.height / 2, -self.width / 2, -self.height / 2, 0, -self.height / 2) path.cubicTo(+self.width / 2, -self.height / 2, +self.width / 2, -self.height / 2, +self.width / 2, 0) path.cubicTo(+self.width / 2, +self.height / 2, +self.width / 2, +self.height / 2, 0, +self.height / 2) path.cubicTo(-self.width / 2, +self.height / 2, -self.width / 2, +self.height / 2, -self.width / 2, 0) path.closeSubpath() c = self.parent_node.color body_gradient = QLinearGradient( self.boundingRect().bottomLeft(), self.boundingRect().topRight()) # 2*self.flow.pythagoras(self.height, self.width)) body_gradient.setColorAt( 0, QColor(c.red(), c.green(), c.blue(), 150)) body_gradient.setColorAt( 1, QColor(c.red(), c.green(), c.blue(), 80)) painter.setBrush(body_gradient) painter.setPen(std_pen) elif GlobalStorage.storage['design style'] == 'dark tron': corner_size = 10 path.lineTo(-self.width / 2 + corner_size / 2, -self.height / 2 + corner_size / 2) path.lineTo(0, -self.height / 2) path.lineTo(+self.width / 2 - corner_size / 2, -self.height / 2 + corner_size / 2) path.lineTo(+self.width / 2, 0) path.lineTo(+self.width / 2 - corner_size / 2, +self.height / 2 - corner_size / 2) path.lineTo(0, +self.height / 2) path.lineTo(-self.width / 2 + corner_size / 2, +self.height / 2 - corner_size / 2) path.closeSubpath() c = QColor('#36383B') painter.setBrush(c) pen = QPen(self.parent_node.color) pen.setWidth(2) painter.setPen(pen) painter.drawPath(path) painter.setFont(self.display_name_font) painter.drawText(self.boundingRect(), Qt.AlignCenter, self.parent_node.title)
def _generateChartImage(self): chart = QtCharts.QChart() chart.legend().setVisible(False) chart.setBackgroundBrush(QBrush(QColor("transparent"))) chart.setMargins(QMargins(0, 0, 0, 0)) chart.setTitleBrush(QBrush(Loader.QSSColor("@dark"))) axis_pen = QPen(Loader.QSSColor("@dark")) axis_pen.setWidth(4) grid_line_pen = QPen(Loader.QSSColor("@light-gray")) labels_font = QFont(Loader.QSSVariable("@font")) labels_font.setPointSize(18) axis_x = QtCharts.QValueAxis() axis_y = QtCharts.QValueAxis() for axis in (axis_x, axis_y): axis.setLinePen(axis_pen) axis.setLabelFormat("%d") axis.setGridLinePen(grid_line_pen) axis.setLabelsFont(labels_font) chart.addAxis(axis_x, Qt.AlignBottom) chart.addAxis(axis_y, Qt.AlignLeft) current_series = {} max_s = 0 for i, m in self._analysis.parameters().selectedMorphotypes().items(): current_series[i] = QtCharts.QSplineSeries() current_series[i].setName(m.name()) current_series[i].setColor(m.color()) s = 0 current_series[i].append(0, 0) for k, img in enumerate(self._analysis.processedImages()): s += img.detectionsCount().get(i, 0) current_series[i].append(k + 1, s) max_s = max(s, max_s) chart.addSeries(current_series[i]) current_series[i].attachAxis(axis_x) current_series[i].attachAxis(axis_y) pen = current_series[i].pen() pen.setWidth(5) current_series[i].setPen(pen) chart.axisX().setRange(0, max(len(self._analysis.processedImages()), 4)) chart.axisY().setRange(0, max(round(max_s), 4)*1.05) chart_view = QtCharts.QChartView(chart) chart_view.setRenderHint(QPainter.Antialiasing) chart_view.resize(QSize(1080, 500)) chart_pixmap = chart_view.grab() self._analysis.setBase64ChartImage(ImageConverter.QPixmapToBase64(chart_pixmap, "png"))
def get_color_for(cls, port_type): try: return cls.colors[port_type] except KeyError: return QColor("#000000")