本文整理汇总了Python中PyQt4.QtCore.QTextStream类的典型用法代码示例。如果您正苦于以下问题:Python QTextStream类的具体用法?Python QTextStream怎么用?Python QTextStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QTextStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_stylesheet_pyqt5
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
示例2: _grep_file
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))
示例3: go_to_definition
def go_to_definition(self):
self.dirty = True
self.results = []
locations = self.get_locations()
if self._isVariable:
preResults = [
[file_manager.get_basename(x.path), x.path, x.lineno, '']
for x in locations
if (x.type == FILTERS['attribs']) and (x.name == self._search)]
else:
preResults = [
[file_manager.get_basename(x.path), x.path, x.lineno, '']
for x in locations
if ((x.type == FILTERS['functions']) or
(x.type == FILTERS['classes'])) and
(x.name.startswith(self._search))]
for data in preResults:
file_object = QFile(data[1])
if not file_object.open(QFile.ReadOnly):
return
stream = QTextStream(file_object)
line_index = 0
line = stream.readLine()
while not self._cancel and not stream.atEnd():
if line_index == data[2]:
data[3] = line
self.results.append(data)
break
#take the next line!
line = stream.readLine()
line_index += 1
示例4: main
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
示例5: _replace_results
def _replace_results(self):
result = QMessageBox.question(self, self.tr("Replace Files Contents"),
self.tr("Are you sure you want to replace the content in "
"this files?\n(The change is not reversible)"),
buttons=QMessageBox.Yes | QMessageBox.No)
if result == QMessageBox.Yes:
for index in xrange(self._result_widget.topLevelItemCount()):
parent = self._result_widget.topLevelItem(index)
root_dir_name = unicode(parent.dir_name_root)
file_name = unicode(parent.text(0))
file_path = file_manager.create_path(root_dir_name, file_name)
file_object = QFile(file_path)
if not file_object.open(QFile.ReadOnly):
return
stream = QTextStream(file_object)
content = stream.readAll()
file_object.close()
pattern = self._find_widget.pattern_line_edit.text()
case_sensitive = self._find_widget.case_checkbox.isChecked()
type_ = QRegExp.RegExp if \
self._find_widget.type_checkbox.isChecked() else \
QRegExp.FixedString
target = QRegExp(pattern, case_sensitive, type_)
content.replace(target, self._find_widget.replace_line.text())
file_manager.store_file_content(file_path, content, False)
示例6: save
def save(self):
if self.filename.startsWith("Unnamed"):
filename = QFileDialog.getSaveFileName(self,
"Text Editor -- Save File As", self.filename,
"Text files (*.txt *.*)")
if filename.isEmpty():
return
self.filename = filename
self.setWindowTitle(QFileInfo(self.filename).fileName())
exception = None
fh = None
try:
fh = QFile(self.filename)
if not fh.open(QIODevice.WriteOnly):
raise IOError(str(fh.errorString()))
stream = QTextStream(fh)
stream.setCodec("UTF-8")
stream << self.toPlainText()
self.document().setModified(False)
except EnvironmentError as e:
exception = e
finally:
if fh is not None:
fh.close()
if exception is not None:
raise exception
示例7: save
def save(self):
"""Hum ... just save ..."""
if self.filename.startswith("Unnamed"):
filename = self.parent().parent().parent().saveAsFile()
if not (filename == ''):
return
self.filename = filename
self.setWindowTitle( QFileInfo(self.filename).fileName())
exception = None
filehandle = None
try:
#Before FileSave plugin hook
for plugin in filter_plugins_by_capability('beforeFileSave',self.enabled_plugins):
plugin.do_beforeFileSave(self)
filehandle = QFile(self.filename)
if not filehandle.open( QIODevice.WriteOnly):
raise IOError, unicode(filehandle.errorString())
stream = QTextStream(filehandle)
stream.setCodec("UTF-8")
stream << self.toPlainText()
self.document().setModified(False)
RecentFiles().append(self.filename)
except (IOError, OSError), ioError:
exception = ioError
示例8: load_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 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()
示例9: save
def save(self, content, path=None):
"""
Write a temprorary file with .tnj extension and copy it over the
original one.
.nsf = Ninja Swap File
#FIXME: Where to locate addExtension, does not fit here
"""
new_path = False
if path:
self.attach_to_path(path)
new_path = True
save_path = self._file_path
if not save_path:
raise NinjaNoFileNameException("I am asked to write a "
"file but no one told me where")
swap_save_path = "%s.nsp" % save_path
# If we have a file system watcher, remove the file path
# from its watch list until we are done making changes.
if self.__watcher:
self.__watcher.removePath(save_path)
flags = QIODevice.WriteOnly | QIODevice.Truncate
f = QFile(swap_save_path)
if settings.use_platform_specific_eol():
flags |= QIODevice.Text
if not f.open(flags):
raise NinjaIOException(f.errorString())
stream = QTextStream(f)
encoding = get_file_encoding(content)
if encoding:
stream.setCodec(encoding)
encoded_stream = stream.codec().fromUnicode(content)
f.write(encoded_stream)
f.flush()
f.close()
#SIGNAL: Will save (temp, definitive) to warn folder to do something
self.emit(SIGNAL("willSave(QString, QString)"),
swap_save_path, save_path)
self.__mtime = os.path.getmtime(swap_save_path)
shutil.move(swap_save_path, save_path)
self.reset_state()
# If we have a file system watcher, add the saved path back
# to its watch list, otherwise create a watcher and start
# watching
if self.__watcher:
if new_path:
self.__watcher.removePath(self.__watcher.files()[0])
self.__watcher.addPath(self._file_path)
else:
self.__watcher.addPath(save_path)
else:
self.start_watching()
return self
示例10: parseURLs
def parseURLs(self, reply, startFrom):
""" Get a dict of new IDs:URLs from the current playlist (newURLs) """
newURLs = {} # {0:URL0, 1:URL1, ...}
count = 0
#Get the delta and start reading it
allData = reply.readAll()
allData = allData.right(startFrom) # Get rid of old data
response = QTextStream(allData, QIODevice.ReadOnly)
data = response.readLine()
# Parse
while (data):
data = str(data.split("\n")[0])
if data:
if "#" in data: # It's a playlist comment
if self.__endTag in data:
self.__playlistFinished = True
elif self.__exceptionTag in data:
if self.DEBUG: print "Exception found!"
self.__exceptionFound = True
self.__exceptionUrl = data.split(":",1)[1].strip()
else:
newURLs[count+self.__loadedChunks] = data
count += 1
data = response.readLine()
return newURLs
示例11: save_file
def save_file(self):
"""
Saving file to the path where getting from QFileDialog
"""
fileobject = None
if self.path is "":
self.path = QFileDialog.getSaveFileName(self,
"TextEditor",
self.tr("unnamed"))
try:
fileobject = QFile(self.path)
if not fileobject.open(QIODevice.WriteOnly):
raise IOError, unicode(fileobject.errorString())
textstream = QTextStream(fileobject)
textstream.setCodec("UTF-8")
textstream << self.textEdit.toPlainText()
self.textEdit.document().setModified(False)
self.setWindowTitle("%s - TextEditor" %
QFileInfo(self.path).fileName())
except (IOError, OSError), error:
QMessageBox.warning(self,
self.tr("TextEditor - Save Error"),
self.tr("Unable to save {0}:{1}".format(
self.path, error)))
self.path = ""
示例12: __init__
def __init__(self,parent=None):
QDialog.__init__(self, parent)
self.setupUi(self)
#Connect signals
self.btnContactUs.clicked.connect(self.onContactUs)
self.btnSTDMHome.clicked.connect(self.onSTDMHome)
#Load about HTML file
aboutLocation = PLUGIN_DIR + "/html/about.htm"
if QFile.exists(aboutLocation):
aboutFile = QFile(aboutLocation)
if not aboutFile.open(QIODevice.ReadOnly):
QMessageBox.critical(self,
QApplication.translate("AboutSTDMDialog","Open Operation Error"),
QApplication.translate("AboutSTDMDialog","Cannot read 'About STDM' source file."))
self.reject()
reader = QTextStream(aboutFile)
aboutSTDM = reader.readAll()
self.txtAbout.setHtml(aboutSTDM)
else:
QMessageBox.critical(self,
QApplication.translate("AboutSTDMDialog","File Does Not Exist"),
QApplication.translate("AboutSTDMDialog","'About STDM' source file does not exist."))
self.reject()
示例13: exportXml
def exportXml(self, fname):
error = None
fh = None
try:
fh = QFile(fname)
if not fh.open(QIODevice.WriteOnly):
raise IOError(str(fh.errorString()))
stream = QTextStream(fh)
stream.setCodec(CODEC)
stream << ("<?xml version='1.0' encoding='{0}'?>\n"
"<!DOCTYPE MOVIES>\n"
"<MOVIES VERSION='1.0'>\n".format(CODEC))
for key, movie in self.__movies:
stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' "
"ACQUIRED='{2}'>\n".format(movie.year,
movie.minutes,
movie.acquired.toString(Qt.ISODate))) \
<< "<TITLE>" << Qt.escape(movie.title) \
<< "</TITLE>\n<NOTES>"
if not movie.notes.isEmpty():
stream << "\n" << Qt.escape(
encodedNewlines(movie.notes))
stream << "\n</NOTES>\n</MOVIE>\n"
stream << "</MOVIES>\n"
except EnvironmentError as e:
error = "Failed to export: {0}".format(e)
finally:
if fh is not None:
fh.close()
if error is not None:
return False, error
self.__dirty = False
return True, "Exported {0} movie records to {1}".format(
len(self.__movies),
QFileInfo(fname).fileName())
示例14: saveQTextStream
def saveQTextStream(self):
error = None
fh = None
try:
fh = QFile(self.__fname)
if not fh.open(QIODevice.WriteOnly):
raise IOError(str(fh.errorString()))
stream = QTextStream(fh)
stream.setCodec(CODEC)
for key, movie in self.__movies:
stream << "{{MOVIE}} " << movie.title << "\n" \
<< movie.year << " " << movie.minutes << " " \
<< movie.acquired.toString(Qt.ISODate) \
<< "\n{NOTES}"
if not movie.notes.isEmpty():
stream << "\n" << movie.notes
stream << "\n{{ENDMOVIE}}\n"
except EnvironmentError as e:
error = "Failed to save: {0}".format(e)
finally:
if fh is not None:
fh.close()
if error is not None:
return False, error
self.__dirty = False
return True, "Saved {0} movie records to {1}".format(
len(self.__movies),
QFileInfo(self.__fname).fileName())
示例15: escribir_archivo
def escribir_archivo(nombre_de_archivo, contenido):
""" Se escribe en el archivo, si el nombre no tiene extensión se agrega .c
"""
extension = (os.path.splitext(nombre_de_archivo)[-1])[1:]
if not extension:
nombre_de_archivo += '.c'
try:
f = QFile(nombre_de_archivo)
if not f.open(QFile.WriteOnly | QFile.Text):
QMessageBox.warning("Guardar", "No se escribio en %s: %s" % (
nombre_de_archivo, f.errorString()))
return False
flujo = QTextStream(f)
encode_flujo = flujo.codec().fromUnicode(contenido)
f.write(encode_flujo)
f.flush()
f.close()
except:
pass
return os.path.abspath(nombre_de_archivo)