def render_html(path_to_html, width=590, height=750, as_xhtml=True): from PyQt5.QtWebKitWidgets import QWebPage from PyQt5.Qt import QEventLoop, QPalette, Qt, QUrl, QSize from calibre.gui2 import is_ok_to_use_qt, secure_web_page if not is_ok_to_use_qt(): return None path_to_html = os.path.abspath(path_to_html) with CurrentDir(os.path.dirname(path_to_html)): page = QWebPage() settings = page.settings() secure_web_page(settings) pal = page.palette() pal.setBrush(QPalette.Background, Qt.white) page.setPalette(pal) page.setViewportSize(QSize(width, height)) page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) loop = QEventLoop() renderer = HTMLRenderer(page, loop) page.loadFinished.connect(renderer, type=Qt.QueuedConnection) if as_xhtml: page.mainFrame().setContent(open(path_to_html, 'rb').read(), 'application/xhtml+xml', QUrl.fromLocalFile(path_to_html)) else: page.mainFrame().load(QUrl.fromLocalFile(path_to_html)) loop.exec_() renderer.loop = renderer.page = None page.loadFinished.disconnect() del page del loop if isinstance(renderer.exception, ParserError) and as_xhtml: return render_html(path_to_html, width=width, height=height, as_xhtml=False) return renderer
def render_html(path_to_html, width=590, height=750, as_xhtml=True): from PyQt5.QtWebKitWidgets import QWebPage from PyQt5.Qt import QEventLoop, QPalette, Qt, QUrl, QSize from calibre.gui2 import is_ok_to_use_qt if not is_ok_to_use_qt(): return None path_to_html = os.path.abspath(path_to_html) with CurrentDir(os.path.dirname(path_to_html)): page = QWebPage() settings = page.settings() settings.setAttribute(settings.PluginsEnabled, False) pal = page.palette() pal.setBrush(QPalette.Background, Qt.white) page.setPalette(pal) page.setViewportSize(QSize(width, height)) page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) loop = QEventLoop() renderer = HTMLRenderer(page, loop) page.loadFinished.connect(renderer, type=Qt.QueuedConnection) if as_xhtml: page.mainFrame().setContent(open(path_to_html, 'rb').read(), 'application/xhtml+xml', QUrl.fromLocalFile(path_to_html)) else: page.mainFrame().load(QUrl.fromLocalFile(path_to_html)) loop.exec_() renderer.loop = renderer.page = None page.loadFinished.disconnect() del page del loop if isinstance(renderer.exception, ParserError) and as_xhtml: return render_html(path_to_html, width=width, height=height, as_xhtml=False) return renderer
def __init__(self, id, spawn_x, spawn_y, aov, v_max, maxHealth, r=30, alpha=0, texturePath="textures/robot_base.png"): super().__init__() self.id = id self.pos = QVector2D(spawn_x, spawn_y) self.spawn = QVector2D(spawn_x, spawn_y) self.aov = aov self.r = r self.alpha = alpha # unit: degrees self.texture = QPixmap(texturePath) self.a = 0 # unit: pixels/second^2 self.a_max = A_MAX # unit: pixels/second^2 self.v = 0 # unit: pixels/second self.v_max = v_max # unit pixels/second self.a_alpha = 0 # unit: degrees/second^2 self.a_alpha_max = A_ALPHA_MAX # unit: degrees/second^2 self.v_alpha = 0 # unit: degrees/second self.v_alpha_max = V_ALPHA_MAX # unit: degrees/second self.guns = [] self.selected_gun = None self.currentGunIndex = 0 self.maxHealth = maxHealth self.health = maxHealth self.healthBar = HealthBar(maxHealth) self.active = True self.protected = False self.timeToRespawn = 0 self.protectionTime = 0 self.deathSound = QSoundEffect(self) self.deathSound.setSource(QUrl.fromLocalFile("sounds/death.wav")) self.deathSound.setVolume(0.1) self.emptyGunSound = QSoundEffect(self) self.emptyGunSound.setSource( QUrl.fromLocalFile("sounds/empty_gun.wav")) self.emptyGunSound.setVolume(0.1) self.respawnSound = QSoundEffect(self) self.respawnSound.setSource(QUrl.fromLocalFile("sounds/respawn.wav")) self.respawnSound.setVolume(0.1)
def webview_refresh(self, name): name_orig = self.revfmap.get(name, name) abspath_orig = self.orig.name_to_abspath(name_orig) abspath = self.ebook.name_to_abspath(name) if isinstance(self.webview_orig, QTextBrowser): self.webview_orig.setSource(QUrl.fromLocalFile(abspath_orig)) self.webview_scram.setSource(QUrl.fromLocalFile(abspath)) else: self.webview_orig.load(QUrl.fromLocalFile(abspath_orig)) self.webview_scram.load(QUrl.fromLocalFile(abspath))
def button_open_camera_clicked(self): ''' 打开摄像头,并同时播放视频,同时进行姿态检测 ''' if self.timer_camera.isActive() == False: #若定时器未启动 flag = self.cap.open( self.CAM_NUM) #参数是0,表示打开笔记本的内置摄像头,参数是视频文件路径则打开视频 if flag == False: #flag表示open()成不成功 msg = QtWidgets.QMessageBox.warning( self, 'warning', "请检查相机于电脑是否连接正确", buttons=QtWidgets.QMessageBox.Ok) else: self.pushButton.setText('关闭') self.timer_camera.start(30) #定时器开始计时30ms,结果是每过30ms从摄像头中取一帧显示 time.sleep(0.03) self.player.setMedia( QMediaContent(QUrl.fromLocalFile(gl.GL_VPath))) #设置视频资源 self.player.play() #视频播放 self.danceMatching.start() #开始姿态检测 else: self.timer_camera.stop() #关闭定时器 self.cap.release() #释放视频流 self.label_show_camera.clear() #清空视频显示区域 self.player.pause() #视频暂停 self.player.setPosition(0) #设置播放进度为初始 self.danceMatching.isEnd = True #设置线程需要被关闭,以达到关闭姿态匹配线程的目的 self.pushButton.setText('开始')
def load_html(path, view, codec='utf-8', mime_type=None, pre_load_callback=lambda x:None, path_is_html=False, force_as_html=False, loading_url=None): from PyQt5.Qt import QUrl, QByteArray if mime_type is None: mime_type = guess_type(path)[0] if not mime_type: mime_type = 'text/html' if path_is_html: html = path else: with open(path, 'rb') as f: html = f.read().decode(codec, 'replace') html = cleanup_html(html) loading_url = loading_url or QUrl.fromLocalFile(path) pre_load_callback(loading_url) if force_as_html or load_as_html(html): view.setHtml(html, loading_url) else: view.setContent(QByteArray(html.encode(codec)), mime_type, loading_url) mf = view.page().mainFrame() elem = mf.findFirstElement('parsererror') if not elem.isNull(): return False return True
def addMedia(self, songInfo_dict: dict): """ 重载addMedia,一次向尾部添加一首歌 """ if not songInfo_dict: return self.playlist.append(songInfo_dict) super().addMedia( QMediaContent(QUrl.fromLocalFile(songInfo_dict['songPath'])))
def load(self, url = ''): p = re.compile('(^file:\/\/)|(^http:\/\/)|(^https:\/\/)|(^data:)') if url and p.match(url) == None: url = QUrl.fromLocalFile(os.path.abspath(url)) else: url = QUrl(url) super(WebView, self).load(url)
def load_html(path, view, codec='utf-8', mime_type=None, pre_load_callback=lambda x:None, path_is_html=False, force_as_html=False): from PyQt5.Qt import QUrl, QByteArray if mime_type is None: mime_type = guess_type(path)[0] if not mime_type: mime_type = 'text/html' if path_is_html: html = path else: with open(path, 'rb') as f: html = f.read().decode(codec, 'replace') html = EntityDeclarationProcessor(html).processed_html self_closing_pat = re.compile(r'<\s*([:A-Za-z0-9-]+)([^>]*)/\s*>') html = self_closing_pat.sub(self_closing_sub, html) loading_url = QUrl.fromLocalFile(path) pre_load_callback(loading_url) if force_as_html or re.search(r'<[a-zA-Z0-9-]+:svg', html) is None and '<![CDATA[' not in html: view.setHtml(html, loading_url) else: view.setContent(QByteArray(html.encode(codec)), mime_type, loading_url) mf = view.page().mainFrame() elem = mf.findFirstElement('parsererror') if not elem.isNull(): return False return True
def __init__(self): super(Video, self).__init__() self.resize(1920, 1080) # ITEM self._item = QGraphicsVideoItem() self._textItem = QGraphicsTextItem() self._view = QGraphicsView() self._scene = QGraphicsScene() self._view.resize(1920, 1080) self._view.setScene(self._scene) self._scene.addItem(self._item) self._scene.addItem(self._textItem) self._textItem.setPlainText('SRT TEXT') self._textItem.setDefaultTextColor(Qt.red) font = self._textItem.font() font.setPixelSize(50) self._textItem.setFont(font) self._view.show() self._item.setSize(QSizeF(1920, 1080)) self._player = QMediaPlayer(self) self._player.setMedia( QMediaContent( QUrl.fromLocalFile( '/Users/huangkai/Documents/PycharmProjects/AllTest/Qt插入背景/AddVideos/Videos/yellow.mov' ))) self._player.setVideoOutput(self._item) self._player.play() self.setCentralWidget(self._view) self._item.setPos(400, 500) # BUTTON self._btn = QPushButton(self) self._btn.resize(100, 50) self._btn.move(500, 500) self._btn.setText('test') self._btn.clicked.connect(self._change_text)
def initUI(self): self.setWindowTitle(TITLE) self.showMaximized() #self.setGeometry(0, 0, 900, 700) # layout self.layout = QHBoxLayout(self) self.setLayout(self.layout) # CallX self.callx_widget = CallXWidget(self, SERVER, USER, PASSWORD, debug_mode=True) self.layout.addWidget(self.callx_widget.ocx) # promo video self.video = QVideoWidget(self) self.player = QMediaPlayer(self) self.player.setVideoOutput(self.video) # set media content if exist a video file if os.path.isfile(PROMO_VIDEO_FILE): self.media_file = QUrl.fromLocalFile(PROMO_VIDEO_FILE) self.mediaContent = QMediaContent(self.media_file) self.playlist = QMediaPlaylist() self.playlist.addMedia(self.mediaContent) self.playlist.setPlaybackMode(QMediaPlaylist.Loop) self.player.setPlaylist(self.playlist) else: print('Video file "{}" not exist'.format(PROMO_VIDEO_FILE)) # init self.showPromo(False) # connect to signals self.callx_widget.stateChanged.connect(self.onStateChanged) self.callx_widget.IncomingChatMessage.connect( self.onIncomingChatMessage)
def show(self, name): if name != self.current_name: self.refresh_timer.stop() self.current_name = name parse_worker.add_request(name) self.view.setUrl(QUrl.fromLocalFile(current_container().name_to_abspath(name))) return True
def show_help(self): ''' Display strftime help file ''' from calibre.gui2 import open_url path = os.path.join(self.parent.resources_path, 'help/timestamp_formats.html') open_url(QUrl.fromLocalFile(path))
def open_local_file(path): if iswindows: with sanitize_env_vars(): os.startfile(os.path.normpath(path)) else: url = QUrl.fromLocalFile(path) open_url(url)
def convert_html_file(self, path, page_layout, settle_time=0, wait_for_title=None): self.working = True self.load_complete = False self.wait_for_title = wait_for_title self.settle_time = settle_time self.page_layout = page_layout self.setUrl(QUrl.fromLocalFile(path))
def show(self, name): if name != self.current_name: self.refresh_timer.stop() self.current_name = name parse_worker.add_request(name) self.view.setUrl( QUrl.fromLocalFile(current_container().name_to_abspath(name))) return True
def main(): must_use_qt() load_builtin_fonts() renderer = Renderer() renderer.setUrl(QUrl.fromLocalFile(sys.argv[-1])) renderer.loadFinished.connect(renderer.do_print) QApplication.instance().exec_() print('Output written to:', OUTPUT)
def addMedias(self, songInfoDict_list: list): """ 向尾部添加要播放的音频文件列表 """ if not songInfoDict_list: return self.playlist.extend(songInfoDict_list) for songInfo_dict in songInfoDict_list: super().addMedia( QMediaContent(QUrl.fromLocalFile(songInfo_dict['songPath'])))
def __init__(self, card): super(CardGraphicsItem, self).__init__() self.path = 'img/' + str( card.value) + CardGraphicsItem.suitnames[card.suit] self.show_face() self.setScale(0.12) self.card = card self.click_sound = QSoundEffect() self.click_sound.setSource(QUrl.fromLocalFile('sound/playcard.wav'))
def getSoundEffect(self, filePath): if filePath in self.soundEffects: return self.soundEffects[filePath] else: soundEffect = QSoundEffect() soundEffect.setSource(QUrl.fromLocalFile(filePath)) soundEffect.setVolume(0.1) self.soundEffects[filePath] = soundEffect return soundEffect
def __openFile(self): if self._downloading: return fpath = pathjoin(self._path, self._fileName) if pathexists(fpath): QDesktopServices.openUrl(QUrl.fromLocalFile(abspath(fpath))) else: QMessageBox.warning( self._item.listWidget().parentWidget(), _("Not found"), _("Sorry, the file \n %s \n was not found!") % abspath(fpath))
def setup_music(self): self.music = QMediaPlayer() self.playlist = QMediaPlaylist() self.playlist.setPlaybackMode(QMediaPlaylist.Loop) file_name = "sound/bg.mp3" self.media = QMediaContent(QUrl.fromLocalFile(file_name)) self.playlist.addMedia(self.media) self.music.setPlaylist(self.playlist) self.music.setVolume(20) self.music.play()
def __init__(self, owner, baseSpeed, timeToReload, damage): super().__init__(owner, baseSpeed, timeToReload, damage, bulletRadius=5) self.soundEffect = QSoundEffect(self) self.soundEffect.setSource(QUrl.fromLocalFile("sounds/handgun.wav")) self.soundEffect.setVolume(0.4)
def set_html(mi, html, web_view): from calibre.gui2.ui import get_gui gui = get_gui() book_id = getattr(mi, 'id', None) if gui and book_id is not None: path = gui.current_db.abspath(book_id, index_is_id=True) if path: web_view.setHtml(html, QUrl.fromLocalFile(os.path.join(path, 'metadata.html'))) return web_view.setHtml(html)
def __init__(self, owner, baseSpeed, timeToReload, damage, bulletsPerShot): super().__init__(owner, baseSpeed, timeToReload, damage, bulletRadius=6) self.bulletsPerShot = bulletsPerShot self.explosionBullets = [] self.soundEffect_launcher = QSoundEffect(self) self.soundEffect_launcher.setSource( QUrl.fromLocalFile("sounds/grenade_launcher.wav")) self.soundEffect_launcher.setVolume(0.1) self.soundEffect_explosion = QSoundEffect(self) self.soundEffect_explosion.setSource( QUrl.fromLocalFile("sounds/explosion.wav")) self.soundEffect_explosion.setVolume(1.5)
def insertMedias(self, index: int, songInfoDict_list: list): """ 插入播放列表 """ if not songInfoDict_list: return self.playlist = self.playlist[:index] + \ songInfoDict_list + self.playlist[index:] mediaContent_list = [ QMediaContent(QUrl.fromLocalFile(songInfo_dict['songPath'])) for songInfo_dict in songInfoDict_list ] super().insertMedia(index, mediaContent_list)
def _openFolder(self): if const.OS_WIN: winFileName = '%s/%s' % (self._path, self._fileName) if self._downloading: winFileName += '.download' winFileName = winFileName.replace('/', '\\') shExArg = '/e,/select,"%s"' % winFileName system('explorer.exe ' + shExArg) else: QDesktopServices.openUrl(QUrl.fromLocalFile(self._path))
def _openFile(self): fileTypes = ("%s(*.html *.htm *.shtml *.shtm *.xhtml);;" "%s(*.png *.jpg *.jpeg *.bmp *.gif *.svg *.tiff);;" "%s(*.txt);;" "%s(*.*)") fileTypes %= ("HTML files", "Image files", "Text files", "All files") filePath = gVar.appTools.getOpenFileName("MainWindow-openFile", self, "Open file...", QDir.homePath(), fileTypes) if filePath: self.loadAddress(QUrl.fromLocalFile(filePath))
def __init__(self, owner, baseSpeed, timeToReload, damage, bulletsPerShot): super().__init__(owner, baseSpeed, timeToReload, damage, bulletRadius=3) self.bulletsPerShot = bulletsPerShot self.soundEffect = QSoundEffect(self) self.soundEffect.setSource(QUrl.fromLocalFile("sounds/shotgun.wav")) self.soundEffect.setVolume(0.1)
def parse_link(self, link): link = link.strip() if link and os.path.exists(link): return QUrl.fromLocalFile(link) has_schema = re.match(r'^[a-zA-Z]+:', link) if has_schema is not None: url = QUrl(link, QUrl.TolerantMode) if url.isValid(): return url if os.path.exists(link): return QUrl.fromLocalFile(link) if has_schema is None: first, _, rest = link.partition('.') prefix = 'http' if first == 'ftp': prefix = 'ftp' url = QUrl(prefix +'://'+link, QUrl.TolerantMode) if url.isValid(): return url return QUrl(link, QUrl.TolerantMode)
def parse_link(self, link): link = link.strip() if link and os.path.exists(link): return QUrl.fromLocalFile(link) has_schema = re.match(r'^[a-zA-Z]+:', link) if has_schema is not None: url = QUrl(link, QUrl.TolerantMode) if url.isValid(): return url if os.path.exists(link): return QUrl.fromLocalFile(link) if has_schema is None: first, _, rest = link.partition('.') prefix = 'http' if first == 'ftp': prefix = 'ftp' url = QUrl(prefix + '://' + link, QUrl.TolerantMode) if url.isValid(): return url return QUrl(link, QUrl.TolerantMode)
def __init__(self, profile, parent=None): QWebEngineView.__init__(self, parent) self._page = Page(profile, self) self._page.set_title.connect(self.set_title.emit) self._page.refresh_all.connect(self.refresh_all.emit) self.titleChanged.connect(self._page.check_for_messages_from_js, type=Qt.QueuedConnection) self.setPage(self._page) self.load( QUrl.fromLocalFile( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'index.html'))) self.renderProcessTerminated.connect(self.render_process_terminated)
def toc_clicked(self, index, force=False): if force or QApplication.mouseButtons() & Qt.LeftButton: item = self.toc_model.itemFromIndex(index) if item.abspath is not None: if not os.path.exists(item.abspath): return error_dialog(self, _('No such location'), _('The location pointed to by this item' ' does not exist.'), det_msg=item.abspath, show=True) url = QUrl.fromLocalFile(item.abspath) if item.fragment: url.setFragment(item.fragment) self.link_clicked(url) self.view.setFocus(Qt.OtherFocusReason)
def drag_data(self): m = self.model() rows = self.selectionModel().selectedRows() paths = [force_unicode(p, enc=filesystem_encoding) for p in m.paths(rows) if p] md = QMimeData() md.setData("application/calibre+from_device", b"dummy") md.setUrls([QUrl.fromLocalFile(p) for p in paths]) drag = QDrag(self) drag.setMimeData(md) cover = self.drag_icon(m.cover(self.currentIndex().row()), len(paths) > 1) drag.setHotSpot(QPoint(-15, -15)) drag.setPixmap(cover) return drag
def refresh(self): if self.current_name: self.refresh_timer.stop() # This will check if the current html has changed in its editor, # and re-parse it if so parse_worker.add_request(self.current_name) # Tell webkit to reload all html and associated resources current_url = QUrl.fromLocalFile(current_container().name_to_abspath(self.current_name)) self.refresh_starting.emit() if current_url != self.view.url(): # The container was changed self.view.setUrl(current_url) else: self.view.refresh() self.refreshed.emit()
def url_for_id(i): try: ans = db.format_path(i, fmt, index_is_id=True) except: ans = None if ans is None: fmts = db.formats(i, index_is_id=True) if fmts: fmts = fmts.split(',') else: fmts = [] for f in fmts: try: ans = db.format_path(i, f, index_is_id=True) except: ans = None if ans is None: ans = db.abspath(i, index_is_id=True) return QUrl.fromLocalFile(ans)
def current_changed(self, current, previous): link = current.data(Qt.UserRole) if link is None: return url = None if link.is_external: if link.href: frag = ('#' + link.anchor.id) if link.anchor.id else '' url = QUrl(link.href + frag) elif link.anchor.location: path = current_container().name_to_abspath(link.anchor.location.name) if path and os.path.exists(path): url = QUrl.fromLocalFile(path) if link.anchor.id: url.setFragment(link.anchor.id) if url is None: self.view.setHtml('<p>' + _('No destination found for this link')) self.current_url = url elif url != self.current_url: self.current_url = url self.view.setUrl(url)
def open_local_file(path): QDesktopServices.openUrl(QUrl.fromLocalFile(path))
def initialize(self, book_id): path = self.db.abspath(book_id, index_is_id=True) if path: self._tb.set_base_url(QUrl.fromLocalFile(os.path.join(path, 'metadata.html'))) return Base.initialize(self, book_id)
def show_help(self): self._log_location() path = os.path.join(self.parent.resources_path, 'help', 'marvin.html') open_url(QUrl.fromLocalFile(path))
def show_html(self, html, in_current_tab=True): if isinstance(html, bytes): html = html.decode('utf-8') tab = self.get_tab_for_load(in_current_tab=in_current_tab) tab.setHtml(html, QUrl.fromLocalFile(os.path.expanduser('~')))
def open_local_file(path): if iswindows: os.startfile(os.path.normpath(path)) else: url = QUrl.fromLocalFile(path) open_url(url)
def localUrl(self, path = ''): return QUrl.fromLocalFile(path).toString()
import os from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.Qt import QUrl from PyQt5 import QtWidgets, QtGui widget = QWebEngineView() fake_url = QUrl.fromLocalFile(os.path.abspath("seamless.html")) widget.setWindowTitle(PINS.title.get().data) reloadAction = QtWidgets.QAction(QtGui.QIcon('exit.png'), '&Reload', widget) reloadAction.setShortcut('F5') reloadAction.setStatusTip('Reload') reloadAction.triggered.connect(widget.reload) widget.addAction(reloadAction) widget.setHtml(PINS.val.get().data, fake_url) widget.show()
class ImagePopup(object): def __init__(self, parent): self.current_img = QPixmap() self.current_url = QUrl() self.parent = parent self.dialogs = [] def __call__(self): if self.current_img.isNull(): return d = ImageView(self.parent, self.current_img, self.current_url) self.dialogs.append(d) d.finished.connect(self.cleanup, type=Qt.QueuedConnection) d() def cleanup(self): for d in tuple(self.dialogs): if not d.isVisible(): self.dialogs.remove(d) if __name__ == '__main__': import sys app = QApplication([]) p = QPixmap() p.load(sys.argv[-1]) u = QUrl.fromLocalFile(sys.argv[-1]) d = ImageView(None, p, u) d() app.exec_()