def exportToPdf(self): data = self.textContent.toPlainText() if not data: return dir = QDir() docsPath = '{}/Documents'.format(dir.homePath()) if not dir.exists(docsPath): docsPath = '{}/Documentos'.format(dir.homePath()) #Regresa una tupla (filename, filter) filename = QFileDialog.getSaveFileName(self, 'Exportar a pdf', docsPath, 'Archivo pdf *.pdf') if not filename: return filename = filename[0] if not '.pdf' in filename: filename += '.pdf' printer = QPrinter(QPrinter.HighResolution) printer.setPaperSize(QPrinter.Letter) printer.setPageMargins(2, 2, 2, 2, QPrinter.Millimeter) printer.setCreator('Notepad') printer.setPrintProgram('Notepad') printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename) self.textContent.print_(printer) self.showMessage('Pdf guardado: {}'.format(filename))
def saveFileAs(self): dir = QDir() docsPath = '{}/Documents'.format(dir.homePath()) if not dir.exists(docsPath): docsPath = '{}/Documentos'.format(dir.homePath()) #Regresa una tupla (filename, filter) filename = QFileDialog.getSaveFileName(self, 'Guardar como', docsPath, self.fileFilter) if not filename: return if self.filename: windowTitle = self.windowTitle().split('-')[0] self.setWindowTitle('{} - {}'.format(windowTitle, filename[0])) else: self.setWindowTitle('{} - {}'.format(self.windowTitle(), filename[0])) self.filename = filename[0] file = QFile(self.filename) if not file.open(QIODevice.WriteOnly): return data = self.textContent.toPlainText() stream = QTextStream(file) stream.setCodec('UTF-8') stream << data file.flush() file.close() self.showMessage('Archivo guardado')
def _browse(self): """Open a dialog box to set the data file The file is opened and we show an alert if annotations are detected. """ # Reload last directory used app_settings = QSettings() last_directory = app_settings.value("last_directory", QDir.homePath()) filepath, filetype = QFileDialog.getOpenFileName( self, self.tr("Open a file"), last_directory, self.tr( "VCF file (*.vcf *.vcf.gz);; CSV file (*.csv *.tsv *.txt)"), ) if filepath: # Display and save directory self.file_path_edit.setText(filepath) app_settings.setValue("last_directory", os.path.dirname(filepath)) if "vcf" in filepath: # TODO: detect annotations on other tyes of files... annotation_type = detect_vcf_annotation(filepath) if annotation_type: text = self.tr( "<b>%s annotations detected!</b>") % annotation_type else: text = self.tr( "<b>No annotation data has been detected!</b>") self.anotation_detect_label.setText(text)
def on_import_clicked(self): """Slot called when import PED file is clicked We open PED file (ped, tfam) to get the their samples that will be associated to the current samples of the project. """ # Reload last directory used app_settings = QSettings() last_directory = app_settings.value("last_directory", QDir.homePath()) filepath, filetype = QFileDialog.getOpenFileName( self, self.tr("Open PED file"), last_directory, self.tr("PED files (*.ped *.tfam)"), ) if not filepath: return LOGGER.info("vcf samples: %s", self.vcf_samples) # Get samples of individual_ids that are already on the VCF file self.view.samples = [ # samples argument is empty dict since its not sample for sample in PedReader(filepath, dict()) if sample[1] in self.vcf_samples ]
def __openEntries(self): didRemoveRows = False if self.tableWidget.rowCount() > 0: messageBox = QMessageBox() messageBox.setWindowTitle("Clear current entries?") messageBox.setText( "Opening a record will delete the current entries. Continue?") messageBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) result = messageBox.exec_() if result == QMessageBox.Ok: didRemoveRows = True model = self.tableWidget.model() # type: QAbstractItemModel for i in range(self.tableWidget.rowCount()): model.removeRow(i) if self.tableWidget.rowCount() == 0 or didRemoveRows: fileName = QFileDialog.getOpenFileName(self.mainWindow, "Open Entry", QDir.homePath(), "CSV Files(*.csv *.txt)") if fileName[0]: with open(fileName[0]) as csvfile: reader = csv.reader(csvfile, delimiter=",") for row in reader: self.tableWidget.insertRow(self.tableWidget.rowCount()) model = self.tableWidget.model() for j in range(self.tableWidget.columnCount()): model.setData( model.index(self.tableWidget.rowCount() - 1, j), row[j])
def openFile(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath()) if fileName != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(fileName))) self.playButton.setEnabled(True)
def go_home(self, checked=False): """Slot for the 'Home' button. Scrolls the treeview to show and select the user's home directory.""" self.ui.comboBox_current_path.setCurrentIndex(-1) home_index = self.file_model.index(QDir.homePath()) self.ui.treeView_file_system.collapseAll() self.ui.treeView_file_system.setCurrentIndex(home_index) self.ui.treeView_file_system.expand(home_index) self.ui.treeView_file_system.scrollTo(home_index, hint=QAbstractItemView.PositionAtTop)
def getConfigFileDir(self): # Get the home directory path homePath = QDir.homePath() if homePath is not None: if homePath[-1] != '/': homePath += '/' debugMessage("HOMEDIR: {}".format(homePath)) return homePath
def add_module(self): module_full_name = QFileDialog.getOpenFileName(self, 'Выберите модуль', QDir.homePath(), '*.module')[0] if module_full_name != '': idx = module_full_name.rfind('/') if idx != -1: module_short_name = module_full_name[idx + 1:] self.check_module(module_full_name, module_short_name)
def open(self): list, _ = QFileDialog.getOpenFileNames(self, 'Open File', QDir.homePath()) for path in list: if path[-3:] == 'm3u': self.load(path) else: self.add_item(path)
def openFile(self): fileName, _ = QFileDialog.getOpenFileName( self, "Open Movie", QDir.homePath() + "/Videos", "Media (*.webm *.mp4 *.ts *.avi *.mpeg *.mpg *.mkv *.VOB *.m4v *.3gp *.mp3 *.m4a *.wav *.ogg *.flac *.m3u *.m3u8)" ) if fileName != '': self.loadFilm(fileName) print("File loaded")
def newNotebook(self): name, ok = QInputDialog.getText( self, "Notebook name", "How would you like your notebook to be named?") if ok: storagePath = QDir.homePath() + "/.config/wikinotebook/" + name nb = self.nbManager.createNewNotebook(name, storagePath) self.switchNotebook(nb.name)
def __init__(self, label: str, button_label: str): super().__init__(QFileDialog()) self.__label = label self.__button_label = button_label self._default_path = QDir.homePath() self.__value_changed_callbacks = [] self.__line_edit = None self.__button = None
def change_video(self, row): dialog = QFileDialog(self, caption="Open Video", directory=QDir.homePath()) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): video_name = self.list_model.item(row, 0) videos = self.list_model.item(row, 2) v = dialog.selectedFiles()[0] video_name.setText(pathlib.Path(v).name) videos.setText(v)
def change_question(self, row): dialog = QFileDialog(self, caption="Open Question", directory=QDir.homePath()) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): questions_name = self.list_model.item(row, 1) questions = self.list_model.item(row, 3) q = dialog.selectedFiles()[0] questions_name.setText(pathlib.Path(q).name) questions.setText(q)
def add_questions(self): dialog = QFileDialog(self, caption="Open Questions", directory=QDir.homePath()) dialog.setFileMode(QFileDialog.ExistingFiles) dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): question_names = dialog.selectedFiles() for question in question_names: last = self.find_last_row('question') if last == -1: self.add_item(question=question) else: self.edit_item(index=last, question=question)
def add_videos(self): dialog = QFileDialog(self, caption="Open Video", directory=QDir.homePath()) dialog.setFileMode(QFileDialog.ExistingFiles) dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): video_names = dialog.selectedFiles() for video in video_names: last = self.find_last_row('video') if last == -1: self.add_item(video=video) else: self.edit_item(index=last, video=video)
def getFilePath(self, caption="find", filters=""): result = {} result["error"] = True result["name"] = "" result["fullname"] = "" #"Buscar Imagen Nueva", #tr("Imagenes (*.png *.xpm *.jpg *.gif *.jpeg *.bmp *ppm)") namefile = QFileDialog.getOpenFileName(None, caption, QDir.homePath(), filters) if namefile[0] != "": result["error"] = False result["name"] = QFileInfo(namefile[0]).fileName() result["fullname"] = namefile[0] return result
def openFile(self): dir = QDir() docsPath = '{}/Documents'.format(dir.homePath()) if not dir.exists(docsPath): docsPath = '{}/Documentos'.format(dir.homePath()) #Regresa una tupla (filename, filter) filename = QFileDialog.getOpenFileName(self, 'Abrir', docsPath, self.fileFilter) if not filename: return self.filename = filename[0] file = QFile(self.filename) if not file.open(QIODevice.ReadOnly): return data = file.readAll() file.close() self.textContent.clear() self.textContent.setText(str(data, encoding='utf-8')) self.setWindowTitle('{} - {}'.format(self.windowTitle(), self.filename))
def open_directory(self): directory_url = QFileDialog.getExistingDirectory( self, '0Open directory', QDir.homePath()) dir = QDir(directory_url) filters = [ '*.mp4', '*.m4v', '*.mov', '*.mpg', '*.mpeg', '*.mp3', '*.m4a', '*.wmv', '*.wav', '*.aiff' ] dir.setNameFilters(filters) file_list = dir.entryList() path = dir.absolutePath() + '/' for file in file_list: self.add_item(path + file)
def export_as_csv(self): """Export variants into CSV file""" # Reload last directory used last_directory = self.app_settings.value("last_directory", QDir.homePath()) filepath, _ = QFileDialog.getSaveFileName(self, self.tr("Save project"), last_directory, self.tr("(*.csv)")) if filepath: with open(filepath, "w") as file: writer = CsvWriter(file) writer.save(self.conn)
def on_load_file(self): """Allow to automatically add words from a file See Also: :meth:`load_file` """ # Reload last directory used last_directory = QSettings().value("last_directory", QDir.homePath()) filepath, _ = QFileDialog.getOpenFileName(self, self.tr("Open Word set"), last_directory, self.tr("Text file (*.txt)")) if filepath: self.load_file(filepath)
def load_config(self): """Loads EnigmaAPI settings from a config file and refershes GUI""" dialog = QFileDialog(self) filename = dialog.getOpenFileName(self, "Load settings", QDir.homePath(), "Enigma config (*.json)")[0] if filename: try: self.__enigma_api.load_from(filename) logging.info('Successfully loaded config from file "%s"', filename) except (FileNotFoundError, JSONDecodeError) as error: QMessageBox.critical( self, "Load config", "Error retrieving data from " "selected file!\nError message:\n\n %s" % repr(error), ) logging.error('Failed to load config from file "%s"', filename, exc_info=True) return except Exception as error: QMessageBox.critical( self, "Load config", "Following error occured during " "applying loaded settings:\n%s" % repr(error), ) logging.error( "Unable to load config from file, keeping old settings...", exc_info=True, ) return # Refresh gui after loading setings self.__rotors.generate_rotors() self.__input_textbox.blockSignals(True) self.refresh_gui() self.__input_textbox.blockSignals(False) self.__rotors.set_positions() logging.info('Checkpoint set to "%s"', str(self.__enigma_api.positions())) self.__enigma_api.set_checkpoint() else: logging.info("No load file selected...")
def video_directory(self): dialog = QFileDialog(self, caption="Open Video Directory", directory=QDir.homePath()) dialog.setFileMode(QFileDialog.Directory) dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): dir_names = dialog.selectedFiles() dir_path = pathlib.Path(dir_names[0]) files = [] for ext in self.vtype_s: files.extend(dir_path.glob(ext)) for video in files: last = self.find_last_row('video') if last == -1: self.add_item(video=str(video)) else: self.edit_item(index=last, video=str(video))
def openProjectBtnHandler(self): """ Handler invoked when the "Open" button is pressed. It causes the plugin to open a file open dialog and then subsequently opening the, by the user, selected file. """ lastPath = self.openFilePath dflPath = lastPath if lastPath != "" else QDir.homePath() filename = QFileDialog.getOpenFileName( self, self.tr("Open BCF File"), dflPath, self.tr("BCF Files (*.bcf *.bcfzip)")) if filename[0] != "": model.openProjectBtnHandler(filename[0]) self.openFilePath = filename[0] self.projectOpened.emit()
def export_message(self): """Opens a dialog to get the save location, exports current Enigma settings and encrypted message to the file""" dialog = QFileDialog(self) filename = dialog.getSaveFileName(self, "Save Enigma message", QDir.homePath(), "*.txt")[0] if filename and not findall(r"\.txt$", filename): filename += ".txt" logging.info( ".txt file extension for save file not found, adding...") if filename: logging.info('Exporing message to "%s"...', filename) with open(filename, "w") as file: message = "\n".join(wrap(self.__output_textbox.text(), 29)) file.write("%s\n%s\n" % (str(self.__enigma_api), message))
def export_ped(self): """Export samples into PED/PLINK file""" # Reload last directory used last_directory = self.app_settings.value("last_directory", QDir.homePath()) # noinspection PyCallByClass filepath, _ = QFileDialog.getSaveFileName(self, self.tr("Save project"), last_directory, "(*.tfam)") if filepath: filepath = filepath if filepath.endswith( ".tfam") else filepath + ".tfam" with open(filepath, "w") as file: writer = PedWriter(file) writer.save(self.conn)
def save_config(self): """Collects data from EnigmaAPI and saves it to selected filename""" dialog = QFileDialog(self) dialog.setDefaultSuffix("json") filename = dialog.getSaveFileName(self, "Save settings", QDir.homePath(), "Enigma config (*.json)")[0] # To prevent from saving files without a file extension... if filename and not findall(r"\.json$", filename.lower()): filename += ".json" logging.info( ".json file extension for save file not found, adding...") if filename: self.__enigma_api.save_to(filename) else: logging.info("No save file selected...")
def __init__(self): super().__init__() self.setTitle(self.tr("Project creation")) self.setSubTitle( self.tr( "This wizard will guide you to create a cutevariant project.")) # Reload last directory used app_settings = QSettings() self.last_directory = app_settings.value("last_directory", QDir.homePath()) self.project_name_edit = QLineEdit() self.project_path_edit = QLineEdit() self.project_path_edit.setText(self.last_directory) self.browse_button = QPushButton(self.tr("Browse")) self.reference = QComboBox() # Unused for now self.reference.hide() self.reference.addItem("hg19") self.registerField("project_name", self.project_name_edit, "text") self.registerField("project_path", self.project_path_edit, "text") self.registerField("reference", self.reference, "currentText") v_layout = QFormLayout() browse_layout = QHBoxLayout() browse_layout.addWidget(self.project_path_edit) browse_layout.addWidget(self.browse_button) browse_layout.setContentsMargins(0, 0, 0, 0) v_layout.addRow(self.tr("Reference genom"), self.reference) v_layout.addRow(self.tr("Project Name"), self.project_name_edit) v_layout.addRow(self.tr("Create in"), browse_layout) self.setLayout(v_layout) self.browse_button.clicked.connect(self._browse) self.project_path_edit.textChanged.connect(self.completeChanged) self.project_name_edit.textChanged.connect(self.completeChanged)
def open_project(self): """Slot to open an already existing project from a QFileDialog""" # Reload last directory used last_directory = self.app_settings.value("last_directory", QDir.homePath()) filepath, _ = QFileDialog.getOpenFileName( self, self.tr("Open project"), last_directory, self.tr("Cutevariant project (*.db)"), ) if filepath: try: self.open(filepath) except Exception as e: self.status_bar.showMessage(e.__class__.__name__ + ": " + str(e)) raise