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


Python QtCore.QTranslator类代码示例

本文整理汇总了Python中PyQt5.QtCore.QTranslator的典型用法代码示例。如果您正苦于以下问题:Python QTranslator类的具体用法?Python QTranslator怎么用?Python QTranslator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QTranslator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: loadQtTranslation

    def loadQtTranslation(self, file, language = "default"):
        #TODO Add support for specifying a language from preferences
        path = None
        if language == "default":
            path = self._getDefaultLanguage(file)
        else:
            path = Resources.getPath(Resources.i18n, language, "LC_MESSAGES", file + ".qm")

        # If all else fails, fall back to english.
        if not path:
            Logger.log("w", "Could not find any translations matching {0} for file {1}, falling back to english".format(language, file))
            try:
                path = Resources.getPath(Resources.i18n, "en", "LC_MESSAGES", file + ".qm")
            except FileNotFoundError:
                Logger.log("w", "Could not find English translations for file {0}. Switching to developer english.".format(file))
                return

        translator = QTranslator()
        if not translator.load(path):
            Logger.log("e", "Unable to load translations %s", file)
            return

        # Store a reference to the translator.
        # This prevents the translator from being destroyed before Qt has a chance to use it.
        self._translators[file] = translator

        # Finally, install the translator so Qt can use it.
        self.installTranslator(translator)
开发者ID:fujitsai,项目名称:Uranium,代码行数:28,代码来源:QtApplication.py

示例2: main

def main():
    app = QApplication([i.encode('utf-8') for i in sys.argv])
    app.setOrganizationName(ffmc.__name__)
    app.setOrganizationDomain(ffmc.__url__)
    app.setApplicationName('FF Multi Converter')
    app.setWindowIcon(QIcon(':/ffmulticonverter.png'))

    locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load('qt_' + locale, ':/'):
        app.installTranslator(qtTranslator)
    appTranslator = QTranslator()
    if appTranslator.load('ffmulticonverter_' + locale, ':/'):
        app.installTranslator(appTranslator)

    if not os.path.exists(config.log_dir):
        os.makedirs(config.log_dir)

    logging.basicConfig(
            filename=config.log_file,
            level=logging.DEBUG,
            format=config.log_format,
            datefmt=config.log_dateformat
            )

    converter = MainWindow()
    converter.show()
    app.exec_()
开发者ID:Ilias95,项目名称:FF-Multi-Converter,代码行数:28,代码来源:ffmulticonverter.py

示例3: main

def main():
    app = QApplication(sys.argv)
    locale = QLocale.system().name()
    conf = prepare.Config()
    local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                             'data', 'locale'))
    translator = QTranslator()

    if not os.path.isfile(conf.config_file):
        if locale in prepare.LANGUISH.keys():
            conf.write_config('squares', 'gray', 30, 30,
                              prepare.LANGUISH[locale]['Lang'], __version__)
            translator.load(os.path.join(local_dir, 'pybigpixel_' +
                                         locale + '.qm'))
            app.installTranslator(translator)

        else:
            conf.write_config('squares', 'gray', 30, 30, 'English',
                              __version__)

    else:
        key = [key for key in prepare.LANGUISH.keys() if
               prepare.LANGUISH[key]['Lang'] == conf.get_languish()]

        if key[0] != 'default':
            translator.load(os.path.join(local_dir, 'pybigpixel_' +
                                         key[0] + '.qm'))
            app.installTranslator(translator)

    window = Window(conf)
    window.show()
    sys.exit(app.exec_())
开发者ID:SWE-JSAM,项目名称:PyBigPixel-creator,代码行数:32,代码来源:pybigpixel.py

示例4: main

def main():
    # DBUS MainLoop
    if not dbus.get_default_main_loop():
        from dbus.mainloop.pyqt5 import DBusQtMainLoop
        DBusQtMainLoop(set_as_default = True)


    # Application Stuff
    from libhistorymanager.window import MainManager

    app = QApplication(sys.argv)
    app.setOrganizationName("history-manager")
    app.setApplicationName("history-manager")
    app.setApplicationVersion("0.2.8b")

    locale = QLocale.system().name()
    translator = QTranslator(app)
    translator.load(join("/usr/share/history-manager", "languages/{}.qm".format(locale)))
    app.installTranslator(translator)

    # Create Main Widget and make some settings
    mainWindow = MainManager(None, app= app)
    mainWindow.resize(640, 480)
    mainWindow.setWindowIcon(QIcon.fromTheme("view-history"))
    mainWindow.show()

    # Create connection for lastWindowClosed signal to quit app
    app.lastWindowClosed.connect(app.quit)

    # Run the applications
    app.exec_()
开发者ID:PisiLinuxNew,项目名称:history-manager,代码行数:31,代码来源:historymanager5.py

示例5: main

def main():
  sys.setrecursionlimit(60)  # to find infinite signal loops?
  
  app = QApplication(sys.argv)
  
  QCoreApplication.setOrganizationName("testPrintFramework")
  QCoreApplication.setOrganizationDomain("testPrintFramework.com")
  QCoreApplication.setApplicationName("testPrintFramework")
  
  # To test translations, in shell  >export LANG=es     or >export LANG=cn
  translator = QTranslator()
  result = translator.load("/home/bootch/Downloads/SubprojectsPensool/qtPrintFramework/resources/translations/qtPrintFramework_es.qm")
  if not result:
      print("Not load translation")
      # Not a failure nor exception: program continues in default (usually English)
  if not app.installTranslator(translator):
      print("Not install translator.")
  
  if config.useQML:
    from qtEmbeddedQmlFramework.resourceManager import resourceMgr
    resourceMgr.setResourceRoot(__file__, 'qtPrintFramework')
    
  mainWindow = MainWindow()
  mainWindow.show()
  sys.exit(app.exec_())
开发者ID:bootchk,项目名称:qtPrintFramework,代码行数:25,代码来源:testPrintFramework.py

示例6: __init__

class CPTranslator:

	def __init__(self, qmPath, language = 'de_DE'):
		self.l18Path = os.path.abspath(qmPath)
		self.language = language
		self.translator = QTranslator()

		self.loadDictionary()

	def getTranslator(self):
		return self.translator

	def loadDictionary(self):
		self.translator.load('%s.po' % (self.language,), self.l18Path)

	def changeLanguage(self, language):
		self.language = language
		self.loadDictionary()

	def pyTranslate(self, context, sourceText, disambiguation = None, params = None):
		txt = QApplication.translate(context, sourceText, disambiguation)
		if params is not None:
			return txt.format(params)
		else:
			return txt
开发者ID:monofox,项目名称:flscp,代码行数:25,代码来源:translator.py

示例7: main

def main():
    if settings.get('log:errors'):
        log_filename = settings.get('log:filename')
        if log_filename:
            try:
                log_file = open(log_filename,"w")
                print ('Redirecting stderr/stdout... to %s' % log_filename)
                sys.stderr = log_file
                sys.stdout = log_file
            except IOError:
                print("Lector could not open log file '%s'!\n" % log_filename \
                      + " Redirecting will not work.")
        else:
            print("Log file is not set. Please set it in settings.")

    app = QApplication(sys.argv)
    opts = [str(arg) for arg in app.arguments()[1:]]
    if '--no-scanner' in opts:
        scanner = False
    else:
        scanner = True
    qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime()))

    locale = settings.get('ui:lang')
    if not locale:
        locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'):
        app.installTranslator(qtTranslator)

    window = Window(scanner)
    window.show()
    app.exec_()
开发者ID:correosdelbosque,项目名称:lector,代码行数:33,代码来源:lector.py

示例8: __init__

	def __init__(self):
		from codec import Codec
		from window import Window
		from system import System
		from datajar import DataJar
		from filesystem import FileSystem

		try:
			manifest = json.load(codecs.open('manifest.json', 'r', 'utf-8'))
		except:
			manifest = {}

		for key in assets.manifest:
			if key in manifest:
				assets.manifest[key] = manifest[key]

		self.app = QApplication(sys.argv)
		self.app.setApplicationName(assets.manifest['name'])
		self.app.setApplicationVersion(assets.manifest['version'])

		assets.sys = System()
		assets.codec = Codec()
		assets.fs = FileSystem()
		assets.dataJar = DataJar()

		translator = QTranslator()
		if translator.load("zh_CN.qm"):
			self.app.installTranslator(translator)

		self.window = Window(None, assets.manifest['path'] + 'index.html')

		sys.exit(self.app.exec_())
开发者ID:Fe-ver,项目名称:hae,代码行数:32,代码来源:haeclient.py

示例9: loadQtTranslation

    def loadQtTranslation(self, file, language = "default"):
        #TODO Add support for specifying a language from preferences
        path = None
        if language == "default":
            # If we have a language set in the environment, try and use that.
            lang = os.getenv("LANGUAGE")
            if lang:
                try:
                    path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm")
                except FileNotFoundError:
                    path = None

            # If looking up the language from the enviroment fails, try and use Qt's system locale instead.
            if not path:
                locale = QLocale.system()

                # First, try and find a directory for any of the provided languages
                for lang in locale.uiLanguages():
                    try:
                        path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm")
                        language = lang
                    except FileNotFoundError:
                        pass
                    else:
                        break

                # If that fails, see if we can extract a language "class" from the
                # preferred language. This will turn "en-GB" into "en" for example.
                if not path:
                    lang = locale.uiLanguages()[0]
                    lang = lang[0:lang.find("-")]
                    try:
                        path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm")
                        language = lang
                    except FileNotFoundError:
                        pass
        else:
            path = Resources.getPath(Resources.i18nLocation, language, "LC_MESSAGES", file + ".qm")

        # If all else fails, fall back to english.
        if not path:
            Logger.log("w", "Could not find any translations matching {0} for file {1}, falling back to english".format(language, file))
            try:
                path = Resources.getPath(Resources.i18nLocation, "en", "LC_MESSAGES", file + ".qm")
            except FileNotFoundError:
                Logger.log("w", "Could not find English translations for file {0}. Switching to developer english.".format(file))
                return

        translator = QTranslator()
        if not translator.load(path):
            Logger.log("e", "Unable to load translations %s", file)
            return

        # Store a reference to the translator.
        # This prevents the translator from being destroyed before Qt has a chance to use it.
        self._translators[file] = translator

        # Finally, install the translator so Qt can use it.
        self.installTranslator(translator)
开发者ID:derekhe,项目名称:Uranium,代码行数:59,代码来源:QtApplication.py

示例10: switch_language

 def switch_language(self):
     translator = QTranslator(self.qapp)
     logging.debug("Loading translations")
     locale = self.preferences["lang"]
     QLocale.setDefault(QLocale(locale))
     if translator.load(":/i18n/{0}".format(locale)):
         if QCoreApplication.installTranslator(translator):
             logging.debug("Loaded i18n/{0}".format(locale))
     else:
         logging.debug("Couldn't load translation")
开发者ID:sethkontny,项目名称:cutecoin,代码行数:10,代码来源:app.py

示例11: install_qt_trans

def install_qt_trans():
    # So, we install the gettext locale, great, but we also should try to install qt_*.qm if
    # available so that strings that are inside Qt itself over which I have no control are in the
    # right language.
    from PyQt5.QtCore import QCoreApplication, QTranslator, QLocale, QLibraryInfo
    lang = str(QLocale.system().name())[:2]
    qmname = 'qt_%s' % lang
    qtr = QTranslator(QCoreApplication.instance())
    qtr.load(qmname, QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    QCoreApplication.installTranslator(qtr)
开发者ID:brownnrl,项目名称:moneyguru,代码行数:10,代码来源:trans.py

示例12: start_gui

def start_gui():
    from .frontends import MainWindow

    app = QApplication(sys.argv)
    trans = QTranslator()
    trans.load(config['lang'], Constant.locale_dir)
    app.installTranslator(trans)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
开发者ID:FZUG,项目名称:repo-checker,代码行数:10,代码来源:__init__.py

示例13: main

def main():
	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qt_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
	inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
开发者ID:ahnan4arch,项目名称:retext,代码行数:54,代码来源:retext.py

示例14: Application

class Application(object):

    def __init__(self, config, use_qt_notifications):

        # This is done dynamically so localization
        # support can be configure beforehand.
        from plover.gui_qt.main_window import MainWindow

        self._app = None
        self._win = None
        self._engine = None
        self._translator = None

        QCoreApplication.setApplicationName(__software_name__.capitalize())
        QCoreApplication.setApplicationVersion(__version__)
        QCoreApplication.setOrganizationName('Open Steno Project')
        QCoreApplication.setOrganizationDomain('openstenoproject.org')

        self._app = QApplication([])
        self._app.setAttribute(Qt.AA_UseHighDpiPixmaps)

        # Enable localization of standard Qt controls.
        self._translator = QTranslator()
        translations_dir = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        self._translator.load('qtbase_' + get_language(), translations_dir)
        self._app.installTranslator(self._translator)

        QApplication.setQuitOnLastWindowClosed(False)

        signal.signal(signal.SIGINT, lambda signum, stack: QCoreApplication.quit())

        # Make sure the Python interpreter runs at least every second,
        # so signals have a chance to be processed.
        self._timer = QTimer()
        self._timer.timeout.connect(lambda: None)
        self._timer.start(1000)

        self._engine = Engine(config, KeyboardEmulation())

        self._win = MainWindow(self._engine, use_qt_notifications)

        self._app.aboutToQuit.connect(self._win.on_quit)

    def __del__(self):
        del self._win
        del self._app
        del self._engine
        del self._translator

    def run(self):
        self._app.exec_()
        self._engine.quit()
        self._engine.wait()
开发者ID:morinted,项目名称:plover,代码行数:53,代码来源:main.py

示例15: main

def main():
    logging.basicConfig(level=logging.WARN,
                        format="%(asctime)s %(levelname)s %(message)s")
    app = QApplication(sys.argv)
    translator = QTranslator(app)
    path = os.path.dirname(rect.__file__)
    if QLocale.system().language() == QLocale.Japanese:
        translator.load(path+"/i18n/trainscanner_ja")
    app.installTranslator(translator)
    se = SettingsGUI()
    se.show()
    se.raise_()
    sys.exit(app.exec_())
开发者ID:vitroid,项目名称:TrainScanner,代码行数:13,代码来源:converter_gui.py


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