def on_load_button_clicked(self): if self.filed.exec(): with Image(filename=self.filed.selectedFiles()[0]) as image: self.image = image.make_blob() pixmap = QPixmap(0, 0) pixmap.loadFromData(self.image) self.image_container.setPixmap(pixmap)
def __init__(self, data, **kwargs): super().__init__(**kwargs) self.setupUi(self) filename, type_, links = data pixmap = QPixmap() LOGGER.debug('load thumbnail from picflash') thumbnail = get(links['thumbnail']) pixmap.loadFromData(thumbnail.content) self.pixmap = pixmap.scaled(150, 150, Qt.KeepAspectRatio) self.label_picture.setPixmap(self.pixmap) filename = path.split(filename)[1] if len(filename) > 50: filename = filename[:50] + ' … ' + filename[-4:] self.groupBox.setTitle(filename) self.lineEdit_sharelink.setText(links['sharelink']) self.lineEdit_hotlink.setText(links['hotlink']) self.lineEdit_deletelink.setText(links['delete_url']) self.lineEdit_preview.setText(links['thumbnail']) self.lineEdit_bb_preview.setText(links['bb_thumbnail']) self.lineEdit_bb_hotlink.setText(links['bb_hotlink']) self.lineEdit_sharelink.setCursorPosition(0) self.lineEdit_hotlink.setCursorPosition(0) self.lineEdit_deletelink.setCursorPosition(0) self.lineEdit_preview.setCursorPosition(0) self.lineEdit_bb_hotlink.setCursorPosition(0) self.lineEdit_bb_preview.setCursorPosition(0)
def __init__(self, parent, image=None): super().__init__(parent) self.image_url = None self.image = image self.filed = QFileDialog(parent) self.filed.setFileMode(QFileDialog.ExistingFile) vertical_layout = QtWidgets.QGridLayout(self) vertical_layout.setObjectName("image") pixmap = QPixmap(0, 0) if self.image is not None: pixmap.loadFromData(self.image) self.image_container = QtWidgets.QLabel(self) self.image_container.setPixmap(pixmap) vertical_layout.addWidget(self.image_container, 0, 0, 2, 2) load_button = QtWidgets.QPushButton(self) load_button.setText("Load Image") load_button.setObjectName("load_button") load_button.clicked.connect(self.on_load_button_clicked) vertical_layout.addWidget(load_button, 0, 2, 1, 1) clear_button = QtWidgets.QPushButton(self) clear_button.setText("Clear Image") clear_button.setObjectName("clear_button") clear_button.clicked.connect(self.on_clear_button_clicked) vertical_layout.addWidget(clear_button, 1, 2, 1, 1)
def on_imagesTree_currentItemChanged(self, current, previous): """ Private slot to show a preview of the selected image. @param current current image entry (QTreeWidgetItem) @param previous old current entry (QTreeWidgetItem) """ if current is None: return imageUrl = QUrl(current.text(1)) if not imageUrl.host(): imageUrl.setHost(QUrl(self.siteAddressLabel.text()).host()) imageUrl.setScheme(QUrl(self.siteAddressLabel.text()).scheme()) import Helpviewer.HelpWindow cache = Helpviewer.HelpWindow.HelpWindow.networkAccessManager().cache() if cache: cacheData = cache.data(imageUrl) else: cacheData = None pixmap = QPixmap() invalidPixmap = False scene = QGraphicsScene(self.imagePreview) if not cacheData: invalidPixmap = True else: pixmap.loadFromData(cacheData.readAll()) if pixmap.isNull(): invalidPixmap = True if invalidPixmap: scene.addText(self.tr("Preview not available.")) else: scene.addPixmap(pixmap) self.imagePreview.setScene(scene)
def show_login_auth_code(self): img_data = self._my12306.auth_code_img('login') pixmap = QPixmap() pixmap.loadFromData(QByteArray(img_data)) self.lb_auth_img.setPixmap(pixmap) self.lb_auth_img.setScaledContents(True) self.lb_auth_img.show()
def show_buy_auth_image(self): img_data = self._my12306.auth_code_img('passenger') pixmap = QPixmap() pixmap.loadFromData(QByteArray(img_data)) self.lb_buy_img.setPixmap(pixmap) self.lb_buy_img.setScaledContents(True) self.lb_buy_img.show()
def on_item_selected(self,index): photo = self.photos[index.row()] if DEBUG: print(photo.title) self.detail_title.setText("Photo: " + photo.title) self.detail_embedding.setPlainText(self.gen_markdown(photo)) q = QPixmap() q.loadFromData(photo.thumb) self.detail_thumb.setPixmap(q)
def generate_qr_code_finished(self, img): buf = BytesIO() img.save(buf, "PNG") qt_pixmap = QPixmap() qt_pixmap.loadFromData(buf.getvalue(), "PNG") self.ui_qr_code.spinner.stop() self.ui_qr_code.qcode.setMargin(2) self.ui_qr_code.qcode.setPixmap(qt_pixmap)
def _set_col_name(self, col: int, pkg: PackageView): item = QTableWidgetItem() item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) name = pkg.model.get_display_name() if name: item.setToolTip('{}: {}'.format(self.i18n['app.name'].lower(), pkg.model.get_name_tooltip())) else: name = '...' item.setToolTip(self.i18n['app.name'].lower()) if len(name) > NAME_MAX_SIZE: name = name[0:NAME_MAX_SIZE - 3] + '...' if len(name) < NAME_MAX_SIZE: name = name + ' ' * (NAME_MAX_SIZE - len(name)) item.setText(name) icon_path = pkg.model.get_disk_icon_path() if pkg.model.installed and pkg.model.supports_disk_cache( ) and icon_path: if icon_path.startswith('/'): if os.path.isfile(icon_path): with open(icon_path, 'rb') as f: icon_bytes = f.read() pixmap = QPixmap() pixmap.loadFromData(icon_bytes) icon = QIcon(pixmap) self.icon_cache.add_non_existing( pkg.model.icon_url, { 'icon': icon, 'bytes': icon_bytes }) else: icon = QIcon(pkg.model.get_default_icon_path()) else: try: icon = QIcon.fromTheme(icon_path) self.icon_cache.add_non_existing(pkg.model.icon_url, { 'icon': icon, 'bytes': None }) except: icon = QIcon(pkg.model.get_default_icon_path()) elif not pkg.model.icon_url: icon = QIcon(pkg.model.get_default_icon_path()) else: icon_data = self.icon_cache.get(pkg.model.icon_url) icon = icon_data['icon'] if icon_data else QIcon( pkg.model.get_default_icon_path()) item.setIcon(icon) self.setItem(pkg.table_index, col, item)
def processIcon(icon_data): """ Create icon pixmap object from raw data """ pix = QPixmap() icon = QIcon() pix.loadFromData(icon_data) icon.addPixmap(pix) return icon
def qrcode(self): url = self.upload(self.aktueller_beleg) proc = subprocess.run(['qrencode', '-o', '-', '-s', '12', '-d', '72', '-t', 'PNG', url], stdout=subprocess.PIPE) image = proc.stdout icon = QPixmap(250, 250) icon.loadFromData(image, 'png') self.ui.button_qrcode.setIcon(QIcon(icon)) self.ui.button_qrcode.setIconSize(QSize(250,250)) self.ui.button_qrcode.setEnabled(False)
def drawIcon(self, data: bytes): pixmap = QPixmap() pixmap.loadFromData(data) scaled = pixmap.scaledToHeight(70, Qt.SmoothTransformation) icon = QIcon() # アイテム選択時にアイコンが青くならないように、normalとselectedに同じ画像を登録する。 icon.addPixmap(scaled, QIcon.Normal) icon.addPixmap(scaled, QIcon.Selected) self.setIcon(icon)
class ImageViewer(QWidget): """ Contact window """ def __init__(self, title, image, default_email=None): super(ImageViewer, self).__init__() self.setStyleSheet( "background-color:#315d90; font: 12pt Helvetica; color: white") self.setWindowTitle("Image Viewer - Photo Crypto") self.src_image = image self.default_email = default_email self.pixmap = QPixmap() self.pixmap.loadFromData(self.src_image.to_bytes()) self.image = QLabel(self) self.image.setPixmap(self.pixmap) self.resize(self.pixmap.width() + 50, self.pixmap.height() + 120) self.image.move(25, 50) self.label = QLabel(title, self) self.label.resize(self.label.sizeHint().width(), self.label.sizeHint().height()) self.label.move(self.width() // 2 - self.label.width() // 2, 10) self.save_button = QPushButton("save", self) self.share_button = QPushButton("share", self) self.save_button.resize(self.share_button.sizeHint().width(), self.share_button.sizeHint().height()) self.save_button.move( self.width() // 2 - self.share_button.sizeHint().width() - 20, self.height() - self.share_button.sizeHint().height() - 20) self.save_button.setStyleSheet(blue_button_style(height=30)) self.save_button.clicked.connect(self.save_image) self.share_button.resize(self.share_button.sizeHint().width(), self.share_button.sizeHint().height()) self.share_button.move( self.width() // 2 + 20, self.height() - self.share_button.sizeHint().height() - 20) self.share_button.setStyleSheet(blue_button_style(height=30)) self.share_button.clicked.connect(self.share_image) def save_image(self): dialog = QFileDialog() dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setNameFilters([ "Image files (*bmp *.jpg *.jpeg *.jpe *.jfif *.png) | *.bmp; *.jpg; *.jpeg; *.jpe; *.jfif; *.png" ]) if dialog.exec_() == QFileDialog.Accepted: path = dialog.selectedFiles() self.src_image.save(*path) else: return # print(path) def share_image(self): save_path = join(WORKING_DIRECTORY, "data", "shared.bmp") self.src_image.save(save_path) email = self.default_email if self.default_email else "" subject = "Encrypted Image" outlook.open_outlook_client(save_path, email, subject)
def insert_data(self, meta): if not meta: return self.item_background = not self.item_background icon_data = meta['tag']['poster'] self.insertRow(0) if not icon_data: icon_data = utils.get_res_to_bytes(':/icons/others/empty.png') if icon_data: pixmap = QPixmap() pixmap.loadFromData(icon_data) i_width, i_heigh = utils.ITEM_WIDTH, utils.ITEM_HEIGHT if meta['tag']['xy']: i_width, i_heigh = meta['tag']['xy'] # icon = QIcon( # pixmap.scaled(i_width, i_heigh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)) item = self.cell(color=self.item_background) # item.setIcon(icon) # item.setSizeHint(QSize(i_width + 5, i_heigh)) pixmap = pixmap.scaled(i_width, i_heigh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) # self.setImage(0, 0, pixmap) # self.setItem(0, 0, item) # item.setData(Qt.UserRole, meta) # item.setTextAlignment(Qt.AlignCenter) item.setData(Qt.DecorationRole, pixmap) self.setItem(0, 0, item) item = self.cell(text=meta.get('tag').get('video_id'), color=self.item_background) item.setData(Qt.UserRole, meta) self.setItem(0, 1, item) title = '' if '标题' in meta: title = meta['标题'] if '电视节目标题' in meta: title = meta['电视节目标题'] if '集标题' in meta: title = meta['集标题'] item = self.cell(text=utils.get_screen_width(title, 100), color=self.item_background) self.setItem(0, 2, item) item = self.cell(text=meta.get('tag').get('tip'), color=self.item_background) self.setItem(0, 3, item) item = self.cell(text=meta.get('tag').get('dital_url'), color=self.item_background) self.setItem(0, 4, item)
class CoverLabel(QLabel): def __init__(self, parent, cover): super().__init__(parent) self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.setText("Drop a cover...") self.setAcceptDrops(True) self.cover_data = cover self.cover = None self._set_cover() def dragEnterEvent(self, event): if event.mimeData().hasUrls(): event.acceptProposedAction() def dropEvent(self, event): url = event.mimeData().urls()[0] if url.scheme() == "file": self.from_file(url.path()) return try: self.cover_data = util.http_get(url.toString()) self._set_cover() except Exception as e: QMessageBox.critical(self, "Error", f"Error downloading {url}: {e}.") def _set_cover(self): if not self.cover_data: return self.cover = QPixmap() self.cover.loadFromData(self.cover_data) size = self.cover.size() self.setToolTip(f"{size.width()} x {size.height()}") self._scale_cover() def _scale_cover(self): if not self.cover: return h = self.height() w = self.width() scaled = self.cover.scaled(w, h, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(scaled) def resizeEvent(self, e): super().resizeEvent(e) self._scale_cover() def from_file(self, path): self.cover_data = open(path, "rb").read() self._set_cover()
def _update_display(self): """ Set the Pixmap of this widget to display the most appropriate image. """ product_pixmap = QPixmap() if self.image: product_pixmap.loadFromData(self.image) else: product_pixmap.loadFromData(self.fallback_image) self.setPixmap(product_pixmap)
def run(self): try: for index,listItem in enumerate(self.list): pixmap = QPixmap() pic = requests.get(listItem[0]).content pixmap.loadFromData(pic) self.signal_load_pic.emit(index,pixmap) except: print(sys.exc_info()[0]) print(sys.exc_info()[1])
def render_dependency_svg(self, index): qp = QPixmap() qp.loadFromData(self.convert_svg_to_png(self.dependency_svgs[index])) self.form.dependency_image_label.setPixmap(qp) self.update_dependency_index_text() self.form.dependency_scrollarea.horizontalScrollBar().setValue( self.form.dependency_scrollarea.horizontalScrollBar().maximum() / 2) self.form.dependency_scrollarea.verticalScrollBar().setValue( self.form.dependency_scrollarea.verticalScrollBar().maximum())
def on_finished(self, reply): if reply in self.replyMap: row = self.replyMap.get(reply) del self.replyMap[reply] pixmap = QPixmap() pixmap.loadFromData(reply.readAll()) image = QLabel() image.setPixmap(pixmap) self.ui.tableWidget.setCellWidget(row, 0, image) self.ui.tableWidget.setRowHeight(row, 120)
def updateView(self): coordinates = coordinates_by_address(self.current_city) if coordinates is None: return False image = get_bytes_map(coordinates, choice(self.map_types)) if image is None: return False pixmap = QPixmap() pixmap.loadFromData(image) self.setPixmap(pixmap)
def image_code_back(self): """ 获取到image_code """ reply = self.sender() data = reply.readAll().data() reply.deleteLater() del reply pix_map = QPixmap() pix_map.loadFromData(data) self.login_widget.image_code_show.setPixmap(pix_map) # 登录验证码 self.register_widget.image_code_show.setPixmap(pix_map) # 注册验证码
def replyFinished(self, reply): qbytearray = reply.readAll() img = QPixmap() img.loadFromData(qbytearray) h = self.centralWidget().height() # img=img.scaledToHeight(h) self.scroll = Scroll(img) self.ptoolbar.setVisible(False) self.setCentralWidget(self.scroll) self.scroll.signal.rebuildScreen.connect(self.test)
def loadCapcha(self, url): # url = 'http://m.vk.com/captcha.php?sid=309220810446&dif=1' data = urllib.request.urlopen(url).read() # pix = QPixmap('captcha.jpg') pix = QPixmap() pix.loadFromData(data) # self.label_img.setText(str(pix)) print(str(pix)) self.label_img.setPixmap(pix)
class ImgWidget(QLabel): def __init__(self, image, from_data=True, parent=None): super(ImgWidget, self).__init__(parent) if from_data: self.pixmap = QPixmap() self.pixmap.loadFromData(image) else: self.pixmap = QPixmap(image) self.setPixmap(self.pixmap) self.resize(self.sizeHint())
def updateMap(self): response = requests.get(self.static_api, params=self.static_params, timeout=0.4) pixmap = QPixmap() f = BytesIO(response.content) f.seek(0) pixmap.loadFromData(f.read()) self.map.setPixmap(pixmap)
def get_pictrue(url): try: req = requests.get(url) photo = QPixmap() photo.loadFromData(req.content) return photo except: msg_box = QMessageBox(QMessageBox.Warning, "响应超时", "网络连接超时") msg_box.show() sys.exit(app.exec_())
def downloadFinished(self): data = self.downloader.downloadedData() image = QPixmap() if data is not None or len(data) >= 0: image.loadFromData(data) if image.isNull(): image.load(self.no_poster) #broadcast the image, to all connected listeners self.result.emit(image)
def on_click_screenshot(self): self.image_data = take_screenshot() if self.image_data != None: pixmap = QPixmap() pixmap.loadFromData(self.image_data, "PNG") self.screenshot_image.setPixmap(pixmap) self.info_label.setText( 'Screenshot taken. Take another screenshot or save this one.') else: self.info_label.setText('Resource not found.')
def update_player_card(self, sprite, card_tuple): """ add a card to player hand """ pixmap = QPixmap() pixmap.loadFromData(sprite, 'PNG') card_label = self.CardLabel(self, player=True) card_label.play_card_signal.connect(self.play_card) card_label.setPixmap(pixmap.scaled(card_label.width(), card_label.height()), card_tuple) self.player_card_labels.append(card_label) self.hand_layouts['self'].addWidget(card_label)
def ItemSelected(self): SelectedItems = self.ImageList.selectedItems() if len(SelectedItems) > 0: CurrentFileContent = SelectedItems[0].Base64String CurrentFileBinary = Base64Converters.GetBinaryFromBase64String( CurrentFileContent) ImagePixmap = QPixmap() ImagePixmap.loadFromData(CurrentFileBinary) self.ImageDisplay.setPixmap(ImagePixmap) self.ImageDisplay.resize(self.ImageDisplay.pixmap().size())
def show_frame(self, label: QLabel, index): if index >= len(self.frames) or index == -1: pixmap = QPixmap(":/newPrefix/placeholder.png") pixmap = pixmap.scaled(label.width(), label.height()) label.setPixmap(pixmap) else: pixmap = QPixmap() pixmap.loadFromData(self.frames[index]) pixmap = pixmap.scaled(label.width(), label.height(), Qt.KeepAspectRatio) label.setPixmap(pixmap)
def show_poster(self, label: QLabel): if self.poster is not None: pixmap = QPixmap() pixmap.loadFromData(self.poster) pixmap = pixmap.scaled(label.width(), label.height(), Qt.KeepAspectRatio) label.setPixmap(pixmap) else: pixmap = QPixmap(":/newPrefix/placeholder.png") pixmap = pixmap.scaled(label.width(), label.height()) label.setPixmap(pixmap)
def __init__(self, silent): super(UpdateDialog, self).__init__() self.setupUi(self) self.layout().setSizeConstraint(QLayout.SetFixedSize) self.silent = silent self.update_data_thread = GetUpdateDataThread() self.download_update_thread = DownloadUpdateThread() self.download_update_thread.chunk_downloaded.connect( self.on_chunk_downloaded) self.download_update_thread.download_complete.connect( self.run_installer) self.download_update_thread.error.connect(self.on_downloader_error) self.update_data_thread.update_available.connect(self.show_update_text) self.update_data_thread.no_update.connect(self.on_no_update) self.update_data_thread.error.connect(self.on_updater_error) self.downloadButton.clicked.connect(self.download_and_run) self.closeButton.clicked.connect(self.update_data_thread.exit) self.closeButton.clicked.connect(self.download_update_thread.exit) self.closeButton.clicked.connect(self.closeEvent) check_on_startup = CONFIG.getboolean("Options", "check_updates_on_startup", fallback=True) CONFIG["Options"][ "check_updates_on_startup"] = "yes" if check_on_startup else "no" save_config() self.checkOnStartupCheckBox.setCheckState( Qt.Checked if check_on_startup else Qt.Unchecked) self.checkOnStartupCheckBox.stateChanged.connect( self.on_startup_check_option_change) icon = QPixmap() icon.loadFromData(APP_ICON) self.setWindowIcon(QIcon(icon)) self.setWindowTitle(tr_str("updater_dialog.title")) self.checkLabel.setText(tr_str("updater_dialog.checking_updates")) self.checkOnStartupCheckBox.setText(tr(self.checkOnStartupCheckBox)) self.downloadButton.setText(tr(self.downloadButton)) self.closeButton.setText(tr(self.closeButton)) self.changelogBrowser.hide() self.progressLabel.hide() self.progressBar.hide() self.downloadButton.hide() self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) self.adjustSize()
def initialize_sprites(self): data, script = self.data, self.script_module sprites = {} for k in data["sprites"].keys(): sprite = data["sprites"][k] if sprite["script"]["class_name"] != "": sprite_instance = Misc.get_sprite( script, sprite["script"]["class_name"]) else: sprite_instance = Sprite() sprite_instance.class_name = sprite["script"]["class_name"] sprite_instance.input = self.input sprite_instance.sound = self.sound sprite_instance.game_application = self sprite_position = sprite["transform"]["position"] sprite_instance.transform.position = Vector2( sprite_position["x"], sprite_position["y"]) sprite_instance.render.enable = sprite["render"]["enable"] sprite_instance.render.layer = sprite["render"]["layer"] sprite_instance.render.scale = sprite["render"]["render_scale"] sprite_instance.is_text = sprite["is_text"] if not sprite["is_text"]: sprite_instance.render.flipX = sprite["render"]["flipX"] sprite_instance.render.default_frame = sprite["render"][ "default_frame"] sprite_instance.collision.enable = sprite["collision"][ "enable"] sprite_instance.collision.size.x = sprite["collision"][ "x_size"] sprite_instance.collision.size.y = sprite["collision"][ "y_size"] sprite_instance.animator.triggers = sprite["sprite"][ "triggers"] sprite_instance.animator.animations = sprite["sprite"][ "animations"] sprite_instance.animator.transitions = sprite["sprite"][ "transitions"] pixmap = QPixmap() pixmap.loadFromData( base64.b64decode(sprite["sprite"]["image"]["data"])) slice_width = pixmap.width( ) // sprite["sprite"]["image"]["col"] slice_height = pixmap.height( ) // sprite["sprite"]["image"]["row"] for y in range(sprite["sprite"]["image"]["row"]): for x in range(sprite["sprite"]["image"]["col"]): frame = pixmap.copy( QRect(x * slice_width, y * slice_height, slice_width, slice_height)) sprite_instance.animator.frames.append(frame) else: sprite_instance.context = sprite["content"] sprite_instance.script_instance = sprite_instance sprites[k] = sprite_instance return sprites
def load_custom_artwork(self): image_file_name, _ = QFileDialog.getOpenFileName( self, "Select Artwork File", None, "Images (*.png *.jpg)") with open(image_file_name, 'rb') as f: self.artwork_bytes = f.read() artwork = QPixmap() artwork.loadFromData(self.artwork_bytes) self.artwork_itunes_label.setPixmap(artwork.scaled(150, 150))
def set_team_logo(self, team, url): req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) data = urlopen(req).read() pixmap = QPixmap() pixmap.loadFromData(data) if team == TeamIndex.TEAM_ONE: self.t1_image_label.setPixmap(pixmap) self.t1_image_label.show() elif team == TeamIndex.TEAM_TWO: self.t2_image_label.setPixmap(pixmap) self.t2_image_label.show()
def _pixmap(self, dataBytes, h=200, w=150): pixmap = QPixmap() pixmap.loadFromData(dataBytes) if h is None or w is None: return pixmap height = pixmap.size().height() width = pixmap.size().width() if width == 0 or height == 0: return pixmap return pixmap.scaled(w, h, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
def showImage(self): self.audioFile = mutagen.File(self.song[0]) pixmap_1 = QPixmap('Plug_2.png').scaled(300, 300) try: photo = self.audioFile.tags.getall('APIC')[0].data pixmap = QPixmap() pixmap.loadFromData(photo) pixmap.scaled(300, 300) self.PictureAlbum.setPixmap(pixmap) except IndexError: self.PictureAlbum.setPixmap(pixmap_1)
def updateAppQRCode(self, target, qrCodePng): qrCodePixmap = QPixmap() qrCodePixmap.loadFromData( qrCodePng, 'png', QtCore.Qt.MonoOnly ) border = 10 #px qrCodePixmap = qrCodePixmap.copy(QtCore.QRect( border, border, qrCodePixmap.width() - border*2, qrCodePixmap.height() - border*2 )) target.setPixmap(qrCodePixmap) target.show()
def setImageMemSrc(self, img, width, height): pic = QPixmap() pic.loadFromData(img.save2Bytes()) self.pixmap = pic if width is not None and height is not None: pic = pic.scaled( width, height, Qt.KeepAspectRatio ) self.setPixmap(pic) # 修改鼠标样式 self.setCursor(Qt.PointingHandCursor)
def load_icon(self): global session #sys.stdout.flush() pixmap = QPixmap() #r = yield from aiohttp.request('get',self.card.url) #pix = yield from r.read() #pixmap.loadFromData(pix) pixmap.loadFromData(session.get(self.card.url).content) #pixmap.setDevicePixelRatio(2) #self.pixmap = pixmap.scaled(100,100) self.pixmap = pixmap self.repaint()
def __setImagePixmapToIamgeLabel(self,img,bytesblag=True): """ 设置预览图片,强行定义其大小为768,432 """ pixmap = QPixmap() if bytesblag == True: pixmap.loadFromData(img) else: pixmap.load(img) pixmap = pixmap.scaled(768,432) self.image_label.setPixmap(pixmap) self.image_label.setScaledContents(True)
def data(self, index, role=Qt.DisplayRole): if role == Qt.DecorationRole: if index.row() < 0: return None iconIndex = self.index(index.row(), self.fieldIndex('icon')) if not self.data(iconIndex) or self.data(iconIndex).isNull(): return None icon = QPixmap() icon.loadFromData(self.data(iconIndex)) return icon return super().data(index, role)
def __init__(self, parent, image=None): super().__init__(parent) self.image = image vertical_layout = QtWidgets.QGridLayout(self) vertical_layout.setObjectName("image") pixmap = QPixmap(0, 0) if self.image is not None: pixmap.loadFromData(self.image) self.image_container = QtWidgets.QLabel(self) self.image_container.setPixmap(pixmap) vertical_layout.addWidget(self.image_container, 0, 0, 2, 2)
def __init__(self, parent, image): super().__init__(parent) self.parent = parent self.image = image vertical_layout = QtWidgets.QGridLayout(self) vertical_layout.setObjectName("image") pixmap = QPixmap(100, 100) if self.image[1] is not None: pixmap.loadFromData(self.image[1]) self.setIcon(QIcon(pixmap)) self.clicked.connect(self.on_image_clicked)
def store_data(self, id, data): id = id.replace('/', '_') directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') makedirs(directory) pixmap = QPixmap() if data is not None and pixmap.loadFromData(data): image_size = pixmap.size() if image_size.width() > self.max_size or image_size.height() > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if imghdr.what(None, data) != 'png' or pixmap.size() != image_size: buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data icon.content_type = 'image/png' else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def QPixmapFactory(image): font = image.font if font is None: return None layer = image.layer images = font.images if image.fileName not in images: return None imageColor = image.color data = images[image.fileName] pixmap = QPixmap() pixmap.loadFromData(data) if imageColor is not None: colorEffect = QGraphicsColorizeEffect() colorEffect.setColor(colorToQColor(imageColor)) colorEffect.setStrength(.8) return applyEffectToPixmap(pixmap, colorEffect) return pixmap
def QPixmapFactory(image): font = image.font if font is None: return None layer = image.layer images = font.images if image.fileName not in images: return None imageColor = image.color # TODO: are we really doing this? if imageColor is None: imageColor = layer.color data = images[image.fileName] pixmap = QPixmap() pixmap.loadFromData(data) if imageColor is not None: colorEffect = QGraphicsColorizeEffect() colorEffect.setColor(imageColor) return applyEffectToPixmap(pixmap, colorEffect) return pixmap
def setHead(self, qq, name, head): """设置头像""" self.blog_head_label.setToolTip(name) pixmap = QPixmap() pixmap.loadFromData(head) path = os.path.join(Settings().dataDir, "images", "head.png") # 头像保存路径 pixmap.save(path, format = "png") if os.path.exists(path): # 如果存在 # 匹配出样式 qss = re.findall("#blog_head_label(.*?)}", self.styleSheet(), re.S) if qss: # 修改头像的样式 qss = "#blog_head_label" + re.sub("url\((.*?)\)", "url(%s/images/head.png)" % Settings().dataDir, qss[0]) + "}" self.blog_head_label.setStyleSheet(qss) return # 不存在则直接处理 # ---变成圆形--- pixmap = self.getRoundPixmap(pixmap) #------------- # 调整大小 pixmap = pixmap.scaled(self.blog_head_label.size()) self.blog_head_label.setIcon(QIcon(pixmap)) self.blog_head_label.setIconSize(self.blog_head_label.size())
def requestPixmap(self, id, size): row = int(id) if row < 0 or row >= self.model.rowCount(): return QPixmap(), QSize() data = self.model.imageData(row) if data == None: return QPixmap(), QSize() pixmap = QPixmap() if not pixmap.loadFromData(data): return QPixmap(), QSize() return pixmap, pixmap.size()
def initUI(self): xkcd_array = requests.get("http://dynamic.xkcd.com/api-0/jsonp/comic/").json() self.setGeometry(300, 300, 1000, 500) title = xkcd_array['title'].encode("latin-1").decode("utf-8") self.setWindowTitle('XKCD - '+title) print(type(title)) alt = xkcd_array['alt'].encode("latin-1").decode("utf-8") self.setToolTip(alt) url = xkcd_array['img'] data = urllib.request.urlopen(url).read() img = QPixmap() img.loadFromData(data) self.resize(img.width(), img.height()) lbl2 = QLabel('asd', self) lbl2.setPixmap(img) self.show()
def QPixmapFactory(image): font = image.font if font is None: return layer = image.layer images = font.images if image.fileName not in images: return None imageColor = image.color if imageColor is None: imageColor = layer.color data = images[image.fileName] data = QPixmap.loadFromData(data, len(data)) if imageColor is None: return data # XXX: color filter left unimplemented return data """
def get(self, id): id = id.replace('/', '_') try: return self.iconmap[id] except KeyError: pixmap = QPixmap() filename = ApplicationData.get(os.path.join('images', id + '.png')) try: with open(filename, 'rb') as f: data = f.read() except (IOError, OSError): data = None if data is not None and pixmap.loadFromData(data): icon = QIcon(pixmap) icon.filename = filename icon.content = data icon.content_type = 'image/png' else: icon = None return self.iconmap.setdefault(id, icon)
def getIcon(self, section, value): if section in ('payplace', 'saleplace'): section = 'place' elif section in ('obversecolor', 'reversecolor'): section = 'color' elif section in ('edge', 'signaturetype'): section = 'edge' table_name = "ref_%s" % section if table_name in self.sections_with_icons: sql = "SELECT icon FROM %s WHERE value=?" % table_name query = QtSql.QSqlQuery(sql, self.db) query.addBindValue(value) query.exec_() if query.first(): data = query.record().value(0) if data: pixmap = QPixmap() if pixmap.loadFromData(data): icon = QIcon(pixmap) return icon return None
def end(qq, name, image): pixmap = QPixmap() pixmap.loadFromData(image) t.setPixmap(pixmap.scaled(30, 30)) t.setToolTip(name)
class WindowSR(QMainWindow): """Main window of SoundRain""" bad_id = pyqtSignal() def __init__(self): super().__init__() self.initWin() self.init_client_id() def initWin(self): """Create main parts of the window""" # Main Window self.setFixedSize(900, 500) self.center() self.setWindowTitle("SoundRain") self.setWindowIcon(QIcon('soundrainlogo.jpg')) # Central Widget self.central_widget = QWidget() self.setCentralWidget(self.central_widget) # QVBox stocking every row self.vertical_grid = QVBoxLayout() # First row: URL request row_url = QHBoxLayout() label_url = QLabel("URL:", self) self.text_url = QLineEdit(self) self.text_url.textChanged.connect(self.block_dl) self.but_url = QPushButton("Search", self) self.but_url.clicked.connect(self.check_url) row_url.addWidget(label_url) row_url.addWidget(self.text_url) row_url.addWidget(self.but_url) # Row of separation 1 row_sep1 = QHBoxLayout() line_sep = QFrame() line_sep.setFrameShape(QFrame.HLine) row_sep1.addWidget(line_sep) # Second row (splitted screen between cover image and music info): row_split = QHBoxLayout() # Cover image column_image = QVBoxLayout() self.label_image = QLabel(self) self.label_image.setMaximumHeight(280) self.label_image.setMinimumHeight(280) self.label_image.setMaximumWidth(280) self.label_image.setMinimumHeight(280) self.cover = QPixmap(280, 280) self.cover.load("unknownperson.jpg") self.label_image.setPixmap(self.cover) column_image.addWidget(self.label_image) # music info column_info = QVBoxLayout() label_name = QLabel("Name", self) self.name = QLineEdit(self) label_artist = QLabel("Artist", self) self.artist = QLineEdit(self) label_album = QLabel("Album", self) self.album = QLineEdit(self) label_genre = QLabel("Genre", self) self.genre = QLineEdit(self) # -- column_info.addWidget(label_name) column_info.addWidget(self.name) column_info.addWidget(label_artist) column_info.addWidget(self.artist) column_info.addWidget(label_album) column_info.addWidget(self.album) column_info.addWidget(label_genre) column_info.addWidget(self.genre) # -- row_split.addLayout(column_image) row_split.addLayout(column_info) # Row of separation 2 row_sep2 = QHBoxLayout() line_sep2 = QFrame() line_sep2.setFrameShape(QFrame.HLine) row_sep2.addWidget(line_sep2) # Add the file location selection row row_file = QHBoxLayout() self.but_file = QPushButton("Save location", self) self.but_file.clicked.connect(self.open_f) self.text_file = QLineEdit(self.default_path(), self) row_file.addWidget(self.but_file) row_file.addWidget(self.text_file) # Row of separation 3 row_sep3 = QHBoxLayout() line_sep3 = QFrame() line_sep3.setFrameShape(QFrame.HLine) row_sep3.addWidget(line_sep3) # Download button row row_dl = QHBoxLayout() self.bar_dl = QProgressBar(self) self.bar_dl.setFixedSize(600, 30) self.bar_dl.setMaximum(100) self.bar_dl.setMinimum(0) self.bar_dl.hide() self.label_dl = QLabel(self) self.label_dl.hide() self.but_dl = QPushButton("Download", self) self.but_dl.clicked.connect(self.manage_download) self.but_dl.setDisabled(True) row_dl.addWidget(self.bar_dl) row_dl.addWidget(self.label_dl) row_dl.addStretch(1) row_dl.addWidget(self.but_dl) # Add every row to the vertical grid self.vertical_grid.addLayout(row_url) self.vertical_grid.addLayout(row_sep1) self.vertical_grid.addLayout(row_split) self.vertical_grid.addLayout(row_sep2) self.vertical_grid.addLayout(row_file) self.vertical_grid.addLayout(row_sep3) self.vertical_grid.addLayout(row_dl) # Set layout of the vertical grid to the central widget self.central_widget.setLayout(self.vertical_grid) self.show() def init_client_id(self): """Ask for client id if it as never been entered, else load it from register with QSettings""" self.client_id = None self.setting = QSettings(QSettings.UserScope, "BoBibelo", "SoundRain", self) if not self.setting.value("SR_bool"): # Setting never set self.client_id_box() self.setting.setValue("SR_bool", True) self.setting.setValue("SR_id", self.client_id) else: self.client_id = self.setting.value("SR_id") self.client = soundcloud.Client(client_id=self.client_id) def client_id_box(self): """Generate the client id box""" self.client_id_bo = QDialog(self) self.client_id_bo.setFixedSize(400, 200) self.client_id_bo.setModal(True) client_id_grid = QVBoxLayout() label_request = QLabel("Enter your Soundcloud Client ID:", self.client_id_bo) self.input_id = QLineEdit(self.client_id_bo) label_help = QLabel("<a href=\"http://bobibelo.github.io/soundrain/help.html\">Need help ?</a>", self.client_id_bo) label_help.setTextFormat(Qt.RichText); label_help.setTextInteractionFlags(Qt.TextBrowserInteraction); label_help.setOpenExternalLinks(True); self.got_id = False button_cancel = QPushButton("Cancel", self.client_id_bo) button_cancel.clicked.connect(self.reject_id) button_accept = QPushButton("Ok", self.client_id_bo) button_accept.clicked.connect(self.get_id) button_grid = QHBoxLayout() button_grid.addStretch(1) button_grid.addWidget(button_cancel) button_grid.addWidget(button_accept) client_id_grid.addWidget(label_request) client_id_grid.addWidget(self.input_id) client_id_grid.addWidget(label_help) client_id_grid.addLayout(button_grid) self.client_id_bo.setLayout(client_id_grid) self.client_id_bo.rejected.connect(self.reject_id) self.client_id_bo.exec_() def get_id(self): """Get client id from the qdialog""" self.client_id = self.input_id.text().strip() if len(self.client_id) != 0: self.got_id = True self.client_id_bo.close() def reject_id(self): """Quit app after user not giving client id""" if not self.got_id: self.close() sys.exit(1) def open_f(self): """Choose the directory where to save music""" self.dirname = QFileDialog.getExistingDirectory() if self.dirname and len(self.dirname) > 0: self.text_file.setText(self.dirname) def center(self): """Places window in the screen's center""" center_geo = self.frameGeometry() center_pos = QDesktopWidget().availableGeometry().center() center_geo.moveCenter(center_pos) self.move(center_geo.topLeft()) def check_url(self): """Test if the music url is correct and if so fill info""" url_pattern = "^https?://(www\.)?soundcloud\.com" if not re.match(url_pattern, self.text_url.text()): QMessageBox.about(self, "Invalid URL", "The requested URL is invalid: %s" % self.text_url.text()) else: self.but_dl.setDisabled(False) if "/sets/" in self.text_url.text(): # Is playlist self.artist.setText("Not available for playlist.") self.name.setText("Not available for playlist.") self.disable_input(True) elif len(self.text_url.text().split('/')) == 4: # Likes self.artist.setText("Not available for likes.") self.name.setText("Not available for likes.") self.disable_input(False) else: self.enable_input() self.get_music_info() def disable_input(self, bo): """Disable artist, and name in case of playlist""" if bo: self.is_playlist = True self.is_likes = False else: self.is_playlist = False self.is_likes = True self.artist.setDisabled(True) self.name.setDisabled(True) def enable_input(self): """Enable artist, and name after a playlist""" self.is_likes = False self.is_playlist = False self.artist.setDisabled(False) self.name.setDisabled(False) def get_track(self): """Returns track""" http_page = httplib2.Http() resp = http_page.request(self.url_str, "HEAD") if int(resp[0]["status"]) >= 400: QMessageBox.about(self, "Error URL", "URL doesn't exist.") return False try: self.track = self.client.get("/resolve", url=self.url_str) except: self.setting.setValue("SR_bool", False) self.init_client_id() self.get_track() return True def get_music_info(self): """Get music info, which will be stocked in self.track, and fill info""" self.url_str = self.text_url.text() if not self.get_track(): return if not self.is_playlist and not self.is_likes: self.artist.setText(self.track.user['username']) self.name.setText(self.track.title) url = self.modifiy_image_size() if url: self.image = requests.get(url).content self.cover.loadFromData(self.image) self.cover = self.cover.scaledToWidth(280) self.label_image.setPixmap(self.cover) else: # Get the last part of URL ( == to playlist name) self.album.setText(self.text_url.text().rsplit('/', 1)[-1]) if self.album.text() != "": self.text_file.setText("%s/%s" % (self.text_file.text(), self.album.text())) if not self.is_likes: self.genre.setText(self.track.genre) else: self.album.setText(self.track.username + "'s favorites") def modifiy_image_size(self): """Change artwork_url so the image can (potentially) look better""" artwork_url = self.track.artwork_url if not artwork_url: return None if "large" in artwork_url: return artwork_url.replace("large", "t500x500") else: return artwork_url def manage_download(self): """Manage download in case of playlist""" if self.is_playlist: playlist = self.client.get('/playlists/%s' % (self.track.id)) count = 1 self.label_dl.show() for song_url in playlist.tracks: self.label_dl.setText("%d / %d" % (count, len(playlist.tracks))) count += 1 self.url_str = song_url["permalink_url"] self.get_track() self.image = requests.get(self.modifiy_image_size()).content self.download() if len(playlist.tracks) == 0: self.fail_box() else: self.success_box() # Success box for playlist self.label_dl.hide() self.enable_input() elif self.is_likes: likes = self.client.get('/users/%s/favorites/' % (self.track.id), linked_partitioning=1, limit=200) set_likes = set() while True: try: link = likes.next_href except: break for like in likes.collection: set_likes.add(like) likes = self.client.get(link, linked_partitioning=1, limit=200) for like in likes.collection: set_likes.add(like) count = 1 self.label_dl.show() for like in set_likes: self.url_str = like.user['permalink_url'] self.track = like self.label_dl.setText("%d / %d" % (count, len(set_likes))) count += 1 self.image = requests.get(self.modifiy_image_size()).content self.download() sys.exit(0) else: self.success_box() # Success box for playlist self.label_dl.hide() self.enable_input() else: if self.download(): self.success_box() # Succes box for single song self.reset() def download(self): """Try to download a single song""" self.setDisabled(True) self.bar_dl.setDisabled(False) self.bar_dl.show() try: self.fi_mp3, headers = urllib.request.urlretrieve(self.create_url(), self.create_filename(), reporthook=self.reporthook) except: self.fail_box() self.setDisabled(False) self.bar_dl.hide() return False self.add_tags() self.setDisabled(False) self.bar_dl.hide() return True def fail_box(self): """Fail box for playlist and single song""" if self.is_playlist: QMessageBox.about(self, "Error Download", "Playlist '%s' failed to download." % self.text_url.text().rsplit('/', 1)[-1]) else: QMessageBox.about(self, "Error Download", "Download failed for song: %s" % self.track.title) def reset(self): """Reset all input & image after end of download""" self.text_url.setText("") self.artist.setText("") self.name.setText("") self.album.setText("") self.genre.setText("") self.image = None self.cover.load("unknownperson.jpg") self.label_image.setPixmap(self.cover) self.but_dl.setDisabled(True) self.text_file.setText(self.default_path()) def block_dl(self): """Disable download button if user change URL (forces him to re-'search')""" self.but_dl.setDisabled(True) def add_tags(self): """Add artists name, music name, album, genre, and cover""" # Set artist name, music name, album, and genre audio_file = EasyMP3(self.fi_mp3) audio_file.tags = None if self.is_playlist: audio_file["artist"] = self.track.user["username"] audio_file["title"] = self.track.title if self.is_likes: audio_file["artist"] = self.track.user["username"] audio_file["title"] = self.track.title else: audio_file["artist"] = self.artist.text() audio_file["title"] = self.name.text() audio_file["genre"] = self.genre.text() audio_file["album"] = self.album.text() audio_file.save() # Determine the mime artwork_url = self.modifiy_image_size() if not artwork_url: return mime = "image/jpeg" if ".png" in artwork_url: mime = "image/png" # Set cover audio_file = MP3(self.fi_mp3, ID3=ID3) audio_file.tags.add( APIC( encoding=3, mime=mime, type=3, desc="Cover", data=self.image ) ) audio_file.save() def success_box(self): """Display a sucess box""" if self.is_playlist: QMessageBox.about(self, "Success", "%s playlist has just been downloaded right into %s" % (self.text_url.text().rsplit('/', 1)[-1], self.text_file.text())) else: QMessageBox.about(self, "Success", "%s has just been downloaded right into %s" % (self.name.text(), self.text_file.text())) def create_url(self): url_str = "http://api.soundcloud.com/tracks/%s/stream?client_id=%s" % (self.track.id, self.client_id) return url_str def create_filename(self): path = self.text_file.text() if self.is_playlist or self.is_likes: name = self.track.title + ".mp3" else: name = self.name.text() + ".mp3" if not os.path.exists(path): os.makedirs(path) fi_str = os.path.join(path, name) return fi_str def default_path(self): """Set the default path""" list_user = os.listdir("/Users") for user in list_user: if user != "Shared" and user != ".localized": break else: user = "******" path = "/Users/" + user + "/Music" return path def reporthook(self, blocks_read, block_size, total_size): """Tracks the progress of music download""" if blocks_read == 0: self.bar_dl.setValue(0) else: amount_read = blocks_read * block_size percent = int((amount_read / total_size) * 100) # Percent of achieved download self.bar_dl.setValue(percent) QApplication.processEvents() return
class Widget(QMainWindow, client_form): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) self.refreshLabel.setVisible(False) self.client = Client(50000, 3000) self.refreshButton.clicked.connect(self.refresh) self.connectButton.clicked.connect(self.connect) self._graphics_scene = QGraphicsScene(self) self.graphicsView.setScene(self._graphics_scene) self._graphics_scene.mousePressEvent = self.mouse_pressed self.exit_action.triggered.connect(self.exit) self.help_action.triggered.connect(self.show_help) self.bullshit_action.triggered.connect(self.send_incorrect_message) self.viewlog_action.triggered.connect(self.open_log) self.connected = False def open_log(self): if os.uname().sysname == "Darwin": webbrowser.open("file:///" + os.path.abspath("./client.log")) else: webbrowser.open("./client.log") def exit(self): if self.connected: self.revert() self.client.disconnect() self.close() def show_help(self): mb = QMessageBox.information( self, "О программе", "Программа удаленного управления рабочим столом.\n\n" "Создатели:\n" "Алексей Абакумкин, ИУ7-72\n" "Роман Инфлянскас, ИУ7-71\n" "(c) 2014, Москва, МГТУ им. Н. Э. Баумана") def critical(self, msg, log=True): self.revert() QMessageBox.critical(self, "Ошибка", msg) if log: logging.error("{ip}\t{msg}\tОшибка".format(ip=self.client.ip, msg=msg)) def send_incorrect_message(self): if self.connected: try: self.client.send_incorrect_message() except: # mb = QMessageBox.critical(self, "Ошибка", "Сервер перестал отвечать") self.critical("Сервер перестал отвечать") def refresh(self): self.serverList.clear() self.refreshLabel.setVisible(True) self.repaint() for x in self.client.refresh_server_list(): self.serverList.addItem("{0}:{1}".format(x[0], x[1])) self.refreshLabel.setVisible(False) def connect(self): if self.connected: self.revert() self.client.disconnect() return try: login, login_ok = QInputDialog.getText(self, 'Логин', 'Введите логин:') if login_ok: passwd, password_ok = QInputDialog.getText(self, 'Пароль', 'Введите пароль:', 2) if password_ok: server_item = self.serverList.currentItem() try: address = server_item.text().split(":") except: # server_item = self.serverList.findItems('', 0)[0] self.serverList.setCurrentRow(0) server_item = self.serverList.currentItem() address = server_item.text().split(":") if self.client.connect_to_server(address, login, passwd): self.connectButton.setText("Отключиться") self.connected = True else: self.critical("Неверный логин или пароль!", log=False) # mb = QMessageBox.critical(self, "Ошибка", "Неверный логин или пароль!") except TimeoutError: self.critical("Сервер перестал отвечать") # mb = QMessageBox.critical(self, "Ошибка", "Сервер перестал отвечать") def revert(self): self._graphics_scene.clear() self.connectButton.setText("Присоединиться") self.connected = False def paintEvent(self, QPaintEvent): if self.connected: try: self.image_base_64 = self.client.recieve_screenshot() except TimeoutError: self.critical("Сервер перестал отвечать") # mb = QMessageBox.critical(self, "Ошибка", "Сервер перестал отвечать") return self.data = QByteArray.fromBase64(self.image_base_64) self.pm = QPixmap() self.pm.loadFromData(self.data, "PNG") self._graphics_scene.clear() self._graphics_scene.addPixmap(self.pm) self.update() def mouse_pressed(self, event): if self.connected: x = int(event.scenePos().x()) y = int(event.scenePos().y()) button = event.button() if button == 4: button = 3 try: self.client.send_mouse_event(x, y, button) except: self.critical("Сервер перестал отвечать") # mb = QMessageBox.critical(self, "Ошибка", "Сервер перестал отвечать") self.revert()
def show(exception_type, value, tb): debug_mode = True Logger.log("c", "An uncaught exception has occurred!") for line in traceback.format_exception(exception_type, value, tb): for part in line.rstrip("\n").split("\n"): Logger.log("c", part) if not debug_mode and exception_type not in fatal_exception_types: return application = QCoreApplication.instance() if not application: sys.exit(1) dialog = QDialog() dialog.setMinimumWidth(640) dialog.setMinimumHeight(640) dialog.setWindowTitle(catalog.i18nc("@title:window", "Oops!")) layout = QVBoxLayout(dialog) label = QLabel(dialog) pixmap = QPixmap() try: data = urllib.request.urlopen("http://www.randomkittengenerator.com/cats/rotator.php").read() pixmap.loadFromData(data) except: try: from UM.Resources import Resources path = Resources.getPath(Resources.Images, "kitten.jpg") pixmap.load(path) except: pass pixmap = pixmap.scaled(150, 150) label.setPixmap(pixmap) label.setAlignment(Qt.AlignCenter) layout.addWidget(label) label = QLabel(dialog) layout.addWidget(label) # label.setScaledContents(True) label.setText( catalog.i18nc( "@label", """ <p>A fatal exception has occurred that we could not recover from!</p> <p>We hope this picture of a kitten helps you recover from the shock.</p> <p>Please use the information below to post a bug report at <a href=\"http://github.com/Ultimaker/Cura/issues\">http://github.com/Ultimaker/Cura/issues</a></p> """, ) ) textarea = QTextEdit(dialog) layout.addWidget(textarea) try: from UM.Application import Application version = Application.getInstance().getVersion() except: version = "Unknown" trace = "".join(traceback.format_exception(exception_type, value, tb)) crash_info = "Version: {0}\nPlatform: {1}\nQt: {2}\nPyQt: {3}\n\nException:\n{4}" crash_info = crash_info.format(version, platform.platform(), QT_VERSION_STR, PYQT_VERSION_STR, trace) textarea.setText(crash_info) buttons = QDialogButtonBox(QDialogButtonBox.Close, dialog) layout.addWidget(buttons) buttons.addButton(catalog.i18nc("@action:button", "Open Web Page"), QDialogButtonBox.HelpRole) buttons.rejected.connect(dialog.close) buttons.helpRequested.connect(lambda: webbrowser.open("http://github.com/Ultimaker/Cura/issues")) dialog.exec_() sys.exit(1)
def GetTypePixmap(self, aTypeId, aSize): pixmap = QPixmap() filename = 'Types/{0}_{1}.png'.format(aTypeId, aSize) pixmap.loadFromData(self.archive.read(filename)) return pixmap
class MusicPlayer(QMainWindow): """MusicPlayer houses all of elements that directly interact with the main window.""" def __init__(self, parent=None): """Initialize the QMainWindow widget. The window title, window icon, and window size are initialized here as well as the following widgets: QMediaPlayer, QMediaPlaylist, QMediaContent, QMenuBar, QToolBar, QLabel, QPixmap, QSlider, QDockWidget, QListWidget, QWidget, and QVBoxLayout. The connect signals for relavant widgets are also initialized. """ super(MusicPlayer, self).__init__(parent) self.setWindowTitle('Mosaic') window_icon = utilities.resource_filename('mosaic.images', 'icon.png') self.setWindowIcon(QIcon(window_icon)) self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) # Initiates Qt objects to be used by MusicPlayer self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.playlist_location = defaults.Settings().playlist_path self.content = QMediaContent() self.menu = self.menuBar() self.toolbar = QToolBar() self.art = QLabel() self.pixmap = QPixmap() self.slider = QSlider(Qt.Horizontal) self.duration_label = QLabel() self.playlist_dock = QDockWidget('Playlist', self) self.library_dock = QDockWidget('Media Library', self) self.playlist_view = QListWidget() self.library_view = library.MediaLibraryView() self.library_model = library.MediaLibraryModel() self.preferences = configuration.PreferencesDialog() self.widget = QWidget() self.layout = QVBoxLayout(self.widget) self.duration = 0 self.playlist_dock_state = None self.library_dock_state = None # Sets QWidget() as the central widget of the main window self.setCentralWidget(self.widget) self.layout.setContentsMargins(0, 0, 0, 0) self.art.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) # Initiates the playlist dock widget and the library dock widget self.addDockWidget(defaults.Settings().dock_position, self.playlist_dock) self.playlist_dock.setWidget(self.playlist_view) self.playlist_dock.setVisible(defaults.Settings().playlist_on_start) self.playlist_dock.setFeatures(QDockWidget.DockWidgetClosable) self.addDockWidget(defaults.Settings().dock_position, self.library_dock) self.library_dock.setWidget(self.library_view) self.library_dock.setVisible(defaults.Settings().media_library_on_start) self.library_dock.setFeatures(QDockWidget.DockWidgetClosable) self.tabifyDockWidget(self.playlist_dock, self.library_dock) # Sets the range of the playback slider and sets the playback mode as looping self.slider.setRange(0, self.player.duration() / 1000) self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) # OSX system menu bar causes conflicts with PyQt5 menu bar if sys.platform == 'darwin': self.menu.setNativeMenuBar(False) # Initiates Settings in the defaults module to give access to settings.toml defaults.Settings() # Signals that connect to other methods when they're called self.player.metaDataChanged.connect(self.display_meta_data) self.slider.sliderMoved.connect(self.seek) self.player.durationChanged.connect(self.song_duration) self.player.positionChanged.connect(self.song_position) self.player.stateChanged.connect(self.set_state) self.playlist_view.itemActivated.connect(self.activate_playlist_item) self.library_view.activated.connect(self.open_media_library) self.playlist.currentIndexChanged.connect(self.change_index) self.playlist.mediaInserted.connect(self.initialize_playlist) self.playlist_dock.visibilityChanged.connect(self.dock_visiblity_change) self.library_dock.visibilityChanged.connect(self.dock_visiblity_change) self.preferences.dialog_media_library.media_library_line.textChanged.connect(self.change_media_library_path) self.preferences.dialog_view_options.dropdown_box.currentIndexChanged.connect(self.change_window_size) self.art.mousePressEvent = self.press_playback # Creating the menu controls, media controls, and window size of the music player self.menu_controls() self.media_controls() self.load_saved_playlist() def menu_controls(self): """Initiate the menu bar and add it to the QMainWindow widget.""" self.file = self.menu.addMenu('File') self.edit = self.menu.addMenu('Edit') self.playback = self.menu.addMenu('Playback') self.view = self.menu.addMenu('View') self.help_ = self.menu.addMenu('Help') self.file_menu() self.edit_menu() self.playback_menu() self.view_menu() self.help_menu() def media_controls(self): """Create the bottom toolbar and controls used for media playback.""" self.addToolBar(Qt.BottomToolBarArea, self.toolbar) self.toolbar.setMovable(False) play_icon = utilities.resource_filename('mosaic.images', 'md_play.png') self.play_action = QAction(QIcon(play_icon), 'Play', self) self.play_action.triggered.connect(self.player.play) stop_icon = utilities.resource_filename('mosaic.images', 'md_stop.png') self.stop_action = QAction(QIcon(stop_icon), 'Stop', self) self.stop_action.triggered.connect(self.player.stop) previous_icon = utilities.resource_filename('mosaic.images', 'md_previous.png') self.previous_action = QAction(QIcon(previous_icon), 'Previous', self) self.previous_action.triggered.connect(self.previous) next_icon = utilities.resource_filename('mosaic.images', 'md_next.png') self.next_action = QAction(QIcon(next_icon), 'Next', self) self.next_action.triggered.connect(self.playlist.next) repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png') self.repeat_action = QAction(QIcon(repeat_icon), 'Repeat', self) self.repeat_action.setShortcut('R') self.repeat_action.triggered.connect(self.repeat_song) self.toolbar.addAction(self.play_action) self.toolbar.addAction(self.stop_action) self.toolbar.addAction(self.previous_action) self.toolbar.addAction(self.next_action) self.toolbar.addAction(self.repeat_action) self.toolbar.addWidget(self.slider) self.toolbar.addWidget(self.duration_label) def file_menu(self): """Add a file menu to the menu bar. The file menu houses the Open File, Open Multiple Files, Open Playlist, Open Directory, and Exit Application menu items. """ self.open_action = QAction('Open File', self) self.open_action.setShortcut('O') self.open_action.triggered.connect(self.open_file) self.open_multiple_files_action = QAction('Open Multiple Files', self) self.open_multiple_files_action.setShortcut('M') self.open_multiple_files_action.triggered.connect(self.open_multiple_files) self.open_playlist_action = QAction('Open Playlist', self) self.open_playlist_action.setShortcut('CTRL+P') self.open_playlist_action.triggered.connect(self.open_playlist) self.open_directory_action = QAction('Open Directory', self) self.open_directory_action.setShortcut('D') self.open_directory_action.triggered.connect(self.open_directory) self.save_playlist_action = QAction('Save Playlist', self) self.save_playlist_action.setShortcut('CTRL+S') self.save_playlist_action.triggered.connect(self.save_playlist) self.exit_action = QAction('Quit', self) self.exit_action.setShortcut('CTRL+Q') self.exit_action.triggered.connect(self.closeEvent) self.file.addAction(self.open_action) self.file.addAction(self.open_multiple_files_action) self.file.addAction(self.open_playlist_action) self.file.addAction(self.open_directory_action) self.file.addSeparator() self.file.addAction(self.save_playlist_action) self.file.addSeparator() self.file.addAction(self.exit_action) def edit_menu(self): """Add an edit menu to the menu bar. The edit menu houses the preferences item that opens a preferences dialog that allows the user to customize features of the music player. """ self.preferences_action = QAction('Preferences', self) self.preferences_action.setShortcut('CTRL+SHIFT+P') self.preferences_action.triggered.connect(lambda: self.preferences.exec_()) self.edit.addAction(self.preferences_action) def playback_menu(self): """Add a playback menu to the menu bar. The playback menu houses """ self.play_playback_action = QAction('Play', self) self.play_playback_action.setShortcut('P') self.play_playback_action.triggered.connect(self.player.play) self.stop_playback_action = QAction('Stop', self) self.stop_playback_action.setShortcut('S') self.stop_playback_action.triggered.connect(self.player.stop) self.previous_playback_action = QAction('Previous', self) self.previous_playback_action.setShortcut('B') self.previous_playback_action.triggered.connect(self.previous) self.next_playback_action = QAction('Next', self) self.next_playback_action.setShortcut('N') self.next_playback_action.triggered.connect(self.playlist.next) self.playback.addAction(self.play_playback_action) self.playback.addAction(self.stop_playback_action) self.playback.addAction(self.previous_playback_action) self.playback.addAction(self.next_playback_action) def view_menu(self): """Add a view menu to the menu bar. The view menu houses the Playlist, Media Library, Minimalist View, and Media Information menu items. The Playlist item toggles the playlist dock into and out of view. The Media Library items toggles the media library dock into and out of view. The Minimalist View item resizes the window and shows only the menu bar and player controls. The Media Information item opens a dialog that shows information relevant to the currently playing song. """ self.dock_action = self.playlist_dock.toggleViewAction() self.dock_action.setShortcut('CTRL+ALT+P') self.library_dock_action = self.library_dock.toggleViewAction() self.library_dock_action.setShortcut('CTRL+ALT+L') self.minimalist_view_action = QAction('Minimalist View', self) self.minimalist_view_action.setShortcut('CTRL+ALT+M') self.minimalist_view_action.setCheckable(True) self.minimalist_view_action.triggered.connect(self.minimalist_view) self.view_media_info_action = QAction('Media Information', self) self.view_media_info_action.setShortcut('CTRL+SHIFT+M') self.view_media_info_action.triggered.connect(self.media_information_dialog) self.view.addAction(self.dock_action) self.view.addAction(self.library_dock_action) self.view.addSeparator() self.view.addAction(self.minimalist_view_action) self.view.addSeparator() self.view.addAction(self.view_media_info_action) def help_menu(self): """Add a help menu to the menu bar. The help menu houses the about dialog that shows the user information related to the application. """ self.about_action = QAction('About', self) self.about_action.setShortcut('H') self.about_action.triggered.connect(lambda: about.AboutDialog().exec_()) self.help_.addAction(self.about_action) def open_file(self): """Open the selected file and add it to a new playlist.""" filename, success = QFileDialog.getOpenFileName(self, 'Open File', '', 'Audio (*.mp3 *.flac)', '', QFileDialog.ReadOnly) if success: file_info = QFileInfo(filename).fileName() playlist_item = QListWidgetItem(file_info) self.playlist.clear() self.playlist_view.clear() self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(filename))) self.player.setPlaylist(self.playlist) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play() def open_multiple_files(self): """Open the selected files and add them to a new playlist.""" filenames, success = QFileDialog.getOpenFileNames(self, 'Open Multiple Files', '', 'Audio (*.mp3 *.flac)', '', QFileDialog.ReadOnly) if success: self.playlist.clear() self.playlist_view.clear() for file in natsort.natsorted(filenames, alg=natsort.ns.PATH): file_info = QFileInfo(file).fileName() playlist_item = QListWidgetItem(file_info) self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) self.player.setPlaylist(self.playlist) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play() def open_playlist(self): """Load an M3U or PLS file into a new playlist.""" playlist, success = QFileDialog.getOpenFileName(self, 'Open Playlist', '', 'Playlist (*.m3u *.pls)', '', QFileDialog.ReadOnly) if success: playlist = QUrl.fromLocalFile(playlist) self.playlist.clear() self.playlist_view.clear() self.playlist.load(playlist) self.player.setPlaylist(self.playlist) for song_index in range(self.playlist.mediaCount()): file_info = self.playlist.media(song_index).canonicalUrl().fileName() playlist_item = QListWidgetItem(file_info) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play() def save_playlist(self): """Save the media in the playlist dock as a new M3U playlist.""" playlist, success = QFileDialog.getSaveFileName(self, 'Save Playlist', '', 'Playlist (*.m3u)', '') if success: saved_playlist = "{}.m3u" .format(playlist) self.playlist.save(QUrl().fromLocalFile(saved_playlist), "m3u") def load_saved_playlist(self): """Load the saved playlist if user setting permits.""" saved_playlist = "{}/.m3u" .format(self.playlist_location) if os.path.exists(saved_playlist): playlist = QUrl().fromLocalFile(saved_playlist) self.playlist.load(playlist) self.player.setPlaylist(self.playlist) for song_index in range(self.playlist.mediaCount()): file_info = self.playlist.media(song_index).canonicalUrl().fileName() playlist_item = QListWidgetItem(file_info) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) def open_directory(self): """Open the selected directory and add the files within to an empty playlist.""" directory = QFileDialog.getExistingDirectory(self, 'Open Directory', '', QFileDialog.ReadOnly) if directory: self.playlist.clear() self.playlist_view.clear() for dirpath, __, files in os.walk(directory): for filename in natsort.natsorted(files, alg=natsort.ns.PATH): file = os.path.join(dirpath, filename) if filename.endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) playlist_item = QListWidgetItem(filename) playlist_item.setToolTip(filename) self.playlist_view.addItem(playlist_item) self.player.setPlaylist(self.playlist) self.playlist_view.setCurrentRow(0) self.player.play() def open_media_library(self, index): """Open a directory or file from the media library into an empty playlist.""" self.playlist.clear() self.playlist_view.clear() if self.library_model.fileName(index).endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(self.library_model.filePath(index)))) self.playlist_view.addItem(self.library_model.fileName(index)) elif self.library_model.isDir(index): directory = self.library_model.filePath(index) for dirpath, __, files in os.walk(directory): for filename in natsort.natsorted(files, alg=natsort.ns.PATH): file = os.path.join(dirpath, filename) if filename.endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) playlist_item = QListWidgetItem(filename) playlist_item.setToolTip(filename) self.playlist_view.addItem(playlist_item) self.player.setPlaylist(self.playlist) self.player.play() def display_meta_data(self): """Display the current song's metadata in the main window. If the current song contains metadata, its cover art is extracted and shown in the main window while the track number, artist, album, and track title are shown in the window title. """ if self.player.isMetaDataAvailable(): file_path = self.player.currentMedia().canonicalUrl().toLocalFile() (album, artist, title, track_number, *__, artwork) = metadata.metadata(file_path) try: self.pixmap.loadFromData(artwork) except TypeError: self.pixmap = QPixmap(artwork) meta_data = '{} - {} - {} - {}' .format(track_number, artist, album, title) self.setWindowTitle(meta_data) self.art.setScaledContents(True) self.art.setPixmap(self.pixmap) self.layout.addWidget(self.art) def initialize_playlist(self, start): """Display playlist and reset playback mode when media inserted into playlist.""" if start == 0: if self.library_dock.isVisible(): self.playlist_dock.setVisible(True) self.playlist_dock.show() self.playlist_dock.raise_() if self.playlist.playbackMode() != QMediaPlaylist.Sequential: self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png') self.repeat_action.setIcon(QIcon(repeat_icon)) def press_playback(self, event): """Change the playback of the player on cover art mouse event. When the cover art is clicked, the player will play the media if the player is either paused or stopped. If the media is playing, the media is set to pause. """ if event.button() == 1 and configuration.Playback().cover_art_playback.isChecked(): if (self.player.state() == QMediaPlayer.StoppedState or self.player.state() == QMediaPlayer.PausedState): self.player.play() elif self.player.state() == QMediaPlayer.PlayingState: self.player.pause() def seek(self, seconds): """Set the position of the song to the position dragged to by the user.""" self.player.setPosition(seconds * 1000) def song_duration(self, duration): """Set the slider to the duration of the currently played media.""" duration /= 1000 self.duration = duration self.slider.setMaximum(duration) def song_position(self, progress): """Move the horizontal slider in sync with the duration of the song. The progress is relayed to update_duration() in order to display the time label next to the slider. """ progress /= 1000 if not self.slider.isSliderDown(): self.slider.setValue(progress) self.update_duration(progress) def update_duration(self, current_duration): """Calculate the time played and the length of the song. Both of these times are sent to duration_label() in order to display the times on the toolbar. """ duration = self.duration if current_duration or duration: time_played = QTime((current_duration / 3600) % 60, (current_duration / 60) % 60, (current_duration % 60), (current_duration * 1000) % 1000) song_length = QTime((duration / 3600) % 60, (duration / 60) % 60, (duration % 60), (duration * 1000) % 1000) if duration > 3600: time_format = "hh:mm:ss" else: time_format = "mm:ss" time_display = "{} / {}" .format(time_played.toString(time_format), song_length.toString(time_format)) else: time_display = "" self.duration_label.setText(time_display) def set_state(self, state): """Change the icon in the toolbar in relation to the state of the player. The play icon changes to the pause icon when a song is playing and the pause icon changes back to the play icon when either paused or stopped. """ if self.player.state() == QMediaPlayer.PlayingState: pause_icon = utilities.resource_filename('mosaic.images', 'md_pause.png') self.play_action.setIcon(QIcon(pause_icon)) self.play_action.triggered.connect(self.player.pause) elif (self.player.state() == QMediaPlayer.PausedState or self.player.state() == QMediaPlayer.StoppedState): self.play_action.triggered.connect(self.player.play) play_icon = utilities.resource_filename('mosaic.images', 'md_play.png') self.play_action.setIcon(QIcon(play_icon)) def previous(self): """Move to the previous song in the playlist. Moves to the previous song in the playlist if the current song is less than five seconds in. Otherwise, restarts the current song. """ if self.player.position() <= 5000: self.playlist.previous() else: self.player.setPosition(0) def repeat_song(self): """Set the current media to repeat and change the repeat icon accordingly. There are four playback modes: repeat none, repeat all, repeat once, and shuffle. Clicking the repeat button cycles through each playback mode. """ if self.playlist.playbackMode() == QMediaPlaylist.Sequential: self.playlist.setPlaybackMode(QMediaPlaylist.Loop) repeat_on_icon = utilities.resource_filename('mosaic.images', 'md_repeat_all.png') self.repeat_action.setIcon(QIcon(repeat_on_icon)) elif self.playlist.playbackMode() == QMediaPlaylist.Loop: self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop) repeat_on_icon = utilities.resource_filename('mosaic.images', 'md_repeat_once.png') self.repeat_action.setIcon(QIcon(repeat_on_icon)) elif self.playlist.playbackMode() == QMediaPlaylist.CurrentItemInLoop: self.playlist.setPlaybackMode(QMediaPlaylist.Random) repeat_icon = utilities.resource_filename('mosaic.images', 'md_shuffle.png') self.repeat_action.setIcon(QIcon(repeat_icon)) elif self.playlist.playbackMode() == QMediaPlaylist.Random: self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png') self.repeat_action.setIcon(QIcon(repeat_icon)) def activate_playlist_item(self, item): """Set the active media to the playlist item dobule-clicked on by the user.""" current_index = self.playlist_view.row(item) if self.playlist.currentIndex() != current_index: self.playlist.setCurrentIndex(current_index) if self.player.state() != QMediaPlayer.PlayingState: self.player.play() def change_index(self, row): """Highlight the row in the playlist of the active media.""" self.playlist_view.setCurrentRow(row) def minimalist_view(self): """Resize the window to only show the menu bar and audio controls.""" if self.minimalist_view_action.isChecked(): if self.playlist_dock.isVisible(): self.playlist_dock_state = True if self.library_dock.isVisible(): self.library_dock_state = True self.library_dock.close() self.playlist_dock.close() QTimer.singleShot(10, lambda: self.resize(500, 0)) else: self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) if self.library_dock_state: self.library_dock.setVisible(True) if self.playlist_dock_state: self.playlist_dock.setVisible(True) def dock_visiblity_change(self, visible): """Change the size of the main window when the docks are toggled.""" if visible and self.playlist_dock.isVisible() and not self.library_dock.isVisible(): self.resize(defaults.Settings().window_size + self.playlist_dock.width() + 6, self.height()) elif visible and not self.playlist_dock.isVisible() and self.library_dock.isVisible(): self.resize(defaults.Settings().window_size + self.library_dock.width() + 6, self.height()) elif visible and self.playlist_dock.isVisible() and self.library_dock.isVisible(): self.resize(defaults.Settings().window_size + self.library_dock.width() + 6, self.height()) elif (not visible and not self.playlist_dock.isVisible() and not self.library_dock.isVisible()): self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) def media_information_dialog(self): """Show a dialog of the current song's metadata.""" if self.player.isMetaDataAvailable(): file_path = self.player.currentMedia().canonicalUrl().toLocalFile() else: file_path = None dialog = information.InformationDialog(file_path) dialog.exec_() def change_window_size(self): """Change the window size of the music player.""" self.playlist_dock.close() self.library_dock.close() self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) def change_media_library_path(self, path): """Change the media library path to the new path selected in the preferences dialog.""" self.library_model.setRootPath(path) self.library_view.setModel(self.library_model) self.library_view.setRootIndex(self.library_model.index(path)) def closeEvent(self, event): """Override the PyQt close event in order to handle save playlist on close.""" playlist = "{}/.m3u" .format(self.playlist_location) if defaults.Settings().save_playlist_on_close: self.playlist.save(QUrl().fromLocalFile(playlist), "m3u") else: if os.path.exists(playlist): os.remove(playlist) QApplication.quit()