Ejemplo n.º 1
1
    def application_init(self):
        '''Инициализация Qt приложения'''
        # Создание приложение
        self.qapp = QApplication(sys.argv)
        self.__app_working_status = True
        # Установка локлизатора
        translator = QTranslator(self.qapp)
        translator.load('lang/tr_ru', os.path.dirname(__file__))
        self.qapp.installTranslator(translator)

        self.mainDialog = MainDialog(self, self.title)
        self.mainDialog.closeApp.connect(self.__finalize_before_quit)

        self.controls = {
            'step': ['X', 'Y', 'Z', 'A'],
            'servo': ['B', 'C'],
            'pins': {
                'P1': [],
                'P2': ['UV', 'VIS']
            }
        }

        self.mainDialog.show()
        self.project_init()
        self.gui_init()
        self.communication_init()

        sys.exit(self.qapp.exec_())
Ejemplo n.º 2
0
def launch_qt_gui(bk, prefs):
    supports_theming = (bk.launcher_version() >= 20200117)
    app = QApplication(sys.argv)
    # Make plugin match Sigil's light/dark theme
    if supports_theming:
        if bk.colorMode() == "dark":
            app.setStyle(QStyleFactory.create("Fusion"))
            app.setPalette(dark_palette(bk.color))

    print('Application dir: {}'.format(QCoreApplication.applicationDirPath()))
    # Install qtbase translator for standard dialogs and such.
    # Use the Sigil language setting unless manually overridden.
    qt_translator = QTranslator()
    if prefs['language_override'] is not None:
        print('Plugin preferences language override in effect')
        qmf = 'qtbase_{}'.format(prefs['language_override'])
    else:
        qmf = 'qtbase_{}'.format(bk.sigil_ui_lang)
    # Get bundled or external translations directory
    qt_trans_dir = getQtTranslationsPath(bk._w.appdir)
    print('Qt translation dir: {}'.format(qt_trans_dir))
    print('Looking for {} in {}'.format(qmf, qt_trans_dir))
    qt_translator.load(qmf, qt_trans_dir)
    print('Translator succesfully installed: {}'.format(
        app.installTranslator(qt_translator)))

    ex = App(bk, prefs)
    ex.show()
    app.exec_()
    return _DETAILS
Ejemplo n.º 3
0
 def change_lang_chinese(self):
     self.app.removeTranslator(default_translator)
     translator = QTranslator()
     translator.load(':/translations/timer_zh_CN')
     self.app.installTranslator(translator)
     self.retranslateUi()
     self.lang = 'zh_CN'
Ejemplo n.º 4
0
 def change_lang_english(self):
     self.app.removeTranslator(default_translator)
     translator = QTranslator()
     translator.load('')
     self.app.installTranslator(translator)
     self.retranslateUi()
     self.lang = 'en'
Ejemplo n.º 5
0
class Translator(QObject):
    def __init__(self, app, engine, translations_path, languages):
        QObject.__init__(self)
        self._app = app
        self._engine = engine
        self._translations_path = translations_path
        self._translator = QTranslator()
        self._languages = self.sortByCode(languages)
        self._default_language_code = 'en'
        self.selectDefaultLanguage()

    def sortByCode(self, languages):
        return sorted(languages, key=lambda k: k['code'])

    def translationFilePath(self, index):
        file_suffix = self._languages[index]['code']
        file_name = f'language_{file_suffix}.qm'
        file_path = os.path.join(self._translations_path, file_name)
        if os.path.isfile(file_path):
            return file_path
        return None

    def systemLanguageCode(self):
        system_locale = QLocale.system().name()
        system_language_code = system_locale[0:2]
        return system_language_code

    def systemLanguageIndex(self):
        for index, language in enumerate(self._languages):
            if language['code'] == self.systemLanguageCode():
                return index
        return self.defaultLanguageIndex()

    def selectSystemLanguage(self):
        self.selectLanguage(self.systemLanguageIndex())

    @Slot(int)
    def selectLanguage(self, index):
        self._app.removeTranslator(self._translator)
        translation_file_path = self.translationFilePath(index)
        if translation_file_path is not None:
            self._translator.load(translation_file_path)
            self._app.installTranslator(self._translator)
        self._engine.retranslate()

    @Slot(result=str)
    def languagesAsXml(self):
        xml = dicttoxml(self._languages, attr_type=False)
        xml = xml.decode()
        return xml

    @Slot(result=int)
    def defaultLanguageIndex(self):
        for index, language in enumerate(self._languages):
            if language['code'] == self._default_language_code:
                return index
        return 0

    def selectDefaultLanguage(self):
        self.selectLanguage(self.defaultLanguageIndex())
Ejemplo n.º 6
0
Archivo: jal.py Proyecto: iliakan/jal
def main():
    sys.excepthook = exception_logger
    os.environ['QT_MAC_WANTS_LAYER'] = '1'    # Workaround for https://bugreports.qt.io/browse/QTBUG-87014

    own_path = os.path.dirname(os.path.realpath(__file__)) + os.sep
    error = init_and_check_db(own_path)

    if error.code == LedgerInitError.EmptyDbInitialized:  # If DB was just created from SQL - initialize it again
        error = init_and_check_db(own_path)

    app = QApplication([])
    language = get_language()
    translator = QTranslator(app)
    language_file = own_path + "languages" + os.sep + language + '.qm'
    translator.load(language_file)
    app.installTranslator(translator)

    if error.code == LedgerInitError.OutdatedDbSchema:
        error = update_db_schema(own_path)
        if error.code == LedgerInitError.DbInitSuccess:
            error = init_and_check_db(own_path)

    if error.code != LedgerInitError.DbInitSuccess:
        window = QMessageBox()
        window.setAttribute(Qt.WA_DeleteOnClose)
        window.setWindowTitle("JAL: Start-up aborted")
        window.setIcon(QMessageBox.Critical)
        window.setText(error.message)
        window.setInformativeText(error.details)
    else:
        window = MainWindow(own_path, language)
    window.show()

    app.exec_()
    app.removeTranslator(translator)
Ejemplo n.º 7
0
def run_GUI(argv):
    # Default material data path

    # Script to be used to test in dev
    a = QApplication(argv)

    # Set CSS
    # a.setStyleSheet("QLineEdit { background-color: yellow }")

    # Setup the translation
    translationFile = "pyleecan_fr.qm"
    translator = QTranslator()
    translator.load(translationFile, "GUI//i18n")
    a.installTranslator(translator)
    if isfile(config_dict["GUI"]["CSS_PATH"]):
        with open(config_dict["GUI"]["CSS_PATH"], "r") as css_file:
            a.setStyleSheet(css_file.read())

    # Load Material Library
    material_dict = load_matlib(machine=None,
                                matlib_path=config_dict["MAIN"]["MATLIB_DIR"])

    # MatLib widget
    mat_widget = DMatLib(material_dict=material_dict)

    # Machine Setup Widget
    c = DMachineSetup(material_dict=material_dict,
                      machine_path=config_dict["MAIN"]["MACHINE_DIR"])

    if EXT_GUI:
        # Setup extended GUI with sub windows
        icon = pixmap_dict["soft_icon"]
        window = SidebarWindow()
        window.setWindowIcon(QIcon(icon))

        update_step = lambda: c.set_nav(c.nav_step.currentRow())
        window.addSubWindow("Design", c, update_step)
        window.DesignWidget = c

        plt_widget = MachinePlotWidget(window)
        window.addSubWindow("Plot", plt_widget, plt_widget.update)

        mat_widget.installEventFilter(window)
        window.addSubWindow("MatLib", mat_widget,
                            mat_widget.update_treeview_material)

        tree = WTreeEdit(c.machine)
        tree_fcn = lambda: tree.update(getattr(c, "machine"))
        window.addSubWindow("TreeEdit", tree, tree_fcn)

        option = WGuiOption(machine_setup=c, matlib=mat_widget)
        window.addSubWindow("Option", option)
        window.show()

    else:
        # "Normal" GUI
        c.show()

    exit(a.exec_())
Ejemplo n.º 8
0
    def testUtf8(self):
        translator = QTranslator()
        translator.load(os.path.join(self.trdir, 'trans_russian.qm'))
        self.app.installTranslator(translator)

        obj = QObject()
        obj.setObjectName(obj.tr('Hello World!'))
        self.assertEqual(obj.objectName(), py3k.unicode_('привет мир!'))
Ejemplo n.º 9
0
    def testUtf8(self):
        translator = QTranslator()
        translator.load(os.path.join(self.trdir, 'trans_russian.qm'))
        self.app.installTranslator(translator)

        obj = QObject()
        obj.setObjectName(obj.tr('Hello World!'))
        self.assertEqual(obj.objectName(), py3k.unicode_('привет мир!'))
Ejemplo n.º 10
0
 def __init__(self, app, engine, translations_path, languages):
     QObject.__init__(self)
     self._app = app
     self._engine = engine
     self._translations_path = translations_path
     self._translator = QTranslator()
     self._languages = self.sortByCode(languages)
     self._default_language_code = 'en'
     self.selectDefaultLanguage()
Ejemplo n.º 11
0
def run_GUI(argv):
    # Default material data path

    # Script to be used to test in dev
    a = QApplication(argv)

    # Set CSS
    # a.setStyleSheet("QLineEdit { background-color: yellow }")

    # Setup the translation
    translationFile = "pyleecan_fr.qm"
    translator = QTranslator()
    translator.load(translationFile, "GUI//i18n")
    a.installTranslator(translator)
    if isfile(config_dict["GUI"]["CSS_PATH"]):
        with open(config_dict["GUI"]["CSS_PATH"], "r") as css_file:
            a.setStyleSheet(css_file.read())

    # Setting the material library
    matlib = MatLib(config_dict["MAIN"]["MATLIB_DIR"])

    # MatLib widget
    mat_widget = DMatLib(matlib, selected=0)

    # Machine Setup Widget
    c = DMachineSetup(dmatlib=mat_widget,
                      machine_path=config_dict["MAIN"]["MACHINE_DIR"])

    if EXT_GUI:
        # Setup extended GUI with sub windows
        icon = dirname(__file__) + "/GUI/Resources/images/icon/pyleecan_64.png"
        window = SidebarWindow()
        window.setWindowIcon(QIcon(icon))

        update_step = lambda: c.set_nav(c.nav_step.currentRow())
        window.addSubWindow("Design", c, update_step)
        window.DesignWidget = c

        plt_widget = MachinePlotWidget(window)
        window.addSubWindow("Plot", plt_widget, plt_widget.update)

        mat_widget.installEventFilter(window)
        window.addSubWindow("MatLib", mat_widget, mat_widget.update_list_mat)

        tree = TreeView()
        tree_fcn = lambda: tree.generate(getattr(c, "machine"))
        window.addSubWindow("TreeView", tree, tree_fcn)

        option = WGuiOption(machine_setup=c, matlib=matlib)
        window.addSubWindow("Option", option)
        window.show()

    else:
        # "Normal" GUI
        c.show()

    exit(a.exec_())
Ejemplo n.º 12
0
def languageDescription(translation):

    translator = QTranslator()
    translator.load(translation)

    locale = QLocale(translator.language())
    return QCoreApplication.translate("main", "{0} ({1})").format(
        locale.languageToString(locale.language()),
        locale.nativeLanguageName())
Ejemplo n.º 13
0
    def testLatin(self):
        #Set string value to Latin
        translator = QTranslator()
        translator.load(os.path.join(self.trdir, 'trans_latin.qm'))
        self.app.installTranslator(translator)

        obj = QObject()
        obj.setObjectName(obj.tr('Hello World!'))
        self.assertEqual(obj.objectName(), py3k.unicode_('Orbis, te saluto!'))
Ejemplo n.º 14
0
    def testLatin(self):
        #Set string value to Latin
        translator = QTranslator()
        translator.load(os.path.join(self.trdir, 'trans_latin.qm'))
        self.app.installTranslator(translator)

        obj = QObject()
        obj.setObjectName(obj.tr('Hello World!'))
        self.assertEqual(obj.objectName(), py3k.unicode_('Orbis, te saluto!'))
Ejemplo n.º 15
0
    def __init__(self, parent):

        self.__errorFound = False

        libPath = QLibraryInfo.location(QLibraryInfo.TranslationsPath)

        #
        # English
        #
        self.enBaseTranslator = QTranslator(parent)
        self.enBaseTranslator.load("qtbase_en", libPath)
        self.enTranslator = QTranslator(parent)
        self.enTranslator.load("ui_en", str(config.LOCALE) + "/en/LC_MESSAGES")

        #
        # Español
        #
        self.esBaseTranslator = QTranslator(parent)
        self.esBaseTranslator.load("qtbase_es", libPath)
        self.esTranslator = QTranslator(parent)
        self.esTranslator.load("ui_es", str(config.LOCALE) + "/es/LC_MESSAGES")

        self.trLast = None
        self.trBaseLast = None
        self.loadedTranslations = []
Ejemplo n.º 16
0
class Application(QApplication):
    known_lang = {
        'C': QApplication.translate('app', 'English'),
        'fr': QApplication.translate('app', 'French')
    }

    def __init__(self, argv):
        params = parse(sys.argv[1:])[0]
        super().__init__(argv)
        self.setOrganizationName('SBA')
        self.setApplicationName('QtImgren')
        if params.lang is None:
            settings = QSettings()
            lang = settings.value('MainWindow/lang')
            loc = QLocale() if lang is None else QLocale(lang)
        elif params.lang == 'native':
            loc = QLocale(None)
        else:
            loc = QLocale(params.lang)
        self.qt_trans = QTranslator()
        self.qt_trans.load(
            loc, 'qtbase', '_',
            QLibraryInfo.location(QLibraryInfo.TranslationsPath))
        self.installTranslator(self.qt_trans)
        self.translator = QTranslator()
        self.translator.load(loc, '', '', ':/lang', '')
        self.installTranslator(self.translator)
        self.setWindowIcon(QIcon(':/icon/app.ico'))
        self.main_window = MainWindow()

    def set_language(self, lang):
        self.removeTranslator(self.translator)
        self.removeTranslator(self.qt_trans)
        loc = QLocale(lang)
        self.qt_trans.load(
            loc, 'qt', '_',
            QLibraryInfo.location(QLibraryInfo.TranslationsPath))
        self.installTranslator(self.qt_trans)
        self.translator.load(loc, '', '', ':/lang', '')
        self.installTranslator(self.translator)

    def get_language(self):
        lang = self.translator.language()
        return 'C' if (lang is None or lang == '') else lang

    def get_languages(self):
        yield 'C', self.translate('app', 'English')
        for lang in QDir(':/lang').entryList():
            if lang in self.known_lang:
                name = self.translate('app', self.known_lang[lang])
            else:
                loc = QLocale(lang)
                name = loc.nativeLanguageName()
            yield lang, name
Ejemplo n.º 17
0
def start():
    app = QApplication(sys.argv)
    app.setOrganizationName('Quring')
    app.setOrganizationDomain('Quring')
    app.setApplicationName('Quring')

    qt_translator = QTranslator()
    qt_translator.load('qt_' + QLocale.system().name(),
                       QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qt_translator)

    main_window = MainWindow()
    logger.info('Showing main window')
    main_window.show()
    sys.exit(app.exec_())
Ejemplo n.º 18
0
def setup_locale():
    """Setups the locale machinery."""
    root_dir = os.path.join(os.path.dirname(sys.argv[0]))
    locales_dir = os.path.join(root_dir, "locale")
    # The gettext support requires the LANG environment variable even on win32.
    if sys.platform == "win32" and "LANG" not in os.environ:
        lang, enc = locale.getdefaultlocale()
        os.environ["LANG"] = lang
    locale.setlocale(locale.LC_ALL, "")
    gettext.install("messages", locales_dir)
    translator = QTranslator(QApplication.instance())
    if not translator.load(QLocale.system(), "qtbase_", directory=locales_dir):
        log.warning("Failed to load the QT locale data.")
    if not QApplication.instance().installTranslator(translator):
        log.warning("Failed to install the QT translator.")
Ejemplo n.º 19
0
    def __init__(self, bk, prefs):
        super().__init__()

        self.bk = bk
        self.prefs = prefs
        self.update = False

        # Install translator for the DOCXImport plugin dialog.
        # Use the Sigil language setting unless manually overridden.
        plugin_translator = QTranslator()
        if prefs['language_override'] is not None:
            print('Plugin preferences language override in effect')
            qmf = '{}_{}'.format(bk._w.plugin_name.lower(),
                                 prefs['language_override'])
        else:
            qmf = '{}_{}'.format(bk._w.plugin_name.lower(), bk.sigil_ui_lang)
        print(
            qmf,
            os.path.join(bk._w.plugin_dir, bk._w.plugin_name, 'translations'))
        plugin_translator.load(
            qmf,
            os.path.join(bk._w.plugin_dir, bk._w.plugin_name, 'translations'))
        print(QCoreApplication.instance().installTranslator(plugin_translator))

        self._ok_to_close = False

        self.FTYPE_MAP = {
            'smap': {
                'title': _translate('App', 'Select custom style-map file'),
                'defaultextension': '.txt',
                'filetypes': 'Text Files (*.txt);;All files (*.*)',
            },
            'css': {
                'title': _translate('App', 'Select custom CSS file'),
                'defaultextension': '.css',
                'filetypes': 'CSS Files (*.css)',
            },
            'docx': {
                'title': _translate('App', 'Select DOCX file'),
                'defaultextension': '.docx',
                'filetypes': 'DOCX Files (*.docx)',
            },
        }

        # Check online github files for newer version
        if self.prefs['check_for_updates']:
            self.update, self.newversion = self.check_for_update()
        self.initUI()
Ejemplo n.º 20
0
def main():
    logging.info("pyOffer version %s started at %s", version, datetime.now())
    locale_set = locale.setlocale(locale.LC_ALL, '')
    logging.info("System locale: %s", locale_set)
    app = QApplication(sys.argv)
    app.setOrganizationName("KonserwSoft")
    app.setApplicationName("pyOffer")

    lang = QLocale.system().name()[0:2]
    logging.info("Loading translation for: %s", lang)
    translator = QTranslator()
    if translator.load(f"translations/{lang}"):
        app.installTranslator(translator)
        logging.info("Loaded translations from: %s", f"translations/{lang}")
    else:
        logging.warning("Failed to load translations from: %s",
                        f"translations/{lang}")

    settings = QSettings()
    settings.beginGroup("database")
    host_name = settings.value("host_name", "127.0.0.1")
    port = int(settings.value("port", "5432"))
    database_name = settings.value("database_name", "koferta_test")
    user_name = settings.value("user_name", "postgres")
    password = settings.value("password", "docker")
    settings.endGroup()
    try:
        logging.info("DB host name: %s", host_name)
        logging.info("DB port: %s", port)
        logging.info("DB database name: %s", database_name)
        logging.info("DB user name: %s", user_name)
        database.connect(host_name, database_name, user_name, password, port)
    except RuntimeError as e:
        QMessageBox.critical(
            None, app.tr("Database connection failed"),
            app.tr(f"Driver error: {e.args[1]}\nDatabase error: {e.args[2]}"))
        return str(e)
    user_dialog = UserSelectionDialog.make()
    if user_dialog.exec_() == QDialog.Accepted:
        logging.debug("User dialog accepted")
        user = User.from_sql_record(user_dialog.chosen_user_record)
        logging.info("Chosen user: %s", user)
        main_window = MainWindow(user)
        main_window.show()
        return app.exec_()
    logging.info("User hasn't been chosen - exiting")
    return 0
Ejemplo n.º 21
0
def main():
    # app disexec теперь на pyqt
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    # Здесь будем работать со стилями(пока в разработке)
    #QApplication.setStyle(QStyleFactory.create("windowsvista"))

    # Русифицируем наше приложение
    translator = QTranslator()
    if (translator.load("qt_ru",
                        QLibraryInfo.location(QLibraryInfo.TranslationsPath))):
        app.installTranslator(translator)

    # Если всё хорошо запускаем приложение
    window = TreeCard(AllTables('database/objects'), 0)
    window.show()
    sys.exit(app.exec_())
Ejemplo n.º 22
0
def launch_qt_gui(bk, prefs):
    supports_theming = (bk.launcher_version() >= 20200117)
    if not ismacos:
        setup_highdpi(bk._w.highdpi)
    setup_ui_font(bk._w.uifont)
    if not ismacos and not iswindows:
        # Qt 5.10.1 on Linux resets the global font on first event loop tick.
        # So workaround it by setting the font once again in a timer.
        QTimer.singleShot(0, lambda: setup_ui_font(bk._w.uifont))

    app = QApplication(sys.argv)
    icon = os.path.join(bk._w.plugin_dir, bk._w.plugin_name, 'plugin.svg')
    app.setWindowIcon(QIcon(icon))

    if tuple_version(qVersion()) >= (5, 10, 0):
        app.setAttribute(Qt.AA_DisableWindowContextHelpButton)

    # Make plugin match Sigil's light/dark theme
    if supports_theming:
        if bk.colorMode() == "dark":
            app.setStyle(QStyleFactory.create("Fusion"))
            app.setPalette(dark_palette(bk.color))

    print('Application dir: {}'.format(QCoreApplication.applicationDirPath()))
    # Install qtbase translator for standard dialogs and such.
    # Use the Sigil language setting unless manually overridden.
    qt_translator = QTranslator()
    if prefs['language_override'] is not None:
        print('Plugin preferences language override in effect')
        qmf = 'qtbase_{}'.format(prefs['language_override'])
    else:
        qmf = 'qtbase_{}'.format(bk.sigil_ui_lang)
    # Get bundled or external translations directory
    qt_trans_dir = getQtTranslationsPath(bk._w.appdir)
    print('Qt translation dir: {}'.format(qt_trans_dir))
    print('Looking for {} in {}'.format(qmf, qt_trans_dir))
    qt_translator.load(qmf, qt_trans_dir)
    print('Translator succesfully installed: {}'.format(
        app.installTranslator(qt_translator)))

    ex = App(bk, prefs)
    ex.show()
    app.exec_()
    return _DETAILS
Ejemplo n.º 23
0
def run():

    translator = QTranslator()
    #translator.load(QLocale, 'csvtool', '_', './i18n')

    app = QApplication(sys.argv)

    main_window = MainWindow(app, translator)
    main_window.show()

    sys.exit(app.exec_())
Ejemplo n.º 24
0
def main():
    # app disexec теперь на pyqt
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    # Здесь будем работать со стилями(пока в разработке)
    #QApplication.setStyle(QStyleFactory.create("windowsvista"))

    # Русифицируем наше приложение
    translator = QTranslator()
    if (translator.load("qt_ru",
                        QLibraryInfo.location(QLibraryInfo.TranslationsPath))):
        app.installTranslator(translator)

    # Получим строку подключения к БД
    connection = {}

    # Если всё хорошо запускаем приложение
    window = TdisMainForm(connection)
    window.show()
    sys.exit(app.exec_())
Ejemplo n.º 25
0
def load_translations(app):
    """Load translations

    .. note:: Init ui/locale setting
    """
    # Load locale setting if exists
    # English is the default language
    app_settings = QSettings()
    locale_name = app_settings.value("ui/locale", "en")

    # site-packages/PySide2/Qt/translations
    lib_info = QLibraryInfo.location(QLibraryInfo.TranslationsPath)

    # Qt translations
    qt_translator = QTranslator(app)
    if qt_translator.load("qt_" + locale_name, directory=lib_info):
        app.installTranslator(qt_translator)

    # qtbase_translator = QTranslator(app)
    # if qtbase_translator.load("qtbase_" + locale_name, directory=lib_info):
    #     app.installTranslator(qtbase_translator)

    # App translations
    app_translator = QTranslator(app)
    if app_translator.load(locale_name, directory=cm.DIR_TRANSLATIONS):
        app.installTranslator(app_translator)
    else:
        # Init setting
        app_settings.setValue("ui/locale", "en")
Ejemplo n.º 26
0
def run():
    """Run the Gui."""
    os.environ["QT_QUICK_CONTROLS_CONF"] = ((
        CONF_DIR / "qtquickcontrols2.conf").resolve().as_posix())

    app = QApplication(sys.argv)

    lang = locale.getdefaultlocale()[0]
    lang_file_path = (
        (TRANSLATION_DIR /
         "jmbde_{lang}.qm".format(lang=lang)).resolve().as_posix())
    translator = QTranslator()
    translator.load(lang_file_path)
    app.installTranslator(translator)

    icon_file_path = (IMAGES_DIR / "jmbde.png").resolve().as_posix()
    app.setWindowIcon(QIcon(icon_file_path))

    main_window = MainWindow(app, translator)
    main_window.show()

    sys.exit(app.exec_())
Ejemplo n.º 27
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_())
Ejemplo n.º 28
0
 def __init__(self, argv):
     params = parse(sys.argv[1:])[0]
     super().__init__(argv)
     self.setOrganizationName('SBA')
     self.setApplicationName('QtImgren')
     if params.lang is None:
         settings = QSettings()
         lang = settings.value('MainWindow/lang')
         loc = QLocale() if lang is None else QLocale(lang)
     elif params.lang == 'native':
         loc = QLocale(None)
     else:
         loc = QLocale(params.lang)
     self.qt_trans = QTranslator()
     self.qt_trans.load(
         loc, 'qtbase', '_',
         QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(self.qt_trans)
     self.translator = QTranslator()
     self.translator.load(loc, '', '', ':/lang', '')
     self.installTranslator(self.translator)
     self.setWindowIcon(QIcon(':/icon/app.ico'))
     self.main_window = MainWindow()
Ejemplo n.º 29
0
    def __setup(self):
        self.__current_language = QLocale.system().name()
        self.__de_translator = QTranslator()

        self.translation_directory = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "crimpy", "languages"))

        self.__engine = QQmlApplicationEngine()
        self.__root_context = RootContext()
        self.__engine.rootContext().setContextProperty("main",
                                                       self.__root_context)
        qmlRegisterType(TwitterConnector, 'Twitter', major, minor,
                        'TwitterModel')
        self.__engine.load(QUrl.fromLocalFile(qml_file))
Ejemplo n.º 30
0
 def selectSystemTranslation(self, language, typemodule):
     dirsystem = "systemnet" if typemodule == True else "system"
     dirsyslan = QDir(self.mDir + QDir.separator() + dirsystem)
     if dirsyslan.exists():
         if QFileInfo(dirsyslan.path() + QDir.separator() + language +
                      ".qm").exists():
             translator = QTranslator(self)
             translator.load(dirsyslan.path() + QDir.separator() + language)
             self.mApp.installTranslator(translator)
         else:
             language = language.split('_')[0]
             if len(language) == 2:
                 if QFileInfo(dirsyslan.path() + QDir.separator() +
                              language + ".qm").exists():
                     translator = QTranslator(self)
                     translator.load(dirsyslan.path() + QDir.separator() +
                                     language)
                     self.mApp.installTranslator(translator)
Ejemplo n.º 31
0
def main():
    app = QGuiApplication(sys.argv)

    py_tranlator = QTranslator()
    res = py_tranlator.load(os.fspath(TRANSLATIONS_DIR / "py.qm"))
    assert res

    qml_tranlator = QTranslator()
    res = qml_tranlator.load(os.fspath(TRANSLATIONS_DIR / "qml.qm"))
    assert res

    # global_tranlator = QTranslator()
    # res = qml_tranlator.load(os.fspath(TRANSLATIONS_DIR / "global.qm"))
    # assert res

    python_model = PythonModel(app)

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("pythonModel", python_model)

    filename = os.fspath(QML_DIRECTORY / "main.qml")
    url = QUrl.fromLocalFile(filename)

    def handle_object_created(obj, obj_url):
        if obj is None and url == obj_url:
            QCoreApplication.exit(-1)

    engine.objectCreated.connect(handle_object_created, Qt.QueuedConnection)
    engine.load(url)

    ok = False

    def handle_timeout():
        nonlocal ok
        if ok:
            QCoreApplication.installTranslator(py_tranlator)
            QCoreApplication.installTranslator(qml_tranlator)
            # QCoreApplication.installTranslator(global_tranlator)
        else:
            QCoreApplication.removeTranslator(py_tranlator)
            QCoreApplication.removeTranslator(qml_tranlator)
            # QCoreApplication.removeTranslator(global_tranlator)

        engine.retranslate()

        ok = not ok

    timer = QTimer(interval=1000, timeout=handle_timeout)
    timer.start()

    sys.exit(app.exec_())
Ejemplo n.º 32
0
 def selectCoreTranslation(self, language, settings):
     settings.setValue("translate", "en")
     dircorelan = QDir(self.mDir + QDir.separator() + "corelocale")
     if dircorelan.exists():
         if QFileInfo(dircorelan.path() + QDir.separator() + language +
                      ".qm").exists():
             settings.setValue("translate", language)
             translator = QTranslator(self)
             translator.load(dircorelan.path() + QDir.separator() +
                             language)
             self.mApp.installTranslator(translator)
         else:
             language = language.split('_')[0]
             if len(language) == 2:
                 if QFileInfo(dircorelan.path() + QDir.separator() +
                              language + ".qm").exists():
                     settings.setValue("translate", language)
                     translator = QTranslator(self)
                     translator.load(dircorelan.path() + QDir.separator() +
                                     language)
                     self.mApp.installTranslator(translator)