예제 #1
0
파일: i18n.py 프로젝트: vegarwe/luma
    def __buildLanguageDictionary(self):
        """Builds the language dictionary used by the application. The
        dictionary is constructed with the locale code as key, and a
        list containing the language name (and possibly the country
        name) as value. The information is based on the ``i18n``entries
        in the ``resources.py`` module, where the alias for a one
        translation file is locale code for the translation.

        If the translation file is named ``luma_nn_NO.ts`` the
        corresponding alias for this file will be ``nb_NO``. Further
        more ``nb`` will map to ``QLocale.NorwegianBokmal``and ``NO``
        will map to ``QLocale.Norway``, resulting in the following entry
        in the dictionary::

            langDict = {
                ...,
                'en' : ['English'], # Default is allways included
                'nb_NO' : ['Norwegian', 'Norway'],
                ...
            }
        """
        for i18n in self.__translationPath:
            if i18n == "hx":
                self.__availableLanguages[i18n] = ["leet", "10100111001"]
            else:
                locale = QLocale(i18n)
                language = QLocale.languageToString(locale.language())
                country = QLocale.countryToString(locale.country())
                self.__availableLanguages[i18n] = [language, country]
예제 #2
0
def main():
    # For the translations to work, the initialization of QApplication and
    # the loading of the translations must be done here instead of the
    # gui module:
    #
    from PyQt4.QtGui import QApplication
    from PyQt4.QtCore import QTranslator, QLocale, QLibraryInfo
    app = QApplication(sys.argv)
    translator = QTranslator()
    success = translator.load(
        QLocale.system(), 'qt', '_',
        QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    if not success:
        success = translator.load(QLocale.system(), 'qt', '_',
                                  utils.qt_translations_dir())
    app.installTranslator(translator)
    if len(sys.argv) >= 2:
        filename = utils.path_to_unicode(sys.argv[1])
    else:
        filename = None
    try:
        interface = gui.Interface(app,
                                  False,
                                  False, [],
                                  preferred_styles=utils.config['gui-styles'])
        manager = ProgramManager(interface, session_file=filename)
        manager.run()
    except utils.EyegradeException as ex:
        print(unicode(ex).encode(sys.stdout.encoding))
        sys.exit(1)
예제 #3
0
파일: util.py 프로젝트: sergeyfarin/kyui
 def locale(value):
     """
     Returns a a string with information about a QLocale.
     @param value QLocale
     @returns str: Formatted as 'language, country'
     """
     return '{}, {}'.format(QLocale.languageToString(value.language()),
                            QLocale.countryToString(value.country()))
예제 #4
0
	def __convertXData(self, data):
		loc = QLocale()
		out = []
		for polozka in data:
			time = QDateTime()
			time.setTime_t(polozka)
			out.append(time.toString(loc.dateFormat(QLocale.ShortFormat)))
		return out
예제 #5
0
파일: plugin.py 프로젝트: maning/inasafe
    def setupI18n(self, thePreferredLocale=None):
        """Setup internationalisation for the plugin.

        See if QGIS wants to override the system locale
        and then see if we can get a valid translation file
        for whatever locale is effectively being used.

        Args:
           thePreferredLocale - optional parameter which if set
           will override any other way of determining locale..
        Returns:
           None.
        Raises:
           TranslationLoadException
        """
        myOverrideFlag = QSettings().value(
            'locale/overrideFlag',
            QVariant(False)).toBool()

        if thePreferredLocale is not None:
            myLocaleName = thePreferredLocale
        elif myOverrideFlag:
            myLocaleName = QSettings().value('locale/userLocale',
                                             QVariant('')).toString()
        else:
            myLocaleName = QLocale.system().name()
            # NOTES: we split the locale name because we need the first two
            # character i.e. 'id', 'af, etc
            myLocaleName = str(myLocaleName).split('_')[0]

        # Also set the system locale to the user overridden local
        # so that the inasafe library functions gettext will work
        # .. see:: :py:func:`common.utilities`
        os.environ['LANG'] = str(myLocaleName)

        LOGGER.debug('%s %s %s %s' % (
            thePreferredLocale,
            myOverrideFlag,
            QLocale.system().name(),
            os.environ['LANG']))

        myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        myTranslationPath = os.path.join(
            myRoot, 'safe_qgis', 'i18n',
            'inasafe_' + str(myLocaleName) + '.qm')

        if os.path.exists(myTranslationPath):
            self.translator = QTranslator()
            myResult = self.translator.load(myTranslationPath)
            if not myResult:
                myMessage = 'Failed to load translation for %s' % myLocaleName
                raise TranslationLoadError(myMessage)
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug('%s %s' % (
            myTranslationPath,
            os.path.exists(myTranslationPath)))
예제 #6
0
    def setup_i18n(self, preferred_locale=None):
        """Setup internationalisation for the plugin.

        See if QGIS wants to override the system locale
        and then see if we can get a valid translation file
        for whatever locale is effectively being used.

        :param preferred_locale: If set will override any other way of
            determining locale.
        :type preferred_locale: str, None
        :raises: TranslationLoadException
        """
        override_flag = QSettings().value(
            'locale/overrideFlag', False, type=bool)

        if preferred_locale is not None:
            locale_name = preferred_locale
        elif override_flag:
            locale_name = QSettings().value('locale/userLocale', '', type=str)
        else:
            locale_name = QLocale.system().name()
            # NOTES: we split the locale name because we need the first two
            # character i.e. 'id', 'af, etc
            locale_name = str(locale_name).split('_')[0]

        # Also set the system locale to the user overridden local
        # so that the inasafe library functions gettext will work
        # .. see:: :py:func:`common.utilities`
        os.environ['LANG'] = str(locale_name)

        LOGGER.debug('%s %s %s %s' % (
            preferred_locale,
            override_flag,
            QLocale.system().name(),
            os.environ['LANG']))

        root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        translation_path = os.path.join(
            root, 'safe_qgis', 'i18n',
            'inasafe_' + str(locale_name) + '.qm')

        if os.path.exists(translation_path):
            self.translator = QTranslator()
            result = self.translator.load(translation_path)
            if not result:
                message = 'Failed to load translation for %s' % locale_name
                raise TranslationLoadError(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug('%s %s' % (
            translation_path,
            os.path.exists(translation_path)))
예제 #7
0
    def setupI18n(self, thePreferredLocale=None):
        """Setup internationalisation for the plugin.

        See if QGIS wants to override the system locale
        and then see if we can get a valid translation file
        for whatever locale is effectively being used.

        Args:
           thePreferredLocale - optional parameter which if set
           will override any other way of determining locale..
        Returns:
           None.
        Raises:
           TranslationLoadException
        """
        myOverrideFlag = QSettings().value('locale/overrideFlag',
                                           QVariant(False)).toBool()

        if thePreferredLocale is not None:
            myLocaleName = thePreferredLocale
        elif myOverrideFlag:
            myLocaleName = QSettings().value('locale/userLocale',
                                             QVariant('')).toString()
        else:
            myLocaleName = QLocale.system().name()
            # NOTES: we split the locale name because we need the first two
            # character i.e. 'id', 'af, etc
            myLocaleName = str(myLocaleName).split('_')[0]

        # Also set the system locale to the user overridden local
        # so that the inasafe library functions gettext will work
        # .. see:: :py:func:`common.utilities`
        os.environ['LANG'] = str(myLocaleName)

        LOGGER.debug(
            '%s %s %s %s' % (thePreferredLocale, myOverrideFlag,
                             QLocale.system().name(), os.environ['LANG']))

        myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        myTranslationPath = os.path.join(
            myRoot, 'safe_qgis', 'i18n',
            'inasafe_' + str(myLocaleName) + '.qm')

        if os.path.exists(myTranslationPath):
            self.translator = QTranslator()
            myResult = self.translator.load(myTranslationPath)
            if not myResult:
                myMessage = 'Failed to load translation for %s' % myLocaleName
                raise TranslationLoadError(myMessage)
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug('%s %s' %
                     (myTranslationPath, os.path.exists(myTranslationPath)))
예제 #8
0
 def __init__(self, component_manager):
     GetTextTranslator.__init__(self, component_manager)
     self.qt_translator = QTranslator(QCoreApplication.instance())
     try:
         self.qt_dir = os.environ["QTDIR"]
     except:
         if sys.platform == "win32":
             self.qt_dir = os.path.join(sys.exec_prefix, "share", "qt4")
         else:
             self.qt_dir = os.path.join("/usr", "share", "qt4")
     # Avoid stuff like Thai numerals if the language is not explicitly
     # set to Thai.
     QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))
예제 #9
0
 def __init__(self, component_manager):
     GetTextTranslator.__init__(self, component_manager)
     self.qt_translator = QTranslator(QCoreApplication.instance())
     try:
         self.qt_dir = os.environ["QTDIR"]
     except:
         if sys.platform == "win32":
             self.qt_dir = os.path.join(sys.exec_prefix, "share", "qt4")
         else:
             self.qt_dir = os.path.join("/usr", "share", "qt4")
     # Avoid stuff like Thai numerals if the language is not explicitly
     # set to Thai.
     QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))
예제 #10
0
    def __init__(self, iface):
        if not valid: return

        # Save reference to the QGIS interface
        self.iface = iface
        try:
            self.QgisVersion = unicode(QGis.QGIS_VERSION_INT)
        except:
            self.QgisVersion = unicode(QGis.qgisVersion)[0]

        if QGis.QGIS_VERSION[0:3] < "1.5":
            # For i18n support
            userPluginPath = qgis.utils.home_plugin_path + "/GdalTools"
            systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools"

            overrideLocale = QSettings().value("locale/overrideFlag",
                                               False,
                                               type=bool)
            if not overrideLocale:
                localeFullName = QLocale.system().name()
            else:
                localeFullName = QSettings().value("locale/userLocale",
                                                   "",
                                                   type=str)

            if QFileInfo(userPluginPath).exists():
                translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"
            else:
                translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"

            self.localePath = translationPath
            if QFileInfo(self.localePath).exists():
                self.translator = QTranslator()
                self.translator.load(self.localePath)
                QCoreApplication.installTranslator(self.translator)
예제 #11
0
def loadTranslators(qtTransDir, app, translationFiles = ()):
    """
    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)
    """
    translations = ("qt", "eric4") + translationFiles
    loc = Preferences.getUILanguage()
    if loc is None:
        return

    if loc == "System":
        loc = str(QLocale.system().name())
    if loc != "C":
        dirs = [getConfig('ericTranslationsDir'), Utilities.getConfigDir()]
        if qtTransDir is not None:
            dirs.append(qtTransDir)

        loca = loc
        for tf in ["%s_%s" % (tr, loc) for tr in translations]:
            translator, ok = loadTranslatorForLocale(dirs, tf)
            loaded_translators[tf] = translator
            if ok:
                app.installTranslator(translator)
            else:
                if tf.startswith("eric4"):
                    loca = None
        loc = loca
    else:
        loc = None
    return loc
예제 #12
0
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_()
예제 #13
0
def loadShortHelp():
    h = {}
    path = os.path.dirname(__file__)
    for f in os.listdir(path):
        if f.endswith("yaml"):
            filename = os.path.join(path, f)
            with open(filename) as stream:
                h.update(yaml.load(stream))
    version = ".".join(QGis.QGIS_VERSION.split(".")[0:2])
    overrideLocale = QSettings().value('locale/overrideFlag', False, bool)
    if not overrideLocale:
        locale = QLocale.system().name()[:2]
    else:
        locale = QSettings().value('locale/userLocale', '')
    locale = locale.split("_")[0]

    def replace(s):
        if s is not None:
            return s.replace(
                "{qgisdocs}",
                "https://docs.qgis.org/%s/%s/docs" % (version, locale))
        else:
            return None

    h = {k: replace(v) for k, v in h.iteritems()}
    return h
예제 #14
0
def getTranslate(namePlugin, nameDir=None):
    if nameDir is None:
        nameDir = namePlugin

    pluginPath = "python/plugins/{}".format(nameDir)

    userPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path()
    userPluginPath = "{0}{1}".format(userPath, pluginPath)

    systemPath = QgsApplication.prefixPath()
    systemPluginPath = "{0}/{1}".format(systemPath, pluginPath)

    overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool)
    localeFullName = QLocale.system().name(
    ) if not overrideLocale else QSettings().value('locale/userLocale', '')

    qmPathFile = "/i18n/{0}_{1}.qm".format(namePlugin, localeFullName)
    pp = userPluginPath if QFileInfo(
        userPluginPath).exists() else systemPluginPath
    translationFile = "{0}{1}".format(pp, qmPathFile)

    if QFileInfo(translationFile).exists():
        translator = QTranslator()
        translator.load(translationFile)
        QCoreApplication.installTranslator(translator)
        return translator
예제 #15
0
파일: lector.py 프로젝트: klukonin/lector
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. Pleaase 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_()
예제 #16
0
파일: i18n.py 프로젝트: ismailsunni/inasafe
def locale():
    """Get the name of the currently active locale.

    :returns: Name of the locale e.g. 'id'
    :rtype: str
    """
    override_flag = QSettings().value(
        'locale/overrideFlag', True, type=bool)

    default = 'en_US'

    if override_flag:
        locale_name = QSettings().value('locale/userLocale', default, type=str)
    else:
        # noinspection PyArgumentList
        locale_name = QLocale.system().name()

    if locale_name == 'C':
        # On travis, locale/userLocale is equal to C. We want 'en'.
        locale_name = default

    # NOTES: we split the locale name because we need the first two
    # character i.e. 'id', 'af, etc
    locale_name = str(locale_name).split('_')[0]
    return locale_name
예제 #17
0
파일: app.py 프로젝트: glasmasin/moneyguru
    def __init__(self):
        ApplicationBase.__init__(self)
        self.prefs = Preferences()
        self.prefs.load()
        global APP_PREFS
        APP_PREFS = self.prefs
        locale = QLocale.system()
        dateFormat = self.prefs.dateFormat
        decimalSep = locale.decimalPoint()
        groupingSep = locale.groupSeparator()
        cachePath = QDesktopServices.storageLocation(QDesktopServices.CacheLocation)
        appdata = getAppData()
        plugin_model_path = op.join(BASE_PATH, 'plugin_examples')
        DateEdit.DATE_FORMAT = dateFormat
        self.model = MoneyGuruModel(
            view=self, date_format=dateFormat, decimal_sep=decimalSep,
            grouping_sep=groupingSep, cache_path=cachePath, appdata_path=appdata,
            plugin_model_path=plugin_model_path
        )
        # on the Qt side, we're single document based, so it's one doc per app.
        self.doc = Document(app=self)
        self.doc.model.connect()
        self.mainWindow = MainWindow(doc=self.doc)
        self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self)
        self.aboutBox = AboutBox(self.mainWindow, self)
        if sys.argv[1:] and op.exists(sys.argv[1]):
            self.doc.open(sys.argv[1])
        elif self.prefs.recentDocuments:
            self.doc.open(self.prefs.recentDocuments[0])

        self.connect(self, SIGNAL('applicationFinishedLaunching()'), self.applicationFinishedLaunching)
        QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
예제 #18
0
파일: run.py 프로젝트: ekimdev/edis
def correr_interfaz(app):
    ESettings().cargar()
    import src.ui.inicio  # lint:ok
    # Traductor
    local = QLocale.system().name()
    qtraductor = QTranslator()
    qtraductor.load("qt_" + local, QLibraryInfo.location(
                    QLibraryInfo.TranslationsPath))

    edis = EDIS()
    app.setWindowIcon(QIcon(paths.ICONOS['icon']))
    # Aplicar estilo
    with open(os.path.join(paths.PATH,
              "extras", "temas", "default.qss")) as tema:
        estilo = tema.read()
    app.setStyleSheet(estilo)
    # Archivos de última sesión
    archivos = ESettings.get('general/archivos')
    # Archivos recientes
    recents_files = ESettings.get('general/recientes')
    if recents_files is None:
        recents_files = []
    edis.cargar_archivos(archivos, recents_files)
    edis.show()
    sys.exit(app.exec_())
def main():
    app = QApplication([i.encode('utf-8') for i in sys.argv])
    app.setOrganizationName(ffmc.__name__)
    app.setOrganizationDomain(ffmc.__url__)
    app.setApplicationName('FF Muli 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_()
예제 #20
0
파일: plugin.py 프로젝트: NyakudyaA/inasafe
    def change_i18n(self, new_locale):
        """Change internationalisation for the plugin.

        Override the system locale  and then see if we can get a valid
        translation file for whatever locale is effectively being used.

        :param new_locale: The new locale i.e. 'id', 'af', etc.
        :type new_locale: str

        :raises: TranslationLoadException
        """

        os.environ['INASAFE_LANG'] = str(new_locale)

        LOGGER.debug('%s %s %s' % (
            new_locale, QLocale.system().name(), os.environ['INASAFE_LANG']))

        root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        translation_path = os.path.join(
            root, 'safe_qgis', 'i18n',
            'inasafe_' + str(new_locale) + '.qm')

        if os.path.exists(translation_path):
            self.translator = QTranslator()
            result = self.translator.load(translation_path)
            if not result:
                message = 'Failed to load translation for %s' % new_locale
                raise TranslationLoadError(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug('%s %s' % (
            translation_path, os.path.exists(translation_path)))
예제 #21
0
def locale():
    """Get the name of the currently active locale.

    :returns: Name of the locale e.g. 'id'
    :rtype: str
    """
    override_flag = QSettings().value(
        'locale/overrideFlag', True, type=bool)

    default = 'en_US'

    if override_flag:
        locale_name = QSettings().value('locale/userLocale', default, type=str)
    else:
        # noinspection PyArgumentList
        locale_name = QLocale.system().name()

    if locale_name == 'C':
        # On travis, locale/userLocale is equal to C. We want 'en'.
        locale_name = default

    # NOTES: we split the locale name because we need the first two
    # character i.e. 'id', 'af, etc
    locale_name = str(locale_name).split('_')[0]
    return locale_name
예제 #22
0
        def merge_data_with_predictions():
            data_model = self.dataview.model()
            predictions_model = self.predictionsview.model()

            # use ItemDelegate to style prediction values
            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())

            # iterate only over visible columns of data's QTableView
            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),
                                         range(data_model.columnCount())))

            # print header
            yield [''] + \
                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
                   for col in range(predictions_model.columnCount())] + \
                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
                   for col in iter_data_cols]

            # print data & predictions
            for i in range(data_model.rowCount()):
                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \
                      [style(predictions_model.data(predictions_model.index(i, j)))
                       for j in range(predictions_model.columnCount())] + \
                      [data_model.data(data_model.index(i, j))
                       for j in iter_data_cols]
예제 #23
0
    def __init__(self, iface):
        """init"""

        self.iface = iface
        self.context = StaticContext()
        self.action_run = None
        self.action_help = None
        self.web_menu = '&MetaSearch'

        LOGGER.debug('Setting up i18n')

        locale_name = str(QLocale.system().name()).split('_')[0]

        LOGGER.debug('Locale name: %s', locale_name)

        # load if exists
        tr_file = os.path.join(self.context.ppath, 'locale', locale_name,
                               'LC_MESSAGES', 'ui.qm')

        if os.path.exists(tr_file):
            self.translator = QTranslator()
            result = self.translator.load(tr_file)
            if not result:
                msg = 'Failed to load translation: %s' % tr_file
                LOGGER.error(msg)
                raise RuntimeError(msg)
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug(translate('Translation loaded: %s' % tr_file))
예제 #24
0
파일: GdalTools.py 프로젝트: boggins/QGIS
    def __init__(self, iface):
        if not valid:
            return

        # Save reference to the QGIS interface
        self.iface = iface
        try:
            self.QgisVersion = unicode(QGis.QGIS_VERSION_INT)
        except:
            self.QgisVersion = unicode(QGis.qgisVersion)[0]

        if QGis.QGIS_VERSION[0:3] < "1.5":
            # For i18n support
            userPluginPath = qgis.utils.home_plugin_path + "/GdalTools"
            systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools"

            overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool)
            if not overrideLocale:
                localeFullName = QLocale.system().name()
            else:
                localeFullName = QSettings().value("locale/userLocale", "", type=str)

            if QFileInfo(userPluginPath).exists():
                translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"
            else:
                translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"

            self.localePath = translationPath
            if QFileInfo(self.localePath).exists():
                self.translator = QTranslator()
                self.translator.load(self.localePath)
                QCoreApplication.installTranslator(self.translator)

        # The list of actions added to menus, so we can remove them when unloading the plugin
        self._menuActions = []
예제 #25
0
    def setupLanguageMenu(self):
        self.languages = QDir(":/languages").entryList()

        if self.current_language is None:
            self.current_language = QLocale.system().name(
            )  # Retrieve Current Locale from the operating system.
            log.debug("Detected user's locale as %s" % self.current_language)

        for language in self.languages:
            translator = QTranslator(
            )  # Create a translator to translate Language Display Text.
            translator.load(":/languages/%s" % language)
            language_display_text = translator.translate(
                "Translation", "Language Display Text")

            languageAction = QAction(self)
            languageAction.setCheckable(True)
            languageAction.setText(language_display_text)
            languageAction.setData(language)
            self.menuLanguage.addAction(languageAction)
            self.langActionGroup.addAction(languageAction)

            if self.current_language == str(language).strip("tr_").rstrip(
                    ".qm"):
                languageAction.setChecked(True)
예제 #26
0
    def init(self, logo, title):
        from qgis.core import QgsApplication
        from PyQt4.QtGui import QApplication, QFont, QIcon
        from PyQt4.QtCore import QLocale, QTranslator
        try:
            import PyQt4.QtSql
        except ImportError:
            pass

        self.app = QgsApplication(self.sysargv, True)
        import roam.roam_style
        self.app.setStyleSheet(roam.roam_style.appstyle)
        QgsApplication.setPrefixPath(self.prefixpath, True)
        QgsApplication.initQgis()

        locale = QLocale.system().name()
        self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale))
        translator = QTranslator()
        translator.load(self.translationFile, "i18n")
        self.app.installTranslator(translator)

        QApplication.setStyle("Plastique")
        QApplication.setFont(QFont('Segoe UI'))
        QApplication.setWindowIcon(QIcon(logo))
        QApplication.setApplicationName(title)

        import roam.editorwidgets.core
        roam.editorwidgets.core.registerallwidgets()
        return self
예제 #27
0
    def change_i18n(self, new_locale):
        """Change internationalisation for the plugin.

        Override the system locale
        and then see if we can get a valid translation file
        for whatever locale is effectively being used.

        :param new_locale: the new locale i.e. 'id', 'af', etc.
        :type new_locale: str
        :raises: TranslationLoadException
        """

        os.environ['LANG'] = str(new_locale)

        LOGGER.debug('%s %s %s' %
                     (new_locale, QLocale.system().name(), os.environ['LANG']))

        root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        translation_path = os.path.join(root, 'safe_qgis', 'i18n',
                                        'inasafe_' + str(new_locale) + '.qm')

        if os.path.exists(translation_path):
            self.translator = QTranslator()
            result = self.translator.load(translation_path)
            if not result:
                message = 'Failed to load translation for %s' % new_locale
                raise TranslationLoadError(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug('%s %s' %
                     (translation_path, os.path.exists(translation_path)))
예제 #28
0
파일: environ.py 프로젝트: FSAS-NUS/Roam
    def init(self, logo, title):
        from qgis.core import QgsApplication
        from PyQt4.QtGui import QApplication, QFont, QIcon
        from PyQt4.QtCore import QLocale, QTranslator
        try:
            import PyQt4.QtSql
        except ImportError:
            pass

        self.app = QgsApplication(self.sysargv, True)
        QgsApplication.setPrefixPath(self.prefixpath, True)
        QgsApplication.initQgis()

        locale = QLocale.system().name()
        self.translationFile = os.path.join(self.i18npath,
                                            '{0}.qm'.format(locale))
        translator = QTranslator()
        translator.load(self.translationFile, "i18n")
        self.app.installTranslator(translator)

        QApplication.setStyle("Plastique")
        QApplication.setFont(QFont('Segoe UI'))
        QApplication.setWindowIcon(QIcon(logo))
        QApplication.setApplicationName(title)

        import roam.editorwidgets.core
        roam.editorwidgets.core.registerallwidgets()
        import roam.qgisfunctions
        return self
예제 #29
0
    def __init__(self, iface):
        """init"""

        self.iface = iface
        self.context = StaticContext()
        self.action_run = None
        self.action_help = None
        self.web_menu = '&MetaSearch'

        LOGGER.debug('Setting up i18n')

        locale_name = str(QLocale.system().name()).split('_')[0]

        LOGGER.debug('Locale name: %s', locale_name)

        # load if exists
        tr_file = os.path.join(self.context.ppath, 'locale', locale_name,
                               'LC_MESSAGES', 'ui.qm')

        if os.path.exists(tr_file):
            self.translator = QTranslator()
            result = self.translator.load(tr_file)
            if not result:
                msg = 'Failed to load translation: %s' % tr_file
                LOGGER.error(msg)
                raise RuntimeError(msg)
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug(translate('Translation loaded: %s' % tr_file))
예제 #30
0
파일: utils.py 프로젝트: vivzqs/Quantum-GIS
def showPluginHelp(packageName=None, filename="index", section=""):
    """ show a help in the user's html browser. The help file should be named index-ll_CC.html or index-ll.html"""
    try:
        source = ""
        if packageName is None:
            import inspect
            source = inspect.currentframe().f_back.f_code.co_filename
        else:
            source = sys.modules[packageName].__file__
    except:
        return
    path = os.path.dirname(source)
    locale = str(QLocale().name())
    helpfile = os.path.join(path, filename + "-" + locale + ".html")
    if not os.path.exists(helpfile):
        helpfile = os.path.join(
            path, filename + "-" + locale.split("_")[0] + ".html")
    if not os.path.exists(helpfile):
        helpfile = os.path.join(path, filename + "-en.html")
    if not os.path.exists(helpfile):
        helpfile = os.path.join(path, filename + "-en_US.html")
    if not os.path.exists(helpfile):
        helpfile = os.path.join(path, filename + ".html")
    if os.path.exists(helpfile):
        url = "file://" + helpfile
        if section != "":
            url = url + "#" + section
        iface.openURL(url, False)
예제 #31
0
def initializeQtTranslations(language=None):
	from PyQt4.QtCore import QTranslator, QCoreApplication, QLocale
	if not language:
		language = str(QLocale.system().name())

	# First we try to load the file with the same system language name 
	# Usually in $LANG and looks something like ca_ES, de_DE, etc.
	file = Paths.searchFile( '%s.qm' % language, 'l10n' )
	if not file:
		# If the first step didn't work try to remove country
		# information and try again.
		language = language.split('_')[0]
		file = Paths.searchFile( '%s.qm' % language, 'l10n' )

	# If no translation files were found, don't crash
	# but continue silently.
	if file:
		translator = QTranslator( QCoreApplication.instance() )
		translator.load( file )
		QCoreApplication.instance().installTranslator( translator )

	# First we try to load the file with the same system language name 
	# Usually in $LANG and looks something like ca_ES, de_DE, etc.
	file = Paths.searchFile( 'qt_%s.qm' % language, 'l10n' )
	if not file:
		# If the first step didn't work try to remove country
		# information and try again.
		language = language.split('_')[0]
		file = Paths.searchFile( 'qt_%s.qm' % language, 'l10n' )
	# If no translation files were found, don't crash
	# but continue silently.
	if file:
		translator = QTranslator( QCoreApplication.instance() )
		translator.load( file )
		QCoreApplication.instance().installTranslator( translator )
예제 #32
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # i18n support
        override_locale = QSettings().value('locale/overrideFlag', False, type=bool)
        if not override_locale:
            locale_full_name = QLocale.system().name()
        else:
            locale_full_name = QSettings().value('locale/userLocale', '', type=unicode)

        self.locale_path = '%s/i18n/rugeocoder_%s.qm' % (_current_path, locale_full_name[0:2])
        if QFileInfo(self.locale_path).exists():
            self.translator = QTranslator()
            self.translator.load(self.locale_path)
            QCoreApplication.installTranslator(self.translator)

        # menu && toolbars
        self.menu_name = self.tr(u'&RuGeocoder')
        self.toolbar = self.iface.addToolBar(self.menu_name)
        self.toolbar.setObjectName(u'RuGeocoderToolbar')

        # instances
        self.__converter_dlg = ConverterDialog()
        self.__geocoder_dlg = BatchGeocodingDialog()

        # Dock tree panel
        self.__quick_tlb = QuickGeocodingToolbox(self.iface)
        self.iface.addDockWidget(PluginSettings.dock_area(), self.__quick_tlb)
        self.__quick_tlb.setFloating(PluginSettings.dock_floating())
        self.__quick_tlb.resize(PluginSettings.dock_size())
        self.__quick_tlb.move(PluginSettings.dock_pos())
        self.__quick_tlb.setVisible(PluginSettings.dock_visibility())
        self.__quick_tlb.set_active_geocoder(PluginSettings.dock_geocoder_name())
        self.__quick_tlb.setWindowIcon(QIcon(path.join(_current_path, 'edit-find-project.png')))
예제 #33
0
파일: lector.py 프로젝트: klukonin/lector
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. Pleaase 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_()
예제 #34
0
파일: trans.py 프로젝트: stevexyz/dupeguru
def install_gettext_trans_under_qt(base_folder, lang=None):
    # 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 PyQt4.QtCore import QCoreApplication, QTranslator, QLocale, QLibraryInfo
    if not lang:
        lang = str(QLocale.system().name())[:2]
    localename = get_locale_name(lang)
    if localename is not None:
        try:
            locale.setlocale(locale.LC_ALL, localename)
        except locale.Error:
            logging.warning("Couldn't set locale %s", localename)
    qmname = 'qt_%s' % lang
    if ISLINUX:
        # Under linux, a full Qt installation is already available in the system, we didn't bundle
        # up the qm files in our package, so we have to load translations from the system.
        qmpath = op.join(QLibraryInfo.location(QLibraryInfo.TranslationsPath),
                         qmname)
    else:
        qmpath = op.join(base_folder, qmname)
    qtr = QTranslator(QCoreApplication.instance())
    qtr.load(qmpath)
    QCoreApplication.installTranslator(qtr)
    install_gettext_trans(base_folder, lang)
예제 #35
0
def main():
    global app, aboutData

    import setproctitle
    setproctitle.setproctitle("iosshy")

    from PyQt4.QtCore import QCoreApplication, QTranslator, QLocale, QSettings
    from PyQt4.QtGui import QApplication, QSystemTrayIcon, QImage

    from tunneldialog import TunnelDialog

    try:
        from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs
        from PyKDE4.kdeui import KApplication, KIcon

        aboutData = KAboutData(
            name, #appName
            name, #catalogName
            ki18n(name), #programName
            version,
            ki18n(description), #shortDescription
            KAboutData.License_BSD, #licenseKey
            ki18n("© 2010 Massimiliano Torromeo"), #copyrightStatement
            ki18n(""), #text
            url #homePageAddress
        )
        aboutData.setBugAddress("http://github.com/mtorromeo/iosshy/issues")
        aboutData.addAuthor(
            ki18n("Massimiliano Torromeo"), #name
            ki18n("Main developer"), #task
            "*****@*****.**" #email
        )
        aboutData.setProgramLogo(QImage(":icons/network-server.png"))

        KCmdLineArgs.init(sys.argv, aboutData)

        app = KApplication()
        app.setWindowIcon(KIcon("network-server"))

        if app.isSessionRestored():
            sys.exit(0)
    except ImportError:
        app = QApplication(sys.argv)
        app.setOrganizationName("MTSoft")
        app.setApplicationName(name)


    if QSystemTrayIcon.isSystemTrayAvailable():
        translator = QTranslator()
        qmFile = "tunneller_%s.qm" % QLocale.system().name()
        if os.path.isfile(qmFile):
            translator.load(qmFile)
        app.installTranslator(translator)

        dialog = TunnelDialog()
        sys.exit(app.exec_())
    else:
        print "System tray not available. Exiting."
        sys.exit(1)
예제 #36
0
def generateDict(verbose=False):
    # As per the Qt4.7 documentation the QLocale.Language enumeration
    # ranges from 1 to 214:
    # http://doc.trolltech.com/4.7/qlocale.html#Language-enum
    lines = ['locales = {\n']
    for l in xrange(1, 214):
        lang = QLocale.languageToString(l)
        for c in QLocale.countriesForLanguage(l):
            code = QLocale(l, c).name()
            country = QLocale.countryToString(c)
            if verbose:
                print code, lang, country
            line = "    '{0}' : ['{1}', '{2}'],\n"
            lines.append(line.format(code, lang, country))

    lines.append('}\n\n')
    return lines
예제 #37
0
def update_translations():
    # Get current locale name
    curlocale = str(QLocale.system().name().toUtf8())

    # Update translations of current locale or create new
    exitcode = os.system(
        "pylupdate4 AboutWindow.py AllScreensDialog.py urtdsc.py -ts translations/urtdsc-" + curlocale + ".ts"
    )
예제 #38
0
파일: app.py 프로젝트: TeddyBoomer/geophar
 def __init__(self, args=[], **kw):
     QApplication.__init__(self, args)
     locale = QLocale.system().name()
     translator=QTranslator ()
     translator.load("qt_" + locale,
                   QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(translator)
     self._print_signal.connect(self._print)
예제 #39
0
파일: dictgen.py 프로젝트: einaru/luma
def generateDict(verbose=False):
    # As per the Qt4.7 documentation the QLocale.Language enumeration
    # ranges from 1 to 214:
    # http://doc.trolltech.com/4.7/qlocale.html#Language-enum
    lines = ['locales = {\n']
    for l in xrange(1, 214):
        lang = QLocale.languageToString(l)
        for c in QLocale.countriesForLanguage(l):
            code = QLocale(l, c).name()
            country = QLocale.countryToString(c)
            if verbose:
                print code, lang, country
            line = "    '{0}' : ['{1}', '{2}'],\n"
            lines.append(line.format(code, lang, country))

    lines.append('}\n\n')
    return lines
예제 #40
0
 def reset(self):
     locale = QLocale.system()
     self.recentDocuments = []
     dateFormat = str(locale.dateFormat(QLocale.ShortFormat))
     dateFormat = clean_format(dateFormat)
     self.dateFormat = dateFormat
     self.tableFontSize = QApplication.font().pointSize()
     self.language = ''
     self.debugMode = False
예제 #41
0
파일: app.py 프로젝트: Grahack/geophar
 def __init__(self, args=[], **kw):
     QApplication.__init__(self, args)
     locale = QLocale.system().name()
     translator=QTranslator ()
     translator.load("qt_" + locale,
                   QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(translator)
     if param.style_Qt:
         self.setStyle(param.style_Qt)
예제 #42
0
def detect_system_language():
    """Returns the matching Qt linguist filename for the user's system language.

    The default is to use en_US if a matching translation does not exist.
    """
    translation = 'tr_{}'.format(QLocale.system().name())
    translation_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                    'frontend', 'qtcommon', 'languages', '{}.ts'.format(translation))
    return '{}.qm'.format(translation) if os.path.isfile(translation_file) else 'tr_en_US.qm'
예제 #43
0
	def __init__(self):
		"""Init method

		@param	self		A Main module instance
		"""
		self._locale = QLocale.system().name()

		self._user = None
		self._config = None
		self._files = []
def startmain():
    """
    Initialise the application and display the main window.
    """
    app = QApplication(sys.argv)
    app.cleanup_files = []

    QApplication.setStyle(QStyleFactory.create('CleanLooks'))
    QApplication.setPalette(QApplication.style().standardPalette())

    QApplication.setApplicationName('Bing Wallpaper Changer')
    QApplication.setApplicationVersion(VERSION)
    QApplication.setOrganizationName('overThere.co.uk')
    QApplication.setWindowIcon(QIcon(':/icons/ui/ot_icon.svg'))

    print 'AppName: %s' % QApplication.applicationName()
    print 'AppVersion: %s' % QApplication.applicationVersion()
    print 'Company Name: %s' % QApplication.organizationName()

    QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedKingdom))

    # Add passed arguments to app.
    app.args = parse_arguments()
    print 'Args:', app.args

    # Check to see if application already running.
    existing_pid = instance_check(app)
    if existing_pid:
        print existing_pid
        if app.args.quit_existing:
            # Command line argument passed to close existing program. Do that, then quit.
            if platform.system() == "Windows":
                subprocess.Popen("taskkill /F /T /PID %i" % existing_pid, shell=True)
            else:
                os.killpg(existing_pid, signal.SIGKILL)
        else:
            message_box_error('Program already running.',
                              'You can only have one copy of the Bing Wallpaper Changer running at once.')
        sys.exit()

    mainwindow = MainWindow()
    # mainwindow.show()
    sys.exit(app.exec_())
예제 #45
0
 def pluginMetadata(fct):
     """ calls metadataParser for current l10n.
         If failed, fallbacks to the standard metadata """
     locale = QLocale.system().name()
     if locale and fct in translatableAttributes:
       value = metadataParser( "%s[%s]" % (fct, locale ) )
       if value: return value
       value = metadataParser( "%s[%s]" % (fct, locale.split("_")[0] ) )
       if value: return value
     return metadataParser( fct )
예제 #46
0
	def __init__(self):
		"""Init module"""

		# self.th will be initiated as a QThread instance
		self.th = None

		# Init default config
		self.setConfig()

		self._locale = QLocale.system().name()
예제 #47
0
파일: qthelpers.py 프로젝트: koll00/Gui_SM
def install_translator(qapp):
    """Install Qt translator to the QApplication instance"""
    global QT_TRANSLATOR
    if QT_TRANSLATOR is None:
        qt_translator = QTranslator()
        if qt_translator.load("qt_"+QLocale.system().name(),
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
            QT_TRANSLATOR = qt_translator # Keep reference alive
    if QT_TRANSLATOR is not None:
        qapp.installTranslator(QT_TRANSLATOR)
예제 #48
0
 def __init__(self, args=[], **kw):
     QApplication.__init__(self, args)
     locale = QLocale.system().name()
     translator=QTranslator ()
     translator.load("qt_" + locale,
                   QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(translator)
     self._print_signal.connect(self._print)
     # Pour Mac OS X
     self.setAttribute(Qt.AA_DontUseNativeMenuBar)
예제 #49
0
 def pluginMetadata(fct):
     """ calls metadataParser for current l10n.
     If failed, fallbacks to the standard metadata """
     locale = QLocale.system().name()
     if locale and fct in translatableAttributes:
         value = metadataParser("%s[%s]" % (fct, locale))
         if value: return value
         value = metadataParser("%s[%s]" % (fct, locale.split("_")[0]))
         if value: return value
     return metadataParser(fct)
예제 #50
0
def install_translator(qapp):
    """Install Qt translator to the QApplication instance"""
    global QT_TRANSLATOR
    if QT_TRANSLATOR is None:
        qt_translator = QTranslator()
        if qt_translator.load(
                "qt_" + QLocale.system().name(),
                QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
            QT_TRANSLATOR = qt_translator  # Keep reference alive
    if QT_TRANSLATOR is not None:
        qapp.installTranslator(QT_TRANSLATOR)
예제 #51
0
def detect_system_language():
    """Returns the matching Qt linguist filename for the user's system language.

    The default is to use en_US if a matching translation does not exist.
    """
    translation = 'tr_{}'.format(QLocale.system().name())
    translation_file = os.path.join(
        os.path.dirname(os.path.realpath(__file__)), 'frontend', 'qtcommon',
        'languages', '{}.ts'.format(translation))
    return '{}.qm'.format(translation) if os.path.isfile(
        translation_file) else 'tr_en_US.qm'
예제 #52
0
def preferred():
    """Return a list of language codes from the operating system preferences.
    
    Language- and country codes will always be separated with an underscore '_'.
    
    """
    try:
        langs = QLocale().uiLanguages()
    except AttributeError:
        # QLocale.uiLanguages is not in Qt 4.7 (only Qt4.8+)
        langs = []
    else:
        # in some systems, language/country codes have '-' and not '_'
        langs = [l.replace('-', '_') for l in langs]
    if not langs:
        try:
            langs.append(locale.getdefaultlocale()[0])
        except ValueError:
            pass
    return langs
예제 #53
0
def preferred():
    """Return a list of language codes from the operating system preferences.
    
    Language- and country codes will always be separated with an underscore '_'.
    
    """
    try:
        langs = QLocale().uiLanguages()
    except AttributeError:
        # QLocale.uiLanguages is not in Qt 4.7 (only Qt4.8+)
        langs = []
    else:
        # in some systems, language/country codes have '-' and not '_'
        langs = [l.replace('-', '_') for l in langs]
    if not langs:
        try: 
            langs.append(locale.getdefaultlocale()[0])
        except ValueError:
            pass
    return langs
예제 #54
0
    def run(self):
        from puding.ui.qt.main_window import MainWindow

        app = QApplication(sys.argv)
        locale = QLocale.system().name()
        translator = QTranslator()
        translator.load("%s/translations/puding_%s.qm" %
                        (self.res.DEV_HOME, locale))
        app.installTranslator(translator)
        main_window = MainWindow()
        main_window.show()
        sys.exit(app.exec_())
예제 #55
0
def main():
    """
    loader function to start the application
    """
    app = QApplication(sys.argv)
    locale = QLocale.system().name()
    translator = QTranslator()
    translator.load("texteditor_%s.qm" % locale)
    app.installTranslator(translator)
    main_window = MainWindow()
    main_window.show()
    app.exec_()
예제 #56
0
class CSumCol(CNumCol):
    u"""
      Numeric column: right aligned, sum formatted
    """
    locale = QLocale()

    def format(self, values):
        sum = forceDouble(values[0])
        return toVariant(self.locale.toString(sum, 'f', 2))

    def formatNative(self, values):
        return forceDouble(values[0])
예제 #57
0
파일: i18n.py 프로젝트: khosrow/luma-devel
    def __buildLanguageDictionary(self):
        """Builds the language dictionary used by the application. The
        dictionary is constructed with the locale code as key, and a
        list containing the language name (and possibly the country
        name) as value. The information is based on the ``i18n``entries
        in the ``resources.py`` module, where the alias for a one
        translation file is locale code for the translation.

        If the translation file is named ``luma_nn_NO.ts`` the
        corresponding alias for this file will be ``nb_NO``. Further
        more ``nb`` will map to ``QLocale.NorwegianBokmal``and ``NO``
        will map to ``QLocale.Norway``, resulting in the following entry
        in the dictionary::

            langDict = {
                ...,
                'en' : ['English'], # Default is allways included
                'nb_NO' : ['Norwegian', 'Norway'],
                ...
            }
        """
        for i18n in self.__translationPath:
            if i18n == 'hx':
                self.__availableLanguages[i18n] = ['leet', '10100111001']
            else:
                locale = QLocale(i18n)
                language = QLocale.languageToString(locale.language())
                country = QLocale.countryToString(locale.country())
                self.__availableLanguages[i18n] = [language, country]
예제 #58
0
    def openHelp(self):
        overrideLocale = QSettings().value('locale/overrideFlag', False, bool)
        if not overrideLocale:
            locale = QLocale.system().name()[:2]
        else:
            locale = QSettings().value('locale/userLocale', '')

        if locale in ['uk']:
            QDesktopServices.openUrl(
                QUrl('http://hub.qgis.org/projects/photo2shape/wiki'))
        else:
            QDesktopServices.openUrl(
                QUrl('http://hub.qgis.org/projects/photo2shape/wiki'))
예제 #59
0
def main(argv=None):
    """
    Creates the main window for the financeager application and begins
    the QApplication if necessary. 
    """
    # locale settings. Default application language is English
    QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))

    app = None

    if not QtGui.QApplication.instance():
        app = QtGui.QApplication(argv)

    # create the main window
    from src.gui.financeagerwindow import FinanceagerWindow
    window = FinanceagerWindow()
    window.show()

    if app:
        return app.exec_()

    return 0