def open(self): fileName = QtGui.QFileDialog.getOpenFileName( self, "Open Bookmark File", QtCore.QDir.currentPath(), "XBEL Files (*.xbel *.xml)")[0] if not fileName: return self.treeWidget.clear() handler = XbelHandler(self.treeWidget) reader = QtXml.QXmlSimpleReader() reader.setContentHandler(handler) reader.setErrorHandler(handler) file = QtCore.QFile(fileName) if not file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text): QtGui.QMessageBox.warning( self, "SAX Bookmarks", "Cannot read file %s:\n%s." % (fileName, file.errorString())) return xmlInputSource = QtXml.QXmlInputSource(file) if reader.parse(xmlInputSource): self.statusBar().showMessage("File loaded", 2000)
def importSAX(self, fname): error = None fh = None try: handler = SaxMovieHandler(self) parser = QtXml.QXmlSimpleReader() parser.setContentHandler(handler) parser.setErrorHandler(handler) fh = QtCore.QFile(fname) input = QtXml.QXmlInputSource(fh) self.clear(False) if not parser.parse(input): raise ValueError(handler.error) except (IOError, OSError, ValueError) as e: error = "Failed to import: {}".format(e) except Exception as e: error = "Failed to import SAX: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__fname = "" self.__dirty = True return True, "Imported {} movie records from {}".format( len(self.__movies), QtCore.QFileInfo(fname).fileName())
def importDOM(self, fname): dom = QtXml.QDomDocument() error = None fh = None try: fh = QtCore.QFile(fname) if not fh.open(QtCore.QIODevice.ReadOnly): raise IOError(fh.errorString()) if not dom.setContent(fh): raise ValueError("could not parse XML") except (IOError, OSError, ValueError) as e: error = "Failed to import: {}".format(e) except Exception as e: error = "Failed to import DOM: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error try: self.populateFromDOM(dom) except ValueError as e: return False, "Failed to import: {}".format(e) self.__fname = "" self.__dirty = True return True, "Imported {} movie records from {}".format( len(self.__movies), QtCore.QFileInfo(fname).fileName())
def loadXMLConfiguration(self): doc = QtXml.QDomDocument("configuration") file = QtCore.QFile("config/config.xml") if not file.open(QtCore.QIODevice.ReadOnly): return if not doc.setContent(file): file.close() return file.close() docElem = doc.documentElement() mainNode = docElem.firstChild() while not mainNode.isNull(): element = mainNode.toElement() if not element.isNull(): if "Network" == element.tagName(): subNetworkNode = element.firstChild() while not subNetworkNode.isNull(): subElement = subNetworkNode.toElement() if not subElement.isNull(): if "DataRetrieving" == subElement.tagName(): self.dataRetrievingManager.parseXMLParameters( subElement) subNetworkNode = subNetworkNode.nextSibling() elif ("Pages" == element.tagName()): self.loadPages(element) mainNode = mainNode.nextSibling()
def to_xml(self): doc = QtXml.QDomDocument() node = doc.createElement(self.typeInfo()) doc.appendChild(node) for i in self._children: i._recurseXml(doc, node) return doc.toString(indent=4)
def readXmlDocument(self): self.contentsDoc = QtXml.QDomDocument() xml_file = QtCore.QFile(':/xml/examples.xml') statusOK, errorStr, errorLine, errorColumn = \ self.contentsDoc.setContent(xml_file, True) if not statusOK: QtGui.QMessageBox.critical( None, "DOM Parser", "Could not read or find the contents document. Error at " "line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr)) sys.exit(-1)
def __init__(self): super(MainWindow, self).__init__() self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction("&Open...", self.openFile, "Ctrl+O") self.fileMenu.addAction("E&xit", self.close, "Ctrl+Q") self.xmlPath = "" self.model = DomModel(QtXml.QDomDocument(), self) self.view = QtGui.QTreeView(self) self.view.setModel(self.model) self.setCentralWidget(self.view) self.setWindowTitle("Simple DOM Model")
def saveXMLConfiguration(self): doc = QtXml.QDomDocument("Configuration") rootNode = doc.createElement("Config") onOffParamNode = self.waterHeaterModule.getXMLConfiguration(doc) rootNode.appendChild(onOffParamNode) doc.appendChild(rootNode) outFile = QtCore.QFile("config/config.xml") if not outFile.open(QtCore.QIODevice.WriteOnly | QtCore.QIODevice.Text): print("Failed to open file for writing.") return stream = QtCore.QTextStream(outFile) stream << doc.toString() outFile.close()
def loadDescription(self): ba = self._menu_manager.getHtml(self.name) exampleDoc = QtXml.QDomDocument() exampleDoc.setContent(ba, False) paragraphs = exampleDoc.elementsByTagName('p') if paragraphs.length() < 1: Colors.debug("- ExampleContent.loadDescription(): Could not load description:", self._menu_manager.info[self.name].get('docfile')) description = Colors.contentColor + "Could not load description. Ensure that the documentation for Qt is built." for p in range(paragraphs.length()): description = self.extractTextFromParagraph(paragraphs.item(p)) if self.isSummary(description): break return Colors.contentColor + description
def openFile(self): filePath, _ = QtGui.QFileDialog.getOpenFileName( self, "Open File", self.xmlPath, "XML files (*.xml);;HTML files (*.html);;" "SVG files (*.svg);;User Interface files (*.ui)") if filePath: f = QtCore.QFile(filePath) if f.open(QtCore.QIODevice.ReadOnly): document = QtXml.QDomDocument() if document.setContent(f): newModel = DomModel(document, self) self.view.setModel(newModel) self.model = newModel self.xmlPath = filePath f.close()
def __init__(self, parent=None): super(XbelTree, self).__init__(parent) self.header().setResizeMode(QtGui.QHeaderView.Stretch) self.setHeaderLabels(("Title", "Location")) self.domDocument = QtXml.QDomDocument() self.domElementForItem = {} self.folderIcon = QtGui.QIcon() self.bookmarkIcon = QtGui.QIcon() self.folderIcon.addPixmap(self.style().standardPixmap(QtGui.QStyle.SP_DirClosedIcon), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.folderIcon.addPixmap(self.style().standardPixmap(QtGui.QStyle.SP_DirOpenIcon), QtGui.QIcon.Normal, QtGui.QIcon.On) self.bookmarkIcon.addPixmap(self.style().standardPixmap(QtGui.QStyle.SP_FileIcon))
def loadXMLConfiguration(self): print("Load XML Configuration for WaterHeater module") doc = QtXml.QDomDocument("configuration") file = QtCore.QFile("config/water_heater.xml") if not file.open(QtCore.QIODevice.ReadOnly): return if not doc.setContent(file): file.close() return file.close() docElem = doc.documentElement() mainNode = docElem.firstChild() while not mainNode.isNull(): element = mainNode.toElement() if not element.isNull(): if "WaterHeater" == element.tagName(): self.parseXMLGeneralParam(element) self.parseXMLRequest(element) mainNode = mainNode.nextSibling()
def findDescriptionAndImages(self, uniqueName, docName): if self.documentationDir.exists(docName): self.examples[uniqueName]['document path'] = docName exampleDoc = QtXml.QDomDocument() exampleFile = QtCore.QFile( self.documentationDir.absoluteFilePath(docName)) exampleDoc.setContent(exampleFile) paragraphs = exampleDoc.elementsByTagName("p") for p in range(paragraphs.length()): descriptionNode = paragraphs.item(p) description = self.readExampleDescription(descriptionNode) if QtCore.QString(description).indexOf( QtCore.QRegExp( QtCore.QString( "((The|This) )?(%1 )?.*(example|demo)").arg( self.examples[uniqueName]['name']), QtCore.Qt.CaseInsensitive)) != -1: self.examples[uniqueName]['description'] = description break images = exampleDoc.elementsByTagName("img") imageFiles = [] for i in range(images.length()): imageElement = images.item(i).toElement() source = QtCore.QString(imageElement.attribute("src")) if "-logo" not in source: imageFiles.append( self.documentationDir.absoluteFilePath(source)) if len(imageFiles) > 0: self.examples[uniqueName]['image files'] = imageFiles
def readInfo(self, resource, dir_): categoriesFile = QtCore.QFile(resource) document = QtXml.QDomDocument() document.setContent(categoriesFile) documentElement = document.documentElement() categoryNodes = documentElement.elementsByTagName("category") self.categories['[main]'] = {} self.categories['[main]']['examples'] = [] self.categories['[main]']['color'] = QtGui.QColor("#f0f0f0") self.readCategoryDescription(dir_, '[main]') self.qtLogo.load( self.imagesDir.absoluteFilePath(":/images/qt4-logo.png")) self.rbLogo.load( self.imagesDir.absoluteFilePath(":/images/rb-logo.png")) for i in range(categoryNodes.length()): elem = categoryNodes.item(i).toElement() categoryName = QtCore.QString(elem.attribute("name")) categoryDirName = QtCore.QString(elem.attribute("dirname")) categoryDocName = QtCore.QString(elem.attribute("docname")) categoryColor = QtGui.QColor(elem.attribute("color", "#f0f0f0")) categoryDir = QtCore.QDir(dir_) if categoryDir.cd(categoryDirName): self.categories[categoryName] = {} self.readCategoryDescription(categoryDir, categoryName) self.categories[categoryName]['examples'] = [] exampleNodes = elem.elementsByTagName("example") self.maximumLabels = max(self.maximumLabels, exampleNodes.length()) # Only add those examples we can find. for j in range(exampleNodes.length()): exampleDir = QtCore.QDir(categoryDir) exampleNode = exampleNodes.item(j) element = exampleNode.toElement() exampleName = element.attribute("name") exampleFileName = element.attribute("filename") uniqueName = categoryName + "-" + exampleName self.examples[uniqueName] = {} if not categoryDocName.isEmpty(): docName = categoryDocName + "-" + exampleFileName + ".html" else: docName = categoryDirName + "-" + exampleFileName + ".html" self.examples[uniqueName]['name'] = exampleName self.examples[uniqueName]['document path'] = "" self.findDescriptionAndImages(uniqueName, docName) self.examples[uniqueName][ 'changedirectory'] = element.attribute( "changedirectory", "true") self.examples[uniqueName]['color'] = QtGui.QColor( element.attribute("color", "#f0f0f0")) if element.attribute("executable", "true") != "true": del self.examples[uniqueName] continue examplePath = None if sys.platform == "win32": examplePyName = exampleFileName + ".pyw" else: examplePyName = exampleFileName + ".py" if exampleDir.exists(examplePyName): examplePath = exampleDir.absoluteFilePath( examplePyName) elif exampleDir.cd(exampleFileName): if exampleDir.exists(examplePyName): examplePath = exampleDir.absoluteFilePath( examplePyName) if examplePath and not examplePath.isNull(): self.examples[uniqueName][ 'absolute path'] = exampleDir.absolutePath() self.examples[uniqueName]['path'] = examplePath self.categories[categoryName]['examples'].append( exampleName) else: del self.examples[uniqueName] self.categories[categoryName]['color'] = categoryColor return len(self.categories)
'names': ['U', 'G', 'O'], 'default': [False, False, False] }, 'Store': { 'type': CheckBoxGroup, 'names': ['U', 'G', 'O'], 'default': [False, False, False] }, } XML_KEY = 'IoctlMethod' app = QtGui.QApplication(sys.argv) mainWin = TableModuleTest() mainWin.resize(820, 640) doc = QtXml.QDomDocument("MyML") root = doc.createElement("Ioctl") doc.appendChild(root) elt = doc.createElement("IoctlMethod") elt.setAttribute('name', 'SET_OUTWIN') elt.setAttribute('capable', True) elt.setAttribute('description', "set outbound SRIO windows to DSP") root.appendChild(elt) elt2 = doc.createElement("IoctlMethod") elt2.setAttribute('name', 'GET_OUTWIN') elt2.setAttribute('capable', True) elt2.setAttribute('description', "get outbound SRIO windows to DSP") root.appendChild(elt2) elt3 = doc.createElement("IoctlMethod") elt3.setAttribute('name', 'GET_INWIN')