def setUp(self): #Set up the needed resources - A temp file and a QFile self.called = False handle, self.filename = mkstemp() os.close(handle) self.qfile = QFile(self.filename)
def testBasic(self): '''QFile.getChar''' obj = QFile(self.filename) obj.open(QIODevice.ReadOnly) self.assertEqual(obj.getChar(), (True, 'a')) self.assertFalse(obj.getChar()[0]) obj.close()
def convertTextureSize(texturePath): if int(cmds.about(v=1)) < 2017: from PySide import QtCore from PySide.QtGui import QPixmap, QImage from PySide.QtCore import QFile, QIODevice else: from PySide2 import QtCore from PySide2.QtGui import QPixmap, QImage from PySide2.QtCore import QFile, QIODevice folder, fileName = ntpath.split(texturePath) origFileName = fileName if fileName[: 8] != 'resized_' else fileName[ 8:] origPath = folder + '/' + origFileName if not os.path.exists(origPath): cmds.warning("original is not exists : %s" % texturePath) return convertedFileName = 'resized_%d_' % ( int(resolusion)) + origFileName renamedPath = folder + "/" + convertedFileName ext = os.path.splitext(fileName)[-1] img = QImage(origPath) pixmap = QPixmap() pixmap = pixmap.fromImage( img.scaled(int(resolusion), int(resolusion), QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.FastTransformation)) qfile = QFile(renamedPath) qfile.open(QIODevice.WriteOnly) pixmap.save(qfile, ext[1:], 100) qfile.close() return renamedPath
def loadDialog(file_name): loader = QUiLoader() the_file = QFile(file_name) the_file.open(QFile.ReadOnly) ret_val = loader.load(the_file) the_file.close() return ret_val
def testBug721(self): obj = QFile(self.filename) obj.open(QIODevice.ReadOnly) memory = obj.map(0, 1) self.assertEqual(len(memory), 1) self.assertEqual(memory[0], py3k.b('a')) obj.unmap(memory)
def main(argv=None): if argv is None: argv = sys.argv app = QApplication(argv) engine = QScriptEngine() if HAS_DEBUGGER: debugger = QScriptEngineDebugger() debugger.attachTo(engine) debugWindow = debugger.standardWindow() debugWindow.resize(1024, 640) scriptFileName = './calculator.js' scriptFile = QFile(scriptFileName) scriptFile.open(QIODevice.ReadOnly) engine.evaluate(unicode(scriptFile.readAll()), scriptFileName) scriptFile.close() loader = QUiLoader() ui = loader.load(':/calculator.ui') ctor = engine.evaluate('Calculator') scriptUi = engine.newQObject(ui, QScriptEngine.ScriptOwnership) calc = ctor.construct([scriptUi]) if HAS_DEBUGGER: display = ui.findChild(QLineEdit, 'display') display.connect(display, SIGNAL('returnPressed()'), debugWindow, SLOT('show()')) ui.show() return app.exec_()
def testDevice(self): '''QTextStream get/set Device''' device = QFile() self.obj.setDevice(device) self.assertEqual(device, self.obj.device()) self.obj.setDevice(None) self.assertEqual(None, self.obj.device())
def loadWindowFromFile(file_name): '''Load the window definition from the resource ui file''' loader = QUiLoader() ui_file = QFile(file_name) ui_file.open(QFile.ReadOnly) the_window = loader.load(ui_file) ui_file.close() return the_window
def _write_doc_to_path(doc, path): # write QDomDocument to path as HROX hrox_file = QFile(path) if not hrox_file.open(QFile.WriteOnly): raise RuntimeError("Failed to open file for writing") stream = QTextStream(hrox_file) doc.save(stream, 1) hrox_file.close()
def save_to_disk(self, filename, data): f = QFile(filename) if not f.open(QIODevice.WriteOnly): print "could not open %s for writing" % filename return False f.write(data.readAll()) f.close() return True
def _read_doc_from_path(path): # reading QDomDocument from HROX path hrox_file = QFile(path) if not hrox_file.open(QFile.ReadOnly): raise RuntimeError("Failed to open file for reading") doc = QDomDocument() doc.setContent(hrox_file) hrox_file.close() return doc
def readRcTextFile(path): """Read whole text file from qt resources system.""" assert path.startswith(':/') f = QFile(path) if not f.open(QFile.ReadOnly | QFile.Text): raise FileNotFoundError('failed to read rc text %s' % path) text = str(f.readAll()) f.close() return text
def download_file(self, path, setting): version_file = self.settings['base_url'].format( self.selected_version()) location = self.get_setting('download_dir').value versions = re.findall('v(\d+)\.(\d+)\.(\d+)', path)[0] minor = int(versions[1]) if minor >= 12: path = path.replace('node-webkit', 'nwjs') self.progress_text = 'Downloading {}'.format( path.replace(version_file, '')) url = QUrl(path) file_name = setting.save_file_path(self.selected_version(), location) archive_exists = QFile.exists(file_name) #dest_files_exist = False # for dest_file in setting.dest_files: # dest_file_path = os.path.join('files', setting.name, dest_file) # dest_files_exist &= QFile.exists(dest_file_path) forced = self.get_setting('force_download').value if archive_exists and not forced: self.continue_downloading_or_extract() return self.out_file = QFile(file_name) if not self.out_file.open(QIODevice.WriteOnly): error = self.out_file.error().name self.show_error('Unable to save the file {}: {}.'.format( file_name, error)) self.out_file = None self.enable_ui() return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.http_request_aborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.http_get_id = self.http.get(path, self.out_file)
def testBug909(self): fileName = QFile(adjust_filename('bug_909.ui', __file__)) loader = QUiLoader() main_win = loader.load(fileName) self.assertEqual(sys.getrefcount(main_win), 2) fileName.close() tw = QTabWidget(main_win) main_win.setCentralWidget(tw) main_win.show()
def readModel(self,fileName): file = QFile(fileName) if (file.open(QIODevice.ReadOnly | QIODevice.Text)): xmlReader = QXmlSimpleReader() xmlReader.setContentHandler(self) xmlReader.setErrorHandler(self) xmlSource = QXmlInputSource(file) xmlReader.parse(xmlSource) return self.modelData else: return None
def __init__(self, parent): QGeoPositionInfoSource.__init__(self, parent) self.logFile = QFile(self) self.timer = QTimer(self) self.timer.timeout.connect(self.readNextPosition) self.logFile.setFileName(translate_filename('simplelog.txt')) assert self.logFile.open(QIODevice.ReadOnly) self.lastPosition = QGeoPositionInfo()
def testPhrase(self): #Test loading of quote.txt resource f = open(adjust_filename('quoteEnUS.txt', __file__), "r") orig = f.read() f.close() f = QFile(':/quote.txt') f.open(QIODevice.ReadOnly) #|QIODevice.Text) print("Error:", f.errorString()) copy = f.readAll() f.close() self.assertEqual(orig, copy)
def testImage(self): #Test loading of sample.png resource f = open(adjust_filename('sample.png', __file__), "rb") orig = f.read() f.close() f = QFile(':/sample.png') f.open(QIODevice.ReadOnly) copy = f.readAll() f.close() self.assertEqual(len(orig), len(copy)) self.assertEqual(orig, copy)
def loadWindow(self, uiFile, mainWindowAsParent=True, connectSlots=True): ''' Load a Window from UI file. ''' path = join(UI_PATH, uiFile) windowFile = QFile(path) windowFile.open(QIODevice.ReadOnly | QIODevice.Text) # Make all loaded windows children of mainWindow, except mainWindow itself window = self.uiLoader.load( windowFile, self.__mainWindow if mainWindowAsParent else None) windowFile.close() if connectSlots: QMetaObject.connectSlotsByName(window) return window
def getPanel(): global fcpdWBpath # read UI file ui_file = QFile(os.path.join(fcpdWBpath, "FCPDwb_taskpanel.ui")) ui_file.open(QFile.ReadOnly) widget = QUiLoader().load(ui_file) ui_file.close() # connection widget.btnLaunch.clicked.connect(lambda: launchPureData(widget)) widget.btnRunStop.clicked.connect(lambda: runStopServer(widget)) return widget
def widgetFromUIFile(filePath): """ Reads an ``.ui`` file and creates a new widget object from it. :param filePath: Where to find the ``.ui`` file :return: The new created widget """ loader = QUiLoader() UIFile = QFile(filePath) UIFile.open(QFile.ReadOnly) widget = loader.load(UIFile) UIFile.close() return widget
def testCallFunction(self): f = QTemporaryFile() self.assertTrue(f.open()) fileName = f.fileName() f.close() f = QFile(fileName) self.assertEqual( f.open(QIODevice.Truncate | QIODevice.Text | QIODevice.ReadWrite), True) om = f.openMode() self.assertEqual(om & QIODevice.Truncate, QIODevice.Truncate) self.assertEqual(om & QIODevice.Text, QIODevice.Text) self.assertEqual(om & QIODevice.ReadWrite, QIODevice.ReadWrite) self.assertTrue(om == QIODevice.Truncate | QIODevice.Text | QIODevice.ReadWrite) f.close()
def downloadFile(self, path, setting): self.progress_text = 'Downloading {}'.format(path.replace(self.base_url.format(self.selected_version()),'')) url = QUrl(path) fileInfo = QFileInfo(url.path()) fileName = setting.save_file_path(self.selected_version()) archive_exists = QFile.exists(fileName) dest_files_exist = True for dest_file in setting.dest_files: dest_file_path = os.path.join('files', setting.name, dest_file) dest_files_exist &= QFile.exists(dest_file_path) forced = self.getSetting('force_download').value if (archive_exists or dest_files_exist) and not forced: self.continueDownloadingOrExtract() return #QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): self.show_error('Unable to save the file {}: {}.'.format(fileName, self.outFile.errorString())) self.outFile = None self.enableUI() return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def save(self,fileName): file = QFile(fileName) file.open(QIODevice.WriteOnly | QIODevice.Text) xmlWriter = QXmlStreamWriter(file) xmlWriter.setAutoFormatting(1) xmlWriter.writeStartDocument() xmlWriter.writeStartElement("rws") for i in range(self.rowCount()): c = self.data(self.index(i,0),QtReduceModel.RawDataRole) xmlWriter.writeStartElement("group") l = c.toDict().items() l.sort() for x in l: xmlWriter.writeStartElement(x[0]) xmlWriter.writeCharacters(x[1]) xmlWriter.writeEndElement() xmlWriter.writeEndElement() xmlWriter.writeEndElement() xmlWriter.writeEndDocument()
def javaInclude(context, engine): fileName = context.argument(0).toString() scriptFile = QFile("commands/" + fileName) if not scriptFile.open(QIODevice.ReadOnly): return -1 stream = QTextStream(scriptFile) s = stream.readAll() # QString scriptFile.close() parent = context.parentContext() # QScriptContext* if parent != 0: context.setActivationObject(context.parentContext().activationObject()) context.setThisObject(context.parentContext().thisObject()) result = engine.evaluate(s) #TODO/PORT/FIXME# what's this for? return 0
def saveHistory(self, fileName, html): #TODO """ TOWRITE :param `fileName`: TOWRITE :type `fileName`: QString :param `html`: TOWRITE :type `html`: bool """ qDebug("CmdPrompt saveHistory") file = QFile(fileName) if (not file.open(QIODevice.WriteOnly | QIODevice.Text)): return # TODO: save during input in case of crash output = QTextStream(file) if html: output << promptHistory.toHtml() else: output << promptHistory.toPlainText()
def OnSaveFilePath(self, filePath): """""" file = QFile(filePath) if not file.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning(self, self.tr('Warning'), self.tr('Cannot write file') + ' %s:\n%s.' % (filePath, file.errorString())) return False outf = QTextStream(file) QApplication.setOverrideCursor(Qt.WaitCursor) outf << self.toPlainText() QApplication.restoreOverrideCursor() self.DoSetCurrentFilePath(filePath) # Clear the Modified Flag. self.document().setModified(False) self.setWindowModified(False) self.setWindowTitle('%s[*]' % self.fileName) return True
def load_stylesheet(theme, 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 """ if theme == 'darkstyle': import themes.darkstyle.pyside_style_rc elif theme == 'robotstyle': import themes.robotstyle.pyside_style_rc from PySide.QtCore import QFile, QTextStream basedir = os.path.abspath(os.path.dirname(__file__)) localPath = "%s/style.qss" % theme f = QFile( os.path.join(basedir, localPath)) 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: 10px; # } # ''' # stylesheet += mac_fix return stylesheet
def __init__(self): self.loadedPaths = set() self.dataSources = [] self.genes = set() self.loader = QUiLoader() infile = QFile("expressionTopology.ui") infile.open(QFile.ReadOnly) self.window = self.loader.load(infile, None) infile.close() self.updateTimeSliders() # Main view self.multiPanel = multiViewPanel(self.window.graphicsView,self) # Events self.window.categoryTable.cellClicked.connect(self.changeColor) self.window.loadButton.clicked.connect(self.loadData) self.window.quitButton.clicked.connect(self.window.close) self.window.addButton.clicked.connect(self.addGene) self.window.geneBox.editTextChanged.connect(self.editGene) self.window.speedSlider.valueChanged.connect(self.changeSpeed) self.window.timeSlider.valueChanged.connect(self.changeTime) self.window.addButton.setEnabled(False) self.window.showFullScreen() #self.window.show() # Start timer # Update timer self.timer = QTimer(self.window) self.timer.timeout.connect(self.nextFrame) self.timer.start(Viz.FRAME_DURATION)
def __init__(self, *args, **kwargs): super(MainWindowController, self).__init__(*args, **kwargs) # vars self._address_valid = False # define ui members for type hinting self._ip_line_edit = self._window.IpAddressLineEdit # type: QLineEdit self._status_label = self._window.Statuslabel # type: QLabel self._update_button = self._window.UpdateButton # type: QPushButton self._update_button = self._window.UpdateButton # type: QPushButton self._progress_bar = self._window.progressBar # type: QProgressBar self._combobox = self._window.comboBox # type: QComboBox # load ui loader = QUiLoader() ui = QFile("ui/main_window.ui") ui.open(QFile.ReadOnly) self._window = loader.load(ui) # type: QWidget ui.close() self._window.show() # init other elements self._init_ip_line_edit()