def load_pixmaps(self, mask: qtg.QPixmap, image: qtg.QPixmap): self.top_container.load_pixmap(mask) self.backdrop_container.load_pixmap(image) self._max_pixmap_dimension = max(mask.width(), mask.height()) self._last_midpoint = qtc.QPoint( self.horizontalScrollBar().value() + self.width() / 2, self.verticalScrollBar().value() + self.height() / 2)
class FaderWidget(QtWidgets.QWidget): pixmap_opacity = 1.0 def __init__(self, old_widget, new_widget, duration=300): super().__init__(new_widget) pr = QtWidgets.QApplication.instance().devicePixelRatio() self.old_pixmap = QPixmap(new_widget.size() * pr) self.old_pixmap.setDevicePixelRatio(pr) old_widget.render(self.old_pixmap) self.timeline = QtCore.QTimeLine() self.timeline.valueChanged.connect(self.animate) self.timeline.finished.connect(self.close) self.timeline.setDuration(duration) self.timeline.start() self.resize(new_widget.size()) self.show() def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setOpacity(self.pixmap_opacity) painter.drawPixmap(0, 0, self.old_pixmap) painter.end() def animate(self, value): self.pixmap_opacity = 1.0 - value self.repaint()
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 run(self): url = ( f"https://api.bilibili.com/medialist/gateway/base/spaceDetail?media_id={self.media_id}&" "pn=1&ps=20&keyword=&order=mtime&type=0&tid=0&jsonp=jsonp") try: data = json.loads(urlopen(url).read()) # load thumbnail image pixmap = QPixmap() pixmap.loadFromData( urlopen(str(data["data"]["info"]["cover"])).read()) # emitting the response signal # self.worker_response.emit( WorkerRespnose( pixmap, data["data"]["info"]["title"], data["data"]["info"]["upper"]["name"], data["data"]["medias"], data["data"]["info"]["media_count"], data["data"]["info"]["ctime"], )) except Exception as e: print(e) # emitting the error signal self.worker_err_response.emit()
def rotateImage90(self, direction): """Rotate image 90º clockwise or counterclockwise.""" if self.image.isNull() == False: if direction == "cw": transform90 = QTransform().rotate(90) elif direction == "ccw": transform90 = QTransform().rotate(-90) pixmap = QPixmap(self.image) #TODO: Try flipping the height/width when flipping the image rotated = pixmap.transformed(transform90, mode=Qt.SmoothTransformation) self.resize(self.image.height(), self.image.width()) #rotated = pixmap.trueMatrix(transform90, pixmap.width, pixmap.height) #self.image_label.setPixmap(rotated.scaled(self.image_label.size(), # Qt.KeepAspectRatio, Qt.SmoothTransformation)) self.image = QImage(rotated) #self.setPixmap(rotated) self.setPixmap( rotated.scaled(self.size(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)) self.repaint() # repaint the child widget else: # No image to rotate pass
def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) qtRectangle = self.frameGeometry() centerPoint = QGuiApplication.screens()[0].geometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) icon_size = 64 icon = QPixmap(resource_path("icon.png")) self.icon_label.setPixmap( icon.scaled( icon_size, icon_size, transformMode=Qt.TransformationMode.SmoothTransformation, )) self.icon_label.setGeometry((self.rect().width() - icon_size) / 2, 10, icon_size, icon_size) self.monitor_error.setStyleSheet("QLabel { color: red}") self.monitor_error.setGeometry(140, 75, self.rect().width(), 20) QApplication.instance().screenAdded.connect(self.check_second_monitor) QApplication.instance().screenRemoved.connect( self.check_second_monitor) self.check_second_monitor() self.startButton.setToolTip("Start Game") self.startButton.move(280, 95) self.startButton.clicked.connect(self.init_game) self.startButton.setEnabled(False) self.randButton.setToolTip("Random Game") self.randButton.move(280, 120) # self.randButton.setFocus(False) self.randButton.clicked.connect(self.random) summary_margin = 50 self.summary_label.setGeometry( summary_margin, 150, self.rect().width() - 2 * summary_margin, 40) self.summary_label.setAlignment(Qt.AlignmentFlag.AlignHCenter) self.gameid_label.move(120, 105) self.textbox.move(180, 100) self.textbox.resize(100, 40) self.textbox.textChanged.connect(self.show_summary) f = self.textbox.font() f.setPointSize(30) # sets the size to 27 self.textbox.setFont(f) self.player_view = PlayerView(self.rect() - QMargins(0, 210, 0, 0), parent=self) if DEBUG: self.textbox.setText(str(2534)) # EDIT self.show() print("Number of screens:", len(QApplication.instance().screens()))
def load_pixmap(self, pixmap: qtg.QPixmap): self._output_changed = False self.setPixmap(pixmap) self._master_pixmap = qtg.QPixmap(pixmap) self._original_pixmap = qtg.QPixmap(pixmap) if self._max_pixmap_dimension == None: self._max_pixmap_dimension = max(pixmap.width(), pixmap.height()) self.update_pixmap()
def set_background(self, pixmap: QPixmap, use_picture_coordinates: bool = True): if use_picture_coordinates: self.x_range = pixmap.width() self.y_range = pixmap.height() self.zoom_reset() self.background.set_picture(pixmap)
def initUI(self) -> None: self.setGeometry(0, 0, self.width, self.height) self.setWindowTitle('Message box') label = QLabel(self) pixmap = QPixmap(self.file_name) label.setPixmap(pixmap) self.resize(pixmap.width(),pixmap.height()) self.show()
def icon_url_changed(self, url): dc = QApplication.instance().disk_cache.data(url) if dc is not None: with closing(dc): raw = dc.readAll() p = QPixmap() p.loadFromData(raw) if not p.isNull(): ic = QIcon() ic.addPixmap(p) self.set_data(DECORATION_ROLE, ic)
def changeValue(self, value): if value == 0: self.label.setPixmap(QPixmap('mute.png')) elif 0 < value <= 30: self.label.setPixmap(QPixmap('min.png')) elif 30 < value < 80: self.label.setPixmap(QPixmap('med.png')) else: self.label.setPixmap(QPixmap('max.png'))
def icon(self): if self._icon is None: self._icon = QIcon() url = places.favicon_url(self.place_id) if url is not None: f = QApplication.instance().disk_cache.data(QUrl(url)) if f is not None: with closing(f): raw = f.readAll() p = QPixmap() p.loadFromData(raw) if not p.isNull(): self._icon.addPixmap(p) return self._icon
def missing_icon(): global _missing_icon if _missing_icon is None: p = QPixmap(ICON_SIZE, ICON_SIZE) p.fill(Qt.GlobalColor.transparent) painter = QPainter(p) pal = QApplication.instance().palette() painter.setPen( QPen(pal.color(QPalette.ColorRole.Text), 0, Qt.PenStyle.DashLine)) margin = 3 r = p.rect().adjusted(margin, margin, -margin, -margin) painter.drawRect(r) painter.end() _missing_icon = QIcon(p) return _missing_icon
def __init__(self, comic_info: ComicInfo, tab_widget: QTabWidget, down_v_box_layout: QVBoxLayout): super().__init__() self.tabWidget = tab_widget self.comicInfo = comic_info self.down_v_box_layout = down_v_box_layout self.setMinimumHeight(200) # 图片 img = QImage.fromData(comic_info.cover) self.img_label = QLabel(self) self.img_label.setScaledContents(True) w, h = image_resize(comic_info.cover, height=200) self.img_label.resize(QtCore.QSize(w, h)) self.img_label.setGeometry(5, 5, w, h) self.img_label.setPixmap(QPixmap.fromImage(img)) # self.img_label.setPixmap(QtGui.QPixmap("/Users/bo/my/tmp/老夫子2/第1卷/1.jpg")) # 标题 self.title = ButtonQLabel(self) self.title.onclick(self.add_tab) self.title.setText(comic_info.title) self.title.setGeometry(180, 10, 550, 35) title_font = QtGui.QFont() title_font.setPointSize(30) title_font.setBold(True) title_font.setUnderline(True) self.title.setFont(title_font) self.title.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor)) # 作者 self.author = QLabel(self) self.author.setText("作者 : " + comic_info.author) self.author.setGeometry(180, 50, 250, 20) # 状态 self.status = QLabel(self) self.status.setText("更新状态 : " + comic_info.status) self.status.setGeometry(500, 50, 150, 20) # 热度 self.status = QLabel(self) self.status.setText("热度 : " + str(comic_info.heat)) self.status.setGeometry(800, 50, 100, 20) # 类型 self.tip = QLabel(self) self.tip.setText("类型 : " + comic_info.tip) self.tip.setGeometry(180, 70, 250, 20) # web self.domain = QLabel(self) self.domain.setText(f"查看原网页 : {comic_info.domain}") self.domain.setText(f'查看原网页 : <a href="{comic_info.url}">{comic_info.domain}</a>') self.domain.setGeometry(500, 70, 250, 20) self.domain.setOpenExternalLinks(True) # 描述 self.describe = QLabel(self) self.describe.setText(" " + comic_info.describe) self.describe.setGeometry(180, 90, 664, 110) self.describe.setWordWrap(True) # 对齐方式 self.describe.setAlignment( QtCore.Qt.AlignmentFlag.AlignLeading | QtCore.Qt.AlignmentFlag.AlignLeft | QtCore.Qt.AlignmentFlag.AlignTop)
def App(): app = QApplication(sys.argv) win = QWidget() win.setWindowTitle("PyQt6 QLabel Example") win.left = 100 win.top = 100 l1 = QLabel("Hello World") l2 = QLabel("Welcome to Python GUI Programming") # # Because you can't instantiate a QLable directly with a QPixmap. # l3 = QLabel() l3.setPixmap(QPixmap("python-small.png")) l1.setAlignment(Qt.Alignment.AlignCenter) l2.setAlignment(Qt.Alignment.AlignCenter) l3.setAlignment(Qt.Alignment.AlignCenter) vbox = QVBoxLayout() vbox.addWidget(l1) vbox.addStretch() vbox.addWidget(l2) vbox.addStretch() vbox.addWidget(l3) vbox.addStretch() win.setLayout(vbox) win.show() sys.exit(app.exec())
def __init__(self): super().__init__() self.resize(*self.window_size) self.setupUi(self) self._ctrl_f = helpers.CtrlKeySequence(Qt.Key.Key_F) self._ctrl_n = helpers.CtrlKeySequence(Qt.Key.Key_N) self._ctrl_r = helpers.CtrlKeySequence(Qt.Key.Key_R) self._file_obj = open(config.word_path) word_picker = WordPicker(self._file_obj, config.word_count, dummy_filter_collection) self._game = Game(word_picker, LetterTracker()) self._game.availableLetters.connect(self.label_available_letters.setText) self._game.guessedLetters.connect(self.label_guessed_letters.setText) self._game.changeImage.connect(self.label_status.setPixmap) self._game.maskChanged.connect(self.label_word.setText) self._game.gameOver.connect(self._game_over) self._game.gameOver.connect(lambda result: self.label_word.setText(self._game.word)) self._result_dialog = GameResultDialogWrapper(parent=self) self.label_status.setPixmap(QPixmap(_image_logo_path)) self.pb_new_game.clicked.connect(self._new_game) self.pb_show_world.clicked.connect(lambda: print(f"word = {self._game.word}"))
def __init__(self, old_widget, new_widget, duration=300): super().__init__(new_widget) pr = QtWidgets.QApplication.instance().devicePixelRatio() self.old_pixmap = QPixmap(new_widget.size() * pr) self.old_pixmap.setDevicePixelRatio(pr) old_widget.render(self.old_pixmap) self.timeline = QtCore.QTimeLine() self.timeline.valueChanged.connect(self.animate) self.timeline.finished.connect(self.close) self.timeline.setDuration(duration) self.timeline.start() self.resize(new_widget.size()) self.show()
def displayMediaFile(self): """Display the selected media file on the QLabel. Used instead of the itemClicked signal to handle whether the user clicks on an item or if arrow keys are used to navigate the items in the tree.""" # Check the state of the movie, i.e. check if a movie is playing. If it is, # stop the movie if self.movie.state() == QMovie.MovieState.Running: self.stopMovie() # Get the text from the QLineEdit, folder_line, and concatenate it with # the selected item's text column = self.files_tree.currentColumn() media_location = self.folder_line.text() + "/" + self.files_tree.selectedItems()[0].text(column) if media_location.split(".")[1] == "gif": self.movie.setFileName(media_location) # Check if image data is valid before playing if self.movie.isValid(): # Use setMovie() to set the label's contents as the selected GIF self.media_label.setMovie(self.movie) self.startMovie() # Call method to begin playing else: # Disable all buttons when an image is selected self.disableMovieButtons() # Set the label's pixmap (have the image fit the current size of the image label) self.media_label.setPixmap(QPixmap(media_location).scaled(self.media_label.size(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation))
def toqpixmap(im): # # This doesn't work. For now using a dumb approach. # im_data = _toqclass_helper(im) # result = QPixmap(im_data["size"][0], im_data["size"][1]) # result.loadFromData(im_data["data"]) qimage = toqimage(im) return QPixmap.fromImage(qimage)
def convertToRGB(self): """Convert image to RGB format.""" if self.image.isNull() == False: converted_img = self.image.convertToFormat(QImage.Format_RGB32) #self.image = converted_img self.image = QImage(converted_img) self.setPixmap(QPixmap().fromImage(converted_img)) self.repaint()
def getIcon(path): pixmap = QPixmap(path) mask = pixmap.createMaskFromColor(QColor('blue'), QtCore.Qt.MaskMode.MaskOutColor) pixmap.fill((QColor(color))) pixmap.setMask(mask) return QtGui.QIcon(pixmap)
def setImage(self): """Assign image path as pixmap. Returns: bool: True if succeeded """ pixmap = QPixmap(self.path()) self.setPixmap(pixmap) return True
def convertToGray(self): """Convert image to grayscale.""" if self.image.isNull() == False: converted_img = self.image.convertToFormat( QImage.Format_Grayscale16) #self.image = converted_img self.image = QImage(converted_img) self.setPixmap(QPixmap().fromImage(converted_img)) self.repaint()
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 setUpMainWindow(self): """Set up the application's main window and widgets.""" self.movie = QMovie() # Create movie object self.media_label = QLabel() # Create label to place images/GIFs on self.media_label.setPixmap(QPixmap("icons/image_label.png")) self.media_label.setFrameShape(QFrame.Shape.StyledPanel) self.media_label.setAlignment(Qt.AlignmentFlag.AlignCenter) self.setCentralWidget(self.media_label)
def display_image(self, img: QImage, window="baseImage"): """ Display the image on a window - which is a label specified in the GUI .ui file """ display_label: QLabel = getattr(self, window, None) if display_label is None: raise ValueError(f"No such display window in GUI: {window}") display_label.setPixmap(QPixmap.fromImage(img)) display_label.setScaledContents(True)
def run(self): try: yt = YouTube(self.url) # load thumbnail image pixmap = QPixmap() pixmap.loadFromData(urlopen(str(yt.thumbnail_url)).read()) # emitting the response signal self.worker_response.emit(( yt, pixmap, yt.title, yt.author, yt.length, yt.publish_date, # populate a list of progressive mp4 resolutions for the download options [f'{res.resolution} - {round(res.filesize/1.049e+6, 1)}MB' for res in yt.streams.filter(progressive='true', file_extension='mp4').order_by('resolution')] )) except: # emitting the error signal self.worker_err_response.emit()
def toqpixmap(im): # # This doesn't work. For now using a dumb approach. # im_data = _toqclass_helper(im) # result = QPixmap(im_data["size"][0], im_data["size"][1]) # result.loadFromData(im_data["data"]) # Fix some strange bug that causes if im.mode == "RGB": im = im.convert("RGBA") qimage = toqimage(im) return QPixmap.fromImage(qimage)
def changeHue(self): for row_pixel in range(self.image.width()): for col_pixel in range(self.image.height()): current_val = QColor(self.image.pixel(row_pixel, col_pixel)) hue = current_val.hue() current_val.setHsv(hue, current_val.saturation(), current_val.value(), current_val.alpha()) self.image.setPixelColor(row_pixel, col_pixel, current_val) self.setPixmap(QPixmap().fromImage(self.image))
def show_qr(self, qr: bytes): title_label = QLabel("请使用微信扫描小程序码完成登陆") title_label.setStyleSheet( "QLabel{color:#ffe3ed;border:none;background-color:transparent;border-radius:5px;}" ) title_label.setAlignment(Qt.Alignment.AlignCenter) title_label.setFixedHeight(20) qr_label = QLabel() pixmap = QPixmap() pixmap.loadFromData(qr) qr_label.setPixmap(pixmap) qr_label.setStyleSheet( "QLabel{color:#ffe3ed;border:none;background-color:transparent;border-radius:5px;}" ) layout_ = QVBoxLayout() layout_.addWidget(title_label, 1) layout_.addWidget(qr_label, 9) self.qr_dialog = QWidget(self) self.qr_dialog.setLayout(layout_) self.main_layout.addWidget(self.qr_dialog, 1, 1, Qt.Alignment.AlignCenter) self.qr_dialog.show()