def __init__(self): folder = QStandardPaths.writableLocation( QStandardPaths.AppDataLocation) folder += "/" + Settings._filepath if not os.path.exists(folder): os.makedirs(folder) filepath = folder + "/" + Settings._filename if not os.path.exists(filepath): config = configparser.ConfigParser() config["Constants"] = { "styleSheetPath": "./ui/stylesheet.qss", "tailerRefreshTimeMs": "500", "spoolPath": "C:\\Users\\nicola\\Desktop\\Spool" } config["Configuration"] = { "styleButtonVisible": "0", "maxLogRowCount": "10" } config["Logging"] = { "path": QStandardPaths.writableLocation( QStandardPaths.AppLocalDataLocation) + "/DV/CSV2JSON/logs/", "filename": "CSV2JSON.txt", "levels": "CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET", "currentLevel": "DEBUG" } config["JsonConfiguration"] = {"StripWidthUm": "100000"} with open(filepath, 'w') as fp: config.write(fp) config = configparser.ConfigParser() config.read(filepath) self.styleSheetPath = config["Constants"]["styleSheetPath"] self.tailerRefreshTimeMs = config["Constants"]["tailerRefreshTimeMs"] self.styleButtonVisible = config["Configuration"]["styleButtonVisible"] self.maxLogRowCount = config["Configuration"]["maxLogRowCount"] self.spoolPath = config["Constants"]["spoolPath"] self.loggingPath = config["Logging"]["path"] self.loggingFilename = config["Logging"]["filename"] self.loggingLevels = config["Logging"]["levels"] self.loggingCurrentLevel = config["Logging"]["currentLevel"] self.jsonConfigurationStripWidthUm = config["JsonConfiguration"][ "StripWidthUm"]
def ask_for_filename_to_save(parent): dir_to_open = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) fname = QFileDialog().getSaveFileName(parent, "Save as PDF", dir_to_open, "PDF Files (*.pdf)") return fname
def saveData(self): if not self.docModified: return if self.docPath is None: path, ftype = QFileDialog.getSaveFileName( self, '保存食谱', QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation), 'Excel 文件(*.xlsx)') if path == '': return if QDir(path) == QDir(self._library_file): QMessageBox.critical(self, G_APPNAME, '%s 是库文件,不能用于保存食谱' % path) return else: path = self.docPath wb = openpyxl.Workbook() ws = wb.active for k, v in self.data.items(): cell = ws.cell(row=k[0] + 1, column=k[1] + 1) cell.value = "\n".join(v) try: wb.save(path) wb.close() except: QMessageBox.critical(self, G_APPNAME, '%s 保存失败' % path) return self.docPath = path self.setDocModified(False)
def abrir_archivo(self): location = QStandardPaths.standardLocations( QStandardPaths.HomeLocation) ubicacion = QFileDialog.getOpenFileName(self, 'Abrir archivo', location[0], 'CSV Files(*.csv)') self.data = pd.read_csv(ubicacion[0])
def __get_sqlite_name(self) -> str: """Create the name for the SqliteDB. Therefor combine the Qt Application Defs: QStandardPaths.DataLocation + QtCoreApplication.applicationName + .sqlite3 * *on Mac is this* `~/Library/Application Support/io.jmuelbert.github/jmbde/jmbde.sqlite3` * *on Linux this* `~/.local/share/<APPNAME>/jmbde.sqlite3` * *on Windows is this* `C:/Users/<USER>/AppData/Local/<APPNAME>/jmbde.sqlite3` Returns: The connection string fot the sqlite database. """ db_data_path = QStandardPaths.writableLocation( QStandardPaths.DataLocation) self.log.info("The Database: {}".format(db_data_path)) write_dir = QDir(db_data_path) if not write_dir.mkpath("."): self.log.error("Failed to create writable directory") if not write_dir.exists(): write_dir.mkpath(db_data_path) # Ensure that we have a writable location on all devices. filename = "{}/{}.sqlite3".format(write_dir.absolutePath(), QCoreApplication.applicationName()) return filename
def setup_menus(self): file_menu = self.menuBar().addMenu("&File") exit_action = file_menu.addAction("E&xit") exit_action.setShortcut(QKeySequence("Ctrl+Q")) character_menu = self.menuBar().addMenu("&Character") import_action = character_menu.addAction("&Import from PDF") import_action.triggered.connect( lambda: self.pdf_wizard_factory.create(self)) import_action = character_menu.addAction("&Create new Character") import_action.triggered.connect(self.create_new_player) export_menu = self.menuBar().addMenu("&Export") export_debug_action = export_menu.addAction("Export Debug") export_debug_action.triggered.connect( lambda: self.export_pdf_wizard_factory.create(self)) resource_menu = self.menuBar().addMenu("&Resources") open_app_data = resource_menu.addAction("Open Appdata Folder") dir_to_open = QStandardPaths.writableLocation( QStandardPaths.AppDataLocation) open_app_data.triggered.connect( lambda: QDesktopServices.openUrl(dir_to_open)) exit_action.triggered.connect(QApplication.instance().quit) logger.debug("Menus set-up")
def draw_index(self): if not self.graph: logger.warning("No graph to draw found!") width = self.contentsRect().width() height = self.contentsRect().height() pagewidth = int(width) - 10 pageheight = int(height) - 10 logger.info(f"{width}x{height}") html = importlib.resources.read_text(__package__, "index.thtml", encoding="utf-8-sig") html = (html.replace( "$graph", "'" + json.dumps(networkx.node_link_data(self.graph)) + "'" if self.graph else """'{"directed":true,"multigraph":true,"graph":[],"nodes":[],"links":[]}'""", ).replace("$width", str(pagewidth)).replace("$height", str(pageheight))) path = pathlib.Path( QStandardPaths.writableLocation( QStandardPaths.AppLocalDataLocation)) / "index.html" logger.info(f"""Saving html to {path.absolute()}""") path.write_text(html) self.index.setHtml(html) self.index.settings().setAttribute(QWebEngineSettings.ShowScrollBars, False) self.webview.setPage(self.index) self.webview.resize(width, height) self.webview.show() self.update()
def __init__(self): QMainWindow.__init__(self) self.setWindowTitle("Lab-Data-Converter") self.create_actions() self.setup_menu() self.settings = QSettings("UCB", "Lab-Data-Converter") self.data_sets = {} self.output_widget = OutputWidget(self) self.data_table = DataTabel(self) self.splitter1 = QSplitter() self.splitter1.setOrientation(Qt.Vertical) self.splitter1.addWidget(self.data_table) self.splitter1.addWidget(self.output_widget) self.splitter1.setSizes([200, 100]) #self.splitter1.setStretchFactor(0, 8) #self.splitter1.setStretchFactor(1, 4) self.setCentralWidget(self.splitter1) QDir.setCurrent(QStandardPaths.standardLocations( QStandardPaths.DocumentsLocation)[-1]) if (self.settings.value("work_dir")): try: QDir.setCurrent(self.settings.value("work_dir")) except: pass
def export(self): # TODO exporter should tell me what file to use dir_to_search = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) dir_to_search = os.path.join(dir_to_search, "exporters") file_to_export_to = os.path.join( dir_to_search, "Character Sheet_WARLOCK_FILLABLE.pdf" ) pdf_file = PDFFile(file_to_export_to) form_fields = pdf_file.get_forms_names() convertable_form_fields = [ field_name for field_name in form_fields if field_name in self.plugin.key_conversion.keys() ] for field in convertable_form_fields: ch_candidate = self.plugin.key_conversion[field] if not ch_candidate: logger.info(f"Value {ch_candidate} is not a valid CH") continue ch = CHProperty(ch_candidate) ch_property = self.player_controller.player_model.get_ch_property(ch) value = ch_property.value pdf_file.set_field(field, value) # TODO maybe go to a model where we do not keep track of set fields and check it at another place (plugin?) # form_fields = [ # # form for form in form_fields if form not in convertable_form_fields # # ] # TODO skills # forms = self.export_skills(form_fields, self.skill_keys) self.plugin.export_character_incremental_lists(pdf_file, self.player_controller) pdf_file.save(self.pdf_target)
def icon(self, appid: str) -> Optional[QIcon]: fn = QStandardPaths.locate(QStandardPaths.AppConfigLocation, "app_icons/" + appid + ".png") if fn == "": return None return QIcon(QPixmap(fn))
def __init__(self, parent=None): """ :param parent: """ super(SlippyMap, self).__init__(parent) self._offset = QPoint() self._tiles_rectangle = QRect() self._tile_pixmaps = {} # Point(x, y) to QPixmap mapping self._manager = QNetworkAccessManager() self._url = QUrl() # public vars self.width = 400 self.height = 300 self.zoom = 4 self.latitude = 59.9138204 self.longitude = 10.7387413 self._emptyTile = QPixmap(TDIM, TDIM) self._emptyTile.fill(Qt.lightGray) self.request = QNetworkRequest() self.cache = QNetworkDiskCache() self.cache.setCacheDirectory( QStandardPaths.writableLocation(QStandardPaths.CacheLocation)) self._manager.setCache(self.cache) self._manager.finished.connect(self.handle_network_data)
def ask_for_filename_to_load(parent): dir_to_open = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) fname = QFileDialog.getOpenFileName(parent, "Open PDF", dir_to_open, "PDF Files (*.pdf)") return fname
def _onActionOpenTriggered(self): fileNames = QFileDialog.getOpenFileNames(self, self.tr("Open Document"), QStandardPaths.writableLocation(QStandardPaths.HomeLocation), self.tr("CSV Files (*.csv);;All Files (*.*)"))[0] for fileName in fileNames: self._openDocument(fileName)
def addFile(self): linetexts = QFileDialog.getOpenFileNames( self, self.tr("Select File"), QStandardPaths.displayName(QStandardPaths.HomeLocation), self.tr("Files (*.ctf *.xml *.ang)"))[0] for line in linetexts: self.uselistmodel.addRow(line) self.toggleButtons()
def selectFile(self, fileLink=None): if fileLink == False: linetext = QFileDialog.getOpenFileName( self, self.tr("Select File"), QStandardPaths.displayName(QStandardPaths.HomeLocation), self.tr("Files (*.*)"))[0] else: linetext = fileLink if linetext != "": self.setWindowTitle(linetext) self.ui.dataFileLineEdit.setText(linetext) self.ui.dataTypeText.setText(linetext.split(".")[1].upper()) if self.ui.fileParserCombo.findText( linetext.split(".")[1].upper() + " Parser") != -1: headerDict = {} self.ui.fileParserCombo.setCurrentIndex( self.ui.fileParserCombo.findText( linetext.split(".")[1].upper() + " Parser")) if linetext.split(".")[1].upper() == "CTF": headerDict = ctf.parse_header_as_dict(linetext) elif linetext.split(".")[1].upper() == "ANG": headerDict = ang.parse_header_as_dict(linetext) elif linetext.split(".")[1].upper() == "XML": print("XML Parser used") self.createtablemodel = TableModelC(headerDict, self) self.filterModel.displayed = [] self.filterModel.setSourceModel(self.createtablemodel) self.filterModel.fileType.append(linetext) self.createTableSearchFilterModel = QSortFilterProxyModel(self) self.createTableSearchFilterModel.setSourceModel(self.filterModel) self.createTableSearchFilterModel.setFilterKeyColumn(1) self.createTableSearchFilterModel.setDynamicSortFilter(True) self.ui.metadataTableView.setModel( self.createTableSearchFilterModel) self.treeModel = TreeModel(["Available File Metadata"], headerDict, self.createtablemodel) if len(self.customInputs) != 0: for i in range(len(self.customInputs)): self.createtablemodel.beginInsertRows( self.createtablemodel.index( len(self.createtablemodel.metadataList), 0), i, i) self.createtablemodel.metadataList.append( self.customInputs[i]) self.createtablemodel.endInsertRows() self.createTreeSearchFilterModel = QSortFilterProxyModel(self) self.createTreeSearchFilterModel.setSourceModel(self.treeModel) self.createTreeSearchFilterModel.setFilterKeyColumn(0) self.createTreeSearchFilterModel.setDynamicSortFilter(True) self.createTreeSearchFilterModel.setRecursiveFilteringEnabled(True) self.ui.metadataTreeView.setModel(self.createTreeSearchFilterModel) self.treeModel.checkChanged.connect(self.filterModel.checkList) self.createtrashDelegate.pressed.connect(self.handleRemoveCreate) self.toggleButtons() return True
def restoreTemplate(self): #Clear data on create side self.createtablemodel.metadataList = [] self.createtablemodel.hiddenList = [] self.filterModel.displayed = [] #open template linetext = QFileDialog.getOpenFileName( self, self.tr("Select File"), QStandardPaths.displayName(QStandardPaths.HomeLocation), self.tr("Files (*.ez)"))[0] if linetext != "": infile = open(linetext, "r") infile.readline() fileType = infile.readline() self.fileType = json.loads(fileType) infile.readline() newList = infile.readline() newList = json.loads(newList) newDict = infile.readline() newDict = json.loads(newDict) self.ui.dataTypeText.setText(self.fileType[0][-3:].upper()) self.ui.fileParserCombo.setCurrentIndex( self.ui.fileParserCombo.findText( self.fileType[0][-3:].upper() + " Parser")) self.ui.dataFileLineEdit.setText(self.fileType[0]) self.createtablemodel = TableModelC(newDict, self) self.filterModel.displayed = [] self.filterModel.setSourceModel(self.createtablemodel) self.filterModel.fileType = self.fileType self.createTableSearchFilterModel = QSortFilterProxyModel(self) self.createTableSearchFilterModel.setSourceModel(self.filterModel) self.createTableSearchFilterModel.setFilterKeyColumn(1) self.createTableSearchFilterModel.setDynamicSortFilter(True) self.ui.metadataTableView.setModel( self.createTableSearchFilterModel) self.treeModel = TreeModelR(["Available File Metadata"], newDict, self.createtablemodel, newList, self.filterModel) for i in range(len(newList)): if "Custom Input" in newList[i]["Source"]: self.numCustoms += 1 self.customInputs.append(newList[i]) self.createtablemodel.beginInsertRows( self.createtablemodel.index( len(self.createtablemodel.metadataList), 0), i, i) self.createtablemodel.metadataList.append(newList[i]) self.createtablemodel.endInsertRows() self.createTreeSearchFilterModel = QSortFilterProxyModel(self) self.createTreeSearchFilterModel.setSourceModel(self.treeModel) self.createTreeSearchFilterModel.setFilterKeyColumn(0) self.createTreeSearchFilterModel.setDynamicSortFilter(True) self.createTreeSearchFilterModel.setRecursiveFilteringEnabled(True) self.ui.metadataTreeView.setModel(self.createTreeSearchFilterModel) self.treeModel.checkChanged.connect(self.filterModel.checkList) self.createtrashDelegate.pressed.connect(self.handleRemoveCreate) self.ui.TabWidget.setCurrentIndex(0)
def selectTemplate(self): startLocation = self.ui.hyperthoughtTemplateLineEdit.text() if startLocation == "": startLocation = QStandardPaths.writableLocation( QStandardPaths.HomeLocation) templateFilePath = QFileDialog.getOpenFileName( self, self.tr("Select File"), startLocation, self.tr("Files (*.ez)"))[0] self.loadTemplateFile(templateFilePath)
def __init__(self): super().__init__() self.settings = QSettings(self) qt_write_base = Path( QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation)) qt_write_base.mkdir(parents=True, exist_ok=True) self.icon_write_dir = qt_write_base / "app_icons" self.icon_write_dir.mkdir(exist_ok=True)
def config_directory() -> str: """Returns the configuration directory (This is the root dir for dial)""" config_directory = ( QStandardPaths.writableLocation(QStandardPaths.ConfigLocation) + os.path.sep + "dial") if not os.path.isdir(config_directory): os.mkdir(config_directory) return config_directory
def open(self): fileDialog = QFileDialog(self) supportedMimeTypes = ["video/mp4", "*.*"] fileDialog.setMimeTypeFilters(supportedMimeTypes) moviesLocation = QStandardPaths.writableLocation( QStandardPaths.MoviesLocation) fileDialog.setDirectory(moviesLocation) if fileDialog.exec_() == QDialog.Accepted: self.playlist.addMedia(fileDialog.selectedUrls()[0]) self.player.play()
def testTestModeEnabled(self): print("QStandardPaths.isTestModeEnabled:", QStandardPaths.isTestModeEnabled()) sp = True QStandardPaths.setTestModeEnabled(sp) self.assertEqual(QStandardPaths.isTestModeEnabled(), sp) sp = False QStandardPaths.setTestModeEnabled(sp) self.assertEqual(QStandardPaths.isTestModeEnabled(), sp)
def go_desktop(self, checked=False): """Slot for the 'Desktop' button. Scrolls the treeview to show and select the user's desktop directory.""" desktop = QStandardPaths.writableLocation(QStandardPaths.DesktopLocation) # Return a list if not desktop: return self.ui.comboBox_current_path.setCurrentIndex(-1) desktop_index = self.file_model.index(desktop) self.ui.treeView_file_system.collapseAll() self.ui.treeView_file_system.setCurrentIndex(desktop_index) self.ui.treeView_file_system.expand(desktop_index) self.ui.treeView_file_system.scrollTo(desktop_index, hint=QAbstractItemView.PositionAtTop)
def go_documents(self, checked=False): """Slot for the 'Documents' button. Scrolls the treeview to show and select the user's documents directory.""" docs = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation) if not docs: return self.ui.comboBox_current_path.setCurrentIndex(-1) docs_index = self.file_model.index(docs) self.ui.treeView_file_system.collapseAll() self.ui.treeView_file_system.setCurrentIndex(docs_index) self.ui.treeView_file_system.expand(docs_index) self.ui.treeView_file_system.scrollTo(docs_index, hint=QAbstractItemView.PositionAtTop)
def nextImageFileName(self): picturesLocation = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation) dateString = QDate.currentDate().toString("yyyyMMdd") pattern = picturesLocation + "/pyside2_camera_" + dateString + "_{:03d}.jpg" n = 1 while True: result = pattern.format(n) if not os.path.exists(result): return result n = n + 1 return None
def appDirectory(): directory = QStandardPaths.writableLocation( QStandardPaths.AppDataLocation) if AppInfo.isDevMode(): directory = directory.replace("python", "Spongo") if not QDir().exists(directory): QDir().mkdir(directory) return directory
def extractFile(self, fileLink=False): if fileLink == False: linetext = QFileDialog.getOpenFileName( self, self.tr("Select File"), QStandardPaths.displayName(QStandardPaths.HomeLocation), self.tr("Files (*" + self.fileType + ")"))[0] else: linetext = fileLink if linetext != "": self.setWindowTitle(linetext) self.ui.dataTypeText.setText(linetext.split(".")[1].upper()) self.ui.otherDataFileLineEdit.setText(linetext) if self.ui.addMetadataFileCheckBox.checkState() == Qt.Checked: self.uselistmodel.removeAllRows() self.uselistmodel.addRow(linetext) self.toggleButtons() if self.ui.fileParserCombo.findText( linetext.split(".")[1].upper() + " Parser") != -1: headerDict = {} self.ui.fileParserCombo.setCurrentIndex( self.ui.fileParserCombo.findText( linetext.split(".")[1].upper() + " Parser")) if linetext.split(".")[1].upper() == "CTF": headerDict = ctf.parse_header_as_dict(linetext) elif linetext.split(".")[1].upper() == "ANG": headerDict = ang.parse_header_as_dict(linetext) elif linetext.split(".")[1].upper() == "XML": print("XML Parser used") if self.templatedata: self.usetablemodel.metadataList = [] self.usefilterModel = FilterModelU(self) self.usefilterModel.setSourceModel(self.usetablemodel) self.unusedTreeModel = TreeModelU(["Available File Metadata"], headerDict, self.usetablemodel, self.editableKeys) self.templatelist = [] self.templatesources = [] for i in range(len(self.templatedata)): self.templatelist.append(self.templatedata[i]) if "Custom Input" not in self.templatedata[i]["Source"]: self.templatesources.append("/".join( self.templatedata[i]['Source'].split("/")[1:])) else: self.usetablemodel.addExistingRow(self.templatedata[i]) self.usesearchFilterModel = QSortFilterProxyModel(self) self.usesearchFilterModel.setSourceModel(self.usefilterModel) self.usesearchFilterModel.setFilterKeyColumn(0) self.usesearchFilterModel.setDynamicSortFilter(True) self.ui.useTemplateTableView.setModel( self.usesearchFilterModel) self.toggleButtons()
def start_simple_tts(self, content: str, ui_config: str): if content == '': self.failed.emit() return out_file = os.path.join( QStandardPaths.writableLocation(QStandardPaths.DownloadLocation), 'tts.wav') self._do_tts(True, self._get_ssml_config_template(ui_config).format(content), out_file) self.allReady.emit()
def open(self): fileDialog = QFileDialog(self) supportedMimeTypes = QMediaPlayer.supportedMimeTypes() if not supportedMimeTypes: supportedMimeTypes.append("video/x-msvideo") # AVI fileDialog.setMimeTypeFilters(supportedMimeTypes) moviesLocation = QStandardPaths.writableLocation(QStandardPaths.MoviesLocation) fileDialog.setDirectory(moviesLocation) if fileDialog.exec_() == QDialog.Accepted: self.playlist.addMedia(fileDialog.selectedUrls()[0]) self.player.play()
def load(self) -> None: settings = QSettings(self.settings_path) settings.beginGroup("Settings") self.input_link = settings.value("input_link", "") self.output_path = settings.value( "output_path", QStandardPaths.writableLocation(QStandardPaths.DownloadLocation)) self.file_format = settings.value("file_format", "webm") self.single_line = bool( settings.value("single_line", "True") == "True") self.theme_color = settings.value("theme_color", "#004d99") settings.endGroup()
def __init__(self, parent=None): super(SettingsDialog, self).__init__(parent) self.settings = QSettings( QStandardPaths.writableLocation(QStandardPaths.ConfigLocation) + "/settings.ini", QSettings.IniFormat) self.usernames = set() self.engines = set() self.newUsername = "" self.newEnginePath = "" self._loadSettings() self.mainLayout = QtWidgets.QFormLayout() self.usernameLineEdit = QtWidgets.QLineEdit(self.newUsername) self.usernameLineEdit.setPlaceholderText("Username (a-zA-Z0-9_)") self.usernameLineEdit.setMinimumHeight(35) self.usernameLineEdit.setValidator(self.validator) self.usernameLineEdit.textChanged.connect(self.validateFields) self.usernameLineEdit.selectAll() self.usernameLineEdit.setCompleter( QtWidgets.QCompleter(list(self.usernames), self)) self.engineEdit = _EngineEdit(self.newEnginePath) self.engineEdit.pathEdit.textChanged.connect(self.validateFields) self.engineEdit.pathEdit.selectAll() self.engineEdit.pathEdit.setCompleter( QtWidgets.QCompleter(list(self.engines), self)) self.resetButton = QtWidgets.QPushButton("Reset") self.resetButton.clicked.connect(self._reset) buttonBox = QtWidgets.QDialogButtonBox() self.okButton = buttonBox.addButton( "Ok", QtWidgets.QDialogButtonBox.AcceptRole) self.cancelButton = buttonBox.addButton( "Cancel", QtWidgets.QDialogButtonBox.RejectRole) self.okButton.clicked.connect(self._ok) self.cancelButton.clicked.connect(self.reject) self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setAlignment(Qt.AlignBottom) self.mainLayout.addRow("Username", self.usernameLineEdit) self.mainLayout.addRow("Engine", self.engineEdit) self.mainLayout.addWidget(self.resetButton) self.mainLayout.addWidget(buttonBox) self.setLayout(self.mainLayout) self.validateFields()
def open_download_directory(): path = QStandardPaths.writableLocation(QStandardPaths.DownloadLocation) DownloadWidget.open_file(path)