def saveLog(self): if self.finished: dial = QFileDialog() dial.setWindowIcon( QIcon(os.path.join(self.projectDir, 'Resources', 'save.png'))) #не работает try: if self.firstOpen: name = dial.getSaveFileName(self, 'Save log', QDir.homePath(), "Text file (*.txt)") self.firstOpen = False else: name = dial.getSaveFileName(parent=self, caption='Save log', filter="Text file (*.txt)") full = str( name )[2:len(str(name)) - 6 - 17] #('C:/Users/Nikita/Desktop/image.png', 'Text file (*.txt)') curdir = os.getcwd() with open('temporaryfilelogtodel.txt', 'w') as f: f.write(str(self.edit.toPlainText())) #Можно записать что-то еще в файл... shutil.copyfile('temporaryfilelogtodel.txt', full) os.remove(os.path.join(curdir, 'temporaryfilelogtodel.txt')) except Exception: dial.accept()
def chooseSetupFile(self): dial = QFileDialog() file = None try: if self.firstOpen: name = dial.getOpenFileName(self, 'Choose file', QDir.homePath()) self.firstOpen = False else: name = dial.getOpenFileName(self, 'Choose file') file = str( name )[2:-6 - self. filepathStrNum] #('C:/Users/Nikita/Desktop/spiral iz chiesl.py', '') file = file.replace('/', os.path.sep) except Exception: dial.accept() return if file: if os.path.basename(file).split('.')[1] != 'py': Message.warningMessage(self, ' ', 'Setup file must be .py') else: self.cxbldle.setText(file)
def addFolder(self): dial = QFileDialog() try: if self.firstOpen: name = dial.getExistingDirectory(self, "Choose folder", QDir.homePath()) self.firstOpen = False else: name = dial.getExistingDirectory(self, "Choose folder") fold = os.path.basename(name) folpath = os.getcwd() shutil.copytree(name, os.path.join('tmp', fold)) folpath = os.path.join(folpath, 'tmp', fold) except Exception: dial.accept() return a = QListWidgetItem(fold) a.setIcon(QIcon(os.path.join('Resources', 'folder.png'))) a.setSizeHint( QSize(100 / 1920 * self.screenWidth, 33 / 1080 * self.screenHeight)) a.__dict__['folderpath'] = folpath self.list.addItem(a)
def savePath(self): if self.pathMaker.pts: Q = QFileDialog() if self.pathMaker.openPathFile == '': self.pathMaker.openPathFile = paths["paths"] + 'tmp.path' f = Q.getSaveFileName(self.pathMaker, paths["paths"], self.pathMaker.openPathFile) Q.accept() if not f[0]: return elif not f[0].lower().endswith('.path'): MsgBox("savePath: Wrong file extention - use '.path'") else: try: with open(f[0], 'w') as fp: for i in range(0, len(self.pathMaker.pts)): p = self.pathMaker.pts[i] x = str("{0:.2f}".format(p.x())) y = str("{0:.2f}".format(p.y())) fp.write(x + ", " + y + "\n") fp.close() except IOError: MsgBox("savePath: Error saving file") return else: MsgBox("savePath: Nothing saved")
def addSourceFile(self): #Т.к. файл с исходным кодом может быть лишь один, нужно удалить выбранный #чтобы выбрать новый if self.lt.count() != 0: item = self.lt.item(0) os.remove(os.path.join('tmp', str(item.text()))) self.lt.takeItem(self.lt.row(item)) dial = QFileDialog() #Получение нужного для добавления файла try: if self.firstOpen: name = dial.getOpenFileName(self, "Choose file", QDir.homePath()) self.firstOpen = False else: name = dial.getOpenFileName(self, "Choose file") file = str( name )[2:-6 - self. filepathStrNum] #('C:/Users/Nikita/Desktop/spiral iz chiesl.py', '') file = file.replace('/', os.path.sep) parts = file.split(os.path.sep) self.fullsource = file if not (('.py' in parts[-1]) or ('pyw' in parts[-1])): #Проверка верности расширения файла if file: #self.warnlbl.setText('Source file must be .py or .pyw') Message.warningMessage(self, ' ', 'Source file must be .py') self.source = None return shutil.copyfile(file, os.path.join( 'tmp', parts[-1])) #parts[-1] Собственно имя файла except Exception: dial.accept() return else: self.source = parts[-1] #self.warnlbl.setText(' ') #Получение нужной иконки исходя из расширения файла ext = '.' + parts[-1].split('.')[1] try: iconpath = self.extensions[ext] except Exception: iconpath = os.path.join(self.resourceFolder, 'blank.ico') a = QListWidgetItem(parts[-1]) a.setIcon(QIcon(iconpath)) a.setSizeHint( QSize(100 / 1920 * self.screenWidth, 35 / 1080 * self.screenHeight)) a.setFlags(a.flags() and Qt.ItemIsEnabled) self.lt.addItem(a)
def openFiles(self): if self.pathMaker.pts: MsgBox("openFiles: Clear Scene First") return Q = QFileDialog() file, _ = Q.getOpenFileName(self.pathMaker, "Choose a path file to open", paths["paths"], "Files(*.path)") Q.accept() if file: self.pathMaker.pts = getPts(file) ## read the file self.pathMaker.openPathFile = os.path.basename(file) self.pathMaker.addPath()
def addSourceFolder(self): dial = QFileDialog() fold = None try: if self.firstOpen: name = dial.getExistingDirectory(self, "Choose folder", QDir.homePath()) self.firstOpen = False else: name = dial.getExistingDirectory(self, "Choose folder") fold = str(name) except Exception: dial.accept() return if fold: self.folder = fold self.folle.setText(self.folder)
def addFile(self): dial = QFileDialog() #Получение нужного для добавления файла try: if self.firstOpen: name = dial.getOpenFileName(self, "Choose file", QDir.homePath()) self.firstOpen = False else: name = dial.getOpenFileName(self, "Choose file") file = str( name )[2:-6 - self. filepathStrNum] #('C:/Users/Nikita/Desktop/spiral iz chiesl.py', '') file = file.replace('/', os.path.sep) parts = file.split(os.path.sep) shutil.copyfile(file, os.path.join( 'tmp', parts[-1])) #parts[-1] Собственно имя файла except Exception: dial.accept() return #Получение нужной иконки исходя из расширения файла ext = '.' + parts[-1].split('.')[-1] ext = ext.lower() try: iconpath = self.extensions[ext] except Exception: iconpath = os.path.join(self.resourceFolder, 'blank.png') a = QListWidgetItem(parts[-1]) a.setIcon(QIcon(iconpath)) a.setSizeHint( QSize(100 / 1920 * self.screenWidth, 33 / 1080 * self.screenHeight)) self.list.addItem(a)
def requestOpenFileOrDir ( parent=None, caption='', directory='', filter='All Files ( * )', initialFilter='', options=None ): def updateText (): # update the contents of the line edit widget with the selected files selected = [] for index in view.selectionModel ().selectedRows (): selected.append ( '"{}"'.format ( index.data () ) ) lineEdit.setText ( ' '.join ( selected ) ) dialog = QFileDialog ( parent, caption = caption ) dialog.setFileMode ( QFileDialog.ExistingFiles ) if options: dialog.setOptions ( options ) dialog.setOption ( QFileDialog.DontUseNativeDialog, True ) if directory: dialog.setDirectory ( directory ) if filter: dialog.setNameFilter ( filter ) if initialFilter: dialog.selectNameFilter ( initialFilter ) # by default, if a directory is opened in file listing mode, # QFileDialog.accept() shows the contents of that directory, but we # need to be able to "open" directories as we can do with files, so we # just override accept() with the default QDialog implementation which # will just return exec_() dialog.accept = lambda: QtWidgets.QDialog.accept ( dialog ) # there are many item views in a non-native dialog, but the ones displaying # the actual contents are created inside a QStackedWidget; they are a # QTreeView and a QListView, and the tree is only used when the # viewMode is set to QFileDialog.Details, which is not this case stackedWidget = dialog.findChild ( QtWidgets.QStackedWidget ) view = stackedWidget.findChild ( QtWidgets.QListView ) view.selectionModel ().selectionChanged.connect ( updateText ) lineEdit = dialog.findChild ( QtWidgets.QLineEdit ) # clear the line edit contents whenever the current directory changes dialog.directoryEntered.connect ( lambda: lineEdit.setText ( '' ) ) dialog.exec_ () return dialog.selectedFiles ()