def saveDlg(img, mainWidget, selected=True): """ Image saving dialog. If selected is False, initially the filename box is left empty and no file is selected. A ValueError exception is raised if the dialog is aborted. @param img: @type img: vImage @param mainWidget: @type mainWidget: QWidget @param selected: @type selected: boolean @return: filename, quality, compression, metaOption @rtype: str, int, int, boolean """ # get last accessed dir lastDir = str( mainWidget.settings.value("paths/dlgsavedir", QDir.currentPath())) # file dialogs dlg = savingDialog(mainWidget, "Save", lastDir) if selected: # default saving format jpg dlg.selectFile(img.filename[:-3] + 'jpg') filename = '' if dlg.exec_(): newDir = dlg.directory().absolutePath() mainWidget.settings.setValue('paths/dlgsavedir', newDir) filenames = dlg.selectedFiles() if filenames: filename = filenames[0] else: raise ValueError("You must select a file") return filename, dlg.sliderQual.value(), dlg.sliderComp.value( ), not dlg.metaOption.isChecked()
def __init__(self): QMainWindow.__init__(self) # 设置时间 self.__time = QDateTime() # 创建图形界面 self.__SetupUI() self.__ConfigureFileToolBar() self.__ConfigureTranslateToolBar() self.__ConfigureMainLayout() # 设置ComboBox的显示内容 self.__ConfigureComboBox() # 设置保存文件的信息 self.__currentPath = QDir.currentPath() self.__ConfigureSysIniFile() self.__ConfigureHistoryFile() salt = random.randint(1466000000, 1467000000) self.__salt = str(salt) self.__httpClient = None self.__statusBar.showMessage( self.__GetCurrentTime() + " - Please choose a file or enter data!", 2000) self.show()
def __init__(self): DossierActuel = QDir(QDir.currentPath()) if not DossierActuel.cd("platform-tools"): url = None if platform.system() == "Windows": url = 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip' elif platform.system() == "Darwin": #MacOS url = 'https://dl.google.com/android/repository/platform-tools-latest-darwin.zip' elif platform.system() == "Linux": url = 'https://dl.google.com/android/repository/platform-tools-latest-linux.zip' reply = requests.get(url) zip_ref = zipfile.ZipFile(io.BytesIO(reply.content)) zip_ref.extractall(DossierActuel.absolutePath()) zip_ref.close() super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.Manager = ManagerDevice(self) self.Manager.start() self.ui.SelectScript.clicked.connect(self.LoadScripts) self.ui.SelectData.clicked.connect(self.LoadData) self.ui.ButtonAllGo.clicked.connect(self.ButtonAllGo) self.ui.tableWidget.itemActivated.connect(self.ClickDevice)
def tree_init(self): self.tree.setModel(self.model) self.tree.setRootIndex( self.model.index(QDir.currentPath() + "/model/storage")) self.tree.clicked.connect(self.file_clicked) self.setWidget(self.tree)
def _dialog(title, name_filter, default_suffix): dialog = QtWidgets.QFileDialog() dialog.setWindowTitle(title) dialog.setNameFilter(name_filter) dialog.setDefaultSuffix(default_suffix) dialog.setDirectory(QDir.currentPath()) dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) return dialog
def __init__(self, tree): super(TreeViewModelItem, self).__init__() self.__tree = tree self.__current = tree self.__view = None self.setRootPath(QDir.currentPath()) self.setIconProvider(EmptyIconProvider()) self.setFilter(QDir.NoDotAndDotDot | QDir.Dirs)
def __init__(self): QDockWidget.__init__(self, "File Menager") self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) model = QFileSystemModel() model.setRootPath(QDir.currentPath()) tree = QTreeView() tree.setModel(model) self.setWidget(tree)
def CallADB(self, Message): self.LastScreen = "" DossierActuel = QDir(QDir.currentPath()) DossierActuel.cd("platform-tools") PathExecutable = "" if platform.system() == "Windows": PathExecutable = DossierActuel.absoluteFilePath("adb.exe") else: PathExecutable = DossierActuel.absoluteFilePath("adb") result = subprocess.run(PathExecutable+" "+Message, env={**os.environ, 'ANDROID_SERIAL': self.SerialNumber}, capture_output=True) return result
def handle_input(self): current_path = QDir.currentPath() filter = QDir(current_path, "text files (*.txt)").filter() dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter(filter) filename = dlg.getOpenFileName() f = open(filename[0], 'r', encoding='utf-8-sig') self.ui.inputFileLabel.setText(filename[0].split('/')[-1]) with f: self.query_list = f.read().splitlines() return
def open_video(): # 打开文件对话框 file_dir, _ = QFileDialog.getOpenFileName(window.pushButton, "打开视频", QDir.currentPath(), "视频文件(*.mp4 *.avi );;所有文件(*)") # 判断是否正确打开文件 if not file_dir: QMessageBox.warning(window.pushButton, "警告", "文件错误或打开文件失败!", QMessageBox.Yes) return print("读入文件成功") # 返回视频路径 return file_dir
def open_file(self): files = QFileDialog.getOpenFileNames(self, "Open file", QDir.currentPath(), "Files (*.csv *.txt)") for file in files[0]: if (file not in self.data_sets): data = read_file(file) if (data is not None): self.data_sets[file] = data self.settings.setValue("work_dir", QFileInfo(file).absolutePath()) self.output_widget.add_to_list(file) else: QMessageBox.critical(self, "Main window", "File " + file[0] + " has an unknown format!") self.data_table.initialize(self.data_sets)
def on_convert(self): export_dialog = QFileDialog() outfile = export_dialog.getSaveFileName(self, "Export to csv file", QDir.currentPath() + "/preview.csv", "csv (*.csv)") info = self.output_widget.output_info() min_rows = min([data.shape[0] for data in self.data_sets.values()]) if (info["first_line"] < 1 or info["first_line"] > min_rows or info["last_line"] < 1 or info["last_line"] > min_rows or info["first_line"] > info["last_line"]): QMessageBox.critical(self, "Row range", "Invalid row range!") else: self.write_file(outfile[0], info["files"], info["first_line"], info["last_line"])
def model_view(): app = QApplication() splitter = QSplitter() model = QFileSystemModel() model.setRootPath(QDir.currentPath()) parentIndex = model.index(QDir.currentPath()) tree = QTreeView(splitter) tree.setModel(model) tree.setRootIndex(parentIndex) list = QListView(splitter) list.setModel(model) list.setRootIndex(parentIndex) table = QTableView(splitter) table.setModel(model) table.setRootIndex(parentIndex) splitter.setWindowTitle("Two views onto the same file system model") splitter.show() app.exec_()
def openFolder(self): self.folderDialog = QFileDialog(self) self.folderDialog.setDirectory(QDir.currentPath()) self.folderDialog.setFileMode(QFileDialog.FileMode.Directory) self.defaultDirectory = self.folderDialog.getExistingDirectory() self.imagesDir = self.defaultDirectory if self.defaultDirectory: self.defaultDirectoryExists = True first_image = str(self.defaultDirectory + "/t0.jpg") print(first_image) self.ui_window.inputImg.setPixmap(first_image) self.opdir = first_image self.inputExists = True self.findImages()
def __init__(self, parent: Optional[QWidget]=...): super().__init__(parent) self.setContextMenuPolicy(Qt.NoContextMenu) url = QUrl.fromLocalFile(QDir.currentPath() + '/resource/dist/index.html') self.channel = QWebChannel() self.channel.registerObject('signalHub', signalHub) self.page().setWebChannel(self.channel) self.page().profile().downloadRequested.connect( self.downloadPlotPngRequested) self.load(url) self.show() signalHub.dataFileOpened.connect(self.clearPlot)
def openImage(self): self.fileDialog = QFileDialog(self) if self.defaultDirectoryExists: self.fileDialog.setDirectory(self.defaultDirectory) else: self.fileDialog.setDirectory(QDir.currentPath()) filters = ["*.png", "*.xpm", "*.jpg"] self.fileDialog.setNameFilters("Images (*.png *.jpg)") self.fileDialog.selectNameFilter("Images (*.png *.jpg)") #self.fileDialog.setFilter(self.fileDialog.selectedNameFilter()) self.opdir = self.fileDialog.getOpenFileName()[0] self.imagesDir = os.path.dirname(self.opdir) if self.opdir: self.inputExists = True self.ui_window.inputImg.setPixmap(self.opdir)
def save_text(self): frmat = '.txt' initial_path = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) if not initial_path: initial_path = QDir.currentPath() initial_path += '/Screenshot_Text-' + \ str(datetime.now()).replace(' ', '_') + frmat file_dialog = QFileDialog(self, "Save as", initial_path) file_dialog.setAcceptMode(QFileDialog.AcceptSave) file_dialog.setFileMode(QFileDialog.AnyFile) if file_dialog.exec() != QDialog.Accepted: return file_name = file_dialog.selectedFiles()[0] with open(file_name, 'w') as wf: wf.write(self.text_edit.toPlainText())
def readSettings(self, settings): settings.beginGroup("fileWidget") self.viewsSplitter.restoreGeometry(settings.value("splitterGeometry")) self.viewsSplitter.restoreState(settings.value("splitterState")) rootPath = settings.value("rootPath") path = settings.value("path") settings.endGroup() if rootPath is None: rootPath = '/' self.setRootPath(rootPath) if path is None: path = QDir.currentPath() self.setPath(path) self.splitterMoved(self.viewsSplitter.handle(1).pos().x(), 0)
def __init__(self, title, central_widget, parent=None): super().__init__(title, parent=parent) self.central_widget = central_widget self.model = QFileSystemModel() self.model.setRootPath(QDir.currentPath()) self.tree = QTreeView() self.tree.pressed.connect(self.setIndex) self.index_ = None self.db_tree = QTreeView() self.db_tree.setAnimated(True) self.db_model = QStandardItemModel() self.db_model.setHorizontalHeaderLabels(["Database"]) self.db_root = self.db_model.invisibleRootItem() self.dbs = []
def save_screenshot(self): frmat = '.png' initial_path = QStandardPaths.writableLocation( QStandardPaths.PicturesLocation) if not initial_path: initial_path = QDir.currentPath() initial_path += '/Screenshot-' + \ str(datetime.now()).replace(' ', '_') + frmat file_dialog = QFileDialog(self, "Save as", initial_path) file_dialog.setAcceptMode(QFileDialog.AcceptSave) file_dialog.setFileMode(QFileDialog.AnyFile) if file_dialog.exec() != QDialog.Accepted: return file_name = file_dialog.selectedFiles()[0] if not self.original_pixmap.save(file_name): logger.error("The image could not be saved to \"{}\".".format( QDir.toNativeSeparators(file_name))) QMessageBox.warning(self, "Save Error", "The image could not be saved to \"{}\".".format( QDir.toNativeSeparators(file_name)))
def open_image(): # 打开文件对话框 file_dir, _ = QFileDialog.getOpenFileName( window.pushButton, "打开图片", QDir.currentPath(), "图片文件(*.jpg *.png *.bmp);;所有文件(*)") # 判断是否正确打开文件 if not file_dir: QMessageBox.warning(window.pushButton, "警告", "文件错误或打开文件失败!", QMessageBox.Yes) return print("读入文件成功") # 分离路径和文件名 (dir_name, full_file_name) = os.path.split(file_dir) # 分离文件主名和扩展名 (file_name, file_type) = os.path.splitext(full_file_name) # 获取文件路径下 所有以当前文件扩展名结尾的文件 files = glob(os.path.join(dir_name, "*{}".format(file_type))) # 返回 文件列表,当前选中的文件名 return files, full_file_name
def openFileDialog(self): file_path = QFileDialog.getOpenFileName(self, "Find Files", QDir.currentPath())[0] file = open(file_path, "r") particles = int(file.readline()) box_width = float(file.readline()) steps_num = int(file.readline()) time_step = float(file.readline()) system_par = { "particles": particles, "box_width": box_width, "steps_num": steps_num, "time_step": time_step } system = np.zeros([particles, 6, steps_num]) for j in range(steps_num): file.readline() for i in range(particles): line = file.readline() system[i, :, j] = np.fromstring(line, sep=" ") system_par["mol_traj"] = system self.system = SimulatedSystem(system_par) self.modifier = ScatterDataMofifier(self.scatter, self.system)
def __init__(self): QMainWindow.__init__(self) self.setupUi(self) # Viewing the filesystem tree treeModel = QFileSystemModel() treeModel.setRootPath(QDir.currentPath()) # We only show the name/path view = self.treeview_os_directories view.setModel(treeModel) view.model().sort(1, order=Qt.DescendingOrder) view.hideColumn(1) view.hideColumn(2) view.hideColumn(3) view.setColumnWidth(0, 10) view.setColumnWidth(1, 1) view.setColumnWidth(2, 1) # Setting a contextual menu self.treeview_os_directories.customContextMenuRequested.connect( self.openMenuDirectories) # Adding actions self.actionSortie.triggered.connect(self.close) # The selected directories/files (search list) will be stored in a global list global dir_list for dir in dir_list: self.listWidget_selected_directories.addItem(QListWidgetItem(dir))
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 __init__(self, parent=None): QObject.__init__(self, parent) self.parent = parent self.usuario = "" self.password = "" self.token = [] self.mmethod = "" self.mpid = "" self.mparams = [] self.mid = 0 self.boolConnect = False self.intCountConnect = 0 self.intReply = 0 self.intReplyMax = 2 self.urlServer = QUrl() self.versionct = "4" #trytond self.mhost = "" self.mdbase = "" self.mport = "" self.preferences = {} self.boolRun = False self.boolDirect = False self.boolRecursive = False self.mtypeCall = "order" self.mDir = QDir.currentPath() self.tempCallData = QJsonArray() self.tempCallFunctionArgs = QJsonArray() self.m_engine = QQmlApplicationEngine() # connect(managerAccess, SIGNAL(finished(QNetworkReply*)), # this, SLOT(replyFinishedOrder(QNetworkReply*))); self.managerAccess = QNetworkAccessManager(self) self.managerAccess.finished[QNetworkReply].connect( self.replyFinishedOrder)
def __init__(self, path=None): super(TreeView, self).__init__() self.model = QFileSystemModel() if path: self.selectedPath = path self.model.setRootPath(self.selectedPath) else: self.selectedPath = QDir.currentPath() self.model.setRootPath(self.selectedPath) mainLayout = QVBoxLayout() mainLayout.setContentsMargins(0, 0, 0, 0) self.setLayout(mainLayout) self.tree = QTreeView() self.tree.setModel(self.model) self.tree.setRootIndex(self.model.index(self.selectedPath)) self.tree.setColumnHidden(1, True) self.tree.setColumnHidden(2, True) self.tree.setColumnHidden(3, True) mainLayout.addWidget(self.tree)
def __init__(self, ui): super(Widget, self).__init__() self.ui = ui self.directory = QDir.currentPath() self.file_name = "" self.pixmap = None self.num_columns = 5 self.num_colours = 8 self.ladder_threshold = 5 self.sample_threshold = 3 self.ladder_bands = 0 self.coords = [] self.calibration_values = [] self.results = [] QObject.connect(ui.selectFile, SIGNAL('clicked()'), self.select_file) QObject.connect(ui.loadImage, SIGNAL('clicked()'), self.load_image) QObject.connect(ui.saveImage, SIGNAL('clicked()'), self.save_image) QObject.connect(ui.sendEmail, SIGNAL('clicked()'), self.show_dialog) self.ui.columns.setMinimum(2) self.ui.columns.setValue(self.num_columns) self.ui.colours.setMinimum(4) self.ui.colours.setValue(self.num_colours) self.ui.ladderThreshold.setMinimum(1) self.ui.ladderThreshold.setMaximum(self.num_colours) self.ui.ladderThreshold.setValue(self.ladder_threshold) self.ui.sampleThreshold.setMinimum(1) self.ui.sampleThreshold.setMaximum(self.num_colours) self.ui.sampleThreshold.setValue(self.sample_threshold) QObject.connect(self.ui.columns, SIGNAL('valueChanged(int)'), self.set_columns) QObject.connect(self.ui.colours, SIGNAL('valueChanged(int)'), self.set_colours) QObject.connect(self.ui.ladderThreshold, SIGNAL('valueChanged(int)'), self.set_ladder_threshold) QObject.connect(self.ui.sampleThreshold, SIGNAL('valueChanged(int)'), self.set_sample_threshold) self.ui.calibrationText.setText("No ladder bands detected.") self.model = ResultsModel() self.ui.results.setModel(self.model) self.ui.results.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.ui.results.show() QObject.connect(self.ui.findContours, SIGNAL('clicked()'), self.find_contours) QObject.connect(self.ui.findContours, SIGNAL('clicked()'), self.update_calibration_text) QObject.connect(self.ui.calibrate, SIGNAL('clicked()'), self.parse_calibration_base_pairs) ui_file = QFile(os.path.join(os.getcwd(), 'src', 'dialog.ui')) ui_file.open(QFile.ReadOnly) loader = QUiLoader() ui = loader.load(ui_file) ui_file.close() self.dialog = Dialog(ui) QObject.connect(self.dialog.ui, SIGNAL('accepted()'), self.send_email) quit_shortcut = QShortcut(QKeySequence.Quit, self.ui) close_shortcut = QShortcut(QKeySequence.Close, self.ui) QObject.connect(quit_shortcut, SIGNAL('activated()'), self.ui.close) QObject.connect(close_shortcut, SIGNAL('activated()'), self.ui.close) if include_camera: QObject.connect(self.ui.takePicture, SIGNAL('clicked()'), self.take_picture) self.ui.whiteBalance.addItems(camera.MODES) QObject.connect(self.ui.whiteBalance, SIGNAL('currentIndexChanged(int)'), self.select_white_balance)
app.setApplicationName("thesa") #QQuickStyle.setStyle("Material") engine = QQmlApplicationEngine() engine_point = engine QtCore.qInstallMessageHandler(qt_message_handler) jchc = QJsonNetwork(app) jchc.setEngine(engine) systemnet = SystemNet(jchc) modelmanager = ModelManager(jchc, engine, app) mtools = Tools(app) mDir=QDir.currentPath() engine.rootContext().setContextProperty("QJsonNetworkQml", jchc) engine.rootContext().setContextProperty("ModelManagerQml", modelmanager) engine.rootContext().setContextProperty("SystemNet", systemnet) engine.rootContext().setContextProperty("ThesaVersion", ThesaVersion) engine.rootContext().setContextProperty("Tools", mtools) engine.rootContext().setContextProperty("DirParent", mDir) engine.rootContext().setContextProperty("ObjectMessageLast", mObjMsg) settings = QSettings()
def __init__(self): super().__init__() # SET => App Icon self.icon = QIcon("img/iconXLNK.png") # End self.tree_view = None self.file_system_model = None # SET => Window Icon self.setWindowIcon(self.icon) # End # WSET => Window Title self.setWindowTitle("XLNK | Data Manager") # End # Menus self.menu = self.menuBar() self.file_menu = self.menu.addMenu("&File") self.edit_menu = self.menu.addMenu("&Edit") self.view_menu = self.menu.addMenu("&View") self.help_menu = self.menu.addMenu("&Help") # End # =================== # Menu Button Actions # Exit QAction exit_action = QAction("Exit", self) exit_action.setShortcut(QKeySequence.Quit) exit_action.triggered.connect(self.close) self.file_menu.addAction(exit_action) # End # End # Tool Bar toolbar = QToolBar(self) self.addToolBar(toolbar) # delete action on toolbar delete_action_tb = QAction("DELETE TABLE ROW", self) delete_action_tb.setStatusTip("Obrisi Red U Tabeli") delete_action_tb.triggered.connect(self.delete_table_row_tb) toolbar.addAction(delete_action_tb) # Dock Widget dock_widget = QDockWidget("EXPLORER", self) # File System Model self.file_system_model = QFileSystemModel() self.file_system_model.setRootPath(QDir.currentPath()) # SET => Tree View MOdel self.tree_view = QTreeView() self.tree_view.setModel(self.file_system_model) self.tree_view.setRootIndex( self.file_system_model.index(QDir.currentPath() + "/data")) self.tree_view.clicked.connect(self.file_clicked_handler) dock_widget.setWidget(self.tree_view) dock_widget.setFloating(False) self.addDockWidget(Qt.LeftDockWidgetArea, dock_widget) # QLabel qlabel = QLabel(self) qlabel.setText("Welcome to XLNK.") # Central Widget self.clicked_file = None self.setCentralWidget(qlabel) self.showMaximized()
def browse(self): filename = QtWidgets.QFileDialog.getOpenFileName( self, "Choose Engine", QDir.currentPath()) self.pathEdit.setText(filename[0])