def get_app_icon(icon_name, widget): dark = bool(widget.palette().brush( 2, QPalette.WindowText).color().lightness() > 128) icon = QIcon.fromTheme(icon_name) if icon.isNull(): for ext in ('svg', 'svgz', 'png'): filename = ":app_icons/%s.%s" % (icon_name, ext) darkname = ":app_icons/dark/%s.%s" % (icon_name, ext) if dark and QFile.exists(darkname): filename = darkname if QFile.exists(filename): del icon icon = QIcon() icon.addFile(filename) break if icon.isNull(): for path in ('/usr/local', '/usr', '%s/.local' % os.getenv('HOME')): for ext in ('png', 'svg', 'svgz', 'xpm'): filename = "%s/share/pixmaps/%s.%s" % (path, icon_name, ext) if QFile.exists(filename): del icon icon = QIcon() icon.addFile(filename) break return icon
def getAppIcon(icon_name, widget, addSearchPaths=[]): dark = bool(widget.palette().brush( 2, QPalette.WindowText).color().lightness() > 128) icon = QIcon.fromTheme(icon_name) if icon.isNull(): for ext in ('svg', 'svgz', 'png'): filename = ":app_icons/%s.%s" % (icon_name, ext) darkname = ":app_icons/dark/%s.%s" % (icon_name, ext) if dark and QFile.exists(darkname): filename = darkname if QFile.exists(filename): del icon icon = QIcon() icon.addFile(filename) break else: for path in addSearchPaths: for ext in ('svg', 'svgz', 'png'): filename = "%s/%s.%s" % (path, icon_name, ext) darkname = "%s/dark/%s.%s" % (path, icon_name, ext) if dark and QFile.exists(darkname): filename = darkname if QFile.exists(filename): del icon icon = QIcon() icon.addFile(filename) break return icon
def redo(self): redo = QFile(self.redoFilename) if redo.exists(): dest = QFile(self.filename) if dest.exists(): dest.remove() QFile.copy(self.redoFilename, self.filename) self.editor.load() else: QFile.copy(self.filename, self.undoFilename) self.editor.save() QFile.copy(self.filename, self.redoFilename)
def Buscar(self): # Obtener nombre de usuario nombre = " ".join(self.lineEditNombre.text().split()).title() if nombre: if QFile.exists("DB_USUARIOS.db"): # Establecer conexión con la base de datos conexion = connect("DB_USUARIOS.db") cursor = conexion.cursor() # Buscar usuario en la base de datos cursor.execute("SELECT * FROM Usuarios WHERE NOMBRE = ?", (nombre, )) resultado = cursor.fetchone() # Validar si se encontro algún resultado if resultado: foto = "Fotos/{}.png".format(resultado[0]) if QFile.exists(foto): # Cargar foto a un QPixmap fotoFinal = QPixmap(foto) # Insertar foto en el QLabel self.labelImagen.setPixmap(fotoFinal) # Insertar nombre de usuario en el QLineEdit self.lineEditNombre.setText(resultado[1]) else: QMessageBox.critical( self, "Guardar imagen", "No se encontro la foto del usuario " "{}.".format(resultado[1]), QMessageBox.Ok) else: self.labelImagen.clear() QMessageBox.critical( self, "Guardar imagen", "El usuario {} no existe.".format(nombre), QMessageBox.Ok) # Cerrar la conexión con la base de datos conexion.close() self.lineEditNombre.setFocus() else: QMessageBox.critical(self, "Guardar imagen", "No se encontro la Base de Datos", QMessageBox.Ok) else: self.lineEditNombre.clear() self.lineEditNombre.setFocus()
def openFile(self): filename, _ = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME')) if not filename: return fh = '' if QFile.exists(filename): fh = QFile(filename) if not fh.open(QFile.ReadOnly): QtGui.qApp.quit() data = fh.readAll() codec = QTextCodec.codecForUtfText(data) unistr = codec.toUnicode(data) tmp = ('Nopepad: %s' % filename) self.setWindowTitle(tmp) basename = QFileInfo(fh).baseName() self.statusBar().showMessage('File \'%s\' loaded' % basename) self.textEdit.setText(unistr)
def set_window_style(window): """ :return the stylesheet string """ # Smart import of the rc file f = QFile(":dark_style.qss") if not f.exists(): print('Custom stylesheet not present') Lumberjack.error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix window.setWindowIcon(QIcon(':/app_icons/rc/PAT_icon.png')) window.setStyleSheet(stylesheet)
def getHtml(self, includeStyleSheet=True, webenv=False, syncScroll=False): if self.markup is None: markupClass = self.getMarkupClass() errMsg = self.tr('Could not parse file contents, check if ' 'you have the <a href="%s">necessary module</a> ' 'installed!') try: errMsg %= markupClass.attributes[MODULE_HOME_PAGE] except (AttributeError, KeyError): # Remove the link if markupClass doesn't have the needed attribute errMsg = errMsg.replace('<a href="%s">', '').replace('</a>', '') return '<p style="color: red">%s</p>' % errMsg text = self.editBox.toPlainText() headers = '' if includeStyleSheet: headers += '<style type="text/css">\n' + self.p.ss + '</style>\n' baseName = self.getDocumentTitle(baseName=True) cssFileName = baseName + '.css' if QFile.exists(cssFileName): headers += ('<link rel="stylesheet" type="text/css" href="%s">\n' % cssFileName) headers += ('<meta name="generator" content="ReText %s">\n' % app_version) self.markup.requested_extensions = [] if syncScroll: self.markup.requested_extensions.append('ReText.mdx_posmap') return self.markup.get_whole_html(text, custom_headers=headers, include_stylesheet=includeStyleSheet, fallback_title=baseName, webenv=webenv)
def read(self, fileNameOrDevice): """ Public method to read an XBEL bookmark file. @param fileNameOrDevice name of the file to read (string) or reference to the device to read (QIODevice) @return reference to the root node (BookmarkNode) """ if isinstance(fileNameOrDevice, QIODevice): self.setDevice(fileNameOrDevice) else: f = QFile(fileNameOrDevice) if not f.exists(): return BookmarkNode(BookmarkNode.Root) f.open(QFile.ReadOnly) self.setDevice(f) root = BookmarkNode(BookmarkNode.Root) while not self.atEnd(): self.readNext() if self.isStartElement(): version = self.attributes().value("version") if self.name() == "xbel" and \ (not version or version == "1.0"): self.__readXBEL(root) else: self.raiseError(QCoreApplication.translate( "XbelReader", "The file is not an XBEL version 1.0 file.")) return root
def getHtmlFromConverted(self, converted, includeStyleSheet=True, webenv=False): if converted is None: markupClass = self.getActiveMarkupClass() errMsg = self.tr('Could not parse file contents, check if ' 'you have the <a href="%s">necessary module</a> ' 'installed!') try: errMsg %= markupClass.attributes[MODULE_HOME_PAGE] except (AttributeError, KeyError): # Remove the link if markupClass doesn't have the needed attribute errMsg = errMsg.replace('<a href="%s">', '').replace('</a>', '') return '<p style="color: red">%s</p>' % errMsg headers = '' if includeStyleSheet: headers += '<style type="text/css">\n' + self.p.ss + '</style>\n' baseName = self.getBaseName() cssFileName = baseName + '.css' if QFile.exists(cssFileName): headers += ('<link rel="stylesheet" type="text/css" href="%s">\n' % cssFileName) headers += ('<meta name="generator" content="ReText %s">\n' % app_version) return converted.get_whole_html(custom_headers=headers, include_stylesheet=includeStyleSheet, fallback_title=baseName, webenv=webenv)
def on_btnFile_exists_clicked(self): self.__showBtnInfo(self.sender()) sous = self.ui.editFile.text().strip() #源文件 if QFile.exists(sous): self.ui.textEdit.appendPlainText("True \n") else: self.ui.textEdit.appendPlainText("False \n")
def saveFileName(self, url): path = url.path() basename = QFileInfo(path).fileName() if not basename: basename = "download" if QFile.exists(basename): i = 0 basename = basename + "." while QFile.exists("%s%s" % (basename, i)): i = i + 1 basename = "%s%s" % (basename, i) return basename
def openFileWrapper(self, fileName): if not fileName: return fileName = QFileInfo(fileName).canonicalFilePath() exists = False for i in range(self.tabWidget.count()): if self.fileNames[i] == fileName: exists = True ex = i if exists: self.tabWidget.setCurrentIndex(ex) elif QFile.exists(fileName): noEmptyTab = ( (self.ind is None) or self.fileNames[self.ind] or self.editBoxes[self.ind].toPlainText() or self.editBoxes[self.ind].document().isModified() ) if noEmptyTab: self.tabWidget.addTab(self.createTab(fileName), "") self.ind = self.tabWidget.count()-1 self.tabWidget.setCurrentIndex(self.ind) if fileName: self.fileSystemWatcher.addPath(fileName) self.fileNames[self.ind] = fileName self.openFileMain()
def readTextFromFile(self, fileName=None, encoding=None): previousFileName = self._fileName if fileName: self._fileName = fileName # Only try to detect encoding if it is not specified if encoding is None and globalSettings.detectEncoding: encoding = self.detectFileEncoding(self._fileName) # TODO: why do we open the file twice: for detecting encoding # and for actual read? Can we open it just once? openfile = QFile(self._fileName) openfile.open(QFile.ReadOnly) stream = QTextStream(openfile) encoding = encoding or globalSettings.defaultCodec if encoding: stream.setCodec(encoding) # If encoding is specified or detected, we should save the file with # the same encoding self.editBox.document().setProperty("encoding", encoding) text = stream.readAll() openfile.close() if previousFileName != self._fileName: self.updateActiveMarkupClass() self.editBox.setPlainText(text) self.editBox.document().setModified(False) cssFileName = self.getBaseName() + '.css' self.cssFileExists = QFile.exists(cssFileName) if previousFileName != self._fileName: self.fileNameChanged.emit()
def openFileWrapper(self, fileName): if not fileName: return fileName = QFileInfo(fileName).canonicalFilePath() exists = False for i, tab in enumerate(self.iterateTabs()): if tab.fileName == fileName: exists = True ex = i if exists: self.tabWidget.setCurrentIndex(ex) elif QFile.exists(fileName): noEmptyTab = ( (self.ind is None) or self.currentTab.fileName or self.currentTab.editBox.toPlainText() or self.currentTab.editBox.document().isModified() ) if noEmptyTab: self.createTab(fileName) self.ind = self.tabWidget.count()-1 self.tabWidget.setCurrentIndex(self.ind) if fileName: self.fileSystemWatcher.addPath(fileName) self.currentTab.readTextFromFile(fileName) self.moveToTopOfRecentFileList(self.currentTab.fileName)
def openFile(self, path=None): if not path: path, _ = QFileDialog.getOpenFileName(self, "Open SVG File", self.currentPath, "SVG files (*.svg *.svgz *.svg.gz)") if path: svg_file = QFile(path) if not svg_file.exists(): QMessageBox.critical(self, "Open SVG File", "Could not open file '%s'." % path) self.outlineAction.setEnabled(False) self.backgroundAction.setEnabled(False) return self.view.openFile(svg_file) if not path.startswith(':/'): self.currentPath = path self.setWindowTitle("%s - SVGViewer" % self.currentPath) self.outlineAction.setEnabled(True) self.backgroundAction.setEnabled(True) self.resize(self.view.sizeHint() + QSize(80, 80 + self.menuBar().height()))
def openFile(self, svg_file: QFile): if not svg_file.exists(): return if self.backgroundItem: drawBackground = self.backgroundItem.isVisible() else: drawBackground = False s = self.scene() s.clear() self.resetTransform() self.svgItem = QGraphicsSvgItem(svg_file.fileName()) self.svgItem.setFlags(QGraphicsItem.ItemClipsToShape) self.svgItem.setCacheMode(QGraphicsItem.NoCache) self.svgItem.setZValue(0) tmp = self.svgItem.renderer().defaultSize() self.default_width = tmp.width() self.default_height = tmp.height() self.backgroundItem = QGraphicsRectItem(self.svgItem.boundingRect()) self.backgroundItem.setBrush(Qt.white) self.backgroundItem.setPen(QPen(Qt.NoPen)) self.backgroundItem.setVisible(drawBackground) self.backgroundItem.setZValue(-1) s.addItem(self.backgroundItem) s.addItem(self.svgItem)
def read(self, fileNameOrDevice): """ Public method to read a user agent file. @param fileNameOrDevice name of the file to read (string) or reference to the device to read (QIODevice) @return dictionary with user agent data (host as key, agent string as value) """ self.__agents = {} if isinstance(fileNameOrDevice, QIODevice): self.setDevice(fileNameOrDevice) else: f = QFile(fileNameOrDevice) if not f.exists(): return self.__agents f.open(QFile.ReadOnly) self.setDevice(f) while not self.atEnd(): self.readNext() if self.isStartElement(): version = self.attributes().value("version") if self.name() == "UserAgents" and \ (not version or version == "1.0"): self.__readUserAgents() else: self.raiseError(QCoreApplication.translate( "UserAgentReader", "The file is not a UserAgents version 1.0 file.")) return self.__agents
def saveV2raycoreJSONFile(self): JSONData = {} JSONData["preferences"] = copy.deepcopy(self.preferences) JSONData["update"] = copy.deepcopy(self.update) JSONData["configFiles"] = copy.deepcopy(self.configFiles) outFile = QFileInfo(self.v2rayshellConfigFileName) fileName = outFile.fileName() if QFile.exists(fileName): QFile.remove(fileName) outFile = QFile(fileName) outFile.open(QIODevice.WriteOnly | QIODevice.Text) if outFile.error() != outFile.NoError: self.msgBox.information(QDialog().move(self.fly), "{}".format(fileName), self.translate("bridgetreasureChest", "Unable to open the file {}: {}.").format(fileName, outFile.errorString())) outFile = None return False outFile.write(codecs.encode(json.dumps(JSONData, indent = 4, sort_keys = False), "utf-8")) if outFile.error() != outFile.NoError: self.msgBox.information(QDialog().move(self.fly), "{}".format(fileName), self.translate("bridgetreasureChest", "Unable to save the file {}: {}.").format(fileName, outFile.errorString())) outFile = None return False outFile.close()
def path_to_stream(requested_path, encoding=None): a_file = QFile(requested_path) if not a_file.exists(): utilities_logger.error( 'Request for nonexistent input file {0}'.format(requested_path)) return None return _qfile_to_stream(a_file, QIODevice.ReadOnly, encoding)
def readThemeIndex(self, themeName): dirList = [] parents = [] themeIndex = QFile() # Read theme index files for i in range(len(self.iconDirs)): themeIndex.setFileName( path.join(unicode(self.iconDirs[i]), unicode(themeName), "index.theme")) if themeIndex.exists(): indexReader = QSettings(themeIndex.fileName(), QSettings.IniFormat) for key in indexReader.allKeys(): if str(key).endswith("/Size"): size = str(indexReader.value(key)) dirList.append((size, unicode(key[:-5]))) parents = indexReader.value('Icon Theme/Inherits') dump = parents parents = list() parents.append(dump) break return QIconTheme(dirList, parents)
def read(self, fileNameOrDevice): """ Public method to read a login data file. @param fileNameOrDevice name of the file to read (string) or reference to the device to read (QIODevice) @return tuple containing the logins, forms and never URLs """ self.__logins = {} self.__loginForms = {} self.__never = [] if isinstance(fileNameOrDevice, QIODevice): self.setDevice(fileNameOrDevice) else: f = QFile(fileNameOrDevice) if not f.exists(): return self.__logins, self.__loginForms, self.__never f.open(QFile.ReadOnly) self.setDevice(f) while not self.atEnd(): self.readNext() if self.isStartElement(): version = self.attributes().value("version") if self.name() == "Password" and \ (not version or version == "1.0"): self.__readPasswords() else: self.raiseError( QCoreApplication.translate( "PasswordReader", "The file is not a Passwords version 1.0 file.")) return self.__logins, self.__loginForms, self.__never
def __openByIODevice(self, fileName): ##用QFile打开文件 fileDevice = QFile(fileName) if not fileDevice.exists(): #判断文件是否存在 return False if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text): return False ###整个文件一次性读取的方式,可行 ## qtBytes=fileDevice.readAll() #返回QByteArray类型 ## pyBytes=bytes(qtBytes.data()) # 将QByteArray转换为bytes类型 ## text=pyBytes.decode("utf-8") #用utf-8编码为字符串 ## self.ui.textEdit.setPlainText(text) ## 逐行读取方式,可行 try: self.ui.textEdit.clear() while not fileDevice.atEnd(): qtBytes = fileDevice.readLine() # 返回QByteArray类型 pyBytes = bytes(qtBytes.data()) # QByteArray转换为bytes类型 lineStr = pyBytes.decode("utf-8") #bytes转换为str型 lineStr = lineStr.strip() #去除结尾增加的空行 self.ui.textEdit.appendPlainText(lineStr) finally: fileDevice.close() return True
def __openByStream(self, fileName): ##用QTextStream打开文件 fileDevice = QFile(fileName) if not fileDevice.exists(): #判断文件是否存在 return False if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text): return False try: fileStream = QTextStream(fileDevice) fileStream.setAutoDetectUnicode(True) #自动检测Unicode fileStream.setCodec("utf-8") #必须设置编码,否则不能正常显示汉字 # 一次性全部读出 ## text=fileStream.readAll() #读取出来就是str ## self.ui.textEdit.setPlainText(text) #逐行读取方式 self.ui.textEdit.clear() while not fileStream.atEnd(): lineStr = fileStream.readLine() #读取文件的一行,读取出来就是str self.ui.textEdit.appendPlainText(lineStr) #添加到文本框显示 finally: fileDevice.close() #关闭文件 return True
def readThemeIndex(self, themeName): dirList = [] parents = [] themeIndex = QFile() # Read theme index files for i in range(len(self.iconDirs)): themeIndex.setFileName(path.join(unicode(self.iconDirs[i]), unicode(themeName), "index.theme")) if themeIndex.exists(): indexReader = QSettings(themeIndex.fileName(), QSettings.IniFormat) for key in indexReader.allKeys(): if str(key).endswith("/Size"): size = str(indexReader.value(key)) dirList.append((size, unicode(key[:-5]))) parents = indexReader.value('Icon Theme/Inherits') dump=parents parents = list() parents.append(dump) break return QIconTheme(dirList, parents)
def openFile(self, path=None): if not path: path, _ = QFileDialog.getOpenFileName( self, "Open SVG File", self.currentPath, "SVG files (*.svg *.svgz *.svg.gz)", ) if path: svg_file = QFile(path) if not svg_file.exists(): QMessageBox.critical(self, "Open SVG File", "Could not open file '%s'." % path) self.outlineAction.setEnabled(False) self.backgroundAction.setEnabled(False) return self.view.openFile(svg_file) if not path.startswith(":/"): self.currentPath = path self.setWindowTitle("%s - SVGViewer" % self.currentPath) self.outlineAction.setEnabled(True) self.backgroundAction.setEnabled(True) self.resize(self.view.sizeHint() + QSize(80, 80 + self.menuBar().height()))
def load_custom_image(self): if not QDir(self.image_tool.getFolderName()).exists(): return filename, _ = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME')) if filename == "": return if not QFile.exists(filename): QMessageBox.information(None, 'Error message', 'System error, unable to locate file.', QMessageBox.Close, QMessageBox.Close) else: try: loaded_image = self.image_tool.loadCustomImages(filename) if loaded_image is None: QMessageBox.information( None, 'Message', 'Image file too small, minimum requirement 16 x 16.', QMessageBox.Close, QMessageBox.Close) return self.tile_use_images = True self.tile_images_list = loaded_image self.puzzle_build() except IOError: QMessageBox.information(None, 'Message', 'This is not an image file.', QMessageBox.Close, QMessageBox.Close)
def __loadRules(self): """ Private method to load the rules of the subscription. """ fileName = self.rulesFileName() f = QFile(fileName) if f.exists(): if not f.open(QIODevice.ReadOnly): E5MessageBox.warning( None, self.tr("Load subscription rules"), self.tr( """Unable to open adblock file '{0}' for reading."""). format(fileName)) else: textStream = QTextStream(f) header = textStream.readLine(1024) if not header.startswith("[Adblock"): E5MessageBox.warning( None, self.tr("Load subscription rules"), self.tr("""AdBlock file '{0}' does not start""" """ with [Adblock.""").format(fileName)) f.close() f.remove() self.__lastUpdate = QDateTime() else: from .AdBlockRule import AdBlockRule self.__updatePeriod = 0 self.__remoteModified = QDateTime() self.__rules = [] self.__rules.append(AdBlockRule(header, self)) while not textStream.atEnd(): line = textStream.readLine() self.__rules.append(AdBlockRule(line, self)) expires = self.__expiresRe.search(line) if expires: period, kind = expires.groups() if kind: # hours self.__updatePeriod = int(period) else: # days self.__updatePeriod = int(period) * 24 remoteModified = self.__remoteModifiedRe.search(line) if remoteModified: day, month, year, time, hour, minute = \ remoteModified.groups() self.__remoteModified.setDate( QDate(int(year), self.__monthNameToNumber[month], int(day))) if time: self.__remoteModified.setTime( QTime(int(hour), int(minute))) self.__populateCache() self.changed.emit() elif not fileName.endswith("_custom"): self.__lastUpdate = QDateTime() self.checkForUpdate()
def Buscar(self): widget = self.sender().objectName() if widget in ("Enter", "Поиск"): cliente = " ".join(self.buscarLineEdit.text().split()).lower() if cliente: sql = "SELECT * FROM CLIENTES WHERE NOMBRE LIKE ?", ("%" + cliente + "%",) else: self.buscarLineEdit.setFocus() return else: self.buscarLineEdit.clear() sql = "SELECT * FROM CLIENTES" if QFile.exists("DB_SIACLE/DB_SIACLE.db"): conexion = sqlite3.connect("DB_SIACLE/DB_SIACLE.db") cursor = conexion.cursor() try: if widget in ("Enter", "Поиск"): cursor.execute(sql[0], sql[1]) else: cursor.execute(sql) datosDevueltos = cursor.fetchall() conexion.close() self.tabla.clearContents() self.tabla.setRowCount(0) if datosDevueltos: fila = 0 for datos in datosDevueltos: self.tabla.setRowCount(fila + 1) idDato = QTableWidgetItem(str(datos[0])) idDato.setTextAlignment(Qt.AlignCenter) self.tabla.setItem(fila, 0, idDato) self.tabla.setItem(fila, 1, QTableWidgetItem(datos[1])) self.tabla.setItem(fila, 2, QTableWidgetItem(datos[2])) self.tabla.setItem(fila, 3, QTableWidgetItem(datos[3])) self.tabla.setItem(fila, 4, QTableWidgetItem(datos[4])) self.tabla.setItem(fila, 5, QTableWidgetItem(datos[5])) self.tabla.setItem(fila, 6, QTableWidgetItem(datos[6])) fila += 1 else: QMessageBox.information(self, "Поиск клиента ", "Не найдено " "информации. ", QMessageBox.Ok) except: conexion.close() QMessageBox.critical(self, "Поиск клиента", "Неизвестная ошибка. ", QMessageBox.Ok) else: QMessageBox.critical(self, "Buscar clientes", "База данных не найдена. ", QMessageBox.Ok) self.buscarLineEdit.setFocus()
def downloadFile(self): self.url = QUrl(self.urlLineEdit.text()) fileInfo = QFileInfo(self.url.path()) fileName = fileInfo.fileName() if not fileName: fileName = 'index.html' if QFile.exists(fileName): ret = QMessageBox.question(self, "HTTP", "There already exists a file called %s in the current " "directory. Overwrite?" % fileName, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if ret == QMessageBox.No: return QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, "HTTP", "Unable to save the file %s: %s." % (fileName, self.outFile.errorString())) self.outFile = None return self.progressDialog.setWindowTitle("HTTP") self.progressDialog.setLabelText("Downloading %s." % fileName) self.downloadButton.setEnabled(False) self.httpRequestAborted = False self.startRequest(self.url)
def resolveExeFile(self, name): dir = self.resolveDir(name) fileName = self.info[name]['filename'].split('/')[-1] pyFile = QFile(dir.path() + '/' + fileName + '.py') if pyFile.exists(): return pyFile.fileName() pywFile = QFile(dir.path() + '/' + fileName + '.pyw') if pywFile.exists(): return pywFile.fileName() Colors.debug("- WARNING: Could not resolve executable:", dir.path(), fileName) return '__executable not found__'
def openFileWrapper(self, fileName): if not fileName: return fileName = QFileInfo(fileName).canonicalFilePath() exists = False for i, tab in enumerate(self.iterateTabs()): if tab.fileName == fileName: exists = True ex = i if exists: self.tabWidget.setCurrentIndex(ex) elif QFile.exists(fileName): noEmptyTab = ( (self.ind is None) or self.currentTab.fileName or self.currentTab.editBox.toPlainText() or self.currentTab.editBox.document().isModified() ) if noEmptyTab: self.createTab(fileName) self.ind = self.tabWidget.count()-1 self.tabWidget.setCurrentIndex(self.ind) if fileName: self.fileSystemWatcher.addPath(fileName) self.currentTab.fileName = fileName self.currentTab.readTextFromFile() editBox = self.currentTab.editBox self.setCurrentFile() self.setWindowModified(editBox.document().isModified())
def fileChanged(self, fileName): ind = self.fileNames.index(fileName) self.tabWidget.setCurrentIndex(ind) if not QFile.exists(fileName): self.editBoxes[ind].document().setModified(True) QMessageBox.warning(self, '', self.tr( 'This file has been deleted by other application.\n' 'Please make sure you save the file before exit.')) elif not self.editBoxes[ind].document().isModified(): # File was not modified in ReText, reload silently self.openFileMain() self.updatePreviewBox() else: text = self.tr( 'This document has been modified by other application.\n' 'Do you want to reload the file (this will discard all ' 'your changes)?\n') if self.autoSaveEnabled: text += self.tr( 'If you choose to not reload the file, auto save mode will ' 'be disabled for this session to prevent data loss.') messageBox = QMessageBox(QMessageBox.Warning, '', text) reloadButton = messageBox.addButton(self.tr('Reload'), QMessageBox.YesRole) messageBox.addButton(QMessageBox.Cancel) messageBox.exec() if messageBox.clickedButton() is reloadButton: self.openFileMain() self.updatePreviewBox() else: self.autoSaveEnabled = False self.editBoxes[ind].document().setModified(True) if fileName not in self.fileSystemWatcher.files(): # https://github.com/retext-project/retext/issues/137 self.fileSystemWatcher.addPath(fileName)
def saveTextdata(self, filePath, data): outFile = QFileInfo(filePath) fileName = outFile.fileName() if QFile.exists(fileName): QFile.remove(fileName) outFile = QFile(outFile.absoluteFilePath()) outFile.open(QIODevice.WriteOnly | QIODevice.Text) if outFile.error() != outFile.NoError: self.msgBox.information( QDialog().move(self.fly), "{}".format(fileName), self.translate("openV2rayJSONFile", "Unable to open the file {}: {}.").format( fileName, outFile.errorString())) outFile = None return False outFile.write(codecs.encode(data, "utf-8")) if outFile.error() != outFile.NoError: self.msgBox.information( QDialog().move(self.fly), "{}".format(fileName), self.translate("openV2rayJSONFile", "Unable to save the file {}: {}.").format( fileName, outFile.errorString())) outFile = None return False outFile.close()
def read(self, fileNameOrDevice): """ Public method to read a login data file. @param fileNameOrDevice name of the file to read (string) or reference to the device to read (QIODevice) @return tuple containing the logins, forms and never URLs """ self.__logins = {} self.__loginForms = {} self.__never = [] if isinstance(fileNameOrDevice, QIODevice): self.setDevice(fileNameOrDevice) else: f = QFile(fileNameOrDevice) if not f.exists(): return self.__logins, self.__loginForms, self.__never f.open(QFile.ReadOnly) self.setDevice(f) while not self.atEnd(): self.readNext() if self.isStartElement(): version = self.attributes().value("version") if self.name() == "Password" and \ (not version or version == "1.0"): self.__readPasswords() else: self.raiseError(QCoreApplication.translate( "PasswordReader", "The file is not a Passwords version 1.0 file.")) return self.__logins, self.__loginForms, self.__never
def load_stylesheet(): """ Load the stylesheet for use in a pyqt5 application. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ warnings.warn( "load_stylesheet_pyqt5() will be deprecated in version 3," "set QtPy environment variable to specify the Qt binding and " "use load_stylesheet()", PendingDeprecationWarning) # Smart import of the rc file import themes.breezedark.breeze_resources # Load the stylesheet content from resources from PyQt5.QtCore import QCoreApplication, QFile, QTextStream from PyQt5.QtGui import QColor, QPalette f = QFile(":/breezedark/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() # Apply OS specific patches # stylesheet = _apply_stylesheet_patches(stylesheet) return stylesheet
def loadCsvOnOpen(self): self.canGnuplot = False filename = self.myfile if QFile.exists(filename): f = open(filename, 'r') self.tableview.setRowCount(0) self.tableview.setColumnCount(3) for rowdata in csv.reader(f, delimiter='\t'): row = self.tableview.rowCount() self.tableview.insertRow(row) if len(rowdata) == 0: self.tableview.setColumnCount(len(rowdata) + 1) else: self.tableview.setColumnCount(len(rowdata)) for column, data in enumerate(rowdata): item = QTableWidgetItem(data) self.tableview.setItem(row, column, item) self.setTableAignment() self.tableview.horizontalHeader().setStretchLastSection(True) self.setHeaders() self.tableview.resizeRowsToContents() self.selectLastRow() self.isChanged = False self.fillCombo()
def __saveFileName(self, directory): """ Private method to calculate a name for the file to download. @param directory name of the directory to store the file into (string) @return proposed filename and original filename (string, string) """ path = parseContentDisposition(self.__reply) info = QFileInfo(path) baseName = info.completeBaseName() endName = info.suffix() origName = baseName if endName: origName += '.' + endName name = directory + baseName if endName: name += '.' + endName if not self.__requestFilename: # do not overwrite, if the user is not being asked i = 1 while QFile.exists(name): # file exists already, don't overwrite name = directory + baseName + ('-{0:d}'.format(i)) if endName: name += '.' + endName i += 1 return name, origName
def getHtmlFromConverted(self, converted, includeStyleSheet=True, webenv=False): if converted is None: markupClass = self.getActiveMarkupClass() errMsg = self.tr( "Could not parse file contents, check if " 'you have the <a href="%s">necessary module</a> ' "installed!" ) try: errMsg %= markupClass.attributes[MODULE_HOME_PAGE] except (AttributeError, KeyError): # Remove the link if markupClass doesn't have the needed attribute errMsg = errMsg.replace('<a href="%s">', "").replace("</a>", "") return '<p style="color: red">%s</p>' % errMsg headers = "" if includeStyleSheet: headers += '<style type="text/css">\n' + self.p.ss + "</style>\n" baseName = self.getBaseName() cssFileName = baseName + ".css" if QFile.exists(cssFileName): headers += '<link rel="stylesheet" type="text/css" href="%s">\n' % cssFileName headers += '<meta name="generator" content="ReText %s">\n' % app_version return converted.get_whole_html( custom_headers=headers, include_stylesheet=includeStyleSheet, fallback_title=baseName, webenv=webenv )
def __finished(self): """ Private slot to handle the download finished. """ self.__finishedDownloading = True if not self.__startedSaving: return noError = self.__reply.error() == QNetworkReply.NoError self.progressBar.setVisible(False) if not self.__isFtpDownload: self.stopButton.setEnabled(False) self.stopButton.setVisible(False) self.pauseButton.setEnabled(False) self.pauseButton.setVisible(False) self.openButton.setEnabled(noError) self.openButton.setVisible(noError) self.__output.close() if QFile.exists(self.__fileName): QFile.remove(self.__fileName) self.__output.rename(self.__fileName) self.__updateInfoLabel() self.__state = DownloadItem.DownloadSuccessful self.statusChanged.emit() self.downloadFinished.emit() if self.__autoOpen: self.__open()
def __iniRead(self): ##开始写文件操作 if not QFile.exists(self.__testFileName): QMessageBox.critical(self, "错误", "文件不存在") return False self.fileDevice = QFile(self.__testFileName) #创建文件对象 if not self.fileDevice.open(QIODevice.ReadOnly): del self.fileDevice #删除对象 return False self.fileStream = QDataStream(self.fileDevice) self.fileStream.setVersion(QDataStream.Qt_5_12) #设置版本号,写入和读取的版本号要兼容 if self.ui.radio_BigEndian.isChecked(): self.fileStream.setByteOrder(QDataStream.BigEndian) else: self.fileStream.setByteOrder(QDataStream.LittleEndian) if self.ui.radio_Single.isChecked(): #必须要设置,float和double都按照这个精度 self.fileStream.setFloatingPointPrecision( QDataStream.SinglePrecision) else: self.fileStream.setFloatingPointPrecision( QDataStream.DoublePrecision) return True
def main(): app = QApplication(sys.argv) filename = os.path.join(os.path.dirname(__file__), "reference.db") create = not QFile.exists(filename) db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(filename) if not db.open(): QMessageBox.warning( None, "Reference Data", "Database Error: {0}".format(db.lastError().text())) sys.exit(1) if create: query = QSqlQuery() query.exec_("""CREATE TABLE reference ( id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, category VARCHAR(30) NOT NULL, shortdesc VARCHAR(20) NOT NULL, longdesc VARCHAR(80))""") form = ReferenceDataDlg() form.show() sys.exit(app.exec_())
def get_ui_qfile(self, name): file = QFile(':/ui/{}'.format(name)) if not file.exists(): raise FileNotFoundError( 'ui file not found: ":/ui/{}"'.format(name)) file.open(QFile.ReadOnly) return file
def setupModel(): filename = os.path.join(os.path.dirname(__file__), "log.db") create = not QFile.exists(filename) db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(filename) if not db.open(): QMessageBox.warning( None, "log.db", "Database not open. Error: %s" % (db.lastError().text())) sys.exit(1) if create: query = QSqlQuery() query.exec("""CREATE TABLE food( id INTEGER PRIMARY KEY NOT NULL, name VARCHAR(40) NOT NULL, rate INTEGER)""") query.exec("""CREATE TABLE intake_food( id INTEGER PRIMARY KEY NOT NULL, id_food Integer, food_date VARCHAR, mass INTEGER, FOREIGN KEY(id_food) REFERENCES food(id))""") for name in (("meat", 5), ("fish", 4), ("bread", 3)): query.exec("INSERT INTO food(name,rate) VALUES ('%s', %d)" % (name[0], name[1]))
def load_stylesheet_pyqt5(): """ Loads the stylesheet for use in a pyqt5 application. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file import theme.pyqt5_style_rc # Load the stylesheet content from resources from PyQt5.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #353434; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def onFileChanged(self, path): # If the file was replaced, the watcher is automatically removed and needs # to be re-added to keep watching it for changes. This happens commonly # with applications that do atomic saving. if (not self.mWatcher.files().__contains__(path)): if (QFile.exists(path)): self.mWatcher.addPath(path) self.fileChanged.emit(path)
def validate(self, text): if QFile.exists(text): textColor = self.mOkTextColor else: textColor = self.mErrorTextColor palette = self.mLineEdit.palette() palette.setColor(QPalette.Active, QPalette.Text, textColor) self.mLineEdit.setPalette(palette)
def __load(self): """ Private method to load the saved history entries from disk. """ historyFile = QFile(self.getFileName()) if not historyFile.exists(): return if not historyFile.open(QIODevice.ReadOnly): E5MessageBox.warning( None, self.tr("Loading History"), self.tr("""<p>Unable to open history file <b>{0}</b>.<br/>""" """Reason: {1}</p>""").format( historyFile.fileName, historyFile.errorString() ), ) return history = [] # double check, that the history file is sorted as it is read needToSort = False lastInsertedItem = HistoryEntry() data = QByteArray(historyFile.readAll()) stream = QDataStream(data, QIODevice.ReadOnly) stream.setVersion(QDataStream.Qt_4_6) while not stream.atEnd(): ver = stream.readUInt32() if ver != HISTORY_VERSION: continue itm = HistoryEntry() itm.url = Utilities.readStringFromStream(stream) stream >> itm.dateTime itm.title = Utilities.readStringFromStream(stream) if not itm.dateTime.isValid(): continue if itm == lastInsertedItem: if not lastInsertedItem.title and len(history) > 0: history[0].title = itm.title continue if not needToSort and history and lastInsertedItem < itm: needToSort = True history.insert(0, itm) lastInsertedItem = itm historyFile.close() if needToSort: history.sort() self.setHistory(history, True) # if the history had to be sorted, rewrite the history sorted if needToSort: self.__lastSavedUrl = "" self.__saveTimer.changeOccurred()
def subtitleControl(self, content): srt = content.canonicalUrl().toLocalFile().split(".") srt.pop(-1) srt.append("srt") srt = ".".join(srt) if QFile.exists(srt): self.subtitle_file = srt self.subtitle_list = SubtitleParse(srt, settings().value("Subtitle/codec") or "ISO 8859-9").parse() else: self.subtitle_list = None
def __downloadRepositoryFileDone(self): """ Private method called after the repository file was downloaded. """ reply = self.sender() if reply in self.__replies: self.__replies.remove(reply) if reply.error() != QNetworkReply.NoError: E5MessageBox.warning( None, self.tr("Error downloading file"), self.tr( """<p>Could not download the requested file""" """ from {0}.</p><p>Error: {1}</p>""" ).format(Preferences.getUI("PluginRepositoryUrl6"), reply.errorString()) ) return ioDevice = QFile(self.pluginRepositoryFile + ".tmp") ioDevice.open(QIODevice.WriteOnly) ioDevice.write(reply.readAll()) ioDevice.close() if QFile.exists(self.pluginRepositoryFile): QFile.remove(self.pluginRepositoryFile) ioDevice.rename(self.pluginRepositoryFile) if os.path.exists(self.pluginRepositoryFile): f = QFile(self.pluginRepositoryFile) if f.open(QIODevice.ReadOnly): # save current URL url = Preferences.getUI("PluginRepositoryUrl6") # read the repository file from E5XML.PluginRepositoryReader import PluginRepositoryReader reader = PluginRepositoryReader(f, self.checkPluginEntry) reader.readXML() if url != Preferences.getUI("PluginRepositoryUrl6"): # redo if it is a redirect self.checkPluginUpdatesAvailable() return if self.__updateAvailable: res = E5MessageBox.information( None, self.tr("New plugin versions available"), self.tr("<p>There are new plug-ins or plug-in" " updates available. Use the plug-in" " repository dialog to get them.</p>"), E5MessageBox.StandardButtons( E5MessageBox.Ignore | E5MessageBox.Open), E5MessageBox.Open) if res == E5MessageBox.Open: self.__ui.showPluginsAvailable()
def signalStart(self, content): srt = content.canonicalUrl().toLocalFile().split(".") srt.pop(-1) srt.append("srt") srt = ".".join(srt) if QFile.exists(srt): self.isSubtitle.emit(True) self.timer.start(100) else: self.isSubtitle.emit(False) self.timer.stop()
def addPath(self, path): # Just silently ignore the request when the file doesn't exist if (not QFile.exists(path)): return entry = self.mWatchCount.find(path) if not entry: self.mWatcher.addPath(path) self.mWatchCount.insert(path, 1) else: # Path is already being watched, increment watch count self.mWatchCount[path] += 1
def main(): if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def __downloadFileDone(self): """ Private method called, after the file has been downloaded from the internet. """ self.__updateButton.setEnabled(True) self.__downloadCancelButton.setEnabled(False) self.__onlineStateChanged( self.__networkConfigurationManager.isOnline()) ok = True reply = self.sender() if reply in self.__replies: self.__replies.remove(reply) if reply.error() != QNetworkReply.NoError: ok = False if not self.__downloadCancelled: E5MessageBox.warning( self, self.tr("Error downloading file"), self.tr( """<p>Could not download the requested file""" """ from {0}.</p><p>Error: {1}</p>""" ).format(self.__downloadURL, reply.errorString()) ) self.downloadProgress.setValue(0) self.__downloadURL = None self.__downloadIODevice.remove() self.__downloadIODevice = None if self.repositoryList.topLevelItemCount(): if self.repositoryList.currentItem() is None: self.repositoryList.setCurrentItem( self.repositoryList.topLevelItem(0)) else: self.__downloadButton.setEnabled( len(self.__selectedItems())) self.__downloadInstallButton.setEnabled( len(self.__selectedItems())) reply.deleteLater() return self.__downloadIODevice.open(QIODevice.WriteOnly) self.__downloadIODevice.write(reply.readAll()) self.__downloadIODevice.close() if QFile.exists(self.__downloadFileName): QFile.remove(self.__downloadFileName) self.__downloadIODevice.rename(self.__downloadFileName) self.__downloadIODevice = None self.__downloadURL = None reply.deleteLater() if self.__doneMethod is not None: self.__doneMethod(ok, self.__downloadFileName)
def updateRecentFiles(self): self.menuRecentFiles.clear() self.recentFilesActions = [] filesOld = readListFromSettings("recentFileList") files = [] for f in filesOld: if QFile.exists(f): files.append(f) self.recentFilesActions.append(self.act(f, trig=self.openFunction(f))) writeListToSettings("recentFileList", files) for action in self.recentFilesActions: self.menuRecentFiles.addAction(action)
def resolveQmlFile(self, name): dir = self.resolveDir(name) fileName = self.info[name]['filename'].split('/')[-1] qmlFile = QFile(dir.path() + '/' + fileName + '.qml') if qmlFile.exists(): return qmlFile.fileName() Colors.debug("- WARNING: Could not resolve QML file:", dir.path(), fileName) return '__QML not found__'