def calendarShortNamesMonths(self, language=""): if language == "": language = QLocale.system().name() myLocale = QLocale(language) lista = QJsonArray() for i in range(1, 13): lista.append(myLocale.monthName(i, QLocale.ShortFormat)) return lista
def calendarLongNamesDays(self, language=""): if language == "": language = QLocale.system().name() myLocale = QLocale(language) lista = QJsonArray() for i in range(1, 8): lista.append(myLocale.dayName(i, QLocale.LongFormat)) return lista
def select_message_from_choices(choices): locale_name = QLocale.system().name() if locale_name in choices: return choices[locale_name] if "_" in locale_name: lang, country = locale_name.split("_") if lang in choices: return choices[lang] return choices["default"]
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))
def getInitialLanguage(): try: import sys frozen = getattr(sys, 'frozen', '') if frozen and frozen in 'macosx_app': from PySide2.QtCore import QLocale initialLanguage = QLocale.system().uiLanguages()[0].split('-')[0] else: import locale initialLanguage = locale.getdefaultlocale()[0].split("_")[0] if initialLanguage not in messages: initialLanguage = constants.FALLBACK_INITIAL_LANGUAGE except: initialLanguage = constants.FALLBACK_INITIAL_LANGUAGE return initialLanguage
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_())
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.")
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
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_())
def __init__(self, app=None): super().__init__() self.app = app self.lang = QLocale.system().name() self.sound_thread = None self.shutdown_job = False self.running_record = [] # 更完备的任务记录信息 # 结构是 [{},{}] running_record = get_json_value('timer.json', 'running_record') if not running_record: running_record = [] self.running_record = running_record self.current_countup_task_info = {} # 'task_name', 'start_time', 'last_time', 'end_time', 'status' self.current_countdown_task_info = {} self.time = 0 self.timeInterval = 1000 # = 1s self.timerUp = QTimer() self.timerUp.setInterval(self.timeInterval) self.timerUp.timeout.connect(self.updateUptime) self.timerDown = QTimer() self.timerDown.setInterval(self.timeInterval) self.timerDown.timeout.connect(self.updateDowntime) self.timerAutoSave = QTimer() self.timerAutoSave.setInterval(AUTOSAVE_INTERVAL * 1000) self.timerAutoSave.timeout.connect(self.auto_save_running_record) self.timerAutoSave.start() self.initUi() self.timeout.connect(self.beep)
def startNexT(cfgfile, active, execScripts, execCode, withGui): """ Starts next with the given config file and activates the given application. :param cfgfile: path to config file :param active: active application (if None, the first application in the config will be used) :return: None """ logger.debug("Starting nexxT...") config = Configuration() lcl = QLocale.system() lcl.setNumberOptions(QLocale.c().numberOptions()) QLocale.setDefault(lcl) if withGui: app = QApplication() if QApplication.instance() is None else QApplication.instance() app.setWindowIcon(QIcon(":icons/nexxT.svg")) app.setOrganizationName("nexxT") app.setApplicationName("nexxT") setupGuiServices(config) else: app = QCoreApplication() if QCoreApplication.instance() is None else QCoreApplication.instance() app.setOrganizationName("nexxT") app.setApplicationName("nexxT") setupConsoleServices(config) if cfgfile is not None: ConfigFileLoader.load(config, cfgfile) if withGui: mainWindow = Services.getService("MainWindow") mainWindow.restoreState() mainWindow.show() # the reference will still be held by the service, but here we don't need it anymore del mainWindow if active is not None: config.activate(active) # pylint: disable=unused-variable # need to hold the reference of this until the method is called i2 = MethodInvoker(dict(object=Application, method="initialize", thread=app.thread()), MethodInvoker.IDLE_TASK) # pylint: disable=unused-variable waitForSignal(config.appActivated) if Application.activeApplication.getState() != FilterState.ACTIVE: waitForSignal(Application.activeApplication.stateChanged, lambda s: s == FilterState.ACTIVE) logger.info("done") def cleanup(): logger.debug("cleaning up loaded services") Services.removeAll() logger.debug("cleaning up loaded plugins") for v in ("last_traceback", "last_type", "last_value"): if hasattr(sys, v): del sys.__dict__[v] #PluginManager.singleton().unloadAll() logger.debug("cleaning up complete") code_globals = {} for c in execCode: logger.info("Executing code '%s'", c) # note that exec is used intentionally here to provide the user with scripting posibilities exec(compile(c, "<string>", 'exec'), code_globals) # pylint: disable=exec-used logger.debug("Executing code done") for s in execScripts: logger.info("Executing script '%s'", s) with open(s) as fscript: # note that exec is used intentionally here to provide the user with scripting possibilities exec(compile(fscript.read(), s, 'exec'), code_globals) # pylint: disable=exec-used logger.debug("Executing script done") res = app.exec_() logger.debug("closing config") config.close() cleanup() logger.internal("app.exec_ returned") return res
engine.rootContext().setContextProperty("QJsonNetworkQml", jchc) engine.rootContext().setContextProperty("ModelManagerQml", modelmanager) engine.rootContext().setContextProperty("SystemNet", systemnet) engine.rootContext().setContextProperty("ThesaVersion", ThesaVersion) engine.rootContext().setContextProperty("Tools", mtools) engine.rootContext().setContextProperty("DirParent", mDir) engine.rootContext().setContextProperty("ObjectMessageLast", mObjMsg) settings = QSettings() defaultLocale = settings.value("translate", "") if defaultLocale=="": defaultLocale = QLocale.system().name() mtools.selectCoreTranslation(defaultLocale, settings) engine.addImportPath(mDir + QDir.separator() + "tools") #engine.load(QUrl("qrc:/main.qml")) engine.load(QUrl.fromLocalFile('main.qml')) if not engine.rootObjects(): msgBox = QMessageBox() msgBox.setText("Error rootObjects") msgBox.exec_() sys.exit(-1) sys.exit(app.exec_())
def __init__(self): super(QSpeak, self).__init__() self.setLocale(QLocale.system()) self.setRate(0.0) self.setVolume(0.0) self.setPitch(0.0)
import sys from PySide2.QtWidgets import QApplication from PySide2.QtCore import QTranslator, QLocale, QLibraryInfo from gui import Window if __name__ == '__main__': app = QApplication(sys.argv) traductor = QTranslator() traductor.load("qtbase_" + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(traductor) win = Window() win.parent = app win.show() sys.exit(app.exec_())
def systemLanguageCode(self): system_locale = QLocale.system().name() system_language_code = system_locale[0:2] return system_language_code
def fedit(data ,result = "list" ,type = "form" ,title = "" ,comment = "" ,icon = None ,parent = None ,apply = None ,ok = True ,cancel = True ,outfile = None ,scrollbar = False ,background_color = None ,widget_color = None # DJB added ,size = None ,position = None ,style = None ): """ Create form dialog and return result (if Cancel button is pressed, return None) :param tuple data : datalist, datagroup (see below) :param str title : form title :param str comment : header comment :param QIcon icon : dialog box icon :param QWidget parent : parent widget :param str ok : customized ok button label :param str cancel : customized cancel button label :param tuple apply : (label, function) customized button label and callback :param function apply : function taking two arguments (result, widgets) :param str result : result serialization ('list', 'dict', 'OrderedDict','JSON' or 'XML') :param str outfile : write result to the file outfile.[py|json|xml] :param str type : layout type ('form' or 'questions') :param bool scrollbar : vertical scrollbar :param str background_color : color of the background :param str widget_color : color of the widgets :return: Serialized result (data type depends on `result` parameter) datalist: list/tuple of (field_name, field_value) datagroup: list/tuple of (datalist *or* datagroup, title, comment) Tips: * one field for each member of a datalist * one tab for each member of a top-level datagroup * one page (of a multipage widget, each page can be selected with a combo box) for each member of a datagroup inside a datagroup Supported types for field_value: - int, float, str, unicode, bool - colors: in Qt-compatible text form, i.e. in hex format or name (red,...) (automatically detected from a string) - list/tuple: * the first element will be the selected index (or value) * the other elements can be couples (key, value) or only values """ # Create a QApplication instance if no instance currently exists # (e.g. if the module is used directly from the interpreter) test_travis = os.environ.get('TEST_CI_WIDGETS', None) if test_travis is not None: app = QApplication.instance() if app is None: app = QApplication([]) timer = QTimer(app) timer.timeout.connect(app.quit) timer.start(1000) elif QApplication.startingUp(): _app = QApplication([]) translator_qt = QTranslator() translator_qt.load('qt_' + QLocale.system().name(),QLibraryInfo.location(QLibraryInfo.TranslationsPath)) _app.installTranslator(translator_qt) serial = ['list', 'dict', 'OrderedDict', 'JSON', 'XML'] if result not in serial: print(f"Warning: '{result}' not in {', '.join(serial)}, default to list", file=sys.stderr) result = 'list' layouts = ['form', 'questions'] if type not in layouts: print(f"Warning: '{type}' not in {', '.join(layouts)}, default to form", file=sys.stderr) type = 'form' dialog = FormDialog(data, title, comment, icon, parent, apply, ok, cancel, result, outfile, type, scrollbar, background_color, widget_color) # djb added if size is not None: dialog.resize(size[0],size[1]) if position is not None: dialog.move(position[0],position[1]) if style is not None: dialog.setStyleSheet(style) if dialog.exec_(): return dialog.get()
parser.addOption(languageListOption) parser.addOption(languageOption) parser.addPositionalArgument("files", "Documents to open.", "[files...]") parser.process(app) # Command line: Language list if parser.isSet(languageListOption): sys.exit(showLanguageList()) # Command line: Language language = parser.value(languageOption) # # Translations locale = QLocale(language) if language else QLocale.system() translator = QTranslator() if translator.load(locale, None, None, ":/translations"): app.installTranslator(translator) translatorQtBase = QTranslator() if translatorQtBase.load( locale, "qtbase", "_", QLibraryInfo.location(QLibraryInfo.TranslationsPath)): app.installTranslator(translatorQtBase) window = MainWindow() fileNames = parser.positionalArguments() for fileName in fileNames: window.openDocument(fileName)