def __init__(self, previewImage, fileName): super(ImageView, self).__init__() self.fileName = fileName mainLayout = QVBoxLayout(self) self.imageLabel = QLabel() self.imageLabel.setPixmap(QPixmap.fromImage(previewImage)) mainLayout.addWidget(self.imageLabel) topLayout = QHBoxLayout() self.fileNameLabel = QLabel(QDir.toNativeSeparators(fileName)) self.fileNameLabel.setTextInteractionFlags(Qt.TextBrowserInteraction) topLayout.addWidget(self.fileNameLabel) topLayout.addStretch() copyButton = QPushButton("Copy") copyButton.setToolTip("Copy file name to clipboard") topLayout.addWidget(copyButton) copyButton.clicked.connect(self.copy) launchButton = QPushButton("Launch") launchButton.setToolTip("Launch image viewer") topLayout.addWidget(launchButton) launchButton.clicked.connect(self.launch) mainLayout.addLayout(topLayout)
def func_browse_eve(self): folder = QDir.toNativeSeparators( QFileDialog.getExistingDirectory(None, "Eve Directory", "", QFileDialog.ShowDirsOnly)) if not folder.endswith(os.sep): folder += os.sep self.ui.txt_client_path.setText(folder) self.settings['eve_path'] = folder
def _update_tool_tip(self): path = self._download_item.path() tool_tip = "{}\n{}".format(self._download_item.url().toString(), QDir.toNativeSeparators(path)) total_bytes = self._download_item.total_bytes() if total_bytes > 0: tool_tip += "\n{}K".format(total_bytes / 1024) state = self.state() if state == QWebEngineDownloadItem.DownloadRequested: tool_tip += "\n(requested)" elif state == QWebEngineDownloadItem.DownloadInProgress: tool_tip += "\n(downloading)" elif state == QWebEngineDownloadItem.DownloadCompleted: tool_tip += "\n(completed)" elif state == QWebEngineDownloadItem.DownloadCancelled: tool_tip += "\n(cancelled)" else: tool_tip += "\n(interrupted)" self.setToolTip(tool_tip)
def __init__(self, toolbox): """ Args: toolbox (ToolboxUI): QMainWindow instance """ from ..ui import open_project_dialog # pylint: disable=import-outside-toplevel super().__init__( parent=toolbox, f=Qt.Dialog) # Setting the parent inherits the stylesheet self._toolbox = toolbox # Set up the user interface from Designer file self.ui = open_project_dialog.Ui_Dialog() self.ui.setupUi(self) self.combobox_context_menu = None # Ensure this dialog is garbage-collected when closed self.setAttribute(Qt.WA_DeleteOnClose) # QActions for keyboard shortcuts self.go_root_action = QAction(self) self.go_home_action = QAction(self) self.go_documents_action = QAction(self) self.go_desktop_action = QAction(self) self.set_keyboard_shortcuts() self.selected_path = "" self.cb_ss = self.ui.comboBox_current_path.styleSheet() self.file_model = CustomQFileSystemModel() self.file_model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) self.icon_provider = ProjectDirectoryIconProvider() self.file_model.setIconProvider(self.icon_provider) self.file_model.setRootPath(QDir.rootPath()) self.ui.treeView_file_system.setModel(self.file_model) self.file_model.sort(0, Qt.AscendingOrder) # Enable validator (experimental, not very useful here) # Validator prevents typing Invalid strings to combobox. (not in use) # When text in combobox is Intermediate, the validator prevents emitting # currentIndexChanged signal when enter is pressed. # Pressing enter still triggers the done() slot of the QDialog. self.validator = DirValidator() self.ui.comboBox_current_path.setValidator(self.validator) self.ui.comboBox_current_path.setInsertPolicy(QComboBox.NoInsert) # Read recent project directories and populate combobox recents = self._toolbox.qsettings().value( "appSettings/recentProjectStorages", defaultValue=None) if recents: recents_lst = str(recents).split("\n") self.ui.comboBox_current_path.insertItems(0, recents_lst) # Set start index to most recent project storage or to root if it does not exist p = self.ui.comboBox_current_path.itemText(0) if os.path.isdir(p): start_index = self.file_model.index(p) else: start_index = self.file_model.index(QDir.rootPath()) else: start_index = self.file_model.index(QDir.rootPath()) self.ui.comboBox_current_path.setCurrentIndex(-1) self.file_model.directoryLoaded.connect(self.expand_and_resize) # Start browsing to start index immediately when dialog is shown self.start_path = self.file_model.filePath(start_index) self.starting_up = True self.ui.treeView_file_system.setCurrentIndex(start_index) self.connect_signals()
def InstallApk(self, Name = "", ListoptionADB = ""):#Locate APK in ressources dir DossierProject = QDir(self.PathProject) DossierProject.cd('Ressource') PathAPK = DossierProject.absoluteFilePath(Name) print(self.CallADB("install "+ListoptionADB+" "+PathAPK))
def saveDlg(img, mainWidget): """ Image saving dialogs. The actual saving is done by a call to mImage.save(). Metadata is copied from sidecar to image file. The function returns the image file name. Exception ValueError or IOError are raised if the saving fails. @param img: @type img: vImage @param mainWidget: @type mainWidget: QWidget @return: filename @rtype: str """ # get last accessed dir lastDir = str(mainWidget.settings.value("paths/dlgdir", QDir.currentPath())) # file dialogs dlg = savingDialog(mainWidget, "Save", lastDir) # default saving format JPG dlg.selectFile(img.filename[:-3] + 'JPG') dlg.dlg.currentChanged.connect(lambda f: print(f)) if dlg.exec_(): newDir = dlg.directory().absolutePath() mainWidget.settings.setValue('paths/dlgdir', newDir) filenames = dlg.selectedFiles() if filenames: filename = filenames[0] else: raise ValueError("You must select a file") if isfile(filename): reply = QMessageBox() reply.setWindowTitle('Warning') reply.setIcon(QMessageBox.Warning) reply.setText("File %s already exists\n" % filename) reply.setStandardButtons(QMessageBox.Cancel) accButton = QPushButton("Save as New Copy") rejButton = QPushButton("OverWrite") reply.addButton(accButton, QMessageBox.AcceptRole) reply.addButton(rejButton, QMessageBox.RejectRole) reply.setDefaultButton(accButton) reply.exec_() retButton = reply.clickedButton() # build a unique name if retButton is accButton: i = 0 base = filename if '_copy' in base: flag = '_' else: flag = '_copy' while isfile(filename): filename = base[:-4] + flag + str(i) + base[-4:] i = i + 1 # overwrite elif retButton is rejButton: pass else: raise ValueError("Saving Operation Failure") # get parameters quality = dlg.sliderQual.value() compression = dlg.sliderComp.value() # call mImage.save to write image to file and return a thumbnail # throw ValueError or IOError thumb = img.save(filename, quality=quality, compression=compression) # write metadata if not dlg.metaOption.isChecked(): tempFilename = mktemp('.jpg') # save thumb jpg to temp file thumb.save(tempFilename) # copy temp file to image file img.restoreMeta(img.filename, filename, thumbfile=tempFilename) os.remove(tempFilename) return filename else: raise ValueError("Saving Operation Failure")
def selectSystemTranslation(self, language, typemodule): dirsystem = "systemnet" if typemodule == True else "system" dirsyslan = QDir(self.mDir + QDir.separator() + dirsystem) if dirsyslan.exists(): if QFileInfo(dirsyslan.path() + QDir.separator() + language + ".qm").exists(): translator = QTranslator(self) translator.load(dirsyslan.path() + QDir.separator() + language) self.mApp.installTranslator(translator) else: language = language.split('_')[0] if len(language) == 2: if QFileInfo(dirsyslan.path() + QDir.separator() + language + ".qm").exists(): translator = QTranslator(self) translator.load(dirsyslan.path() + QDir.separator() + language) self.mApp.installTranslator(translator)
def selectCoreTranslation(self, language, settings): settings.setValue("translate", "en") dircorelan = QDir(self.mDir + QDir.separator() + "corelocale") if dircorelan.exists(): if QFileInfo(dircorelan.path() + QDir.separator() + language + ".qm").exists(): settings.setValue("translate", language) translator = QTranslator(self) translator.load(dircorelan.path() + QDir.separator() + language) self.mApp.installTranslator(translator) else: language = language.split('_')[0] if len(language) == 2: if QFileInfo(dircorelan.path() + QDir.separator() + language + ".qm").exists(): settings.setValue("translate", language) translator = QTranslator(self) translator.load(dircorelan.path() + QDir.separator() + language) self.mApp.installTranslator(translator)
def browse_destination(self): dest_dir = QFileDialog.getExistingDirectory(self, 'Open directory', QDir.homePath()) if len(dest_dir) != 0: self.ui.editDestination.setText(dest_dir)
def action_record_stop_button(self): # check if the session name & video path file fields are filled if not self.session_name.text() or not self.video_file_path.text(): self.error_dialog( 'Please inform both the Session Name and the Video/Audio Path!' ) return # check if the directory exists if not QDir(self.video_file_path.text()).exists(): self.error_dialog('The directory {} does not exist!'.format( self.video_file_path.text())) return # check if the directory is writable if not os.access(self.video_file_path.text(), os.W_OK): self.error_dialog('The directory {} is not writable!'.format( self.video_file_path.text())) return if self.recording: # it is already recording # we will stop the session self.recording_label.setPixmap(cfg.ASSETS_IMAGES_FOLDER + 'gray_rec.png') self.record_stop_button.setText('Record session') # enable fields self.session_name.setEnabled(True) self.video_file_path.setEnabled(True) self.list_cameras.setEnabled(True) self.list_audio_devices.setEnabled(True) self.list_backing_tracks.setEnabled(True) self.volume_slider.setEnabled(True) # stop session self.record_session.stop() # restart camera self.wait_for_video_process() else: # it is not yet recording # we will start the session # on MacOs it is possible to keep showing the camera # on GUI while it is recording the SAME camera. # Unfortunately, it is not possible neither on Linux # nor on Windows. This is the reason why we are # stopping the camera here and restarting it # after the recording is finished self.camera.stop() self.recording_label.setPixmap(cfg.ASSETS_IMAGES_FOLDER + 'red_rec.png') self.record_stop_button.setText('Recording… Press here to stop') # disable fields self.session_name.setEnabled(False) self.video_file_path.setEnabled(False) self.list_cameras.setEnabled(False) self.list_audio_devices.setEnabled(False) self.list_backing_tracks.setEnabled(False) self.volume_slider.setEnabled(False) # start session if self.backing_track_player.state( ) == QMediaPlayer.State.PlayingState: self.backing_track_player.stop() self.record_session.start_recording( self.session_name.text(), self.video_file_path.text(), self.list_cameras.currentData().description(), self.list_audio_devices.currentData(), self.list_backing_tracks.currentText(), int(self.volume_slider.value())) self.recording = not self.recording
class Loader(QWidget): def __init__(self, parent=None): super(Loader, self).__init__(parent=parent) self.ui = Ui_Loader() self.ui.setupUi(self) self.dir = QDir(QDir.currentPath() + '/programs/') self.dir.setFilter(QDir.Files or QDir.NoDotAndDotDot) self.fs_watcher = QFileSystemWatcher(self.dir.path()) self.fs_watcher.addPath(self.dir.path()) self.fs_watcher.directoryChanged.connect(self.update_program_list) self.send_status = QProgressDialog self.sender = Sender self.serialpropertiesvalues = \ { 'baudrate': Serial.BAUDRATES, 'parity': Serial.PARITIES, 'databits': Serial.BYTESIZES, 'stopbits': Serial.STOPBITS, 'flowcontrol': ['NoControl', 'SoftwareControl', 'HardwareControl'] } self.update_program_list() self.update_serial_port_list() # self.set_serial_port_options() self.ui.updateProgramListButton.clicked.connect(self.refresh) self.ui.programListWidget.itemSelectionChanged.connect( self.selection_changed) self.ui.sendButton.clicked.connect(self.send_program) self.ui.serialPortChooser.currentTextChanged.connect( self.selection_changed) self.ui.serialPortChooser.currentTextChanged.connect(save_port) # self.ui.baudRateInput.textChanged.connect(save_baud) # self.ui.parityChooser.currentTextChanged.connect(save_parity) # self.ui.dataBitsChooser.currentTextChanged.connect(save_databits) # self.ui.stopBitsChooser.currentTextChanged.connect(save_stopbits) # self.ui.flowControlChooser.currentTextChanged.connect(save_flowcontrol) self.thread_pool = QThreadPool() def set_serial_port_options(self): for key in parities.keys(): self.ui.parityChooser.addItem(key) for key in bytesize.keys(): self.ui.dataBitsChooser.addItem(key) for key in stopbits.keys(): self.ui.stopBitsChooser.addItem(key) self.ui.flowControlChooser.addItems(flowcontrol) if globalSettings.contains('serialport/port'): self.selectpreviousvalues() else: self.saveconfig() def selectpreviousvalues(self): self.ui.serialPortChooser.setCurrentText( globalSettings.value('serialport/port')) self.ui.baudRateInput.setText( globalSettings.value('serialport/baudrate')) self.ui.parityChooser.setCurrentText( globalSettings.value('serialport/parity')) self.ui.dataBitsChooser.setCurrentText( globalSettings.value('serialport/databits')) self.ui.stopBitsChooser.setCurrentText( globalSettings.value('serialport/stopbits')) self.ui.flowControlChooser.setCurrentText( globalSettings.value('serialport/flowcontrol')) def saveconfig(self): save_port(self.ui.serialPortChooser.currentText()) save_baud(self.ui.baudRateInput.text()) save_parity(self.ui.parityChooser.currentText()) save_databits(self.ui.dataBitsChooser.currentText()) save_stopbits(self.ui.stopBitsChooser.currentText()) save_flowcontrol(self.ui.flowControlChooser.currentText()) def update_serial_port_list(self): self.ui.serialPortChooser.clear() for port in list_ports.comports(): self.ui.serialPortChooser.addItem(port.device) def update_program_list(self): self.ui.programListWidget.clear() self.dir.refresh() self.ui.programListWidget.addItems(self.dir.entryList()) self.ui.programListWidget.clearSelection() def selection_changed(self): if self.ui.serialPortChooser.currentText() is not None \ and self.ui.programListWidget.currentItem() is not None: self.ui.sendButton.setEnabled(True) else: self.ui.sendButton.setDisabled(True) def refresh(self): self.update_program_list() self.update_serial_port_list() def send_program(self): selections = self.ui.programListWidget.selectedItems() for selection in selections: filename = selection.text() filepath = self.dir.path() + '/' + filename port_chosen = self.ui.serialPortChooser.currentText() confirm = ConfirmSend(self) confirm.ui.dialogLabel.setText(f'Send program \'{filename}\'?') confirm.exec() if confirm.result() == QDialog.Accepted: self.send_status = QProgressDialog(self) self.sender = Sender( port_chosen, filepath, globalSettings.value('serialport/baudrate'), globalSettings.value('serialport/databits'), globalSettings.value('serialport/parity'), globalSettings.value('serialport/stopbits'), globalSettings.value('serialport/flowcontrol'), self) self.send_status.setMaximum(self.sender.file.size()) self.send_status.canceled.connect(self.sender.cancel) self.sender.signals.update_status.connect( self.send_status.setValue) self.thread_pool.start(self.sender) self.send_status.exec_() self.send_status.deleteLater()
def get_paths(): # TODO 将来地区多了需要重新设计 # TODO 增加所有的json文件夹 base_dir = Path(QDir.currentPath()) paths = base_dir / "data" / "行测" / "国家" / "json" return (paths,)
def _on_repo_clicked(self): directory = QFileDialog.getExistingDirectory( self, "Select sync repo", "", QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) self._repo_edit.setText(QDir.toNativeSeparators(directory))
def isComplete(self): """Conditions to unlock next button""" return True if (QDir(self.project_path_edit.text()).exists() and self.project_path_edit.text() and self.project_name_edit.text()) else False
def setUp(self): self.original = QDir("./")
def open(self): if (self.maybeSave()): fileName = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) if not fileName.isEmpty(): self.scribbleArea.openImage(fileName)
class MainWindow(QMainWindow): # Home do usuário. home = QDir().home().path() def __init__(self): super(MainWindow, self).__init__() # Caminho até o arquivo de interface. # path = QDir(__file__).currentPath() # ui_file = QDir(path).filePath('MainWindow.ui') ui_file = QDir(QDir(__file__).currentPath()).filePath('MainWindow.ui') # Carregando o arquivo de interface. self.ui = QUiLoader().load(ui_file, None) # Widgets. self.label = self.ui.findChild(QObject, 'label') btn_open_file = self.ui.findChild(QObject, 'btn_open_file') btn_open_file.clicked.connect(self.open_file_dialog) btn_open_files = self.ui.findChild(QObject, 'btn_open_files') btn_open_files.clicked.connect(self.open_files_dialog) btn_open_dir = self.ui.findChild(QObject, 'btn_open_dir') btn_open_dir.clicked.connect(self.open_dir_dialog) btn_save_file = self.ui.findChild(QObject, 'btn_save_file') btn_save_file.clicked.connect(self.open_save_dialog) self.ui.show() def open_file_dialog(self): file = QFileDialog().getOpenFileName( parent=self, caption='Selecione um arquivo', dir=str(self.home), filter=('PNG (*.png);;JPG (*.jpg, *.jpeg);;' 'TXT (*.txt);;Todos (*.*)'), ) if file[0]: self.label.setText( f'<b>Arquivo selecionado</b>: {file[0]}<br>' f'<b>Filtro utilizado</b>: {file[1]}', ) def open_files_dialog(self): files = QFileDialog().getOpenFileNames( parent=self, caption='Selecione os arquivos', dir=str(self.home), filter=('PNG (*.png);;JPG (*.jpg, *.jpeg);;' 'TXT (*.txt);;Todos (*.*)'), ) if files[0]: text = '<b>Arquivos selecionados</b>:<br>' for file in files[0]: text += f'- {file}<br>' text += f'<b>Filtro utilizado</b>: {files[1]}' self.label.setText(text) def open_dir_dialog(self): path = QFileDialog().getExistingDirectory( parent=self, caption='Selecione um diretório', dir=str(self.home), ) if path: self.label.setText(f'<b>Diretório selecionado</b>: {path}') def open_save_dialog(self): file = QFileDialog().getSaveFileName( parent=self, caption='Salvar arquivo', dir=str(self.home), filter='.png;;.txt;;.jpg;;', ) if file[0]: if file[0].endswith(file[1]): text = f'<b>Arquivo salvo em</b>: {file[0]}<br>' else: text = f'<b>Arquivo salvo em</b>: {file[0]}{file[1]}<br>' text += f'<b>Filtro utilizado</b>: {file[1]}' self.label.setText(text)
def __init__(self, parent=None): QObject.__init__(self, parent) self.mpid = "" self.mDir = QDir.currentPath() self.mApp = parent
def testBeginEntryList(self): obj = TestFSHandler() qdir = QDir('/bup') for n1, n2 in zip(qdir.entryList(), ['.', '..', 'A', 'B', 'C']): self.assertEqual(n1, n2) self.assertEqual(len(qdir.entryList()), 5)
def browse_source(self): source_file = QFileDialog.getOpenFileName(self, 'Open file', QDir.homePath(), 'PDF files (*.pdf)') if len(source_file[0]) != 0: self.ui.editSource.setText(source_file[0])