def run(self): self.ui.label.setText(self.ui.ui.nereyeEdit.text()) dosyaListesi = self.birlestir(self.ui.ui.neredenEdit.text()) dosyaYaz = QFile(self.ui.ui.nereyeEdit.text()) if dosyaYaz.exists() and not self.uzerineYaz: self.emit(SIGNAL("durdur")) return dosyaYaz.open(QIODevice.WriteOnly) oku = 1024*1024 boyut = self.toplamBoyut(dosyaListesi)/oku self.ui.progressBar.setMaximum(boyut) sayac = 0 for i in dosyaListesi: self.ui.label2.setText(i) dosyaOku = QFile(i) dosyaOku.open(QIODevice.ReadOnly) while not dosyaOku.atEnd(): dosyaYaz.writeData(dosyaOku.read(oku)) sayac += 1 self.emit(SIGNAL("value"), sayac) self.msleep(1) if dosyaOku.atEnd(): break dosyaYaz.close() self.msleep(500)
def savePluginInfo(self, filename=None): ''' write plugin info to xml (plugin active/inactive ...) xmlfile: specifies alternative path to xml file with plugin information ''' if not filename: filename = self.xmlFile # create xml Xml = QDomDocument("xmldoc") rootNode = Xml.createElement("SysCDbgActivePlugins") Xml.appendChild(rootNode) for i in self.pluginActions.itervalues(): pluginNode = Xml.createElement("plugin") pluginNode.setAttribute("path", i.path) if i.isChecked(): pluginNode.setAttribute("active", "y") else: pluginNode.setAttribute("active", "n") rootNode.appendChild(pluginNode) # create and write xml file fileObject = QFile(filename) fileObject.open(QIODevice.WriteOnly) fileObject.writeData(Xml.toString()) fileObject.close()
def main(): GlobalVariables.init() app = QApplication([]) File = QFile("darkorange.stylesheet") File.open(QFile.ReadOnly) StyleSheet = QLatin1String(File.readAll()) app.setStyleSheet(StyleSheet) tdviz = TDViz.TDVizCustom() tdviz.show() if GlobalVariables.isprojector: # @UndefinedVariable tdviz.setGeometry(1920, 0, 1280, 1024) else: tdviz.showFullScreen() yscreenf = 1.0*tdviz._renWin.GetSize()[1]/1080.0 cam = tdviz._ren.GetActiveCamera() cam.SetScreenBottomLeft(-262.5,148.5-148.5*2.0*yscreenf,-410) cam.SetScreenBottomRight(262.5,148.5-148.5*2.0*yscreenf,-410) cam.SetScreenTopRight(262.5,148.5,-410) sys.exit(app.exec_())
def open_to_stream(filename, mode, stream_version=QDataStream.Qt_4_5): file = QFile(filename) file.open(mode) stream = QDataStream(file) stream.setVersion(stream_version) return FileStream(file, stream)
def load_stylesheet(pyside=True): """ Loads the stylesheet. Takes care of importing the rc module. :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 if pyside: import qdarkstyle.pyside_style_rc else: import qdarkstyle.pyqt_style_rc # Load the stylesheet content from resources if not pyside: from PyQt4.QtCore import QFile, QTextStream else: from PySide.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): print("Unable to set stylesheet, file not found\n") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) return ts.readAll()
def savePluginInfo(self, xmlfile=None): ''' write plugin info to xml (plugin active/inactive ...) xmlfile: specifies alternative path to xml file with plugin information (default: plugins/plugins.xml) ''' #create xml Xml = QDomDocument("xmldoc") rootNode = Xml.createElement("SysCDbgActivePlugins") Xml.appendChild(rootNode) for i in range(self.pluginActions.__len__()): pluginNode = Xml.createElement("plugin") pluginNode.setAttribute("path", self.pluginActions[i].path) if self.pluginActions[i].isChecked(): pluginNode.setAttribute("active", "y") else: pluginNode.setAttribute("active", "n") rootNode.appendChild(pluginNode) #create and write xml file fname = self.xmlFile if xmlfile != None: fname = xmlfile if fname.endswith(".xml") == False: fname += ".xml" fileObject = QFile(fname) fileObject.open(QIODevice.WriteOnly) fileObject.writeData(Xml.toString()) fileObject.close()
def main(argv): app = QApplication(sys.argv) app.setWindowIcon(QIcon(QPixmap(":/logo_small"))) app.setOrganizationName('Hardcoded Software') app.setApplicationName('moneyGuru') settings = QSettings() LOGGING_LEVEL = logging.DEBUG if adjust_after_deserialization(settings.value('DebugMode')) else logging.WARNING setupQtLogging(level=LOGGING_LEVEL) logging.debug('started in debug mode') if ISLINUX: stylesheetFile = QFile(':/stylesheet_lnx') else: stylesheetFile = QFile(':/stylesheet_win') stylesheetFile.open(QFile.ReadOnly) textStream = QTextStream(stylesheetFile) style = textStream.readAll() stylesheetFile.close() app.setStyleSheet(style) lang = settings.value('Language') locale_folder = op.join(BASE_PATH, 'locale') hscommon.trans.install_gettext_trans_under_qt(locale_folder, lang) # Many strings are translated at import time, so this is why we only import after the translator # has been installed from qt.app import MoneyGuru app.setApplicationVersion(MoneyGuru.VERSION) mgapp = MoneyGuru() install_excepthook() exec_result = app.exec_() del mgapp # Since PyQt 4.7.2, I had crashes on exit, and from reading the mailing list, it seems to be # caused by some weird crap about C++ instance being deleted with python instance still living. # The worst part is that Phil seems to say this is expected behavior. So, whatever, this # gc.collect() below is required to avoid a crash. gc.collect() return exec_result
def createMap(filename): """ Creates a Python dictionary from a CSV file. The CSV file must be semicolon separated (";") and must not contain quotes. """ # Open the CSV file file = QFile( "%s/%s" % (basedir,filename)) file.open(QIODevice.OpenMode(QIODevice.ReadOnly)) map = {} # Read all lines while True: qByteArray = file.readLine() # Break the while loop when the end is reached if qByteArray.size() == 0: break # Remove the trailing end line line = QString(qByteArray).remove(QRegExp("\n")) # Split the line list = line.split(";") # Set the key and value to the map map[str(list[0].toUpper().toUtf8())] = str(list[1].toUtf8()) return map
def testQgsCentroidFillSymbolLayerV2(self): ''' Create a new style from a .sld file and match test ''' mTestName = 'QgsCentroidFillSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile,True) mFile.close() mSymbolLayer = QgsCentroidFillSymbolLayerV2.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsCentroidFillSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'regular_star' mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#55aaff' mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#00ff00' mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage
def get_searchable_content(self): """ Pulls out tags from the object and returns them in order to be used by the filtered() method. """ f = QFile(self.fileinfo.absoluteFilePath()) f.open(QIODevice.ReadOnly) #stream = QTextStream(f) #stream.setCodec("UTF-8") try: doc = QDomDocument() doc.setContent( f.readAll() ) docelt = doc.documentElement() texts = [] for tagName in FileSystemItem.xmlSearchableTags: nodes = docelt.elementsByTagName(tagName) for i in range(nodes.count()): node = nodes.at(i) value = node.firstChild().toText().data() #print value texts.append( value ) # Add keywords nodes = docelt.elementsByTagName("keywordList") for i in range(nodes.count()): kwnode = nodes.at(i) valnodes = kwnode.toElement().elementsByTagName("value") for j in range(valnodes.count()): value = valnodes.at(j).firstChild().toText().data() texts.append(value) return u' '.join(texts) finally: f.close()
def testQgsSVGFillSymbolLayer(self): ''' Create a new style from a .sld file and match test ''' mTestName = QString ('QgsSVGFillSymbolLayer') mFilePath = QDir.toNativeSeparators( QString('%1/symbol_layer/%2.sld').arg( unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile (mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile,True) mFile.close() mSymbolLayer = QgsSVGFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSVGFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 'accommodation_camping.svg' mValue = os.path.basename (str (mSymbolLayer.svgFilePath())) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 6 mValue = mSymbolLayer.patternWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage
def testQgsSvgMarkerSymbolLayerV2(self): ''' Create a new style from a .sld file and match test ''' mTestName = QString ('QgsSvgMarkerSymbolLayerV2') mFilePath = QDir.toNativeSeparators (QString ('%1/symbol_layer/%2.sld').arg (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile (mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile,True) mFile.close() mSymbolLayer = QgsSvgMarkerSymbolLayerV2.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSvgMarkerSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'skull.svg') mValue = os.path.basename (str(mSymbolLayer.path())) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 12 mValue = mSymbolLayer.size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 45 mValue = mSymbolLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage
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 qdarkstyle.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; } ''' stylesheet += mac_fix return stylesheet
def run(self): self.ui.label.setText(self.ui.ui.neredenEdit.text()) dosyaOku = QFile(self.ui.ui.neredenEdit.text()) dosyaOku.open(QIODevice.ReadOnly) oku = 1024*1024 partBoyutu = int(self.ui.ui.mbEdit.text()) self.ui.progressBar.setMaximum(dosyaOku.size()/oku) partAdi = self.ui.ui.nereyeEdit.text() sayac = 0 partSayici = 1 while not dosyaOku.atEnd(): partAdi = "%s%s"%(partAdi[:-3], str(partSayici).zfill(3)) self.ui.label2.setText(partAdi) partSayici += 1 dosyaYaz = QFile(partAdi) if dosyaYaz.exists() and not self.uzerineYaz: self.emit(SIGNAL("durdur")) return dosyaYaz.open(QIODevice.WriteOnly) #self.uzerineYaz = False for i in range(partBoyutu): dosyaYaz.writeData(dosyaOku.read(oku)) sayac += 1 self.emit(SIGNAL("value"), sayac) self.msleep(1) if dosyaOku.atEnd(): break dosyaYaz.close() self.msleep(500)
def __init__(self, iface): """Constructor for the dialog. Args: iface: QgsInterface instance. """ QDialog.__init__(self, iface.mainWindow()) self.setupUi(self) # Settings Tab # Show the current value of client_id and client_secret client_id = settings.read('gmeconnector/CLIENT_ID') client_secret = settings.read('gmeconnector/CLIENT_SECRET') if client_id is None: client_id = '' if client_secret is None: client_secret = '' self.lineEdit1.setText(client_id) self.lineEdit2.setText(client_secret) # Other settings self.comboBoxProjects.setEnabled(False) self.checkBoxDefault.stateChanged.connect(self.comboBoxProjects.setEnabled) self.comboBoxFormat.addItem('JPEG', 'image/jpeg') self.comboBoxFormat.addItem('PNG', 'image/png') defaultFormat = settings.read('gmeconnector/WMS_IMAGE_FORMAT') if defaultFormat: defaultIndex = self.comboBoxFormat.findText(defaultFormat) if defaultIndex != -1: self.comboBoxFormat.setCurrentIndex(defaultIndex) self.comboBoxFormat.currentIndexChanged.connect(self.handleFormatChanged) # OAuth help oAuthPage = QWebPage() oAuthPage.setLinkDelegationPolicy(QWebPage.DelegateAllLinks) self.webViewOAuth.setPage(oAuthPage) # Load the oauth_help file helpFile = QFile(':/plugins/googlemapsengineconnector/oauth_help.html') helpFile.open(QIODevice.ReadOnly | QIODevice.Text) helpStr = QTextStream(helpFile) helpText = helpStr.readAll() self.webViewOAuth.setHtml(helpText) self.webViewOAuth.linkClicked.connect(self.handleWebLink) # About Tab aboutPage = QWebPage() aboutPage.setLinkDelegationPolicy(QWebPage.DelegateAllLinks) self.webViewAbout.setPage(aboutPage) # Load the about.html file and add current version info. aboutFile = QFile(':/plugins/googlemapsengineconnector/about.html') aboutFile.open(QIODevice.ReadOnly | QIODevice.Text) aboutStr = QTextStream(aboutFile) aboutText = aboutStr.readAll() newText = aboutText.format(version='1.0') self.webViewAbout.setHtml(newText) self.webViewAbout.linkClicked.connect(self.handleWebLink)
def _parseConnection(self): mapFile = QFile('maps' + os.path.sep + self.mapName + '.map') mapFile.open(QFile.ReadOnly) self.connections = [[] for dummy in xrange(self.countries + 1)] while not mapFile.atEnd(): connection = QString(mapFile.readLine()).split(QRegExp(r'\D'), QString.SkipEmptyParts) country = connection[0].toInt()[0] for other in xrange(1, len(connection)): self.connections[country].append(connection[other].toInt()[0])
def __init__(self): path = os.path.join(os.path.dirname(__file__), 'regex-lib.xml') if os.path.isfile(path): try: f = QFile(path) f.open(QIODevice.ReadOnly | QIODevice.Text) self.data = QTextStream(f).readAll() finally: if f: f.close()
def downloadFinished(self, reply): if reply.error(): print("Failed to download") else: attFile = QFile(self.downloadAs) attFile.open(QIODevice.WriteOnly) attFile.write(reply.readAll()) attFile.close() print("Succeeded") reply.deleteLater()
def __init__(self,l1='',l2='',l3='',t1='',t2='',focus='',parent=None): super(TextDialog, self).__init__(parent) self.text1 = QtGui.QLineEdit() self.text2 = QtGui.QLineEdit() self.label = QtGui.QLabel() self.label2 = QtGui.QLabel('test1') self.label3 = QtGui.QLabel('test2') buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) mainLayout = QtGui.QVBoxLayout() mainLayout.addWidget(self.label) hbox1 = QtGui.QHBoxLayout() hbox1.addWidget(self.label2) hbox1.addWidget(self.text1) mainLayout.addLayout(hbox1) hbox2 = QtGui.QHBoxLayout() hbox2.addWidget(self.label3) hbox2.addWidget(self.text2) mainLayout.addLayout(hbox2) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Dialog") self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.resize(300,150) style_css = QFile("style/dialog.css") style_css.open(QFile.ReadOnly) style = QString(style_css.readAll()) self.setStyleSheet(style) l1 = unicode(l1,'utf-8','ignore') l2 = unicode(l2,'utf-8','ignore') l3 = unicode(l3,'utf-8','ignore') if l1: self.label.setText(l1) if l2: self.label2.setText(l2) if l3: self.label3.setText(l3) if t1: self.text1.setText(t1) if t2: self.text2.setText(t2) if focus != "": self.text2.setFocus() self.exec_()
def __init__(self, parent = None): QObject.__init__(self, parent) self.m_webPage = QWebPage(self) converter = QFile(':/resources/coffee-script.js') converter.open(QFile.ReadOnly) script = QString.fromUtf8(converter.readAll()) converter.close() self.m_webPage.mainFrame().evaluateJavaScript(script) self.m_webPage.mainFrame().addToJavaScriptWindowObject('converter', self)
def show_splash_screen(self): """ Show splash screen """ file = QFile(':herculeum.qss') file.open(QFile.ReadOnly) styleSheet = str(file.readAll().data(), 'ascii') self.qt_app.setStyleSheet(styleSheet) pixmap = QPixmap(':splash.png') self.splash_screen = QSplashScreen(pixmap) self.splash_screen.show()
def saveNoteAs(self): self.saveCurrentNote() fileName = QFileDialog.getSaveFileName(self, self.tr('Save as'), '', '(*.md *.mkd *.markdown);;'+self.tr('All files(*)')) if fileName == '': return if not QFileInfo(fileName).suffix(): fileName += '.md' fh = QFile(fileName) fh.open(QIODevice.WriteOnly) savestream = QTextStream(fh) savestream << self.notesEdit.toPlainText() fh.close()
def readWidget(filename): f = QFile(filename) f.open(QFile.ReadOnly) if engine == 'pyside': loader = QUiLoader() myWidget = loader.load(f, self) else: myWidget = uic.loadUi(f) f.close() return myWidget
def save(self): fileName = QFileDialog.getSaveFileName(self, caption='Save As...') try: file = QFile(fileName + '.txt') file.open(QIODevice.WriteOnly | QIODevice.Text) out = QTextStream(file) out << self.plainTextEdit.toPlainText() out.flush() file.close() self.close() return True except IOError: return False
def testQgsSimpleLineSymbolLayerV2(self): ''' Create a new style from a .sld file and match test ''' mTestName = QString ('QgsSimpleLineSymbolLayerV2') mFilePath = QDir.toNativeSeparators( QString('%1/symbol_layer/%2.sld').arg( unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile (mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile,True) mFile.close() mSymbolLayer = QgsSimpleLineSymbolLayerV2.createFromSld( mDoc.elementsByTagName('LineSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSimpleLineSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'#aa007f') mValue = mSymbolLayer.color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 1.26 mValue = mSymbolLayer.width() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.RoundCap mValue = mSymbolLayer.penCapStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.MiterJoin mValue = mSymbolLayer.penJoinStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = True mValue = mSymbolLayer.useCustomDashPattern() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = [5.0, 2.0] mValue = mSymbolLayer.customDashVector() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage
def do_ftp_put(self): num = len(self.files) for i in range(num): file = self.files[i] fhandle = QFile(file) fhandle.open(QIODevice.ReadOnly) byte_array = QByteArray() byte_array.append(fhandle.readData(fhandle.size())) fileinfo = QFileInfo(file) filename = fileinfo.fileName() self.ftp.put(byte_array, filename) self.ftp.close()
def newFile(self): print self.sender().__class__.__name__ index = self.currentIndex() if self.model()!=None: newFile=QInputDialog.getText(self, QString("New File"), QString("FileName")) if newFile[1]: finfo=self.model().fileInfo(index) if (finfo.isDir()): newFileName = finfo.absoluteFilePath()+"/"+newFile[0] else: newFileName = finfo.dir().absoluteFilePath()+"/"+newFile[0] f=QFile(newFileName) f.open(QIODevice.WriteOnly) f.close()
def get_source(self, env, tmpl): from PyQt4.QtCore import QFile if self.debug: # 强制重新加载模板 path = './res/template/%s' % tmpl html = open(path).read() else: path = ':/template/%s' % tmpl f = QFile(path) f.open(QFile.ReadOnly) html = f.readAll() f.close() html = unicode(html, 'u8') return html, path, lambda: not self.debug
def testQgsPointPatternFillSymbolLayer(self): ''' Create a new style from a .sld file and match test ''' # at the moment there is an empty createFromSld implementation # that return nulls mTestName = QString('QgsPointPatternFillSymbolLayer') mFilePath = QDir.toNativeSeparators( QString ('%1/symbol_layer/%2.sld').arg( unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile (mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile,True) mFile.close() mSymbolLayer = QgsPointPatternFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsPointPatternFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'triangle') mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'#ffaa00') mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'#ff007f') mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 5 mValue = mSymbolLayer.subSymbol().symbolLayer(0).angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 3 mValue = mSymbolLayer.subSymbol().symbolLayer(0).size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue) assert mExpectedValue == mValue, mMessage
def load(self, content=None): """ Open file """ if content is None: absPath = '%s/%s.%s' % (self.path, self.filename, self.extension) file = QFile(absPath) if not file.open(QIODevice.ReadOnly): self.error("Error opening image file: %s" % absPath) return False else: content = file.readAll() self.rawContent = content image = QImage() image.loadFromData(content) if image.isNull(): self.error("cannot load image") return False else: self.imageLabel.setPixmap(QPixmap.fromImage(QImage(image))) self.scaleFactor = 1.0 self.imageLabel.adjustSize() return True
def loadTemplate(self, filePath): """ Loads a document template into the view and updates the necessary STDM-related controls. """ if not QFile.exists(filePath): QMessageBox.critical(self.composerView(), QApplication.translate("OpenTemplateConfig","Open Template Error"), \ QApplication.translate("OpenTemplateConfig","The specified template does not exist.")) return templateFile = QFile(filePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self.composerView(), QApplication.translate("ComposerWrapper","Open Operation Error"), \ "{0}\n{1}".format(QApplication.translate("ComposerWrapper","Cannot read template file."), \ templateFile.errorString() )) return templateDoc = QDomDocument() if templateDoc.setContent(templateFile): #Load items into the composition and configure STDM data controls self.composition().loadFromTemplate(templateDoc) self.clearWidgetMappings() #Load data controls composerDS = ComposerDataSource.create(templateDoc) self._configureDataControls(composerDS) #Load symbol editors spatialFieldsConfig = SpatialFieldsConfiguration.create( templateDoc) self._configureSpatialSymbolEditor(spatialFieldsConfig)
def _grep_file(self, file_path, file_name): if not self.by_phrase: with open(file_path, 'r') as f: content = f.read() words = [word for word in self.search_pattern.pattern().split('|')] words.insert(0, True) def check_whole_words(result, word): return result and content.find(word) != -1 if not reduce(check_whole_words, words): return file_object = QFile(file_path) if not file_object.open(QFile.ReadOnly): return stream = QTextStream(file_object) lines = [] line_index = 0 line = stream.readLine() while not self._cancel and not (stream.atEnd() and not line): column = self.search_pattern.indexIn(line) if column != -1: lines.append((line_index, line)) #take the next line! line = stream.readLine() line_index += 1 #emit a signal! relative_file_name = file_manager.convert_to_relative( self.root_dir, file_path) self.emit(SIGNAL("found_pattern(PyQt_PyObject)"), (relative_file_name, lines))
def get_template_element(self, path): """ Gets the template element. :param path: The path of the template :type path: String :return: QDomDocument, QDomDocument.documentElement() :rtype: Tuple """ config_file = os.path.join(path) config_file = QFile(config_file) if not config_file.open(QIODevice.ReadOnly): template = os.path.basename(path) self.prog.setLabelText( QApplication.translate('TemplateUpdater', 'Failed to update {}'.format(template))) error_title = QApplication.translate('TemplateContentReader', 'File Reading Error') error_message = QApplication.translate( 'TemplateContentReader', 'Failed to update {0}. ' 'Check the file permission of {0}'.format(template)) QMessageBox.critical(iface.mainWindow(), error_title, error_message) return None doc = QDomDocument() status, msg, line, col = doc.setContent(config_file) if not status: return None doc_element = doc.documentElement() return doc_element
def get_cdrom_drives(): drives = [] cdinfo = QFile(LINUX_CDROM_INFO) if cdinfo.open(QIODevice.ReadOnly | QIODevice.Text): drive_names = [] drive_audio_caps = [] line = cdinfo.readLine() while not line.isEmpty(): if line.indexOf(':') != -1: key, values = line.split(':') if key == 'drive name': drive_names = QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts) elif key == 'Can play audio': drive_audio_caps = [v == '1' for v in QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts)] line = cdinfo.readLine() # Show only drives that are capable of playing audio for drive in drive_names: if drive_audio_caps[drive_names.indexOf(drive)]: device = u'/dev/%s' % drive symlink_target = QFile.symLinkTarget(device) if symlink_target != '': device = symlink_target drives.append(device) return sorted(drives)
def __init__(self, platform, msiFileName, productName, manufacturer, productVersion, language): self.platform = platform self.msiFile = FileObject(msiFileName) self.tempDir = tempfile.mkdtemp() self.productCode = msilib.gen_uuid() self.upgradeCode = msilib.gen_uuid() self.productVersion = productVersion self.manufacturer = manufacturer self.language = language self.productName = productName self.RegsitryComponent = "RegistryComponent" self.registryRecords = [] self.template = QFile(":/files/pyMagicTemplateMSI2.msi") self.template.open(QFile.ReadOnly) data = self.template.readAll() self.templatePath = msiFileName x = QFile(self.templatePath) if x.open(QFile.WriteOnly): print "opened file for write" x.write(data) else: print "could not open file for writing" x.close() self.template.close()
def testQgsPointPatternFillSymbolLayer(self): ''' Create a new style from a .sld file and match test ''' # at the moment there is an empty createFromSld implementation # that return nulls mTestName = 'QgsPointPatternFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsPointPatternFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsPointPatternFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'triangle' mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#ffaa00' mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#ff007f' mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 5 mValue = mSymbolLayer.subSymbol().symbolLayer(0).angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 3 mValue = mSymbolLayer.subSymbol().symbolLayer(0).size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def _editTemplate(self, templatePath, newName): """ Updates the template document to use the new name. """ templateFile = QFile(templatePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Open Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector","Cannot read template file."), \ templateFile.errorString() )) return (False, "") templateDoc = QDomDocument() if templateDoc.setContent(templateFile): composerElement = templateDoc.documentElement() titleAttr = composerElement.attributeNode("title") if not titleAttr.isNull(): titleAttr.setValue(newName) #Try remove file status = templateFile.remove() if not status: return (False, "") #Create new file newTemplatePath = self._composerTemplatesPath( ) + "/" + newName + ".sdt" newTemplateFile = QFile(newTemplatePath) if not newTemplateFile.open(QIODevice.WriteOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector","Could not save template file."), \ newTemplateFile.errorString() )) return (False, "") if newTemplateFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector","Save Error"), \ QApplication.translate("TemplateDocumentSelector","Could not save template file.")) return (False, "") newTemplateFile.close() return (True, newTemplatePath)
def __init__(self, args, parent=None): QObject.__init__(self, parent) # variable declarations self.m_defaultPageSettings = {} self.m_pages = [] self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_returnValue = 0 self.m_terminated = False # setup the values from args self.m_scriptFile = args.script self.m_args = args.script_args self.m_filesystem = FileSystem(self) self.m_pages.append(self.m_page) do_action('PhantomInitPre') if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) # Provide WebPage with a non-standard Network Access Manager self.m_netAccessMan = NetworkAccessManager(args.disk_cache, args.ignore_ssl_errors, self) self.m_page.setNetworkAccessManager(self.m_netAccessMan) self.m_page.javaScriptConsoleMessageSent.connect( self.printConsoleMessage) self.m_defaultPageSettings['loadImages'] = args.load_images self.m_defaultPageSettings['loadPlugins'] = args.load_plugins self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent() self.m_defaultPageSettings[ 'localAccessRemote'] = args.local_access_remote self.m_page.applySettings(self.m_defaultPageSettings) self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)) # inject our properties and slots into javascript self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self) self.m_page.mainFrame().addToJavaScriptWindowObject( 'fs', self.m_filesystem) bootstrap = QFile(':/bootstrap.js') if not bootstrap.open(QFile.ReadOnly): sys.exit('Can not bootstrap!') bootstrapper = str(bootstrap.readAll()) bootstrap.close() if not bootstrapper: sys.exit('Can not bootstrap!') self.m_page.mainFrame().evaluateJavaScript(bootstrapper) do_action('PhantomInitPost')
def saveHtmlOnly(self, htmlFile): fileDir = os.path.dirname(htmlFile) QDir().mkpath(fileDir) html = QFile(htmlFile) html.open(QIODevice.WriteOnly) savestream = QTextStream(html) savestream << """ <html><head> <meta charset="utf-8"> <link rel="stylesheet" href="/css/notebook.css" type="text/css" /> </head> """ # Note content savestream << self.toHtml() savestream << "</html>" html.close()
def loadStyle(self, layer, filename): qfile = QFile(filename) if not qfile.open(QIODevice.ReadOnly): Log.debug("Unable to open file " + filename) return rules = qfile.readData(qfile.size()) qfile.close() layer.loadNamedStyle(filename)
def get_style(style_sheet): try: mod = importlib.import_module("." + style_sheet, __name__) hasattr(mod, "qt_resource_name") f = QFile(":/%s/style.qss" % style_sheet) f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() except ImportError as e: print "Style sheet not available. Use available_styles() to check for valid styles" return u"" except Exception as e: print "Style sheet available, but an error occured..." traceback.print_exc() return u"" return stylesheet
def on_pushButton_4_clicked(self): # 我们先清空显示,然后显示“无法添加!”,这样如果添加失败则会显示“无法添加!” self.listWidget.clear() self.listWidget.addItem(QString("无法添加!")) file = QFile("my.xml") if (not file.open(QIODevice.ReadOnly)): raise Exception("open my.xml Err") doc = QDomDocument() status, rrorMsg, errorLine, errorColumn = doc.setContent(file) if not status: file.close() raise Exception(str(rrorMsg)) file.close() root = doc.documentElement() # 获取根元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) text = QDomText() # 我们获得了最后一个孩子结点的编号,然后加1,便是新的编号 num = root.lastChild().toElement().attribute(QString("编号")) count = num.toInt() + 1 id.setValue(QString.number(count)) book.setAttributeNode(id) text = doc.createTextNode(self.lineEdit_2.text()) title.appendChild(text) text = doc.createTextNode(self.lineEdit_3.text()) author.appendChild(text) book.appendChild(title) book.appendChild(author) root.appendChild(book) if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("file open Err") out = QTextStream(file) doc.save(out, 4) file.close() # 最后更改显示为“添加成功!” self.listWidget.clear() self.listWidget.addItem(QString("添加成功!"))
def handle_download(reply): print "Download finish time: {}".format(datetime.now()) print "Finished: {}".format(reply.isFinished()) # print "Bytes received: {}".format(len(reply.readAll())) print(type(reply), dir(reply), help(reply.write)) url = reply.url().path() print(url) # with open("C:\Users\julien.moura\Documents\GIS DataBase\youhou.xml", "wb") as fifi: # fifi.write(reply.writeData()) newFile = QFile() newFile.setFileName( "C:\Users\julien.moura\Documents\GIS DataBase\youhou_2.htm") newFile.open(QIODevice.WriteOnly) newFile.write(reply.readAll()) newFile.close() print("done") reply.deleteLater()
def set_instance_document(self, file_p): """ :return: """ file_path = QFile(file_p) if file_path.open(QIODevice.ReadOnly): self.instance_doc.setContent(file_path)
def testQgsEllipseSymbolLayerV2(self): ''' Create a new style from a .sld file and match test ''' mTestName = QString('QgsEllipseSymbolLayerV2') mFilePath = QDir.toNativeSeparators( QString('%1/symbol_layer/%2.sld').arg(unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsEllipseSymbolLayerV2.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsEllipseSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'circle') mValue = mSymbolLayer.symbolName() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'#ffff7f') mValue = mSymbolLayer.fillColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QString(u'#aaaaff') mValue = mSymbolLayer.outlineColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 7 mValue = mSymbolLayer.symbolWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 5 mValue = mSymbolLayer.symbolHeight() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def read_project(settings, openFileName): """ Toplevel reader routine. """ status = None handle = None try: handle = QFile(openFileName) if not handle.open(QIODevice.ReadOnly): raise IOError(handle.errorString()) stream = QDataStream(handle) # check header magic = stream.readInt32() if magic != MAGIC_NUMBER: status = ("Unrecognized file type - \n{0}\nis not " "a sconcho spf file!").format(openFileName) raise IOError(status) version = stream.readInt32() stream.setVersion(QDataStream.Qt_4_5) # initialize API specific entries repeatLegends = {} rowRepeats = [] textItems = [] rowLabels = {} columnLabels = {} if version == 1: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats) = read_API_1_version(stream, settings) elif version == 2: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems) = \ read_API_2_version(stream, settings) elif version == 3: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels) = \ read_API_3_version(stream, settings) else: raise IOError("unsupported API version") except (IOError, OSError) as e: status = "Failed to open %s: %s " % (openFileName, e) finally: if handle is not None: handle.close() if status is not None: return (False, status, None, None, None, None, None, None, None, None) return (True, None, patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels)
def load_stylesheet(pyside=True): """ Load the stylesheet. Takes care of importing the rc module. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ warnings.warn( "load_stylesheet() will not receive pyside parameter in version 3. " "Set QtPy environment variable to specify the Qt binding insteady.", FutureWarning ) # Smart import of the rc file if pyside: import qdarkstyle.pyside_style_rc else: import qdarkstyle.pyqt_style_rc # Load the stylesheet content from resources if not pyside: from PyQt4.QtCore import QFile, QTextStream else: from PySide.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: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def set_instance_document(self, file_p): """ :param file_p: str :return: file :rtype QFile """ file_path = QFile(file_p) if file_path.open(QIODevice.ReadOnly): self.instance_doc.setContent(file_path)
def ReadProjectInfoXml(self): try: result = DlgCrcCheck.smethod_0(None, self.m_strProjectInfoFullName) except: return False if not result: return False doc = QDomDocument() qFile = QFile(self.m_strProjectInfoFullName) if qFile.open(QFile.ReadOnly): doc.setContent(qFile) qFile.close() else: raise UserWarning, "can not open file:" + self.m_strProjectInfoFullName dialogNodeList = doc.elementsByTagName("ProjectListClass") if dialogNodeList.isEmpty(): raise UserWarning, "This file is not correct." dialogElem = dialogNodeList.at(0).toElement() ctrlNodesList = dialogElem.elementsByTagName("ProjectInfo") for i in range(ctrlNodesList.count()): pj = ProjectInfo() lineEditElem = ctrlNodesList.at(i).toElement() objectNameNode = lineEditElem.elementsByTagName("Name").at(0) objectNameElem = objectNameNode.toElement() pj.Name = objectNameElem.text() pathElem = objectNameElem.nextSiblingElement() pj.Path = pathElem.text() createdElem = pathElem.nextSiblingElement() pj.Created = createdElem.text() procedureNameElem = createdElem.nextSiblingElement() pj.ProcedureName = procedureNameElem.text() projNameElem = procedureNameElem.nextSiblingElement() pj.ProjName = projNameElem.text() ptElem = projNameElem.nextSiblingElement() pj.Pt = ptElem.text() subProjNameElem = ptElem.nextSiblingElement() pj.SubProjName = subProjNameElem.text() userNameElem = subProjNameElem.nextSiblingElement() pj.UserName = userNameElem.text() workspaceNameElem = userNameElem.nextSiblingElement() pj.WorkspaceName = workspaceNameElem.text() fullNameElem = workspaceNameElem.nextSiblingElement() pj.FullName = fullNameElem.text() self.ProjectsList.append(pj) return True
def read_network_path(): """get the netowrk config file location""" network_config = QFile(os.path.join(USER_PLUGIN_DIR, 'network_path.txt')) if network_config.open(QIODevice.ReadOnly): stream = QTextStream(network_config) f_path = stream.readLine() if f_path: return f_path
def get_embed_firms(self, fileName): # ":/resources/blank.bin" baseName = ':/resources/' bFile = QFile(baseName + fileName) if not bFile.open(QIODevice.ReadOnly): self.consolelog(u'读取内嵌资源 %s 出错!' % fileName) return content = bFile.readAll() return bytearray(content)
def restoreLayout(self): if os.path.isfile(get_config_path("layout.dat")): try: f = open(get_config_path("layout.dat"), 'rb') geometry, state = pickle.load(f) self.restoreGeometry(geometry) self.restoreState(state) except Exception as e: print("Exception on restoreLayout, {}".format(e)) else: try: f = QFile(':/default_layout.dat') f.open(QIODevice.ReadOnly) geometry, state = pickle.loads(f.readAll()) self.restoreGeometry(geometry) self.restoreState(state) except Exception as e: print("Exception on restoreLayout, {}".format(e))
def upload(self, filePath, returnDict=True): self.returnDict = returnDict file = QFile(filePath) file.open(QFile.ReadOnly) url = QUrl(self.apiUrl + "imports/?api_key={}".format(self.apiKey)) files = {'file': file} multipart = self._createMultipart(files=files) request = QNetworkRequest(url) request.setHeader( QNetworkRequest.ContentTypeHeader, 'multipart/form-data; boundary=%s' % multipart.boundary()) request.setRawHeader('User-Agent', 'QGISCartoDB 0.2.x') reply = self.manager.post(request, multipart) loop = QEventLoop() reply.uploadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def load_stylesheet(pyside=True): """ Loads the stylesheet. Takes care of importing the rc module. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Validate that rc files is updated compile_qrc.compile_all() # Smart import of the rc file if pyside: import qdarkgraystyle.pyside_style_rc else: import qdarkgraystyle.pyqt_style_rc # Load the stylesheet content from resources if not pyside: from PyQt4.QtCore import QFile, QTextStream else: from PySide.QtCore import QFile, QTextStream f = QFile(':qdarkgraystyle/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: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def load_stylesheet(pyside=True): """ Loads the stylesheet. Takes care of importing the rc module. :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 if pyside: import vnTrader.qdarkstyle.pyside_style_rc else: import vnTrader.qdarkstyle.pyqt_style_rc # Load the stylesheet content from resources if not pyside: # PyQt 4/5 compatibility try: from PyQt4.QtCore import QFile, QTextStream except ImportError: from PyQt5.QtCore import QFile, QTextStream else: from PySide.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: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def smethod_0(iwin32Window_0): FatoList.FatoList() fatoList = FatoList() if (not QFile.exists(FatoList.fileName)): return fatoList file0 = QFile(FatoList.fileName) file0.open(QIODevice.ReadOnly) dataStream = QDataStream(file0) str0 = dataStream.readQString() num = dataStream.readInt() if (not (str0 == "PHXHSAF") or num != 1): raise Messages.ERR_INVALID_FILE_FORMAT # throw new Exception(Messages.ERR_INVALID_FILE_FORMAT) num1 = dataStream.readInt() for i in range(num1): fatoList.append(Fato.smethod_0(dataStream, num)) fatoList.method_1() return fatoList
def parseRn(self): """ """ fh = QFile(":/releasenotes.txt") fh.open(QFile.ReadOnly) rn = fh.readAll() rn = str(rn, 'utf8') fh.close() rnHtml = ["<br/>"] for line in rn.splitlines(): if not line.startswith('\t'): pass elif line.startswith('\t\t'): rnHtml.append("<span> %s</span><br/>" % line) elif line.startswith('\t'): rnHtml.append(" %s<br/>" % line) return "".join(rnHtml)
def set_log_path(self, log_path): for i in range(self.repeat_count * 2): f = QFile(log_path) if not f.open(QIODevice.Append | QIODevice.Text): f = None if i == self.repeat_count: log_path = QDir.temp().absoluteFilePath( "SurveyingCalculation.log") f.close() self.logfile = log_path
def httpDownload(theManager, theUrl, theOutPath, theProgressDlg=None): """ Download file from theUrl. Params: * theManager - a QNetworkManager instance * theUrl - url of file * theOutPath - output path * theProgressDlg - progress dialog widget Returns: True if success, otherwise return a tuple with format like this (QNetworkReply.NetworkError, error_message) Raises: * IOError - when cannot create theOutPath """ # prepare output path myFile = QFile(theOutPath) if not myFile.open(QFile.WriteOnly): raise IOError(myFile.errorString()) # slot to write data to file def writeData(): myFile.write(myReply.readAll()) myRequest = QNetworkRequest(QUrl(theUrl)) myReply = theManager.get(myRequest) myReply.readyRead.connect(writeData) if theProgressDlg: # progress bar def progressEvent(theReceived, theTotal): QCoreApplication.processEvents() theProgressDlg.setLabelText("%s / %s" % (theReceived, theTotal)) theProgressDlg.setMaximum(theTotal) theProgressDlg.setValue(theReceived) # cancel def cancelAction(): myReply.abort() myReply.downloadProgress.connect(progressEvent) theProgressDlg.canceled.connect(cancelAction) # wait until finished while not myReply.isFinished(): QCoreApplication.processEvents() myFile.close() myResult = myReply.error() if myResult == QNetworkReply.NoError: return True else: return (myResult, str(myReply.errorString()))
def table_view_dependencies(table_name, column_name=None): """ Find database views that are dependent on the given table and optionally the column. :param table_name: Table name :type table_name: str :param column_name: Name of the column whose dependent views are to be extracted. :type column_name: str :return: A list of views which are dependent on the given table name and column respectively. :rtype: list(str) """ views = [] # Load the SQL file depending on whether its table or table/column if column_name is None: script_path = PLUGIN_DIR + '/scripts/table_related_views.sql' else: script_path = PLUGIN_DIR + '/scripts/table_column_related_views.sql' script_file = QFile(script_path) if not script_file.exists(): raise IOError('SQL file for retrieving view dependencies could ' 'not be found.') else: if not script_file.open(QIODevice.ReadOnly): raise IOError('Failed to read the SQL file for retrieving view ' 'dependencies.') reader = QTextStream(script_file) sql = reader.readAll() if sql: t = text(sql) if column_name is None: result = _execute( t, table_name=table_name ) else: result = _execute( t, table_name=table_name, column_name=column_name ) # Get view names for r in result: view_name = r['view_name'] views.append(view_name) return views