def slot_folder_show_clicked(self, checked): if self.vfs_view_current().node_selected_count() > 0: path = self.vfs_view_current().common_prefix() if self.sender() == self.ui.bt_extract_folder_show: root = self.vfs.working_dir + 'extracted/' elif self.sender() == self.ui.bt_extract_gltf_3d_folder_show: root = self.vfs.working_dir + 'gltf2_3d/' elif self.sender() == self.ui.bt_mod_folder_show: root = self.vfs.working_dir + 'mod/' elif self.sender() == self.ui.bt_mod_build_folder_show: root = self.vfs.working_dir + 'build/' path = None else: root = None if root: if path: path = os.path.join(root, path) else: path = root path = path.replace('\\', '/') if not os.path.isdir(path): path, _ = os.path.split(path) if os.path.isdir(path): QDesktopServices.openUrl(QUrl(f'{path}')) else: self.vfs.logger.warning(f'Folder does not exist: {path}')
def opendir(self): """打开输出目录""" path = self.file_path if path: QDesktopServices.openUrl(QUrl('file:///' + path)) else: self.note('未找到文件')
def onPreviewFile(self): # User Office 365 Api to preview word/powerpoint/excel documents in browser if self.index is not None: item = self.model.itemFromIndex(self.index) url = 'http://view.officeapps.live.com/op/view.aspx?src=' + item.data( -1) print(url) QDesktopServices.openUrl(url)
def open_desktop_directory(self, directory: Path): """ Open directory with desktop explorer """ if path_exists(directory): q = QtCore.QUrl.fromLocalFile(directory.as_posix()) QDesktopServices.openUrl(q) else: self.ovr.display( _('Verzeichnis existiert nicht.<br>{}<br>').format( directory.as_posix()), 5000)
def InitUpdateBack(self, data): try: r = QMessageBox.information(self, "更新", "当前版本{} ,检查到更新,是否前往更新\n{}".format(config.UpdateVersion, data), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if r == QMessageBox.Yes: QDesktopServices.openUrl(QUrl(config.UpdateUrl2)) except Exception as es: Log.Error(es)
def impl(): # code below was added to resolve issue on Linux # 'kde-open5: /opt/pvtbox/libQt5Core.so.5: # version `Qt_5.9.7_PRIVATE_API' not found # (required by /usr/lib64/libQt5Xml.so.5)' if get_platform() == "Linux" and \ os.environ.get("XDG_CURRENT_DESKTOP", None) == "KDE": os.environ["XDG_CURRENT_DESKTOP"] = "X-Generic" QDesktopServices.openUrl(QUrl(uri))
def gen_strategy_slot(self): filename, _ = QFileDialog.getSaveFileName(self, "策略模板", "/", "Python files(*.py)") if filename: filename = filename if filename.endswith( '.py') else filename + '.py' with open(filename, 'w') as f: f.write(strategy_template) TipDialog(f"策略模板已生成") QDesktopServices.openUrl(QUrl("file:" + os.path.dirname(filename)))
def generate_menu(self, pos): row_num = -1 for i in self.py_table.selectionModel().selection().indexes(): row_num = i.row() menu = QMenu() item1 = menu.addAction("打开所在文件夹") action = menu.exec_(self.py_table.mapToGlobal(pos)) row_data = self.py_table.item(row_num, 1) if action == item1 and row_data: path = row_data.text() QDesktopServices.openUrl(QUrl("file:" + os.path.dirname(path)))
def InitUpdateBack(self, data): try: r = QMessageBox.information( self, "更新", "当前版本{} ,检查到更新,是否前往更新\n{}".format(config.UpdateVersion, data), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if r == QMessageBox.Yes: QDesktopServices.openUrl( QUrl("https://github.com/tonquer/picacg-windows/releases")) except Exception as es: Log.Error(es)
def last_save_dir_handler(self) -> None: """ Handler for last save dir button. :return None: """ self._logger.debug("running") if self._save_dir == "": QDesktopServices.openUrl(QUrl.fromLocalFile(QDir().homePath())) else: QDesktopServices.openUrl(QUrl.fromLocalFile(self._save_dir)) self._logger.debug("done")
def __open_last_save_dir(self): """ Opens native file manager to the last directory used for an experiment. If no experiment has been performed, opens default home path. :return: """ self.logger.debug("running") if self.__save_dir == "": QDesktopServices.openUrl(QUrl.fromLocalFile(QDir().homePath())) else: QDesktopServices.openUrl(QUrl.fromLocalFile(self.__save_dir)) self.logger.debug("done")
def runReport(self, pid, method, par): self.boolDirect = True self.mtypeCall = "report" self.mpid = pid self.mmethod = method self.mparams = par # bparams = self.prepareParams() request = self.prepareRequest() # reply = self.data_request(request, bparams) data = reply.readAll() parseError = QJsonParseError() resultObject = {} resultObject["data"] = "error" document = QJsonDocument.fromJson(data, parseError) if parseError.error == True: resultObject["data"] = "error" else: if document.isObject(): jv = document.object() if jv.__contains__( "result") == True and jv["result"].__class__() == []: #tryton 4.0 #'result': ['pdf', {'base64':wwwwww, '__class__':'bytes'}, False,'Printis'] jre = jv["result"] namesecs = "tryton_" + self.mpid + str( QDateTime.currentMSecsSinceEpoch()) + "." + jre[0] mdir = QDir(self.mDir + QDir.separator() + "tempReports") if mdir.exists() == False: s = QDir(self.mDir) s.mkdir("tempReports") filename = self.mDir + QDir.separator( ) + "tempReports" + QDir.separator() + namesecs file = QFile(filename) if file.open(QIODevice.WriteOnly) == False: #error self.signalResponse.emit(self.mpid, 7, {}) print("error", filename, file.errorString()) else: bafile = QByteArray.fromBase64( jre[1]["base64"].encode()) file.write(bafile) file.close() QDesktopServices.openUrl(QUrl(filename)) else: if document.isArray() == True: self.signalResponse.emit(self.mpid, 7, {}) self.processingData(data, reply)
def list_doubleClicked(self): index = self.listview.selectionModel().currentIndex() path = self.fileModel.fileInfo(index).absoluteFilePath() # folderpath = self.fileModel.fileInfo(index).path() if not self.fileModel.fileInfo(index).isDir(): if self.checkIsApplication(path) == True: self.process.startDetached(path) else: QDesktopServices.openUrl( QUrl(path, QUrl.TolerantMode | QUrl.EncodeUnicode)) else: self.treeview.setCurrentIndex(self.dirModel.index(path)) self.treeview.setFocus() # self.listview.setRootIndex(self.fileModel.setRootPath(path)) self.setWindowTitle(path)
def qt_open_path(path): system = get_platform() if system == 'Windows': from common.file_path import FilePath path = FilePath(path).shortpath # code below was added to resolve issue on Linux # 'kde-open5: /opt/pvtbox/libQt5Core.so.5: # version `Qt_5.9.7_PRIVATE_API' not found # (required by /usr/lib64/libQt5Xml.so.5)' if system == "Linux" and \ os.environ.get("XDG_CURRENT_DESKTOP", None) == "KDE": os.environ["XDG_CURRENT_DESKTOP"] = "X-Generic" QDesktopServices.openUrl(QUrl.fromLocalFile(path))
def search(self): try: imap = imaplib.IMAP4_SSL(host=self.host) imap.login(self.userName, self.password) imap.select() error, searchResult = imap.search(None, "SUBJECT " + self.subject) num = searchResult[0] if 0 != len(num): self.found = True if b' ' not in num: typ, data = imap.fetch(num, '(RFC822)') mail = mailparser.parse_from_bytes(data[0][1]) htmlParser = ParseLink() htmlParser.feed(mail.body) url = htmlParser.link if 0 != len(url): QDesktopServices.openUrl(url) self.delete(imap, num) self.errorList = "" else: self.errorList = "URL not found in mail" else: self.errorList = "More than one email found, possible attack" else: self.errorList = "Email not found" imap.close() imap.logout() except socket.gaierror as error: code, self.errorList = error.args self.found = True except imaplib.IMAP4.error as error: self.controller.resetPassword(self.address) reason, = error.args self.errorList = reason.decode() self.found = True self.done = True
def __create_menu(self) -> None: menu_bar = self.menuBar() file_menu = menu_bar.addMenu("File") import_action = file_menu.addAction("Import Audio...") import_action.setShortcut(QKeySequence("Ctrl+I")) import_action.triggered.connect(self.__import_audio) open_file_action = file_menu.addAction("Open...") open_file_action.setShortcut(QKeySequence("Ctrl+O")) open_file_action.triggered.connect(self.__open_file) file_menu.addSeparator() save_action = file_menu.addAction("Save") save_action.setShortcut(QKeySequence("Ctrl+S")) save_action.triggered.connect(self.__save_current_file) save_as_action = file_menu.addAction("Save As...") save_as_action.setShortcut(QKeySequence("Ctrl+Shift+S")) save_as_action.triggered.connect(self.__save_current_file_as) file_menu.addSeparator() exit_action = file_menu.addAction("Exit") exit_action.setShortcut(QKeySequence("Alt+f4")) exit_action.triggered.connect(QCoreApplication.quit) help_menu = menu_bar.addMenu("Help") documentation_action = help_menu.addAction("Open Documentation...") documentation_action.triggered.connect( lambda: QDesktopServices.openUrl(libchapters.DOCUMENTATION)) help_menu.addSeparator() about_action = help_menu.addAction("About...") about_action.triggered.connect(self.__show_about_dialog)
def setup_menus(self): file_menu = self.menuBar().addMenu("&File") exit_action = file_menu.addAction("E&xit") exit_action.setShortcut(QKeySequence("Ctrl+Q")) character_menu = self.menuBar().addMenu("&Character") import_action = character_menu.addAction("&Import from PDF") import_action.triggered.connect( lambda: self.pdf_wizard_factory.create(self)) import_action = character_menu.addAction("&Create new Character") import_action.triggered.connect(self.create_new_player) export_menu = self.menuBar().addMenu("&Export") export_debug_action = export_menu.addAction("Export Debug") export_debug_action.triggered.connect( lambda: self.export_pdf_wizard_factory.create(self)) resource_menu = self.menuBar().addMenu("&Resources") open_app_data = resource_menu.addAction("Open Appdata Folder") dir_to_open = QStandardPaths.writableLocation( QStandardPaths.AppDataLocation) open_app_data.triggered.connect( lambda: QDesktopServices.openUrl(dir_to_open)) exit_action.triggered.connect(QApplication.instance().quit) logger.debug("Menus set-up")
def ClickOpenFilePath(self): selected = self.tableWidget.selectedIndexes() selectRows = set() for index in selected: selectRows.add(index.row()) if not selectRows: return # 只去第一个 row = selectRows.pop() col = 0 bookId = self.tableWidget.item(row, col).text() task = self.downloadDict.get(bookId) assert isinstance(task, DownloadInfo) QDesktopServices.openUrl( QUrl.fromLocalFile(os.path.dirname(task.savePath))) return
def open_directory(self, checked=False): """Open file explorer in View data directory.""" url = "file:///" + self.data_dir # noinspection PyTypeChecker, PyCallByClass, PyArgumentList res = QDesktopServices.openUrl(QUrl(url, QUrl.TolerantMode)) if not res: self._toolbox.msg_error.emit("Failed to open directory: {0}".format(self.data_dir))
def openLink(self, key, arg="", fileArg=None): """Use `QDesktopServices` to open an url using the system default applications Parameters: key: the entry key or the link (if `arg` == "link") arg: if `arg` == "file", `fileArg` must be the file name if `arg` == "link", `key` must be the link to be opened for any other values, the link will be generated using the `physbiblio.view.viewWntry.getLink` method fileArg: the file name if `arg` == "file", or the argument passed to `physbiblio.view.viewWntry.getLink` if needed """ if isinstance(key, list): for k in key: self.openLink(k, arg, fileArg) else: if arg == "file": url = QUrl.fromLocalFile(fileArg) elif arg == "link": url = QUrl(key) else: link = self.getLink(key, arg=arg, fileArg=fileArg) url = QUrl(link) if QDesktopServices.openUrl(url): pBLogger.debug(ccstr.openSuccess % (url.toString(), key)) else: pBLogger.warning(ccstr.openFailed % key)
def __menu_opened(self, position): action = self.thumb_menu.exec_( self.tableWidget_shotlist.mapToGlobal(position)) if action == self.action_finder: # self.finderpath set by cell_entered SLOT if self.finderpath: QDesktopServices.openUrl("file:///" + self.finderpath) elif action == self.action_preview: if self.previewitem: self.item_doubleclicked(self.previewitem) elif action == self.action_reindex: self.reindex_clicked() else: pass
def acceptNavigationRequest(self, url: QUrl, type_: QWebEnginePage.NavigationType, is_main_frame: bool) -> bool: if not is_main_frame: return super().acceptNavigationRequest(url, type_, is_main_frame) if (type_ != QWebEnginePage.NavigationTypeTyped and url.authority() != self.url().authority()): # The web is only allowed pages on the same origin # Cross origin pages would open in browser if url.scheme() in ("http", "https"): QDesktopServices.openUrl(url) return False return super().acceptNavigationRequest(url, type_, is_main_frame)
def export_html_report(self): # Report file path name = f'MaterialMerger_Report_{datetime.now().strftime("%d%m%Y_%H%M")}.html' report_file = QUrl.fromLocalFile( os.path.abspath(os.path.expanduser(f'~\\Documents\\{name}'))) # Result browser html content html_data = str(self.resultBrowser.toHtml()) # Write report try: with open(report_file.toLocalFile(), 'w') as f: f.write(html_data) except Exception as e: LOGGER.error(e) QDesktopServices.openUrl(report_file)
def open_directory(self): """Open this item's data directory in file explorer.""" url = "file:///" + self.data_dir # noinspection PyTypeChecker, PyCallByClass, PyArgumentList res = QDesktopServices.openUrl(QUrl(url, QUrl.TolerantMode)) if not res: self._logger.msg_error.emit( f"Failed to open directory: {self.data_dir}")
def _open_psd_file(self, ignore: bool = False): self.ui.lastFileWidget.setEnabled(True) if AppSettings.app['open_editor'] or ignore: external_app_path: Path = Path(AppSettings.app['editor_path']) if external_app_path.exists() and external_app_path.is_file(): # Open Psd in user defined editor args = [ external_app_path.as_posix(), self.current_psd_file.resolve().__str__() ] Popen(args) else: # Default behaviour if no editor set # Open psd thru QDesktopService with OS associated app file_url = QUrl.fromLocalFile(self.current_psd_file.as_posix()) QDesktopServices.openUrl(file_url)
def accessibility_popup(self): global has_prompted_accessibility if has_prompted_accessibility: return has_prompted_accessibility = True msgbox = QMessageBox( QMessageBox.Warning, "Permission required", "RuneKit needs Screen Recording permission\n\nOpen System Preferences > Security > Privacy > Screen Recording to allow this", QMessageBox.Open | QMessageBox.Ignore, ) button = msgbox.exec() if button == QMessageBox.Open: QDesktopServices.openUrl( "x-apple.systempreferences:com.apple.preference.security?Privacy_Screen Recording" )
def data_generate_menu(self, pos): row_num = -1 for i in self.data_list.selectionModel().selection().indexes(): row_num = i.row() if row_num < 0: return menu = QMenu() open_item = menu.addAction("打开文件所在位置") del_item = menu.addAction("移除") delall_item = menu.addAction("移除所有") action = menu.exec_(self.data_list.mapToGlobal(pos)) if action == del_item: self.data_list.takeItem(row_num) elif action == delall_item: self.data_list.clear() elif action == open_item: QDesktopServices.openUrl( QUrl("file:" + os.path.dirname(self.data_list.item(row_num).text())))
def open_results(self, checked=False): """Open output directory in file browser.""" if not os.path.exists(self.output_dir): self._toolbox.msg_warning.emit( "Tool <b>{0}</b> has no results. " "Click Execute to generate them.".format(self.name)) return url = "file:///" + self.output_dir # noinspection PyTypeChecker, PyCallByClass, PyArgumentList res = QDesktopServices.openUrl(QUrl(url, QUrl.TolerantMode)) if not res: self._toolbox.msg_error.emit( "Failed to open directory: {0}".format(self.output_dir))
def doc_action(self, action: QAction): file, tab_page = Path('.'), None if self.context_tab_index >= 0: tab_page = self.ui.view_mgr.tab.widget(self.context_tab_index) file = self.ui.view_mgr.file_mgr.get_file_from_widget( tab_page) or Path('.') if not path_exists(file) or not file.is_file(): self.ui.msg( _('Kein gültiger Pfad für das Dokument gesetzt. Das Dokument muss zuerst gespeichert werden.' ), 5000) return if action == self.copy_action: self.ui.app.clipboard().setText(file.as_posix()) self.ui.msg( _('Dokumenten Pfad wurde in die Zwischenablage kopiert.<br/><i>{}<i>' ).format(file.as_posix())) elif action == self.open_action: q = QUrl.fromLocalFile(file.parent.as_posix()) QDesktopServices.openUrl(q)
def open_data_file(self, index): """Open data file in default program.""" if not index: return if not index.isValid(): logging.error("Index not valid") return data_file = self.data_files()[index.row()] url = "file:///" + os.path.join(self.data_dir, data_file) # noinspection PyTypeChecker, PyCallByClass, PyArgumentList res = QDesktopServices.openUrl(QUrl(url, QUrl.TolerantMode)) if not res: self._logger.msg_error.emit( f"Opening file <b>{data_file}</b> failed")
def open_file(file): QDesktopServices.openUrl(QUrl.fromLocalFile(file))
def launch(self): QDesktopServices.openUrl(QUrl.fromLocalFile(self.fileName))