def __init__(self, game, boardrect, parent=None): super().__init__(parent) self.game = game self.boardrect = boardrect margin_size = self.boardrect.x() self.__answerbarrect = boardrect.adjusted(-ANSWERBARS, 0, ANSWERBARS, 0) self.__correctrect = QRect(0, 0, margin_size, self.boardrect.height()) self.__incorrectrect = QRect(self.boardrect.right(), 0, margin_size, self.boardrect.height()) arrow_size = QSize(int(margin_size * 0.7), int(margin_size * 0.7)) self.__leftarrowrect = QRect(QPoint(0, 0), arrow_size) self.__leftarrowrect.moveCenter(self.__correctrect.center()) self.__rightarrowrect = QRect(QPoint(0, 0), arrow_size) self.__rightarrowrect.moveCenter(self.__incorrectrect.center()) self.__leftarrowimage = QPixmap(resource_path("left-arrow.png")) self.__rightarrowimage = QPixmap(resource_path("right-arrow.png")) self.__spaceimage = QPixmap(resource_path("space.png")) self.show() self.__lit = False self.arrowhints = False self.spacehints = False
def UiComponents(self): button = QPushButton("Close Window", self) button.setGeometry(QRect(100, 100, 111, 50)) button.setIcon(QtGui.QIcon("home.png")) button.setIconSize(QSize(40, 40)) button.setToolTip("This Is Click Me Button") button.clicked.connect(ClickMe)
def cropImage(self): """Crop selected portions in the image.""" if self.image.isNull() == False: rect = QRect(10, 20, 400, 200) original_image = self.image cropped = original_image.copy(rect) self.image = QImage(cropped) self.setPixmap(QPixmap().fromImage(cropped))
def mousePressEvent(self, event): """Handle mouse press event.""" self.origin = event.pos() if not (self.rubber_band): self.rubber_band = QRubberBand(QRubberBand.Rectangle, self) self.rubber_band.setGeometry(QRect(self.origin, QSize())) self.rubber_band.show() #print(self.rubber_band.height()) print(self.rubber_band.x())
def drawText_centered(self, center_point: Tuple[int, int], text: str): rect_height = 2 * self.font().pointSize() rect_width = rect_height * len(text) rect_position = complex( *center_point) - complex(rect_width, rect_height) / 2 rect_position = complex_to_tuple_rounded(rect_position) text_rect = QRect(*rect_position, rect_width, rect_height) self.drawText(text_rect, Qt.AlignmentFlag.AlignCenter, text)
def __init__(self, text, rect, parent=None): super().__init__(text, parent) self.setStyleSheet("color: white;") self.setGeometry(QRect(rect)) self.setAlignment(Qt.AlignmentFlag.AlignCenter) self.setWordWrap(True) self.font = QFont("Helvetica") self.font.setPixelSize(72) self.setFont(self.font) shadow = QGraphicsDropShadowEffect(self) shadow.setBlurRadius(40) shadow.setColor(QColor("black")) shadow.setOffset(3) self.setGraphicsEffect(shadow)
class BorderWidget(QWidget): def __init__(self, game, boardrect, parent=None): super().__init__(parent) self.game = game self.boardrect = boardrect margin_size = self.boardrect.x() self.__answerbarrect = boardrect.adjusted(-ANSWERBARS, 0, ANSWERBARS, 0) self.__correctrect = QRect(0, 0, margin_size, self.boardrect.height()) self.__incorrectrect = QRect(self.boardrect.right(), 0, margin_size, self.boardrect.height()) arrow_size = QSize(int(margin_size * 0.7), int(margin_size * 0.7)) self.__leftarrowrect = QRect(QPoint(0, 0), arrow_size) self.__leftarrowrect.moveCenter(self.__correctrect.center()) self.__rightarrowrect = QRect(QPoint(0, 0), arrow_size) self.__rightarrowrect.moveCenter(self.__incorrectrect.center()) self.__leftarrowimage = QPixmap(resource_path("left-arrow.png")) self.__rightarrowimage = QPixmap(resource_path("right-arrow.png")) self.__spaceimage = QPixmap(resource_path("space.png")) self.show() self.__lit = False self.arrowhints = False self.spacehints = False @property def lit(self): return self.__lit @lit.setter @updateUI def lit(self, val): self.__lit = val def paintEvent(self, event): qp = QPainter() qp.begin(self) if self.lit: qp.setBrush(HIGHLIGHTBRUSH) qp.drawRect(self.__answerbarrect) if self.arrowhints and self.parent().alex: qp.setBrush(CORRECTBRUSH) qp.drawRect(self.__correctrect) qp.setBrush(INCORRECTBRUSH) qp.drawRect(self.__incorrectrect) qp.setBrush(HIGHLIGHTBRUSH) qp.drawPixmap(self.__leftarrowrect, self.__leftarrowimage) qp.drawPixmap(self.__rightarrowrect, self.__rightarrowimage) if self.spacehints and self.parent().alex: qp.setBrush(HIGHLIGHTBRUSH) qp.drawPixmap(self.__leftarrowrect, self.__spaceimage) qp.drawPixmap(self.__rightarrowrect, self.__spaceimage)
def __init__(self, parent=None, window=None): """Construct Dialog Box. kwargs: parent (QWidget, optional) Parent widget object. Defaults to None. window (QWidget, optional) Program's MainWindow. Defaults to None. """ super().__init__(parent=parent) self.window = window font = QFont() font2 = QFont() font.setPointSize(11) font2.setPointSize(20) fixed = QSizePolicy.Policy.Fixed sizePolicy = QSizePolicy(fixed, fixed) self.resize(365, 229) self.setWindowTitle("About") self.setObjectName("aboutBox") self.setGeometry(QRect(180, 190, 171, 32)) self.setSizePolicy(sizePolicy) self.label = QLabel(self) self.label_2 = QLabel(self) self.label_3 = QLabel(self) self.label_4 = QLabel(self) self.label_5 = QLabel(self) self.label_6 = QLabel(self) self.label.setGeometry(QRect(20, 10, 161, 51)) self.label_2.setGeometry(QRect(150, 30, 49, 16)) self.label_3.setGeometry(QRect(20, 80, 211, 16)) self.label_4.setGeometry(QRect(20, 160, 201, 20)) self.label_5.setGeometry(QRect(20, 120, 341, 41)) self.label_6.setGeometry(QRect(20, 110, 121, 16)) self.label.setFont(font2) self.label_3.setFont(font) self.label_5.setFont(font) self.label_6.setFont(font) self.label.setText("BlackJack") self.label_2.setText("v 0.3") self.label_3.setText("Copyright 2021 AlexPdev Inc.") self.label_4.setText("https://fsf.org/") self.label_5.setText("License GNU LESSER GENERAL PUBLIC LICENSE") self.label_6.setText("Creator AlexPdev") self.button = QPushButton("Ok", parent=self) self.button.pressed.connect(self.okbutton)
def __init__(self, question, parent=None): super().__init__(parent) self.question = question self.responses_open = False # pheight = parent.geometry().height() # height = pheight * (1 - SCOREHEIGHT) # width = height / CELLRATIO self.resize(parent.size()) # self.move( # self.parent().geometry().width() / 2 - self.parent().boardwidget.geometry().width() / 2, 0 # ) if self.parent().alex: anheight = ANSWERHEIGHT * self.size().height() self.qurect = self.rect().adjusted( QUMARGIN, QUMARGIN, -2 * QUMARGIN, -ANSWERHEIGHT * self.size().height(), ) self.anrect = QRect( QUMARGIN, self.size().height() * (1 - ANSWERHEIGHT), self.size().width() - 2 * QUMARGIN, ANSWERHEIGHT * self.size().height(), ) self.answer_label = QuestionLabel(question.answer, self.anrect, self) else: self.qurect = self.rect().adjusted(QUMARGIN, QUMARGIN, -2 * QUMARGIN, -2 * QUMARGIN) self.anrect = None self.answer_label = None self.question_label = QuestionLabel(question.text.upper(), self.qurect, self) self.show()
def doLayout(self, rect, testOnly): x = rect.x() y = rect.y() lineHeight = 0 for item in self.itemList: wid = item.widget() spaceX = self.spacing() + wid.style().layoutSpacing( QSizePolicy.ControlType.PushButton, QSizePolicy.ControlType.PushButton, Qt.Orientation.Horizontal, ) spaceY = self.spacing() + wid.style().layoutSpacing( QSizePolicy.ControlType.PushButton, QSizePolicy.ControlType.PushButton, Qt.Orientation.Vertical, ) nextX = x + item.sizeHint().width() + spaceX if nextX - spaceX > rect.right() and lineHeight > 0: x = rect.x() y = y + lineHeight + spaceY nextX = x + item.sizeHint().width() + spaceX lineHeight = 0 if not testOnly: item.setGeometry(QRect( QPoint(x, y), item.sizeHint(), )) x = nextX lineHeight = max(lineHeight, item.sizeHint().height()) return y + lineHeight - rect.y()
def get_masked_image(path, size=64, overlay_text=""): """ Returns a pixmap from an image file masked with a smooth circle. The returned pixmap will have a size of *size* × *size* pixels. :param str path: Path to image file. :param int size: Target size. Will be the diameter of the masked image. :param str overlay_text: Overlay text. This will be shown in white sans-serif on top of the image. :return: Masked image with overlay text. :rtype: QPixmap """ with open(path, "rb") as f: imgdata = f.read() imgtype = path.split(".")[-1] # Load image and convert to 32-bit ARGB (adds an alpha channel): image = QImage.fromData(imgdata, imgtype) image.convertToFormat(QImage.Format.Format_ARGB32) # Crop image to a square: imgsize = min(image.width(), image.height()) width = (image.width() - imgsize) / 2 height = (image.height() - imgsize) / 2 rect = QRect( round(width), round(height), imgsize, imgsize, ) image = image.copy(rect) # Create the output image with the same dimensions and an alpha channel # and make it completely transparent: out_img = QImage(imgsize, imgsize, QImage.Format.Format_ARGB32) out_img.fill(Qt.GlobalColor.transparent) # Create a texture brush and paint a circle with the original image onto # the output image: brush = QBrush(image) # Create texture brush painter = QPainter(out_img) # Paint the output image painter.setBrush(brush) # Use the image texture brush painter.setPen(Qt.PenStyle.NoPen) # Don't draw an outline painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) # Use AA painter.drawEllipse(0, 0, imgsize, imgsize) # Actually draw the circle if overlay_text: # draw text font = QtGui.QFont("Arial Rounded MT Bold") font.setPointSize(imgsize * 0.4) painter.setFont(font) painter.setPen(Qt.GlobalColor.white) painter.drawText(QRect(0, 0, imgsize, imgsize), Qt.AlignmentFlag.AlignCenter, overlay_text) painter.end() # We are done (segfault if you forget this) # Convert the image to a pixmap and rescale it. Take pixel ratio into # account to get a sharp image on retina displays: pr = QtWidgets.QApplication.instance().devicePixelRatio() pm = QPixmap.fromImage(out_img) pm.setDevicePixelRatio(pr) size = int(pr * size) pm = pm.scaled( size, size, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation, ) return pm
def mouseMoveEvent(self, event): """Handle mouse move event.""" self.rubber_band.setGeometry( QRect(self.origin, event.pos()).normalized())
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self._background_color = QColor(204, 204, 204, 255) self.beforeRenderPassRecording.connect( self._render, type=Qt.ConnectionType.DirectConnection) self._mouse_device = QtMouseDevice(self) self._mouse_device.setPluginId("qt_mouse") self._key_device = QtKeyDevice() self._key_device.setPluginId("qt_key") self._previous_focus = None # type: Optional["QQuickItem"] self._app = QCoreApplication.instance() # Remove previously added input devices (if any). This can happen if the window was re-loaded. self._app.getController().removeInputDevice("qt_mouse") self._app.getController().removeInputDevice("qt_key") self._app.getController().addInputDevice(self._mouse_device) self._app.getController().addInputDevice(self._key_device) self._app.getController().getScene().sceneChanged.connect( self._onSceneChanged) self._app.getController().activeViewChanged.connect( self._onActiveViewChanged) Selection.selectionChanged.connect(self._onSceneChanged) self._preferences = Application.getInstance().getPreferences() self._preferences.addPreference("general/window_width", self.DEFAULT_WINDOW_WIDTH) self._preferences.addPreference("general/window_height", self.DEFAULT_WINDOW_HEIGHT) self._preferences.addPreference("general/window_left", self.DEFAULT_WINDOW_LEFT) self._preferences.addPreference("general/window_top", self.DEFAULT_WINDOW_TOP) self._preferences.addPreference("general/window_state", Qt.WindowState.WindowNoState.value) self._preferences.addPreference("general/restore_window_geometry", True) restored_geometry = QRect( int(self._preferences.getValue("general/window_left")), int(self._preferences.getValue("general/window_top")), int(self._preferences.getValue("general/window_width")), int(self._preferences.getValue("general/window_height"))) if not self._preferences.getValue("general/restore_window_geometry"): # Ignore whatever the preferences said. Logger.log( "i", "Not restoring window geometry from preferences because 'restore_window_geometry' is false" ) restored_geometry = QRect(self.DEFAULT_WINDOW_LEFT, self.DEFAULT_WINDOW_TOP, self.DEFAULT_WINDOW_WIDTH, self.DEFAULT_WINDOW_HEIGHT) # Make sure restored geometry is not outside the currently available screens screen_found = False for screen in self._app.screens(): if restored_geometry.intersects(screen.availableGeometry()): screen_found = True break if not screen_found: Logger.log( "w", "Could not restore to previous location on screen, since the sizes or number of monitors " "have changed since then") # Unable to find the screen that this window used to be on, so just use the defaults restored_geometry = QRect(self.DEFAULT_WINDOW_LEFT, self.DEFAULT_WINDOW_TOP, self.DEFAULT_WINDOW_WIDTH, self.DEFAULT_WINDOW_HEIGHT) self.setGeometry(restored_geometry) # Translate window state back to enum. try: window_state = int( self._preferences.getValue("general/window_state")) except ValueError: self._preferences.resetPreference("general/window_state") window_state = int( self._preferences.getValue("general/window_state")) if window_state == Qt.WindowState.WindowNoState.value: self.setWindowState(Qt.WindowState.WindowNoState) elif window_state == Qt.WindowState.WindowMaximized.value: self.setWindowState(Qt.WindowState.WindowMaximized) self._mouse_x = 0 self._mouse_y = 0 self._mouse_pressed = False self._viewport_rect = QRectF(0, 0, 1.0, 1.0) self.closing.connect(self.preClosing) Application.getInstance().setMainWindow(self) self._fullscreen = False self._full_render_required = True self._allow_resize = True
def paintEvent(self, event): h = self.geometry().height() w = self.geometry().width() qp = QPainter() qp.begin(self) qp.setBrush(FILLBRUSH) qp.drawRect(QRectF(0, DIVIDERWIDTH, w, h)) qp.setBrush(DIVIDERBRUSH) dividerrect = QRectF(0, 0, w, DIVIDERWIDTH) qp.drawRect(dividerrect) # Light dividers num_lights = 9 light_width = w // num_lights light_padding = 3 ungrouped_rects = [ QRect( light_width * i + light_padding, light_padding, light_width - 2 * light_padding, DIVIDERWIDTH - 2 * light_padding, ) for i in range(num_lights) ] grouped_rects = [[ rect for j, rect in enumerate(ungrouped_rects) if abs(num_lights // 2 - j) == i ] for i in range(5)] qp.setBrush(LIGHTBRUSH) qp.setPen(LIGHTPEN) for i, rects in enumerate(grouped_rects): if i < self.__light_level: for rect in rects: qp.drawRect(rect) margin = 50 players = self.game.players sw = w // len(players) if self.game.current_round.final: highlighted_players = [ p for p in players if p not in self.game.wagered ] else: highlighted_players = [] ap = self.game.answering_player if ap: highlighted_players.append(ap) for i, p in enumerate(players): if p.score < 0: qp.setPen(HOLEPEN) else: qp.setPen(SCOREPEN) qp.setFont(SCOREFONT) qp.drawText( self.__scorerect(i), Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, f"{p.score:,}", ) namerect = QRectF(sw * i, h - NAMEHEIGHT, sw, NAMEHEIGHT) qp.setFont(NAMEFONT) qp.setPen(NAMEPEN) if p in highlighted_players: qp.setBrush(HIGHLIGHTBRUSH) qp.drawRect(namerect) qp.setPen(HIGHLIGHTPEN) qp.drawText( namerect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, p.name, )
def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) hovering = index.data(HOVER_ROLE) is True painter.save() painter.setRenderHint(QPainter.RenderHint.Antialiasing) painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) rect = option.rect is_current = index.data(Qt.ItemDataRole.FontRole) is not None if not hovering and is_current: qpp = QPainterPath() qpp.addRoundedRect(QRectF(rect), 6, 6) painter.fillPath(qpp, self.current_background) icon_rect = QRect(rect.left() + self.MARGIN, rect.top() + self.MARGIN, ICON_SIZE, ICON_SIZE) left = icon_rect.right() + 2 * self.MARGIN text_rect = QRect(left, icon_rect.top(), rect.width() - left + rect.left(), icon_rect.height()) mark = index.data(MARK_ROLE) if hovering or mark: text_rect.adjust(0, 0, -text_rect.height(), 0) text = index.data(DISPLAY_ROLE) or '' muted = index.data(MUTED_ROLE) if muted: mc = get_icon('volume-off.svg').pixmap(ICON_SIZE, ICON_SIZE) painter.drawPixmap( QRect(text_rect.left(), text_rect.top(), ICON_SIZE, text_rect.height()), mc, mc.rect()) text_rect.adjust(ICON_SIZE, 0, 0, 0) font = index.data(Qt.ItemDataRole.FontRole) if font: painter.setFont(font) text_flags = Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft | Qt.TextFlag.TextSingleLine text = elided_text(text, font, text_rect.width(), 'right') if option.state & QStyle.StateFlag.State_Selected: painter.setPen(QPen(self.highlighted_text)) painter.drawText(text_rect, text_flags, text) if mark: hrect = QRect(text_rect.right(), text_rect.top(), text_rect.height(), text_rect.height()) painter.fillRect(hrect, QColor('#ffffaa')) painter.drawText(hrect, Qt.AlignmentFlag.AlignCenter, mark) elif hovering: hrect = QRect(text_rect.right(), text_rect.top(), text_rect.height(), text_rect.height()) close_hover = index.data(CLOSE_HOVER_ROLE) is True if close_hover: pen = painter.pen() pen.setColor(QColor('red')) painter.setPen(pen) painter.drawText(hrect, Qt.AlignmentFlag.AlignCenter, '✖ ') if index.data(LOADING_ROLE) > 0: lc = self.frames[self.frame_number] painter.drawPixmap(icon_rect.topLeft(), lc) else: icurl = index.data(URL_ROLE) if icurl == WELCOME_URL: icon = welcome_icon() elif icurl == DOWNLOADS_URL: icon = get_icon(DOWNLOAD_ICON_NAME) else: icon = index.data(DECORATION_ROLE) icon.paint(painter, icon_rect) painter.restore()
def heightForWidth(self, width): height = self.doLayout(QRect(0, 0, width, 0), True) return height