def on_btnDir_setPath_clicked(self): self.__showBtnInfo(self.sender()) curDir=QDir.currentPath() lastDir=QDir(curDir) self.ui.textEdit.appendPlainText("选择目录之前,QDir所指目录是:"+lastDir.absolutePath()) aDir=QFileDialog.getExistingDirectory(self,"选择一个目录",curDir,QFileDialog.ShowDirsOnly) if aDir=="": return lastDir.setPath(aDir) self.ui.textEdit.appendPlainText("\n选择目录之后,QDir所指目录是:"+lastDir.absolutePath()+"\n")
def getSettingsFile(): appPath = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) appDir = QDir(appPath) if not appDir.exists(): logger.debug('Creating app directory') appDir.mkpath(appDir.absolutePath()) else: logger.debug('App directory already exists') if appDir.setCurrent(appDir.absolutePath()): logger.debug('Changing cwd to app data directory') else: logger.debug('Changing cwd to app data directory failed') return QFile('settings.json')
def saveSettings(settings): logger.debug('Saving settings') currentDir = QDir() logger.debug(currentDir.absolutePath()) settingsFile = getSettingsFile() if not settingsFile.open(QIODevice.WriteOnly | QIODevice.Text | QIODevice.Truncate): logger.debug('Settings file could not be opened for writing') else: stream = QTextStream(settingsFile) stream << settings settingsFile.flush() settingsFile.close() currentDir.setCurrent(currentDir.absolutePath()) logger.debug('Changing cwd to runtime')
def loadProfile(shortGameName, profileName, zEditInstallFolder) -> Merges: zEditProfileDir = QDir(zEditInstallFolder + "/" + ZEditConfig.RELATIVE_PROFILE_DIR) if not zEditProfileDir.exists(): moWarn("Profiles path does not exist: {}".format( zEditProfileDir.absolutePath())) return profiles = ZEditConfig.parseProfileList(shortGameName) for name in profiles: if name == profileName: relName = name + "/merges.json" if not zEditProfileDir.exists(relName): moWarn('Profile "{}" does not have a "merges.json" file.'. format(name)) return try: filePath = zEditProfileDir.absoluteFilePath(relName) with open(filePath) as f: m = Merges(json.load(f)) m.profileName = name m.profilePath = filePath return m except ValueError as ex: moWarn( 'Failed to read zEdit profile. Invalid file: "{}": {}'. format(filePath, str(ex))) moError('Profile "{}" was not found'.format(profileName)) return Merges()
def __installEric6Doc(self, engine): """ Private method to install/update the eric6 help documentation. @param engine reference to the help engine (QHelpEngineCore) @return flag indicating success (boolean) """ versionKey = "eric6_ide" info = engine.customValue(versionKey, "") lst = info.split('|') dt = QDateTime() if len(lst) and lst[0]: dt = QDateTime.fromString(lst[0], Qt.ISODate) qchFile = "" if len(lst) == 2: qchFile = lst[1] docsPath = QDir(getConfig("ericDocDir") + QDir.separator() + "Help") files = docsPath.entryList(["*.qch"]) if not files: engine.setCustomValue( versionKey, QDateTime().toString(Qt.ISODate) + '|') return False for f in files: if f == "source.qch": fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f) if dt.isValid() and \ fi.lastModified().toString(Qt.ISODate) == \ dt.toString(Qt.ISODate) and \ qchFile == fi.absoluteFilePath(): return False namespace = QHelpEngineCore.namespaceName( fi.absoluteFilePath()) if not namespace: continue if namespace in engine.registeredDocumentations(): engine.unregisterDocumentation(namespace) if not engine.registerDocumentation(fi.absoluteFilePath()): self.errorMessage.emit( self.tr( """<p>The file <b>{0}</b> could not be""" """ registered. <br/>Reason: {1}</p>""") .format(fi.absoluteFilePath, engine.error()) ) return False engine.setCustomValue( versionKey, fi.lastModified().toString(Qt.ISODate) + '|' + fi.absoluteFilePath()) return True return False
def getProfiles(shortGameName, zEditInstallFolder) -> List[Merges]: """ This returns the content of each profiles 'merges.json' """ result = [] zEditProfileDir = QDir(zEditInstallFolder + "/" + ZEditConfig.RELATIVE_PROFILE_DIR) if not zEditProfileDir.exists(): qDebug("Profiles path does not exist: {}".format( zEditProfileDir.absolutePath())) return result profiles = ZEditConfig.parseProfileList(shortGameName) for name in profiles: relName = name + "/merges.json" if not zEditProfileDir.exists(relName): continue try: filePath = zEditProfileDir.absoluteFilePath(relName) with open(filePath) as f: m = Merges(json.load(f)) m.profileName = name m.profilePath = filePath result.append(m) except ValueError as ex: qWarning('Invalid file "{}": {}'.format(filePath, str(ex))) return result
def onMapsDirectoryChanged(self): prefs = preferences.Preferences.instance() mapsDir = QDir(prefs.mapsDirectory()) if (not mapsDir.exists()): mapsDir.setPath(QDir.currentPath()) self.model().setRootPath(mapsDir.canonicalPath()) self.setRootIndex(self.model().index(mapsDir.absolutePath()))
def _appBundlePluginsPath(cls, appDirPath): ''' path to plugin directory of OSX app's bundle (especially when sandboxed, i.e. in a cls-contained bundle w/o shared libraries) If not (platform is OSX and app has PlugIns dir in the bundle), returns None. On other platforms (or when OSX app is not sandboxed) plugins are not usually bundled, but in the shared install directory of the Qt package. Implementation: use Qt since it understands colons (e.g. ':/') for resource paths. (Instead of Python os.path, which is problematic.) Convert string to QDir, move it around, convert back to string of abs path without colons. ''' # appDirPath typically "/Users/<user>/Library/<appName>.app/Contents/MacOS" on OSX. appDir = QDir(appDirPath) if not appDir.cdUp(): logAlert("Could not cdUp from appDir") # assert like ..../Contents if appDir.cd("PlugIns"): # !!! Capital I result = appDir.absolutePath() # assert like ..../Contents/PlugIns else: logAlert("Could not cd to PlugIns") result = None assert result is None or isinstance(result, str) return result
def show_background_picture(self): # 随机一张壁纸全屏显示 self.showFullScreen() if os.listdir(CONFIG.DIR_WALLPAPERS): window_size = QApplication.desktop().screenGeometry() self.label_background.setGeometry(0, 0, window_size.width(), window_size.height()) wallpapers = [ CONFIG.DIR_WALLPAPERS + "/" + wallpaper for wallpaper in os.listdir(CONFIG.DIR_WALLPAPERS) if os.path.isfile(CONFIG.DIR_WALLPAPERS + "/" + wallpaper) ] # print(wallpapers) if wallpapers: try: index = random.randint(0, len(wallpapers) - 1) self.label_background.setPixmap( QPixmap(QDir.absolutePath(QDir( wallpapers[index]))).scaled( window_size.width(), window_size.height())) self.label_message.show() except: pass self.label_count.show()
def __installEric6Doc(self, engine): """ Private method to install/update the eric6 help documentation. @param engine reference to the help engine (QHelpEngineCore) @return flag indicating success (boolean) """ versionKey = "eric6_ide" info = engine.customValue(versionKey, "") lst = info.split('|') dt = QDateTime() if len(lst) and lst[0]: dt = QDateTime.fromString(lst[0], Qt.ISODate) qchFile = "" if len(lst) == 2: qchFile = lst[1] docsPath = QDir(getConfig("ericDocDir") + QDir.separator() + "Help") files = docsPath.entryList(["*.qch"]) if not files: engine.setCustomValue(versionKey, QDateTime().toString(Qt.ISODate) + '|') return False for f in files: if f == "source.qch": fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f) namespace = QHelpEngineCore.namespaceName( fi.absoluteFilePath()) if not namespace: continue if (dt.isValid() and namespace in engine.registeredDocumentations() and (fi.lastModified().toString(Qt.ISODate) == dt.toString(Qt.ISODate)) and qchFile == fi.absoluteFilePath()): return False if namespace in engine.registeredDocumentations(): engine.unregisterDocumentation(namespace) if not engine.registerDocumentation(fi.absoluteFilePath()): self.errorMessage.emit( self.tr( """<p>The file <b>{0}</b> could not be""" """ registered. <br/>Reason: {1}</p>""").format( fi.absoluteFilePath, engine.error())) return False engine.setCustomValue( versionKey, fi.lastModified().toString(Qt.ISODate) + '|' + fi.absoluteFilePath()) return True return False
def __init__(self, world, parent=None): super().__init__(parent) self.info_text = [] self.performance = 0 self._animal_brush = QBrush(QColor(74, 172, 225)) self._food_brush = QBrush(QColor(100, 100, 100)) self._food_bitten_brush = QBrush(QColor(180, 140, 100)) self._mammoth_brush = QBrush(QColor(50, 50, 200)) self._animal_pen = Qt.NoPen self._selected_animal_pen = QPen(QColor(255, 180, 0), 3) self.selected_animal = None self.constants_window = None self.neural_network_viewer_window = None self.population_graph_window = None self.graphics_window = None self.loader_window = None self.setupUi(self) self.horizontalLayout.insertWidget(0, self.draw_widget) snapshot_dir = QDir('./snapshots/') snapshot_dir.mkpath('.') self.snapshot_directory_combobox.addItem(snapshot_dir.absolutePath()) self.world = world self.draw_widget.paintEvent = self.on_draw_widget_paintEvent self.draw_widget.mousePressEvent = self.on_draw_widget_mousePressEvent self.draw_widget.mouseMoveEvent = self.on_draw_widget_mouseMoveEvent self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.timer.start(self.TIMER_INTERVAL) self._prev_time = time.perf_counter()
def loadSettings(): logger.debug('Loading settings') currentDir = QDir() logger.debug(currentDir.absolutePath()) settingsFile = getSettingsFile() settings = None if not settingsFile.open(QIODevice.ReadOnly | QIODevice.Text | QIODevice.ExistingOnly): logger.debug('Settings file could not be opened for reading') else: stream = QTextStream(settingsFile) settings = stream.readAll() settingsFile.close() currentDir.setCurrent(currentDir.absolutePath()) logger.debug('Changing cwd to runtime') return settings
def __init__(self, mainWindow, parent = None): super().__init__(parent) self.mMainWindow = mainWindow self.setRootIsDecorated(False) self.setHeaderHidden(True) self.setItemsExpandable(False) self.setUniformRowHeights(True) self.setDragEnabled(True) self.setDefaultDropAction(Qt.MoveAction) prefs = preferences.Preferences.instance() prefs.mapsDirectoryChanged.connect(self.onMapsDirectoryChanged) mapsDir = QDir(prefs.mapsDirectory()) if (not mapsDir.exists()): mapsDir.setPath(QDir.currentPath()) self.mFSModel = FileSystemModel(self) self.mFSModel.setRootPath(mapsDir.absolutePath()) nameFilters = QStringList("*.tmx") # The file system model name filters are plain, whereas the plugins expose # a filter as part of the file description filterFinder = QRegExp("\\((\\*\\.[^\\)\\s]*)") for format in PluginManager.objects(MapFormat): if not (format.capabilities() & MapFormat.Read): continue filter = format.nameFilter() if (filterFinder.indexIn(filter) != -1): nameFilters.append(filterFinder.cap(1)) self.mFSModel.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDot) self.mFSModel.setNameFilters(nameFilters) self.mFSModel.setNameFilterDisables(False) # hide filtered files self.setModel(self.mFSModel) headerView = self.header() headerView.hideSection(1) # Size column headerView.hideSection(2) headerView.hideSection(3) self.setRootIndex(self.mFSModel.index(mapsDir.absolutePath())) self.header().setStretchLastSection(False) self.header().setSectionResizeMode(0, QHeaderView.Stretch) self.activated.connect(self.onActivated) self.mMainWindow = None self.mFSModel = None
def listSaves(self, folder: QDir) -> List[mobase.ISaveGame]: profiles = list() for path in Path(folder.absolutePath()).glob("*/Saved Games/*"): if (path.name == "Autosave" or path.name == "Pictures" or "_invalid" in path.name): continue if path.is_dir(): saveFolder = QDir(str(path)) if not saveFolder.exists("SaveGame.inf"): savePath = saveFolder.absolutePath() QFile.rename(savePath, savePath + "_invalid") continue else: continue profiles.append(path) return [BlackAndWhite2SaveGame(path) for path in profiles]
def on_btnDir_absPath_clicked(self): self.__showBtnInfo(self.sender()) sous = self.ui.editDir.text() if sous == "": self.ui.textEdit.appendPlainText("请先选择一个目录") return dirObj = QDir(sous) text = dirObj.absolutePath() self.ui.textEdit.appendPlainText(text + "\n")
def listSaves(self, folder: QDir) -> List[mobase.ISaveGame]: profiles = list() for path in Path(folder.absolutePath()).glob("profile_*"): # profile_9 is only for the Multiplayer DLC "The Butcher's Circus" # and contains different files than other profiles if path.name == "profile_9": continue profiles.append(path) return [DarkestDungeonSaveGame(path) for path in profiles]
def on_btnDir_exists_clicked(self): self.__showBtnInfo(self.sender()) sous = self.ui.editDir.text() ## if sous=="": ## self.ui.textEdit.appendPlainText("请先选择一个目录") ## return dirObj = QDir(sous) #若sous为空,则使用其当前目录 self.ui.textEdit.appendPlainText(dirObj.absolutePath() + "\n") if dirObj.exists(): self.ui.textEdit.appendPlainText("True \n") else: self.ui.textEdit.appendPlainText("False \n")
def ValidateSave(self) -> bool: """Checks if a valid footprint name and folder are selected Returns: bool: true if the selected folder exists """ name = self.ui.le_Name.text() folder = QDir(self.ui.le_Path.text()) folderInfo = QFileInfo(folder.absolutePath()) if (folderInfo.isDir() and folderInfo.isWritable()): return folder.exists() and name != "" else: return False
def deleteTempFiles(self): dir=QDir("data") rootdir=dir.absolutePath() try: filelist=os.listdir(rootdir) except : return for f in filelist: filepath = os.path.join( rootdir, f ) if os.path.isfile(filepath): os.remove(filepath) elif os.path.isdir(filepath): shutil.rmtree(filepath,True)
def run(self): # Lists ISO files in local directory root=QDir(self.destination) root.setFilter(QDir.AllDirs|QDir.NoDot|QDir.NoDotDot) dirs=root.entryList() for dir in dirs: sub=QDir(self.destination+'/'+dir) sub.setNameFilters(["*.iso"]) sub.setFilter(QDir.Files) local=sub.entryList() if len(local)!=0: for iso in local: isoSize=QFileInfo(sub.absolutePath()+'/' +iso).size() self.localList.append([dir,iso,isoSize]) # List the remote directory commande = ['rsync', '-avHP', '--list-only',str(self.path)] try: if self.password != "": envir = os.environ.copy() envir['RSYNC_PASSWORD']=str(self.password) process = Popen(commande, shell=False, stdout=PIPE, stderr=PIPE, env=envir) else: process = Popen(commande, shell=False, stdout=PIPE, stderr=PIPE) except OSError as e: self.lvM.emit(self.tr("Command rsync not found: ")+str(e)) self.endSignal.emit(1) return except ValueError as e: self.lvM.emit(self.tr("Error in rsync parameters: ")+str(e)) self.endSignal.emit(2) return except Exception as e: # Unknown error in rsync self.lvM.emit(self.tr("Error in rsync: ")+str(e)) self.endSignal.emit(3) return process.poll() while True : item=process.stdout.readline().rstrip().decode('unicode_escape') self.lvM.emit(item) if str(item.lower()).endswith('.iso') : words=item.split() self.list.append(words[-1]) process.poll() if process.returncode != None: break self.endSignal.emit(0)
def veritabaniBaglan(): veritabani = QSqlDatabase.database() if not veritabani.isValid(): veritabani = QSqlDatabase.addDatabase("QSQLITE") if not veritabani.isValid(): logger.error("Veritabanı Eklenemedi !") yaz_dir = QDir() if not yaz_dir.mkpath("."): logger.error("Yazılabilir dizin oluşturulamadı !") # Erişilebilir bir veritabanı dosyası oluşturulmuştur. dosyaAdi = "{}/chat-database.sqlite3".format(yaz_dir.absolutePath()) # Veritabanı mevcut değilse open() fonksiyonu SQLite'ı oluşturacaktır. veritabani.setDatabaseName(dosyaAdi) if not veritabani.open(): logger.error("Veritabanı Açılamadı") QFile.remove(dosyaAdi)
def __init__(self, parent=None): super().__init__(parent) self.info_text = [] self.performance = 0 self._animal_brush = QBrush(QColor(74, 172, 225)) self._food_brush = QBrush(QColor(100, 100, 100)) self._food_bitten_brush = QBrush(QColor(180, 140, 100)) self._mammoth_brush = QBrush(QColor(50, 50, 200)) self._animal_pen = Qt.NoPen self._selected_animal_pen = QPen(QColor(255, 180, 0), 3) self.selected_animal = None self.constants_window = None self.neural_network_viewer_window = None self.population_graph_window = None self.graphics_window = None self.setupUi(self) self.horizontalLayout.insertWidget(0, self.draw_widget) snapshot_dir = QDir('./snapshots/') snapshot_dir.mkpath('.') self.snapshot_directory_combobox.addItem(snapshot_dir.absolutePath()) world_constants = WorldConstants() self.draw_widget.setFixedWidth(world_constants.WORLD_WIDTH) self.draw_widget.setFixedHeight(world_constants.WORLD_HEIGHT) self.world = world.World(constants=world_constants, save_genealogy=False) self.mammoth_analyzer = MammothAnalyzer(self.world) self.draw_widget.paintEvent = self.on_draw_widget_paintEvent self.draw_widget.mousePressEvent = self.on_draw_widget_mousePressEvent self.draw_widget.mouseMoveEvent = self.on_draw_widget_mouseMoveEvent self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.timer.start(self.TIMER_INTERVAL) self._prev_time = time.clock()
def __installQtDoc(self, name, version, engine): """ Private method to install/update a Qt help document. @param name name of the Qt help document (string) @param version Qt version of the help documens (integer) @param engine reference to the help engine (QHelpEngineCore) @return flag indicating success (boolean) """ versionKey = "qt_version_{0}@@{1}".format(version, name) info = engine.customValue(versionKey, "") lst = info.split("|") dt = QDateTime() if len(lst) and lst[0]: dt = QDateTime.fromString(lst[0], Qt.ISODate) qchFile = "" if len(lst) == 2: qchFile = lst[1] if version == 4: docsPath = QDir(QLibraryInfo.location(QLibraryInfo.DocumentationPath) + QDir.separator() + "qch") elif version == 5: docsPath = QDir(QLibraryInfo.location(QLibraryInfo.DocumentationPath)) else: # unsupported Qt version return False files = docsPath.entryList(["*.qch"]) if not files: engine.setCustomValue(versionKey, QDateTime().toString(Qt.ISODate) + "|") return False for f in files: if f.startswith(name): fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f) namespace = QHelpEngineCore.namespaceName(fi.absoluteFilePath()) if not namespace: continue if ( dt.isValid() and namespace in engine.registeredDocumentations() and fi.lastModified().toString(Qt.ISODate) == dt.toString(Qt.ISODate) and qchFile == fi.absoluteFilePath() ): return False if namespace in engine.registeredDocumentations(): engine.unregisterDocumentation(namespace) if not engine.registerDocumentation(fi.absoluteFilePath()): self.errorMessage.emit( self.tr( """<p>The file <b>{0}</b> could not be""" """ registered. <br/>Reason: {1}</p>""" ).format(fi.absoluteFilePath, engine.error()) ) return False engine.setCustomValue(versionKey, fi.lastModified().toString(Qt.ISODate) + "|" + fi.absoluteFilePath()) return True return False
def listSaves(self, folder: QDir) -> List[mobase.ISaveGame]: ext = self._mappings.savegameExtension.get() return [ BasicGameSaveGame(path) for path in Path(folder.absolutePath()).glob(f"**/*.{ext}") ]
from PyQt5.QtCore import QDir import os import cv2 dirTrain1 = QDir('C:/Users/home/Desktop/mitos dataset eval/cutted/mitosis') dirTrain2 = QDir('C:/Users/home/Desktop/mitos dataset eval/cutted/noMitos') imagesFilter = ['*.png', '*.tif', '*.bmp'] infoList1 = dirTrain1.entryInfoList(imagesFilter) infoList2 = dirTrain2.entryInfoList(imagesFilter) for e in infoList1: filePath = e.absoluteFilePath() basenameExt = os.path.basename(filePath) baseName, _ = os.path.splitext(basenameExt) im = cv2.imread(filePath) savePath = dirTrain1.absolutePath() + '/' + baseName + '.png' cv2.imwrite(savePath, im) for e in infoList2: filePath = e.absoluteFilePath() basenameExt = os.path.basename(filePath) baseName, _ = os.path.splitext(basenameExt) im = cv2.imread(filePath) cv2.imwrite(dirTrain2.absolutePath() + '/' + baseName + '.png', im)
def __installQtDoc(self, name, version, engine): """ Private method to install/update a Qt help document. @param name name of the Qt help document (string) @param version Qt version of the help documens (integer) @param engine reference to the help engine (QHelpEngineCore) @return flag indicating success (boolean) """ versionKey = "qt_version_{0}@@{1}".format(version, name) info = engine.customValue(versionKey, "") lst = info.split('|') dt = QDateTime() if len(lst) and lst[0]: dt = QDateTime.fromString(lst[0], Qt.ISODate) qchFile = "" if len(lst) == 2: qchFile = lst[1] if version == 4: docsPath = QDir( QLibraryInfo.location(QLibraryInfo.DocumentationPath) + QDir.separator() + "qch") elif version == 5: docsPath = QLibraryInfo.location(QLibraryInfo.DocumentationPath) if (not os.path.isdir(docsPath) or len(QDir(docsPath).entryList(["*.qch"])) == 0): # Qt installer is a bit buggy; it's missing a symbolic link docsPathList = QDir.fromNativeSeparators(docsPath).split("/") docsPath = os.sep.join( docsPathList[:-3] + ["Docs", "Qt-{0}.{1}".format(*qVersionTuple())]) docsPath = QDir(docsPath) else: # unsupported Qt version return False files = docsPath.entryList(["*.qch"]) if not files: engine.setCustomValue(versionKey, QDateTime().toString(Qt.ISODate) + '|') return False for f in files: if f.startswith(name + "."): fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f) namespace = QHelpEngineCore.namespaceName( fi.absoluteFilePath()) if not namespace: continue if (dt.isValid() and namespace in engine.registeredDocumentations() and (fi.lastModified().toString(Qt.ISODate) == dt.toString(Qt.ISODate)) and qchFile == fi.absoluteFilePath()): return False if namespace in engine.registeredDocumentations(): engine.unregisterDocumentation(namespace) if not engine.registerDocumentation(fi.absoluteFilePath()): self.errorMessage.emit( self.tr( """<p>The file <b>{0}</b> could not be""" """ registered. <br/>Reason: {1}</p>""").format( fi.absoluteFilePath, engine.error())) return False engine.setCustomValue( versionKey, fi.lastModified().toString(Qt.ISODate) + '|' + fi.absoluteFilePath()) return True return False
def listSaves(self, folder: QDir) -> List[mobase.ISaveGame]: return [ BasicGameSaveGame(path) for path in Path(folder.absolutePath()).glob("save_*") ]
def media(url): return QMediaContent( QUrl.fromLocalFile(QDir.absolutePath(QDir(url))))
class APISChronology(QDialog, FORM_CLASS): def __init__(self, country, parent=None): """Constructor.""" super(APISChronology, self).__init__(parent) self.candidateCountry = country self.setupUi(self) # Initial window size/pos last saved. Use default values for first time if GetWindowSize("chronology"): self.resize(GetWindowSize("chronology")) if GetWindowPos("chronology"): self.move(GetWindowPos("chronology")) self.settings = QSettings(QSettings().value("APIS/config_ini"), QSettings.IniFormat) self.currentChronology = None self.chronologiesDir = None self.isSetup = False self.uiChronologyCombo.currentIndexChanged.connect( self.updateChronology) self.accepted.connect(self.onAccepted) self.rejected.connect(self.onRejected) self.loadAvailableChronologies() def loadAvailableChronologies(self): self.chronologiesDir = QDir(self.settings.value("APIS/chronology_dir")) if self.chronologiesDir.exists(): chronologiesJsonFiles = self.chronologiesDir.entryList(['*.json'], QDir.Files) if len(chronologiesJsonFiles) > 0: for chronology in chronologiesJsonFiles: if QFile( os.path.join(self.chronologiesDir.absolutePath(), chronology) ).exists( ): # and is chronology json file (find some token to verify) self.uiChronologyCombo.addItem( QFileInfo(chronology).completeBaseName()) indexCandidate = self.uiChronologyCombo.findText( self.candidateCountry) indexDefault = self.uiChronologyCombo.findText( self.settings.value("APIS/default_chronology", "AUT")) # QMessageBox.information(self, "Info", "{}, {}, {}".format(self.candidateCountry, indexCandidate, indexDefault)) if indexCandidate >= 0: self.uiChronologyCombo.setCurrentIndex(indexCandidate) elif indexDefault >= 0: self.uiChronologyCombo.setCurrentIndex(indexDefault) else: self.uiChronologyCombo.setCurrentIndex(0) self.isSetup = True else: QMessageBox.warning( self, "Keine Chronologien vorhanden", "Im angegebenen Verzeichnis ({0}) sind keine Chronologien vorhanden!" .format(self.chronologiesDir.absolutePath())) else: QMessageBox.warning( self, "Ordner existiert nicht", "Das angegebenen Verzeichnis ({0}) existiert nicht!".format( self.chronologiesDir.absolutePath())) def nested_dict_iter(self, nested): for key, value in nested.items(): if isinstance(value, Mapping): yield from self.nested_dict_iter(value) else: yield key, value def updateChronology(self): # QMessageBox.information(self, "Info", "{0}".format(self.sender())) chronology = self.sender().currentText() fileName = os.path.join(self.chronologiesDir.absolutePath(), "{}.json".format(chronology)) with open(fileName) as jsonFile: data = json.load(jsonFile) del data # blub = JsonJ(data) # QMessageBox.information(self, "Info", json.dumps(blub)) # if "name" in data and data["name"] == chronology and "children" in data: # for item in data["children"]: # continue # else: # QMessageBox.warning(self, "Chronologie JSON Datei fehlerhaft", "Die Chronologie JSON Datei ({0}) ist fehlerhaft!".format(fileName)) def onAccepted(self): SetWindowSizeAndPos("chronology", self.size(), self.pos()) def onRejected(self): SetWindowSizeAndPos("chronology", self.size(), self.pos())
def listSaves(self, folder: QDir) -> List[mobase.ISaveGame]: return [ Witcher1SaveGame(path) for path in Path(folder.absolutePath()).glob("*.TheWitcherSave") ]