def updateFileMenu(self): """ Updates the file menu dynamically, so that recent files can be shown. """ self.menuFile.clear() # self.menuFile.addAction(self.actionNew) # disable for now self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionSave_as) self.menuFile.addAction(self.actionClose_Model) recentFiles = [] for filename in self.recentFiles: if QFile.exists(filename): recentFiles.append(filename) if len(self.recentFiles) > 0: self.menuFile.addSeparator() for i, filename in enumerate(recentFiles): action = QAction("&%d %s" % (i + 1, QFileInfo(filename).fileName()), self) action.setData(filename) action.setStatusTip("Opens recent file %s" % QFileInfo(filename).fileName()) action.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1+i))) action.triggered.connect(self.load_model) #self.connect(action, SIGNAL("triggered()"), self.load_model) self.menuFile.addAction(action) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit)
def get_file_name(self, url): path = url.path() basename = QFileInfo(path).fileName() if not basename: basename = "download" if QFile.exists(basename): print "aaaaaaaaaaaaaaaah" return return basename
def grabFileName(self): result = QFileDialog.getOpenFileName( self, "Open file", FileBrowseWidget.lastDirectory, self.fileTypeName) fname = result[0] if fname != '': fileInfo = QFileInfo(fname) try: FileBrowseWidget.lastDir = fileInfo.baseName() except: pass self.lineEdit.setText(fname)
def toQFileInfo(p): if (not p) or isinstance(p, QFileInfo): fileInfo = p else: fileInfo = QFileInfo(p) if fileInfo and fileInfo.isRelative(): raise ValueError("Given path is relative: '{}'".format( fileInfo.filePath())) return fileInfo
def on_modelClosed(self, modelController): if not modelController: return filename = QFileInfo(modelController.filename).fileName() if self._modelIndexes.has_key(filename): index = self._modelIndexes[filename] item = self._modelListWidget.takeItem(index) del item self._models.pop(filename) # remove the model self._modelIndexes.pop(filename) if self._modelListWidget.count() > 0: self._modelListWidget.item(0).setSelected(True)
def on_activeModelChanged(self, modelController): if not modelController: self._modelListWidget.setCurrentIndex(None) # deselect all return filename = QFileInfo(modelController.filename).fileName() if self._modelIndexes.has_key(filename): # known model, just select it self._modelListWidget.item(self._modelIndexes[filename]).setSelected(True) else: # new model, add it to the list # truncatedFilename = QFileInfo(filename).fileName() self._modelListWidget.addItem(filename) self._models[filename] = modelController index = self._modelListWidget.count() - 1 self._modelIndexes[filename] = index self._modelListWidget.item(index).setSelected(True)
def data(self, index, role): '''Return data for *index* according to *role*.''' if not index.isValid(): return None column = index.column() item = index.internalPointer() if role == self.ITEM_ROLE: return item elif role == Qt.DisplayRole: if column == 0: return item.name elif column == 1: if item.size: return item.size elif column == 2: return item.type elif column == 3: if item.modified is not None: return item.modified.strftime('%c') elif role == Qt.DecorationRole: if column == 0: icon = self.iconFactory.icon(QFileInfo(item.path)) if icon is None or icon.isNull(): if isinstance(item, Directory): icon = QIcon(':icon_folder') elif isinstance(item, Mount): icon = QIcon(':icon_drive') elif isinstance(item, Collection): icon = QIcon(':icon_collection') else: icon = QIcon(':icon_file') return icon elif role == Qt.TextAlignmentRole: if column == 1: return Qt.AlignRight else: return Qt.AlignLeft return None
def downloadFile(self, path, setting): self.progress_text = 'Downloading {}'.format(path.replace(self.base_url.format(self.selected_version()),'')) url = QUrl(path) fileInfo = QFileInfo(url.path()) fileName = setting.save_file_path(self.selected_version()) archive_exists = QFile.exists(fileName) dest_files_exist = True for dest_file in setting.dest_files: dest_file_path = os.path.join('files', setting.name, dest_file) dest_files_exist &= QFile.exists(dest_file_path) forced = self.getSetting('force_download').value if (archive_exists or dest_files_exist) and not forced: self.continueDownloadingOrExtract() return #QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): self.show_error('Unable to save the file {}: {}.'.format(fileName, self.outFile.errorString())) self.outFile = None self.enableUI() return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def generateRFSettings(self): result = QFileDialog.getSaveFileName(self, "Save file", FileBrowseWidget.lastDirectory, "RF settings .yaml (*.yaml)") fname = result[0] if fname != '': fileInfo = QFileInfo(fname) try: FileBrowseWidget.lastDir = fileInfo.baseName() except: pass try: rf_settings = layout.parser.RFSettings.from_rand() timeNow = datetime.datetime.now().strftime("%Y-%M-%d at %H:%M") with open(fname, 'w') as outFile: outFile.write("# Generated on {}\n".format(timeNow) + rf_settings.to_yaml()) self.rfSettingsFile.lineEdit.setText(fname) except IOError as e: # TODO: proper error message print("error writing file: " + str(e))
def __init__(self, res): QWidget.__init__(self) self.res = res layout = QVBoxLayout() self.setLayout(layout) preview = QLabel() if 'image' in res.mime: pixmap = QPixmap(res.file_path).scaledToWidth(32) else: info = QFileInfo(res.file_path) pixmap = QFileIconProvider().icon(info).pixmap(32, 32) preview.setPixmap(pixmap) preview.setMask(pixmap.mask()) preview.setMaximumHeight(32) label = QLabel() label.setText(res.file_name) layout.addWidget(preview) layout.addWidget(label) layout.setAlignment(Qt.AlignHCenter) self.setFixedWidth(64) self.setFixedHeight(64)
def abspath(path): """As a replacement of os.path.abspath, which has encoding issue for unicode path @param path unicode or str @return unicode """ return QFileInfo(path).absoluteFilePath() if path else u""
def initialize(self): locale = QLocale() model = self.state.model if not bool(model): self.browser.setHtml("<font color=red>Information can only " "be shown if an index is open</font>") return top, total, _ = self.state.indicatorCounts() fullname = QDir.toNativeSeparators(os.path.abspath(model.filename)) creator = model.config(Gconf.Key.Creator) created = model.config("Created") created = locale.toString( QDateTime.fromString(created, "yyyy-MM-dd HH:mm:ss")) updated = locale.toString(QFileInfo(model.filename).lastModified()) size = os.path.getsize(model.filename) KB = 1024 MB = KB * KB if size < MB: size = "~{:,} KB ({:,} bytes)".format(round(size / KB), size) else: size = "~{:,} MB ({:,} bytes)".format(round(size / MB), size) filename = re.sub(r"\.xix$", "", os.path.basename(fullname), re.IGNORECASE) version = str(model.version()) secs = self.state.workTime + int(time.monotonic() - self.state.startTime) hours, secs = divmod(secs, 3600) if hours: worktime = "{:,}h{}'".format(hours, secs // 60) else: worktime = "{}'".format(secs // 60) uuid = model.config(UUID) LEFT_STYLE = """ style=" margin-right: 0; padding-right: 0; spacing-right: 0; border-right: 0; " """ RIGHT_STYLE = """ style=" margin-left: 0; padding-left: 0; spacing-left: 0; border-left: 0; " """ color1 = "#DDDDFF" color2 = "#EEEEFF" STYLE = ' style="background-color: {};"' texts = [ """<html><table border=0 style=" background-color: {}; ">""".format(color1) ] for i, (name, value, right, debug) in enumerate(( ("Index", filename, False, False), ("Creator", creator, False, False), ("Filename", fullname, False, False), ("Size", size, False, False), ("Created", created, False, False), ("Updated", updated, False, False), ("Total Entries", "{:,}".format(total), True, False), ("Main Entries", "{:,}".format(top), True, False), ("Subentries", "{:,}".format(total - top), True, False), ("Worktime", worktime, True, False), (None, None, False, False), ("Index Format", version, True, False), ("Index UUID", uuid, True, True), )): if debug and not self.state.window.debug: continue if name is None: color1 = "#EEEEEE" color2 = "#DDDDDD" continue style = STYLE.format(color1 if i % 2 == 0 else color2) align = " align=right" if right else "" texts.append("""<tr{}><td{}>{} </td> <td{}{}>{}</td></tr>""".format(style, LEFT_STYLE, html.escape(name), align, RIGHT_STYLE, html.escape(value))) texts.append("</table></html>") self.browser.setHtml("".join(texts))
def testBasic(self): '''QFileInfo(QFile)''' obj = QFileInfo(QFile())