本文整理汇总了Python中PyQt5.QtCore.QTextCodec类的典型用法代码示例。如果您正苦于以下问题:Python QTextCodec类的具体用法?Python QTextCodec怎么用?Python QTextCodec使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QTextCodec类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: findCodecs
def findCodecs(self):
codecMap = []
iso8859RegExp = QRegExp('ISO[- ]8859-([0-9]+).*')
for mib in QTextCodec.availableMibs():
codec = QTextCodec.codecForMib(mib)
sortKey = codec_name(codec).upper()
rank = 0
if sortKey.startswith('UTF-8'):
rank = 1
elif sortKey.startswith('UTF-16'):
rank = 2
elif iso8859RegExp.exactMatch(sortKey):
if len(iso8859RegExp.cap(1)) == 1:
rank = 3
else:
rank = 4
else:
rank = 5
codecMap.append((str(rank) + sortKey, codec))
codecMap.sort()
self.codecs = [item[-1] for item in codecMap]
示例2: showEncodingDialog
def showEncodingDialog(self):
if not self.maybeSave(self.ind):
return
codecsSet = set(bytes(QTextCodec.codecForName(alias).name())
for alias in QTextCodec.availableCodecs())
encoding, ok = QInputDialog.getItem(self, '',
self.tr('Select file encoding from the list:'),
[bytes(b).decode() for b in sorted(codecsSet)],
0, False)
if ok:
self.currentTab.readTextFromFile(None, encoding)
示例3: openFile
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)
示例4: aboutToShowSaveAsMenu
def aboutToShowSaveAsMenu(self):
currentText = self.textEdit.toPlainText()
for action in self.saveAsActs:
codecName = action.data()
codec = QTextCodec.codecForName(codecName)
action.setVisible(codec and codec.canEncode(currentText))
示例5: run
def run(self, argv, error_message, in_build_dir=False):
""" Execute a command and capture the output. """
if in_build_dir:
project = self._project
saved_cwd = os.getcwd()
build_dir = project.path_from_user(project.build_dir)
build_dir = QDir.toNativeSeparators(build_dir)
os.chdir(build_dir)
self._message_handler.verbose_message(
"{0} is now the current directory".format(build_dir))
else:
saved_cwd = None
self._message_handler.verbose_message(
"Running '{0}'".format(' '.join(argv)))
QCoreApplication.processEvents()
process = QProcess()
process.readyReadStandardOutput.connect(
lambda: self._message_handler.progress_message(
QTextCodec.codecForLocale().toUnicode(
process.readAllStandardOutput()).strip()))
stderr_output = QByteArray()
process.readyReadStandardError.connect(
lambda: stderr_output.append(process.readAllStandardError()))
process.start(argv[0], argv[1:])
finished = process.waitForFinished()
if saved_cwd is not None:
os.chdir(saved_cwd)
self._message_handler.verbose_message(
"{0} is now the current directory".format(saved_cwd))
if not finished:
raise UserException(error_message, process.errorString())
if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0:
raise UserException(error_message,
QTextCodec.codecForLocale().toUnicode(stderr_output).strip())
示例6: __init__
def __init__(self):
# Create a byte array that stays in scope as long as we do
self.buffer = QByteArray()
# Initialize the "real" QTextStream with a ByteArray buffer.
super().__init__(self.buffer, QIODevice.ReadWrite)
# The default codec is codecForLocale, which might vary with
# the platform, so set a codec here for consistency. UTF-16
# should entail minimal or no conversion on input or output.
self.setCodec( QTextCodec.codecForName('UTF-16') )
示例7: showEncodingDialog
def showEncodingDialog(self):
if not self.maybeSave(self.ind):
return
encoding, ok = QInputDialog.getItem(self, '',
self.tr('Select file encoding from the list:'),
[bytes(b).decode() for b in QTextCodec.availableCodecs()],
0, False)
if ok:
self.currentTab.readTextFromFile(encoding)
示例8: updateTextEdit
def updateTextEdit(self):
mib = self.encodingComboBox.itemData(self.encodingComboBox.currentIndex())
codec = QTextCodec.codecForMib(mib)
data = QTextStream(self.encodedData)
data.setAutoDetectUnicode(False)
data.setCodec(codec)
self.decodedStr = data.readAll()
self.textEdit.setPlainText(self.decodedStr)
示例9: loadTranslators
def loadTranslators(qtTransDir, app, translationFiles=()):
"""
Module function to load all required translations.
@param qtTransDir directory of the Qt translations files (string)
@param app reference to the application object (QApplication)
@param translationFiles tuple of additional translations to
be loaded (tuple of strings)
@return the requested locale (string)
"""
import Preferences
global loaded_translators
if qVersion() < "5.0.0":
# set the default encoding for tr()
QTextCodec.setCodecForTr(QTextCodec.codecForName("utf-8"))
translations = ("qt", "eric6") + translationFiles
loc = Preferences.getUILanguage()
if loc is None:
return
if loc == "System":
loc = QLocale.system().name()
if loc != "C":
dirs = [getConfig('ericTranslationsDir'), Globals.getConfigDir()]
if qtTransDir is not None:
dirs.append(qtTransDir)
loca = loc
for tf in ["{0}_{1}".format(tr, loc) for tr in translations]:
translator, ok = loadTranslatorForLocale(dirs, tf)
loaded_translators[tf] = translator
if ok:
app.installTranslator(translator)
else:
if tf.startswith("eric6"):
loca = None
loc = loca
else:
loc = None
return loc
示例10: read
def read(self):
""" Reads the file and returns the content """
_file = QFile(self.filename)
if not _file.open(QIODevice.ReadOnly | QIODevice.Text):
raise Exception(_file.errorString())
# Codec
codec = QTextCodec.codecForLocale()
stream = QTextStream(_file)
stream.setCodec(codec)
return stream.readAll()
示例11: __init__
def __init__(self, parent=None):
super().__init__(parent=parent)
# merge stderr channel into stdout channel
self.setProcessChannelMode(QProcess.MergedChannels)
# prepare decoding process' output to Unicode
codec = QTextCodec.codecForLocale()
self._decoder_stdout = codec.makeDecoder()
# only necessary when stderr channel isn't merged into stdout:
# self._decoder_stderr = codec.makeDecoder()
self.readyReadStandardOutput.connect(self._ready_read_standard_output)
示例12: read_file
def read_file(self, path):
"""Read in a file
"""
file = QFile(path)
fileinfo = QFileInfo(file)
file.open(QIODevice.ReadOnly)
data = file.readAll()
codec = QTextCodec.codecForName("UTF-8")
self.contents = codec.toUnicode(data).rstrip("\n")
self.filename = fileinfo.fileName()
示例13: save
def save(self, data, path=None):
if path:
self.filename = path
self.is_new = False
_file = QFile(self.filename)
if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate):
raise Exception(_file.errorString())
stream = QTextStream(_file)
stream.setCodec(QTextCodec.codecForLocale())
stream << data
stream.flush()
_file.close()
# Emit the signal
self.fileSaved.emit(self.filename)
示例14: on_load
def on_load():
file = QFile(filename)
fileinfo = QFileInfo(file)
file.open(QFile.ReadOnly)
data = file.readAll()
codec = QTextCodec.codecForUtfText(data)
unistr = codec.toUnicode(data)
self.page().mainFrame().findFirstElement("#editor").setInnerXml(unistr)
self.page().mainFrame().evaluateJavaScript("init()")
suffix = fileinfo.suffix()
self.page().mainFrame().evaluateJavaScript("editor.getSession().setMode('%s');" % (
self.SUFIX_2_MODE[suffix] if suffix in self.SUFIX_2_MODE else self.SUFIX_2_MODE[None]
))
示例15: open
def open(self, filename):
if not QFile.exists(filename):
return
file = QFile(filename)
file.open(QFile.ReadOnly)
data = file.readAll()
codec = QTextCodec.codecForUtfText(data)
unistr = codec.toUnicode(data)
self._set_window_title(filename)
self.webView.page().mainFrame().findFirstElement("#editor").setInnerXml(unistr)
self.webView.page().mainFrame().evaluateJavaScript("init()")
self._set_mode_by_filename(filename)