class Card(QWidget): def __init__(self, parent: QWidget, card_details: Dict[str, Any]): super().__init__() if parent is not None: self.setParent(parent) self.model = create_card(card_details) self.setupUi() def get_card_background_colour(self): if isinstance(self.model, SpellCard): return QColor(CardColours[CardType.SPELL]) elif isinstance(self.model, TrapCard): return QColor(CardColours[CardType.TRAP]) else: pass def setupUi(self): self.main_layout = QVBoxLayout() self.name_attr_layout = QHBoxLayout() self.name_label = QLabel(self.model.name) font = self.name_label.font() font.setBold(True) font.setCapitalization(QFont.AllUppercase) font.setPointSize(12) self.name_label.setFont(font) self.name_label.setMargin(5) pixmap = get_attr_icon(self.model.attribute) self.attr_icon = QLabel() self.attr_icon.setPixmap(pixmap) self.attr_icon.setAlignment(Qt.AlignRight) self.name_attr_layout.addWidget(self.name_label) self.name_attr_layout.addWidget(self.attr_icon) self.main_layout.addLayout(self.name_attr_layout) self.level_layout = QHBoxLayout() self.main_layout.addLayout(self.level_layout) self.picture_frame = QFrame() self.picture_frame.setFixedSize(250, 250) self.picture_frame.setFrameStyle(QFrame.Box | QFrame.Plain) self.picture_frame.setFrameShadow(QFrame.Shadow.Raised) self.picture_frame.setLineWidth(1) self.picture_frame.setContentsMargins(0, 0, 0, 0) self.picture_frame.setLayout(QGridLayout()) self.image_holder = QLabel() pixmap = self._get_card_image() self.image_holder.setPixmap( pixmap.scaled( self.picture_frame.width(), self.picture_frame.height(), Qt.KeepAspectRatio, )) self.picture_frame.layout().addWidget(self.image_holder) self.main_layout.addWidget(self.picture_frame) # Card sets here? self.desc_group_box = QGroupBox() self.desc_group_box.setMaximumWidth(250) self.set_up_group_box() self.main_layout.addWidget(self.desc_group_box) self.id_label = QLabel(self.model.id) self.id_label.setAlignment(Qt.AlignLeft) self.id_label.setMargin(5) self.main_layout.addWidget(self.id_label) self.setLayout(self.main_layout) pal = QPalette() pal.setColor(QPalette.Background, self.get_card_background_colour()) self.setAutoFillBackground(True) self.setPalette(pal) def _get_card_image(self): image_name = self.model.img_url.split("/")[-1] if os.path.exists(self.get_image_path(image_name)): image = Image.open(self.get_image_path(image_name)) else: image_data = requests.get(self.model.img_url).content image = Image.open(BytesIO(image_data)) image.save(self.get_image_path(image_name)) image = image.crop((44, 106, 380, 438)) # this is about correct data = image.tobytes("raw", "RGB") qimage = QImage(data, image.size[0], image.size[1], QImage.Format_RGB888) pixmap = QPixmap.fromImage(qimage) return pixmap def get_image_path(self, image_name): return os.path.join(os.getcwd(), "images", image_name) def set_up_group_box(self): self.desc_group_box.setLayout(QVBoxLayout()) self.desc_label = QLabel(self.model.desc) self.desc_label.setWordWrap(True) self.desc_group_box.layout().addWidget(self.desc_label) if isinstance(self.model, (MonsterCard)): self.desc_group_box.setTitle(self.get_group_box_title()) line = QFrame() line.setFrameShape((QFrame.HLine)) line.setFrameShadow(QFrame.Sunken) self.desc_group_box.layout().addWidget(line) label = QLabel( f"ATK/{self.model.attack} DEF/{self.model.defence}") label.setAlignment(Qt.AlignRight) self.desc_group_box.layout().addWidget(label) def get_group_box_title(self): return "[TEST/TEST]"
class ppControlWidget(QWidget, QThread): def __init__(self): QWidget.__init__(self) QThread.__init__(self) pygame.init() pygame.joystick.init() self._joycnt = pygame.joystick.get_count() print(self._joycnt) if (self._joycnt == 0): print('no joystick found') #sys.exit(0) else: pygame.joystick.Joystick(0).init() if (pygame.joystick.Joystick(0).get_numaxes() < 4): self._joycnt = 0 self._running = True self._instance = None self._periodicity = 0.05 #time period between loops self.frame = QFrame() self.frame.setFixedSize(100, 50) self.btconfig = QPushButton(QIcon("res/config.png"), "") self.setFixedSize(140, 50) self.layout = QHBoxLayout() self.layout.addWidget(self.frame) self.layout.addWidget(self.btconfig) self.setLayout(self.layout) if (self._joycnt > 0): self._joystick = pygame.joystick.Joystick(0) self._joystick.init() print(self._joystick.get_name()) pygame.event.pump() self._Sticks = { 'gaz': self._joystick.get_axis(joytofunc['functoaxis']['gaz']) * joytofunc['funcreverse']['gaz'], 'yaw': self._joystick.get_axis(joytofunc['functoaxis']['yaw']) * joytofunc['funcreverse']['yaw'], 'pitch': self._joystick.get_axis(joytofunc['functoaxis']['pitch']) * joytofunc['funcreverse']['pitch'], 'roll': self._joystick.get_axis(joytofunc['functoaxis']['roll']) * joytofunc['funcreverse']['roll'] } self._Switchs = { 'start': self._joystick.get_button(joytofunc['functoswitch']['start']), 'rth': self._joystick.get_button(joytofunc['functoswitch']['rth']) } else: self._joystick = None self._Sticks = {'gaz': 0, 'yaw': 0, 'pitch': 0, 'roll': 0} self._Switchs = {'start': 0, 'rth': 0} self.btconfig.clicked.connect(self.config) self.ConfigDialog = ppConfigControlWindow(parent=self) self.start() def __del__(self): self._running = False pygame.quit() def paintEvent(self, paintEvent): painter = QPainter(self) r = self.frame.rect() r -= QMargins(0, 0, 1, 1) painter.drawRect(r) c1 = QPoint(r.width() / 4, r.height() / 2) c2 = QPoint(3 * r.width() / 4, r.height() / 2) r1 = (r.height() * 0.90) / 2 rc = (r.height() * 0.1) / 2 painter.drawEllipse(c1, r1, r1) painter.drawEllipse(c2, r1, r1) c1 = QPoint(r.width() / 4 + (self._Sticks['yaw'] * r1), r.height() / 2 - (self._Sticks['gaz'] * r1)) c2 = QPoint(3 * r.width() / 4 + (self._Sticks['roll'] * r1), r.height() / 2 - (self._Sticks['pitch'] * r1)) painter.drawEllipse(c1, rc, rc) painter.drawEllipse(c2, rc, rc) def resizeEvent(self, event): pass def run(self): global bindaxis while (self._running): pygame.event.pump() if (self._joycnt > 0): self._Sticks = { 'gaz': self._joystick.get_axis(joytofunc['functoaxis']['gaz']) * joytofunc['funcreverse']['gaz'], 'yaw': self._joystick.get_axis(joytofunc['functoaxis']['yaw']) * joytofunc['funcreverse']['yaw'], 'pitch': self._joystick.get_axis(joytofunc['functoaxis']['pitch']) * joytofunc['funcreverse']['pitch'], 'roll': self._joystick.get_axis(joytofunc['functoaxis']['roll']) * joytofunc['funcreverse']['roll'] } self._Switchs = { 'start': self._joystick.get_button( joytofunc['functoswitch']['start']), 'rth': self._joystick.get_button(joytofunc['functoswitch']['rth']) } p = round(100 * self._Sticks['pitch']) r = round(100 * self._Sticks['roll']) y = round(100 * self._Sticks['yaw']) t = round(100 * self._Sticks['gaz']) to = self._Switchs['start'] rt = self._Switchs['rth'] self.ConfigDialog.freshValues(p, r, y, t, to, rt) if (self._instance is not None): self._instance.PCMD(p, r, y, t) for event in pygame.event.get(): # User did something if not (bindaxis == None): if event.type == pygame.JOYAXISMOTION: if abs(event.value) > 0.5: joytofunc['functoaxis'][bindaxis] = event.axis bindaxis = None if event.type == pygame.JOYBUTTONDOWN: joytofunc['functoswitch'][bindaxis] = event.button bindaxis = None if event.type == pygame.JOYBUTTONDOWN: if (event.button in joytofunc['switchtofunc'].keys()): if (joytofunc['switchtofunc'][event.button] == 'start' ): try: self._instance.tkof_lnd_emcy() except: print("no device selected") if (joytofunc['switchtofunc'][event.button] == 'rth'): try: self._instance.rth() except: print("no device selected") self.update() time.sleep(self._periodicity) def config(self): w = self.ConfigDialog w.show() @property def Sticks(self): return self._Sticks @property def device(self): return self._instance @device.setter def device(self, dev): if dev is not None: self._instance = dev
class colorPicker(QDialog): "custom colorDialog from Orthallelous" currentColorChanged = Signal(QColor) colorSelected = Signal(QColor) def __init__(self, initial=None, parent=None): super(colorPicker, self).__init__(parent) self.setup() self.setColor(initial) def currentColor(self): return self._color def setColor(self, qcolor=None): if qcolor is None: self._color = QColor('#ffffff') else: self._color = QColor(qcolor) self._colorEdited() @staticmethod def getColor(initial=None, parent=None, title=None): dialog = colorPicker(initial, parent) if title: dialog.setWindowTitle(title) result = dialog.exec_() color = dialog._color return color def closeValid(self): "emits colorSelected signal with valid color on OK" self.currentColorChanged.emit(self._color) self.colorSelected.emit(self._color) self.close() def closeInvalid(self): "emits colorSelected signal with invalid color on Cancel" self._color = QColor() self.colorSelected.emit(QColor()) self.close() def setOption(self, option, Bool=True): if option == QColorDialog.NoButtons: if not Bool: self.dialogButtons.blockSignals(False) self.dialogButtons.setEnabled(True) self.dialogButtons.show() else: self.dialogButtons.blockSignals(True) self.dialogButtons.setEnabled(False) self.dialogButtons.hide() self.setFixedSize(self.sizeHint()) def _colorEdited(self): "internal color editing" sender, color = self.sender(), self._color for i in self.inputs: i.blockSignals(True) # get values if sender in self.rgbInputs: # RGB color.setRgb(*[i.value() for i in self.rgbInputs]) elif sender in self.hsvInputs: # HSV color.setHsv(*[i.value() for i in self.hsvInputs]) elif sender in self.cmykInputs: # CMYK color.setCmyk(*[i.value() for i in self.cmykInputs]) elif sender is self.htmlInput: # HTML color.setNamedColor('#' + str(self.htmlInput.text()).lower()) elif sender is self.colorWheel: # WHEEL color = self._color = self.colorWheel.getColor() elif sender is self.colorNamesCB: # NAMED dat = self.colorNamesCB.itemData(self.colorNamesCB.currentIndex()) try: color = self._color = QColor(dat.toString()) # PyQt except: color = self._color = QColor(str(dat)) # PySide self.colorNamesCB.setToolTip(self.colorNamesCB.currentText()) else: pass # set values for i, j in zip(color.getRgb()[:-1], self.rgbInputs): j.setValue(i) for i, j in zip(color.getHsv()[:-1], self.hsvInputs): j.setValue(i) for i, j in zip(color.getCmyk()[:-1], self.cmykInputs): j.setValue(i) self.htmlInput.setText(color.name()[1:]) self.colorWheel.setColor(color) idx = self.colorNamesCB.findData(color.name()) self.colorNamesCB.setCurrentIndex(idx) # will be blank if not in list pal = self.colorDisplay.palette() pal.setColor(self.colorDisplay.backgroundRole(), color) self.colorDisplay.setPalette(pal) #self.colorDisplay.setStyleSheet('background:' + color.name()) for i in self.inputs: i.blockSignals(False) self.currentColorChanged.emit(color) def pickColor(self): "pick a color on the screen, part 1" # screenshot desktop self._img = QApplication.primaryScreen().grabWindow(0) self._view = QGraphicsView(self) scene = QGraphicsScene(self) # display screenshot at full size self._view.setWindowFlags(Qt.FramelessWindowHint) self._view.setWindowFlags(Qt.WindowType_Mask) self._view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scene.addPixmap(self._img) #; self._view.setScene(scene) self._mag = magnifier() self._mag.setBackground(self._img) self._mag.setSize(11, 11) scene.addItem(self._mag) self._view.setScene(scene) self._appview = QApplication self._appview.setOverrideCursor(Qt.CrossCursor) self._view.showFullScreen() self._view.mousePressEvent = self._pickedColor def _pickedColor(self, event): "pick a color on the screen, part 2" color = QColor(self._img.toImage().pixel(event.globalPos())) self._view.hide() self._appview.restoreOverrideCursor() self._color = color self._colorEdited() self._mag = self._appview = self._view = self._img = None def showColors(self): "show location of colors on color wheel" if self.showButton.isChecked(): self.colorWheel.showNamedColors(True) else: self.colorWheel.showNamedColors(False) def useRandom(self, state=True): "toggles show colors button and random color button" if state: self.showButton.blockSignals(True) self.showButton.setChecked(False) self.showButton.hide() self.showColors() self.rndButton.blockSignals(False) self.rndButton.show() else: self.showButton.blockSignals(False) self.showButton.show() self.rndButton.blockSignals(True) self.rndButton.hide() def randomColor(self): "select a random color" rand = random.randint col = QColor() col.setHsv(rand(0, 359), rand(0, 255), rand(0, 255)) #col.setRgb(rand(0, 255), rand(0, 255), rand(0, 255)) self.setColor(col) return col def getNamedColors(self): "returns a list [(name, #html)] from the named colors combobox" lst = [] for i in range(self.colorNamesCB.count()): name = str(self.colorNamesCB.itemText(i)) try: # PyQt html = str(self.colorNamesCB.itemData(i).toString()) except AttributeError: # PySide html = str(self.colorNamesCB.itemData(i)) lst.append((name, html)) return lst def addNamedColors(self, lst): "add a list [('name', '#html'), ] of named colors (repeats removed)" col = self.getNamedColors() + lst lst = [(i[0], QColor(i[1])) for i in col] sen = set() add = sen.add # http://stackoverflow.com/a/480227 uni = [x for x in lst if not (x[1].name() in sen or add(x[1].name()))] self.colorNamesCB.clear() for i, j in sorted(uni, key=lambda q: q[1].getHsv()): icon = QPixmap(16, 16) icon.fill(j) self.colorNamesCB.addItem(QIcon(icon), i, j.name()) self.colorWheel.setNamedColors([(i, j.name()) for i, j in uni]) self.cNameLabel.setToolTip('Named colors\n{:,} colors'.format( len(uni))) def setup(self): self.setAttribute(Qt.WA_DeleteOnClose) fixed = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) rightCenter = (Qt.AlignRight | Qt.AlignVCenter) # all the input boxes self.inputGrid = QGridLayout() self.inputGrid.setSpacing(5) h_spc = self.inputGrid.horizontalSpacing() v_spc = self.inputGrid.verticalSpacing() # RGB self.redInput = QSpinBox() self.grnInput = QSpinBox() self.bluInput = QSpinBox() self.rgbInputs = [self.redInput, self.grnInput, self.bluInput] self.redLabel = QLabel('&R:') self.redLabel.setToolTip('Red') self.grnLabel = QLabel('&G:') self.grnLabel.setToolTip('Green') self.bluLabel = QLabel('&B:') self.bluLabel.setToolTip('Blue') self.rgbLabels = [self.redLabel, self.grnLabel, self.bluLabel] self.redLabel.setBuddy(self.redInput) self.grnLabel.setBuddy(self.grnInput) self.bluLabel.setBuddy(self.bluInput) # HSV self.hueInput = QSpinBox() self.satInput = QSpinBox() self.valInput = QSpinBox() self.hsvInputs = [self.hueInput, self.satInput, self.valInput] self.hueInput.setWrapping(True) self.hueLabel = QLabel('&H:') self.hueLabel.setToolTip('Hue') self.satLabel = QLabel('&S:') self.satLabel.setToolTip('Saturation') self.valLabel = QLabel('&V:') self.valLabel.setToolTip('Value') self.hsvLabels = [self.hueLabel, self.satLabel, self.valLabel] self.hueLabel.setBuddy(self.hueInput) self.satLabel.setBuddy(self.satInput) self.valLabel.setBuddy(self.valInput) # CMYK self.cInput = QSpinBox() self.mInput = QSpinBox() self.yInput = QSpinBox() self.kInput = QSpinBox() self.cmykInputs = [self.cInput, self.mInput, self.yInput, self.kInput] self.cLabel = QLabel('&C:') self.cLabel.setToolTip('Cyan') self.mLabel = QLabel('&M:') self.mLabel.setToolTip('Magenta') self.yLabel = QLabel('&Y:') self.yLabel.setToolTip('Yellow') self.kLabel = QLabel('&K:') self.kLabel.setToolTip('Black') self.cmykLabels = [self.cLabel, self.mLabel, self.yLabel, self.kLabel] self.cLabel.setBuddy(self.cInput) self.mLabel.setBuddy(self.mInput) self.yLabel.setBuddy(self.yInput) self.kLabel.setBuddy(self.kInput) for i in self.rgbInputs + self.hsvInputs + self.cmykInputs: i.setRange(0, 255) i.setFixedSize(35, 22) i.setAlignment(Qt.AlignCenter) i.setButtonSymbols(QAbstractSpinBox.NoButtons) self.hueInput.setRange(0, 359) # HTML self.htmlInput = QLineEdit() self.htmlInput.setFixedSize(35 + 22 + h_spc, 22) # spans 2 cols self.htmlInput.setPlaceholderText('html') self.htmlInput.setAlignment(Qt.AlignCenter) regex = QRegExp('[0-9A-Fa-f]{1,6}') valid = QRegExpValidator(regex) self.htmlInput.setValidator(valid) self.htmlLabel = QLabel('&#') self.htmlLabel.setToolTip('Web color') self.htmlLabel.setBuddy(self.htmlInput) self.inputLabels = (self.rgbLabels + self.hsvLabels + self.cmykLabels + [ self.htmlLabel, ]) for i in self.inputLabels: i.setFixedSize(22, 22) i.setAlignment(rightCenter) #i.setFrameShape(QFrame.Box) self.inputs = self.rgbInputs + self.hsvInputs + self.cmykInputs for i in self.inputs: i.valueChanged.connect(self._colorEdited) self.htmlInput.editingFinished.connect(self._colorEdited) # picker button self.pickButton = QPushButton('&Pick') self.pickButton.setToolTip('Pick a color from the screen') self.pickButton.setFixedSize(35, 22) self.pickButton.clicked.connect(self.pickColor) # color display self.colorDisplay = QFrame() self.colorDisplay.setFixedSize(55, 4 * 22 + 3 * v_spc) # spans 4 rows self.colorDisplay.setFrameShape(QFrame.Panel) self.colorDisplay.setFrameShadow(QFrame.Sunken) self.colorDisplay.setAutoFillBackground(True) # show button / random button self.showButton = QPushButton('Sho&w') self.showButton.setToolTip('Show named colors on color wheel') self.showButton.setFixedSize(35, 22) self.showButton.setCheckable(True) self.showButton.clicked.connect(self.showColors) self.rndButton = QPushButton('R&and') self.rndButton.setToolTip('Select a random color') self.rndButton.setFixedSize(35, 22) self.rndButton.clicked.connect(self.randomColor) # color wheel self.colorWheel = wheel() self.colorWheel.setFixedSize(256, 256) #265, 265) self.colorWheel.currentColorChanged.connect(self.setColor) # named colors combo box self.colorNamesCB = QComboBox() self.colorNamesCB.setFixedSize(70 + 66 + 4 * h_spc, 22) # spans 5 cols #self.colorNamesCB.addItem('- Color Names -') self.cNameLabel = QLabel('&Named:') self.cNameLabel.setBuddy(self.colorNamesCB) self.cNameLabel.setAlignment(rightCenter) #self.cNameLabel.setFrameShape(QFrame.Box) self.cNameLabel.setFixedSize(55, 22) lst = [i for i in QColor.colorNames() if str(i) != 'transparent'] lst = [(i, QColor(i)) for i in lst] lst.append(('Cosmic latte', '#fff8e7')) lst.append(('rebeccapurple', '#663399')) self.addNamedColors(lst) self.colorNamesCB.currentIndexChanged.connect(self._colorEdited) self.inputs += [self.htmlInput, self.colorWheel, self.colorNamesCB] # ok/cancel buttons self.dialogButtons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.dialogButtons.accepted.connect(self.closeValid) self.dialogButtons.rejected.connect(self.closeInvalid) self.dialogButtons.setCenterButtons(True) # pass QColorDialog.NoButtons, False to setOption to remove # assemble grid! # 0 1 2 3 4 5 6 # # color wheeeeeeeeeeeeellll 0 # disp r: rrr h: hhh c: ccc 1 # disp g: ggg s: sss m: mmm 2 # disp b: bbb v: vvv y: yyy 3 # disp ## -html- pic k: kkk 4 # name coooommmboooobox rnd 5 #.addWidget(widget, row, col, rspan, cspan) self.inputGrid.addWidget(self.colorWheel, 0, 0, 1, 7) self.inputGrid.addWidget(self.colorDisplay, 1, 0, 4, 1) for i, lab in enumerate(self.rgbLabels, 1): self.inputGrid.addWidget(lab, i, 1, 1, 1) self.inputGrid.addWidget(self.htmlLabel, 4, 1, 1, 1) for i, wid in enumerate(self.rgbInputs, 1): self.inputGrid.addWidget(wid, i, 2) self.inputGrid.addWidget(self.htmlInput, 4, 2, 1, 2) for i, lab in enumerate(self.hsvLabels, 1): self.inputGrid.addWidget(lab, i, 3, 1, 1) for i, wid in enumerate(self.hsvInputs, 1): self.inputGrid.addWidget(wid, i, 4, 1, 1) self.inputGrid.addWidget(self.pickButton, 4, 4, 1, 1) for i, lab in enumerate(self.cmykLabels, 1): self.inputGrid.addWidget(lab, i, 5, 1, 1) for i, wid in enumerate(self.cmykInputs, 1): self.inputGrid.addWidget(wid, i, 6, 1, 1) self.inputGrid.addWidget(self.colorNamesCB, 5, 1, 1, 5) self.inputGrid.addWidget(self.cNameLabel, 5, 0, 1, 1) self.inputGrid.addWidget(self.showButton, 5, 6, 1, 1) self.inputGrid.addWidget(self.rndButton, 5, 6, 1, 1) self.inputGrid.addWidget(self.dialogButtons, 6, 0, 1, 7) self.setWindowTitle('Select color') ico = self.style().standardIcon(QStyle.SP_DialogResetButton) self.setWindowIcon(ico) self.setLayout(self.inputGrid) self.setFixedSize(self.sizeHint()) self.useRandom() #False)