Пример #1
0
 def __init__(self, *args, **kwargs):
     """Initialize object."""
     super().__init__(*args, **kwargs)
     locale = QLocale(QLocale.English, country=QLocale.UnitedStates)
     locale.setNumberOptions(locale.RejectGroupSeparator)
     self.setLocale(locale)
     self.setFocusPolicy(Qt.StrongFocus)
     self.step_exponent = 0
     self.app = QApplication.instance()
Пример #2
0
 def createEditor(self, parent, option, index):
     """Create editor."""
     editor = QDoubleSpinBoxPlus(parent)
     editor.setMinimum(self.mini)
     editor.setMaximum(self.maxi)
     editor.setDecimals(self.prec)
     locale = QLocale(QLocale.English, country=QLocale.UnitedStates)
     locale.setNumberOptions(locale.RejectGroupSeparator)
     editor.setLocale(locale)
     return editor
Пример #3
0
    def __init__(self, parent):
        QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))
        super().__init__()
        if not isinstance(parent, DockArea):
            raise Exception('no valid parent container, expected a DockArea')

        self.wait_time = 2000  #ms
        self.offline = True
        self.dockarea = parent
        self.mainwindow = parent.parent()
        self.spectro_widget = QtWidgets.QWidget()
        self.data_dict = None
        """
        List of the possible plugins that could be used with Spectrometer module
        type : dimensionality of the detector
        name: name of the plugin
        calib = True means there is a builtin calibration of the frequency axis
        movable : tells if the dispersion can be set (for instance by moving a grating)
        unit: valid only if calib is True. Unit of the calibration axis (x_axis of the detector), most often in
              nanometers. Possible values are 'nm', 'radfs' (rad/femtosecond), 'eV'
        laser: if False,  laser cannot be changed by the program, do it manually
        laser_list: if laser is True, laser_list gives a list of selectable lasers
        
        """

        self.current_det = None  # will be after initialization

        self.laser_set_manual = True

        #init the object parameters
        self.detector = None
        self.save_file_pathname = None
        self._spectro_wl = 550  # center wavelngth of the spectrum
        self.viewer_freq_axis = utils.Axis(data=None,
                                           label='Photon energy',
                                           units='')
        self.raw_data = []

        #init the user interface
        self.dashboard = self.set_dashboard()
        self.dashboard.preset_loaded_signal.connect(
            lambda: self.show_detector(False))
        self.dashboard.preset_loaded_signal.connect(self.set_detector)
        self.dashboard.preset_loaded_signal.connect(self.initialized)
        self.set_GUI()
        self.dashboard.new_preset_created.connect(
            lambda: self.create_menu(self.menubar))

        self.show_detector(False)
        self.dockarea.setEnabled(False)
Пример #4
0
    def _window_initialize(self):
        super()._window_initialize()
        self._interactor = self.figure.plotter.interactor
        self._window = self.figure.plotter.app_window
        self._window_load_icons()
        self._window_set_theme()
        self._window.setLocale(QLocale(QLocale.Language.English))
        self._window.signal_close.connect(self._window_clean)
        self._window_before_close_callbacks = list()
        self._window_after_close_callbacks = list()

        # patch closeEvent
        def closeEvent(event):
            # functions to call before closing
            accept_close_event = True
            for callback in self._window_before_close_callbacks:
                ret = callback()
                # check if one of the callbacks ignores the close event
                if isinstance(ret, bool) and not ret:
                    accept_close_event = False

            if accept_close_event:
                self._window.signal_close.emit()
                event.accept()
            else:
                event.ignore()

            # functions to call after closing
            for callback in self._window_after_close_callbacks:
                callback()

        self._window.closeEvent = closeEvent
Пример #5
0
    def setup_ui(self):
        """
        界面初始化
        :return:
        """

        self.translator = create_translator(path=os.path.join(
            os.path.dirname(__file__), 'translations',
            'qt_{0}.qm'.format(QLocale.system().name())))  # translator

        self.setTabKeyNavigation(True)
        self.setDragEnabled(True)
        self.setDragDropOverwriteMode(True)
        self.setAlternatingRowColors(False)
        self.setUniformRowHeights(True)
        self.setSortingEnabled(True)
        self.setAnimated(True)
        self.setAllColumnsShowFocus(False)
        self.setWordWrap(False)
        self.setHeaderHidden(False)
        self.setObjectName("treeView_files")
        self.header().setSortIndicatorShown(True)

        self.model = PMFileSystemModel()
        self.model.setRootPath(self.initial_dir)

        self.setModel(self.model)
        self.setRootIndex(self.model.index(self.initial_dir))
        self.setAnimated(False)
        self.setSortingEnabled(True)  # 启用排序
        self.header().setSortIndicatorShown(True)  # 启用标题排序
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_context_menu)
        self.init_context_menu()
Пример #6
0
    def setup_ui(self):
        self.translator = create_translator(
            path=os.path.join(os.path.dirname(__file__), 'translations',
                              'qt_{0}.qm'.format(QLocale.system().name())))  # translator
        self.nodes: Dict[str, 'QTreeWidgetItem'] = {}
        self.setColumnCount(2)
        header_item = QTreeWidgetItem()
        header_item.setText(0, self.tr('Name'))
        self.setColumnWidth(0, 200)
        header_item.setText(1, self.tr('Value'))
        header_item.setTextAlignment(0, Qt.AlignCenter)
        header_item.setTextAlignment(1, Qt.AlignCenter)
        self.setHeaderItem(header_item)
        self.auto_expand = False

        self.itemClicked.connect(self.on_item_clicked)
        self.itemDoubleClicked.connect(self.on_item_double_clicked)
        self.customContextMenuRequested.connect(self.on_right_clicked)
        self.setContextMenuPolicy(Qt.CustomContextMenu)

        self.context_menu = QMenu()
        show_action = self.context_menu.addAction(self.tr('View'))
        save_action = self.context_menu.addAction(self.tr('Save as '))
        cancel_action = self.context_menu.addAction(self.tr('Undo'))
        redo_action = self.context_menu.addAction(self.tr('Redo'))
        delete_action = self.context_menu.addAction(self.tr('Delete'))
        show_action.triggered.connect(self.on_show_data_by_context_menu)
Пример #7
0
 def __init__(self, data, header, editable=True, parent=None, show_checkbox=False):
     QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))
     super().__init__(parent)
     if isinstance(data, np.ndarray):
         data_tot = []
         for dat in data:
             data_tot.append([float(d) for d in dat])
         data = data_tot
     self._data = data  # stored data as a list of list
     self._checked = [False for _ in range(len(self._data))]
     self._show_checkbox = show_checkbox
     self.data_tmp = None
     self.header = header
     if not isinstance(editable, list):
         self.editable = [editable for h in header]
     else:
         self.editable = editable
Пример #8
0
    def __init__(self, parent):
        QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))
        super().__init__()
        if not isinstance(parent, DockArea):
            raise Exception('no valid parent container, expected a DockArea')
        self.dockarea = parent
        self.window = self.dockarea.parent()

        self.setupUI()

        self.raw_datas = dict([])
        self.raw_axis = None
        self.text_peak_items = []
        self.arrow_peak_items = []
        self.table_model = None
        self.calib_plot = None
        self.filenames = []
Пример #9
0
def _check_locale():
    # There seems to be a setlocale() call deep down in the initialization of
    # QApplication, if the user has set the LC_NUMERIC environment variables to
    # a locale with decimalpoint different from "." the application will fail
    # hard quite quickly.
    current_locale = QLocale()
    decimal_point = str(current_locale.decimalPoint())
    if decimal_point != ".":
        msg = f"""
** WARNING: You are using a locale with decimalpoint: '{decimal_point}' - the ert application is
            written with the assumption that '.' is  used as decimalpoint, and chances
            are that something will break if you continue with this locale. It is highly
            recommended that you set the decimalpoint to '.' using one of the environment
            variables 'LANG', LC_ALL', or 'LC_NUMERIC' to either the 'C' locale or
            alternatively a locale which uses '.' as decimalpoint.\n"""  # noqa

        sys.stderr.write(msg)
Пример #10
0
 def __init__(self, parent=None, data: Dict = None):
     super().__init__(parent)
     self.translator = create_translator(path=os.path.join(
         os.path.dirname(__file__), 'translations',
         'qt_{0}.qm'.format(QLocale.system().name())))  # translator
     self.tree_data = data
     self.set_data(data)
     self.clicked.connect(self.on_item_clicked)
     self.expandAll()
Пример #11
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)
Пример #12
0
def main():
    translator = QtCore.QTranslator()
    system_language = QLocale.languageToString(QLocale.system().language())
    print("System Locale: {}".format(system_language))
    print("Localization loaded: {}".format(
        translator.load("{}.qm".format(system_language.lower()),
                        "translations")))
    if translator.isEmpty():
        print("Fallback Localization loaded: {}".format(
            translator.load("english.qm", "translations")))
    app = QtWidgets.QApplication(sys.argv)
    app.installTranslator(translator)

    w = QtWidgets.QWidget()
    trayIcon = SystemTrayIcon(QtGui.QIcon("icons/icon.png"), w)

    trayIcon.show()
    sys.exit(app.exec_())
Пример #13
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)
Пример #14
0
 def install_translator():
     global _trans
     app = QApplication.instance()
     assert app is not None
     _trans = QTranslator()
     _trans.load(QLocale.system(),
                 'qt_zh_CN.qm',
                 directory=os.path.join(os.path.dirname(__file__),
                                        'translations'))
     app.installTranslator(_trans)
Пример #15
0
 def _set_setpoint(self):
     """Set current setpoint for every visible widget."""
     dlg = QInputDialog(self)
     dlg.setLocale(QLocale(QLocale.English))
     new_value, ok = dlg.getDouble(self, "New setpoint", "Value")
     if ok:
         for dclink in self.dclink_widgets:
             sp = dclink.setpoint.sp_lineedit
             sp.setText(str(new_value))
             try:
                 sp.send_value()
             except TypeError:
                 pass
Пример #16
0
def install_translator(qapp):
    """Install Qt translator to the QApplication instance"""
    global QT_TRANSLATOR
    if QT_TRANSLATOR is None:
        from qtpy.QtCore import QLocale, QTranslator, QLibraryInfo
        locale = QLocale.system().name()
        # Qt-specific translator
        qt_translator = QTranslator()
        paths = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        if qt_translator.load("qt_" + locale, paths):
            QT_TRANSLATOR = qt_translator  # Keep reference alive
    if QT_TRANSLATOR is not None:
        qapp.installTranslator(QT_TRANSLATOR)
Пример #17
0
    def __init__(self, dockarea: DockArea, dashboard=None):
        QObject.__init__(self)
        ActionManager.__init__(self)
        ParameterManager.__init__(self)
        QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))

        if not isinstance(dockarea, DockArea):
            raise Exception('no valid parent container, expected a DockArea')

        self.dockarea = dockarea
        self.mainwindow = dockarea.parent()
        self.dashboard = dashboard

        self.docks = dict([])
        self.statusbar = None
        self._toolbar = QtWidgets.QToolBar()

        if self.mainwindow is not None:
            self.mainwindow.addToolBar(self._toolbar)
            self.statusbar = self.mainwindow.statusBar()

        self.set_toolbar(self._toolbar)
Пример #18
0
    def label(self, value):
        """
        Convert a value into its representing label

        The value is converted to a plain text using
        `QLocale().toString(value)`.
        This method is often overloaded by applications to have individual
        labels.
        
        :param float value: Value
        :return: Label string
        """
        return QLocale().toString(value)
Пример #19
0
 def _set_current_sp(self):
     """Set current setpoint for every visible widget."""
     dlg = QInputDialog(self)
     dlg.setLocale(QLocale(QLocale.English))
     new_value, ok = dlg.getDouble(self, "Insert current setpoint", "Value")
     if ok:
         for key, widget in self.ps_widgets_dict.items():
             if key in self.filtered_widgets:
                 sp = widget.setpoint.sp_lineedit
                 sp.setText(str(new_value))
                 try:
                     sp.send_value()
                 except TypeError:
                     pass
Пример #20
0
    def _window_initialize(self,
                           *,
                           window=None,
                           central_layout=None,
                           fullscreen=False):
        super()._window_initialize()
        self._interactor = self.figure.plotter.interactor
        if window is None:
            self._window = self.figure.plotter.app_window
        else:
            self._window = window

        if fullscreen:
            self._window.setWindowState(Qt.WindowFullScreen)

        if central_layout is not None:
            central_widget = self._window.centralWidget()
            if central_widget is None:
                central_widget = QWidget()
                self._window.setCentralWidget(central_widget)
            central_widget.setLayout(central_layout)
        self._window_load_icons()
        self._window_set_theme()
        self._window.setLocale(QLocale(QLocale.Language.English))
        self._window.signal_close.connect(self._window_clean)
        self._window_before_close_callbacks = list()
        self._window_after_close_callbacks = list()

        # patch closeEvent
        def closeEvent(event):
            # functions to call before closing
            accept_close_event = True
            for callback in self._window_before_close_callbacks:
                ret = callback()
                # check if one of the callbacks ignores the close event
                if isinstance(ret, bool) and not ret:
                    accept_close_event = False

            if accept_close_event:
                self._window.signal_close.emit()
                event.accept()
            else:
                event.ignore()

            # functions to call after closing
            for callback in self._window_after_close_callbacks:
                callback()

        self._window.closeEvent = closeEvent
Пример #21
0
 def createEditor(self, parent, option, index):
     """Create editor widget"""
     model = index.model()
     value = model.get_value(index)
     if model._data.dtype.name == "bool":
         value = not value
         model.setData(index, to_qvariant(value))
         return
     elif value is not np.ma.masked:
         editor = QLineEdit(parent)
         editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
         editor.setAlignment(Qt.AlignCenter)
         if is_number(self.dtype):
             validator = QDoubleValidator(editor)
             validator.setLocale(QLocale('C'))
             editor.setValidator(validator)
         editor.returnPressed.connect(self.commitAndCloseEditor)
         return editor
Пример #22
0
 def __init__(self, data=None):
     super().__init__()
     self.translator = create_translator(
         path=os.path.join(os.path.dirname(__file__), 'translations',
                           'qt_{0}.qm'.format(QLocale.system().name())))  # translator
     self.data = None
     self.menu = QMenu()
     self.action_insert_row = self.menu.addAction(QCoreApplication.translate('PMTableView','Insert Row'))
     self.action_insert_row.triggered.connect(lambda: self.on_change_row_col(self.INSERT_ROW))
     self.action_delete_row = self.menu.addAction(QCoreApplication.translate('PMTableView','Delete Row'))
     self.action_delete_row.triggered.connect(lambda: self.on_change_row_col(self.DELETE_ROW))
     self.action_insert_col = self.menu.addAction(QCoreApplication.translate('PMTableView','Insert Column'))
     self.action_insert_col.triggered.connect(lambda: self.on_change_row_col(self.INSERT_COLUMN))
     self.action_delete_col = self.menu.addAction(QCoreApplication.translate('PMTableView','Delete Column'))
     self.action_delete_col.triggered.connect(lambda: self.on_change_row_col(self.DELETE_COLUMN))
     # self.menu.addAction("aaaaaa")
     if data is not None:
         self.set_data(data)
Пример #23
0
 def maxLabelHeight(self, font):
     """
     :param QFont font: Font
     :return: the maximum height of a label
     """
     ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)
     if not ticks:
         return 0
     if self.labelAutoSize():
         vmax = sorted(
             [v for v in ticks if self.scaleDiv().contains(v)],
             key=lambda obj: len(QLocale().toString(obj)),
         )[-1]
         return np.ceil(self.labelSize(font, vmax).height())
         ## Original implementation (closer to Qwt's C++ code, but slower):
         # return np.ceil(max([self.labelSize(font, v).height()
         #                for v in ticks if self.scaleDiv().contains(v)]))
     else:
         return self._get_max_label_size(font).height()
Пример #24
0
def main():
    app = QApplication(sys.argv)

    app.setWindowIcon(QIcon(':/icons/app.svg'))

    fontDB = QFontDatabase()
    fontDB.addApplicationFont(':/fonts/Roboto-Regular.ttf')
    app.setFont(QFont('Roboto'))

    f = QFile(':/style.qss')
    f.open(QFile.ReadOnly | QFile.Text)
    app.setStyleSheet(QTextStream(f).readAll())
    f.close()

    translator = QTranslator()
    translator.load(':/translations/' + QLocale.system().name() + '.qm')
    app.installTranslator(translator)

    mw = MainWindow()
    mw.show()

    sys.exit(app.exec_())
Пример #25
0
 def __init__(self, *args, **kwargs):
     QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))
     super().__init__(*args, **kwargs)
     self.setupview()
Пример #26
0
def opensesame():

    import os, sys, platform
    # Add the folder that contains the OpenSesame modules to the path. This is
    # generally only necessary if OpenSesame is directly run from source,
    # instead from an installation.
    if os.path.exists(os.path.join(os.getcwd(), 'libopensesame')):
        sys.path.insert(0, os.getcwd())
    # Support for multiprocessing when packaged
    # In OS X the multiprocessing module is horribly broken, but a fixed
    # version has been released as the 'billiard' module
    if platform.system() == 'Darwin':
        # Use normal multirpocessing module from python 3.4 and on
        if sys.version_info >= (3, 4):
            from multiprocessing import freeze_support, set_start_method
            freeze_support()
            set_start_method('forkserver')
        else:
            from billiard import freeze_support, forking_enable
            freeze_support()
            forking_enable(0)
    else:
        from multiprocessing import freeze_support
        freeze_support()
    # Parse the (optional) environment file that contains special paths, etc.
    from libopensesame.misc import resource, filesystem_encoding, \
     parse_environment_file
    parse_environment_file()
    # Force the new-style Qt API
    import sip
    import qtpy
    sip.setapi('QString', 2)
    sip.setapi('QVariant', 2)
    # Load debug package (this must be after the working directory change)
    from libopensesame import debug
    # Do the basic window initialization
    from qtpy.QtWidgets import QApplication

    # From Qt 5.6 on, QtWebEngine is the default way to render web pages
    # QtWebEngineWidgets must be imported before a QCoreApplication instance is created
    try:
        from qtpy import QtWebEngineWidgets
    except ImportError:
        pass

    app = QApplication(sys.argv)
    # Enable High DPI display with PyQt5
    if hasattr(qtpy.QtCore.Qt, 'AA_UseHighDpiPixmaps'):
        app.setAttribute(qtpy.QtCore.Qt.AA_UseHighDpiPixmaps)
    from libqtopensesame.qtopensesame import qtopensesame
    opensesame = qtopensesame(app)
    opensesame.__script__ = __file__
    app.processEvents()
    # Import the remaining modules
    from qtpy.QtCore import QObject, QLocale, QTranslator
    import os.path
    # Load the locale for UI translation. The locale can be specified on the
    # command line using the --locale parameter
    locale = QLocale().system().name()
    for i in range(len(sys.argv) - 1):
        if sys.argv[i] == '--locale':
            locale = sys.argv[i + 1]
    qm = resource(os.path.join(u'locale', locale) + u'.qm')
    # Say that we're trying to load de_AT, and it is not found, then we'll try
    # de_DE as fallback.
    if qm is None:
        l = locale.split(u'_')
        if len(l):
            _locale = l[0] + u'_' + l[0].upper()
            qm = resource(os.path.join(u'locale', _locale + u'.qm'))
            if qm is not None:
                locale = _locale
    opensesame._locale = locale
    if qm is not None:
        debug.msg(u'installing %s translator' % qm)
        translator = QTranslator()
        translator.load(qm)
        app.installTranslator(translator)
    else:
        debug.msg(u'no translator found for %s' % locale)
    # Now that the window is shown, load the remaining modules and resume the
    # GUI initialization.
    opensesame.resume_init()
    opensesame.restore_window_state()
    opensesame.refresh()
    opensesame.show()
    # Added for OS X, otherwise Window will not appear
    opensesame.raise_()
    # Exit using the application exit status
    sys.exit(app.exec_())
Пример #27
0
class TtsLanguages:

    isoLang2epeakLang = {
        "af": ("af", "afrikaans", "other/af"),
        "an": ("an", "aragonese", "europe/an"),
        "bg": ("bg", "bulgarian", "europe/bg"),
        "bs": ("bs", "bosnian", "europe/bs"),
        "ca": ("ca", "catalan", "europe/ca"),
        "cs": ("cs", "czech", "europe/cs"),
        "cy": ("cy", "welsh", "europe/cy"),
        "da": ("da", "danish", "europe/da"),
        "de": ("de", "german", "de"),
        # espeak el voice cannot read accented Greek words
        "el": ("el", "greek", "europe/el"),
        # To read accented Greek words, use grc instead of el
        "grc": ("grc", "greek-ancient", "other/grc"),
        #"en": ("en", "default", "default"),
        "en": ("en", "english", "default"),
        #"en-gb": ("en-gb", "english", "en"),
        "en-gb": ("en-gb", "english-gb", "en"),
        "en-sc": ("en-sc", "en-scottish", "other/en-sc"),
        "en-uk-north": ("en-uk-north", "english-north", "other/en-n"),
        "en-uk-rp": ("en-uk-rp", "english_rp", "other/en-rp"),
        "en-uk-wmids": ("en-uk-wmids", "english_wmids", "other/en-wm"),
        "en-us": ("en-us", "english-us", "en-us"),
        "en-wi": ("en-wi", "en-westindies", "other/en-wi"),
        "eo": ("eo", "esperanto", "other/eo"),
        "es": ("es", "spanish", "europe/es"),
        "es-la": ("es-la", "spanish-latin-am", "es-la"),
        "et": ("et", "estonian", "europe/et"),
        "fa": ("fa", "persian", "asia/fa"),
        "fa-pin": ("fa-pin", "persian-pinglish", "asia/fa-pin"),
        "fi": ("fi", "finnish", "europe/fi"),
        "fr-be": ("fr-be", "french-Belgium", "europe/fr-be"),
        "fr": ("fr-fr", "french", "fr"),
        "ga": ("ga", "irish-gaeilge", "europe/ga"),
        "hi": ("hi", "hindi", "asia/hi"),
        "hr": ("hr", "croatian", "europe/hr"),
        "hu": ("hu", "hungarian", "europe/hu"),
        "hy": ("hy", "armenian", "asia/hy"),
        "hy-west": ("hy-west", "armenian-west", "asia/hy-west"),
        "id": ("id", "indonesian", "asia/id"),
        "is": ("is", "icelandic", "europe/is"),
        "it": ("it", "italian", "europe/it"),
        "jbo": ("jbo", "lojban", "other/jbo"),
        "ka": ("ka", "georgian", "asia/ka"),
        "kn": ("kn", "kannada", "asia/kn"),
        "ku": ("ku", "kurdish", "asia/ku"),
        "la": ("la", "latin", "other/la"),
        "lfn": ("lfn", "lingua_franca_nova", "other/lfn"),
        "lt": ("lt", "lithuanian", "europe/lt"),
        "lv": ("lv", "latvian", "europe/lv"),
        "mk": ("mk", "macedonian", "europe/mk"),
        "ml": ("ml", "malayalam", "asia/ml"),
        "ms": ("ms", "malay", "asia/ms"),
        "ne": ("ne", "nepali", "asia/ne"),
        "nl": ("nl", "dutch", "europe/nl"),
        "no": ("no", "norwegian", "europe/no"),
        "pa": ("pa", "punjabi", "asia/pa"),
        "pl": ("pl", "polish", "europe/pl"),
        "pt-br": ("pt-br", "brazil", "pt"),
        "pt": ("pt-pt", "portugal", "europe/pt-pt"),
        "ro": ("ro", "romanian", "europe/ro"),
        "ru": ("ru", "russian", "europe/ru"),
        "sk": ("sk", "slovak", "europe/sk"),
        "sq": ("sq", "albanian", "europe/sq"),
        "sr": ("sr", "serbian", "europe/sr"),
        "sv": ("sv", "swedish", "europe/sv"),
        "sw": ("sw", "swahili-test", "other/sw"),
        "ta": ("ta", "tamil", "asia/ta"),
        "tr": ("tr", "turkish", "asia/tr"),
        "vi": ("vi", "vietnam", "asia/vi"),
        "vi-hue": ("vi-hue", "vietnam_hue", "asia/vi-hue"),
        "vi-sgn": ("vi-sgn", "vietnam_sgn", "asia/vi-sgn"),
        "zh-cn": ("zh", "mandarin", "asia/zh"),
        "zh-tw": ("zh-yue", "cantonese", "asia/zh-yue"),
        "he": ("he", "hebrew", "he"),
    }

    # QLocale: https://doc-snapshots.qt.io/qtforpython-5.14/PySide2/QtCore/QLocale.html
    isoLang2qlocaleLang = {
        "en": (QLocale(QLocale.English, QLocale.UnitedStates), "English-UnitedStates"),
        "it": (QLocale(QLocale.Italian, QLocale.Italy), "Italian-Italy"),
        "sv": (QLocale(QLocale.Swedish, QLocale.Sweden), "Swedish-Sweden"),
        #"": (QLocale(QLocale.French, QLocale.Canada), "French-Canada"),
        "de": (QLocale(QLocale.German, QLocale.Germany), "German-Germany"),
        "he": (QLocale(QLocale.Hebrew, QLocale.Israel), "Hebrew-Israel"),
        "id": (QLocale(QLocale.Indonesian, QLocale.Indonesia), "Indonesian-Indonesia"),
        "en-gb": (QLocale(QLocale.English, QLocale.UnitedKingdom), "English-UnitedKingdom"),
        #"": (QLocale(QLocale.Spanish, QLocale.Argentina), "Spanish-Argentina"),
        #"": (QLocale(QLocale.Dutch, QLocale.Belgium), "Dutch-Belgium"),
        "ro": (QLocale(QLocale.Romanian, QLocale.Romania), "Romanian-Romania"),
        "pt": (QLocale(QLocale.Portuguese, QLocale.Portugal), "Portuguese-Portugal"),
        "es": (QLocale(QLocale.Spanish, QLocale.Spain), "Spanish-Spain"),
        #"": (QLocale(QLocale.Spanish, QLocale.Mexico), "Spanish-Mexico"),
        "th": (QLocale(QLocale.Thai, QLocale.Thailand), "Thai-Thailand"),
        #"": (QLocale(QLocale.English, QLocale.Australia), "English-Australia"),
        "ja": (QLocale(QLocale.Japanese, QLocale.Japan), "Japanese-Japan"),
        "sk": (QLocale(QLocale.Slovak, QLocale.Slovakia), "Slovak-Slovakia"),
        "hi": (QLocale(QLocale.Hindi, QLocale.India), "Hindi-India"),
        "pt": (QLocale(QLocale.Portuguese, QLocale.Brazil), "Portuguese-Brazil"),
        "ar": (QLocale(QLocale.Arabic, QLocale.SaudiArabia), "Arabic-SaudiArabia"),
        "hu": (QLocale(QLocale.Hungarian, QLocale.Hungary), "Hungarian-Hungary"),
        # Use zh-cn for Taiwan Chinese, Taiwanese speaks Mandarin instead of Cantonese
        #"zh-tw": (QLocale(QLocale.Chinese, QLocale.Taiwan), "Chinese-Taiwan"),
        # we use grc here instead of el
        "grc": (QLocale(QLocale.Greek, QLocale.Greece), "Greek-Greece"),
        "ru": (QLocale(QLocale.Russian, QLocale.Russia), "Russian-Russia"),
        #"": (QLocale(QLocale.English, QLocale.Ireland), "English-Ireland"),
        "no": (QLocale(QLocale.NorwegianBokmal, QLocale.Norway), "NorwegianBokmal-Norway"),
        #"": (QLocale(QLocale.English, QLocale.India), "English-India"),
        "da": (QLocale(QLocale.Danish, QLocale.Denmark), "Danish-Denmark"),
        "fi": (QLocale(QLocale.Finnish, QLocale.Finland), "Finnish-Finland"),
        "zh-tw": (QLocale(QLocale.Chinese, QLocale.HongKong), "Chinese-HongKong"),
        #"": (QLocale(QLocale.English, QLocale.SouthAfrica), "English-SouthAfrica"),
        "fr": (QLocale(QLocale.French, QLocale.France), "French-France"),
        "zh-cn": (QLocale(QLocale.Chinese, QLocale.China), "Chinese-China"),
        "nl": (QLocale(QLocale.Dutch, QLocale.Netherlands), "Dutch-Netherlands"),
        "tr": (QLocale(QLocale.Turkish, QLocale.Turkey), "Turkish-Turkey"),
        "ko": (QLocale(QLocale.Korean, QLocale.SouthKorea), "Korean-SouthKorea"),
        "pl": (QLocale(QLocale.Polish, QLocale.Poland), "Polish-Poland"),
        "cs": (QLocale(QLocale.Czech, QLocale.CzechRepublic), "Czech-CzechRepublic"),
    }
Пример #28
0
import getpass
import locale
from typing import Optional

USER_NAME = getpass.getuser()
if USER_NAME == 'sdoyle' and 0:  # or 'id' in msg:
    locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")
    from qtpy.QtCore import QLocale
    QLocale.setDefault(QLocale(QLocale.German))


def func_str_or_none(value: Optional[float]) -> str:
    """
    converts a float/None to a locale-formatted string,
    so basically ``str(value)``

    ..todo :: rename

    """
    if value is None:
        return ''
    return func_str(value)


def func_str(value: float) -> str:
    """
    converts a float to a locale-formatted string,
    so basically ``str(value)``

    ..todo :: rename