当前位置: 首页>>代码示例>>Python>>正文


Python QtCore.QTextCodec类代码示例

本文整理汇总了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]
开发者ID:Axel-Erfurt,项目名称:pyqt5,代码行数:25,代码来源:codecs.py

示例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)
开发者ID:retext-project,项目名称:retext,代码行数:11,代码来源:window.py

示例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)
开发者ID:loveq369,项目名称:PyQt5-tests,代码行数:26,代码来源:text_reader.py

示例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))
开发者ID:Axel-Erfurt,项目名称:pyqt5,代码行数:7,代码来源:codecs.py

示例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())
开发者ID:doudz,项目名称:pyqtdeploy,代码行数:45,代码来源:builder.py

示例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') )
开发者ID:tallforasmurf,项目名称:PPQT2,代码行数:9,代码来源:utilities.py

示例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)
开发者ID:daffodil,项目名称:retext,代码行数:9,代码来源:window.py

示例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)
开发者ID:Axel-Erfurt,项目名称:pyqt5,代码行数:10,代码来源:codecs.py

示例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
开发者ID:pycom,项目名称:EricShort,代码行数:43,代码来源:Startup.py

示例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()
开发者ID:centaurialpha,项目名称:pireal,代码行数:12,代码来源:pfile.py

示例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)
开发者ID:jcornford,项目名称:pyecog,代码行数:13,代码来源:pyqtgraph_playing.py

示例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()
开发者ID:mbarbon,项目名称:pugdebug,代码行数:13,代码来源:document.py

示例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)
开发者ID:centaurialpha,项目名称:pireal,代码行数:16,代码来源:pfile.py

示例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]
                ))
开发者ID:gitter-badger,项目名称:cetech,代码行数:16,代码来源:scripteditor.py

示例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)
开发者ID:cyberegoorg,项目名称:cetech,代码行数:17,代码来源:scripteditor.py


注:本文中的PyQt5.QtCore.QTextCodec类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。