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]
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]
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)
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])
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))
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
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
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.dirty = False self.setObjectName("MainWindow") self.resize(800, 600) self.setWindowTitle("GA") # TODO # TODO app_icon = get_icon('OpenFisca22.png') # self.setWindowIcon(app_icon) self.setLocale(QLocale(QLocale.French, QLocale.France)) self.setDockOptions(QMainWindow.AllowNestedDocks | QMainWindow.AllowTabbedDocks | QMainWindow.AnimatedDocks) self.centralwidget = QWidget(self) self.gridLayout = QGridLayout(self.centralwidget) self.setCentralWidget(self.centralwidget) self.centralwidget.hide() self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) # Showing splash screen pixmap = QPixmap(':/images/splash.png', 'png') self.splash = QSplashScreen(pixmap) font = self.splash.font() font.setPixelSize(10) self.splash.setFont(font) self.splash.show() self.splash.showMessage( "Initialisation...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # if CONF.get('main', 'current_version', '') != __version__: # CONF.set('main', 'current_version', __version__) # Execute here the actions to be performed only once after # each update (there is nothing there for now, but it could # be useful some day... self.start()
def report_abstract_model(model, view=None): # use ItemDelegate to style values style = lambda x: view.itemDelegate().displayText(x, QLocale()) # iterate only over visible columns of QTableView iter_columns = list( filter(lambda x: not view.isColumnHidden(x), range(model.columnCount()))) # If all columns are hidden if len(iter_columns) == 0: return content = ((style(model.data(model.index(row, col)), ) for col in iter_columns) for row in range(model.rowCount())) try: header = [ model.headerData(col, Qt.Horizontal, Qt.DisplayRole) for col in iter_columns ] except: header = None if header: content = chain([header], content) try: header_vertical = [ model.headerData(row, Qt.Vertical, Qt.DisplayRole) for row in range(model.rowCount()) ] header_vertical = [" "] + header_vertical content = chain( chain([header_vertical[rowi]], row) for rowi, row in enumerate(content)) has_vertical_header = True except: has_vertical_header = False return report_list(content, header_rows + bool(header), header_columns + has_vertical_header)
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
def main(argv): app = QApplication( argv) # Early so that QT is initialized before other imports app.setWindowIcon(resourceIcon("application/window_icon_cutout")) # 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 = """ ** WARNING: You are using a locale with decimalpoint: '{}' - 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 reccomended 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""".format( decimal_point) sys.stderr.write(msg) if len(argv) == 1: config_file = QFileDialog.getOpenFileName(None, "Open Configuration File") config_file = str(config_file) if len(config_file) == 0: print( "-----------------------------------------------------------------" ) print( "-- You must supply the name of configuration file as the first --" ) print( "-- commandline argument: --" ) print( "-- --" ) print( "-- bash% gert <config_file> --" ) print( "-- --" ) print( "-- If the configuration file does not exist, gert will create --" ) print( "-- create a new configuration file. --" ) print( "-----------------------------------------------------------------" ) sys.exit(1) else: config_file = argv[1] help_center = HelpCenter("ERT") help_center.setHelpMessageLink("welcome_to_ert") strict = True verbose = False verbose_var = os.getenv("ERT_VERBOSE", "False") lower_verbose_var = verbose_var.lower() if lower_verbose_var == "true": verbose = True if not os.path.exists(config_file): print("Trying to start new config") new_configuration_dialog = NewConfigurationDialog(config_file) success = new_configuration_dialog.exec_() if not success: print("Can not run without a configuration file.") sys.exit(1) else: config_file = new_configuration_dialog.getConfigurationPath() dbase_type = new_configuration_dialog.getDBaseType() num_realizations = new_configuration_dialog.getNumberOfRealizations( ) storage_path = new_configuration_dialog.getStoragePath() EnKFMain.createNewConfig(config_file, storage_path, dbase_type, num_realizations) strict = False if os.path.isdir(config_file): print("The specified configuration file is a directory!") sys.exit(1) splash = ErtSplash() splash.version = "Version %s" % ert_gui.__version__ splash.show() splash.repaint() now = time.time() res_config = ResConfig(config_file) os.chdir(res_config.config_path) ert = EnKFMain(res_config, strict=strict, verbose=verbose) ert_gui.configureErtNotifier(ert, config_file) window = GertMainWindow() window.setWidget(SimulationPanel()) plugin_handler = PluginHandler(ert, ert.getWorkflowList().getPluginJobs(), window) help_tool = HelpTool("ERT", window) window.addDock("Configuration Summary", SummaryPanel(), area=Qt.BottomDockWidgetArea) window.addTool(IdeTool(os.path.basename(config_file), help_tool)) window.addTool(PlotTool()) window.addTool(ExportTool()) window.addTool(WorkflowsTool()) window.addTool(ManageCasesTool()) window.addTool(PluginsTool(plugin_handler)) window.addTool(RunAnalysisTool()) window.addTool(LoadResultsTool()) window.addTool(help_tool) window.adjustSize() sleep_time = 2 - (time.time() - now) if sleep_time > 0: time.sleep(sleep_time) window.show() splash.finish(window) window.activateWindow() window.raise_() ResLog.log( 3, "Versions: ecl:%s res:%s ert:%s" % (ecl.__version__, res.__version__, ert_gui.__version__)) if not ert._real_enkf_main().have_observations(): em = QMessageBox.warning( window, "Warning!", "No observations loaded. Model update algorithms disabled!") finished_code = app.exec_() sys.exit(finished_code)
def getLanguage(self): locale_app = QLocale() locale_os = QLocale.system() info = [] var = QLocale.languageToString(locale_app.language()) return var
from PyQt4.QtGui import QRegExpValidator from PyQt4.QtCore import QDate, QRegExp, QLocale _FONT_ = QtGui.QFont('Ubuntu') _FONT_.setBold(True) # default file name prefix _XMLFILE_ = 'financeager_year_' from datetime import datetime _CURRENTMONTH_ = datetime.now().month - 1 # QDate is not affected by QLocale.setDefault() in main #_MONTHS_ = [unicode(QDate.longMonthName(m)) for m in range(1, 13)] locale = QLocale() _MONTHS_ = [unicode(locale.monthName(m)) for m in range(1, 13)] # default category names used to set up models at start _EXPCATEGORIES_ = ['Bars, Party', 'Groceries', 'Household', 'Restaurants', 'Travelling', 'Clothes', 'Miscellaneous' ] _RECCATEGORIES_ = [ 'Work', 'Gifts', 'Scholarships' ] _HEADERLABELS_ = ['Name', 'Value', 'Date'] # global validator to check user given dates _DATEVALIDATOR_ = QRegExpValidator(QRegExp('\d{1,2}\.')) def loadUi(modpath, widget): """
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.dirty = False self.isLoaded = False self.calibration_enabled = False self.aggregate_enabled = False self.setObjectName("MainWindow") self.resize(800, 600) self.setWindowTitle("OpenFisca") app_icon = get_icon('OpenFisca22.png') self.setWindowIcon(app_icon) self.setLocale(QLocale(QLocale.French, QLocale.France)) self.setDockOptions(QMainWindow.AllowNestedDocks | QMainWindow.AllowTabbedDocks | QMainWindow.AnimatedDocks) self.centralwidget = QWidget(self) self.gridLayout = QGridLayout(self.centralwidget) self.setCentralWidget(self.centralwidget) self.centralwidget.hide() self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) # Showing splash screen pixmap = QPixmap(':/images/splash.png', 'png') self.splash = QSplashScreen(pixmap) font = self.splash.font() font.setPixelSize(10) self.splash.setFont(font) self.splash.show() self.splash.showMessage( "Initialisation...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # if CONF.get('main', 'current_version', '') != __version__: # CONF.set('main', 'current_version', __version__) # Execute here the actions to be performed only once after # each update (there is nothing there for now, but it could # be useful some day... self.scenario = Scenario() # Preferences self.general_prefs = [SimConfigPage, PathConfigPage, CalConfigPage] self.oldXAXIS = 'sal' self.reforme = False self.apply_settings() # Dockwidgets creation self.splash.showMessage( "Creating widgets...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.create_dockwidgets() self.populate_mainwidow() ################################################################# ## Menu initialization ################################################################# self.splash.showMessage( "Creating menubar...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # Menu Fichier self.file_menu = self.menuBar().addMenu("Fichier") action_export_png = create_action(self, 'Exporter le graphique', icon='document-save png.png', triggered=self._graph.save_figure) action_export_csv = create_action(self, 'Exporter la table', icon='document-save csv.png', triggered=self._table.saveCsv) action_pref = create_action(self, u'Préférences', QKeySequence.Preferences, icon='preferences-desktop.png', triggered=self.edit_preferences) action_quit = create_action(self, 'Quitter', QKeySequence.Quit, icon='process-stop.png', triggered=SLOT('close()')) file_actions = [ action_export_png, action_export_csv, None, action_pref, None, action_quit ] add_actions(self.file_menu, file_actions) # Menu Edit self.edit_menu = self.menuBar().addMenu(u"Édition") action_copy = create_action(self, 'Copier', QKeySequence.Copy, triggered=self.global_callback, data='copy') edit_actions = [None, action_copy] add_actions(self.edit_menu, edit_actions) # Menu Simulation self.simulation_menu = self.menuBar().addMenu(u"Simulation") self.action_refresh_bareme = create_action( self, u'Calculer barèmes', shortcut='F9', icon='calculator_green.png', triggered=self.refresh_bareme) self.action_refresh_aggregate = create_action( self, u'Calculer aggrégats', shortcut='F10', icon='calculator_blue.png', triggered=self.refresh_aggregate) self.action_calibrate = create_action(self, u'Caler les poids', shortcut='CTRL+K', icon='scale22.png', triggered=self.calibrate) action_bareme = create_action(self, u'Barème', icon='bareme22.png', toggled=self.modeBareme) action_cas_type = create_action(self, u'Cas type', icon='castype22.png', toggled=self.modeCasType) action_mode_reforme = create_action( self, u'Réforme', icon='comparison22.png', toggled=self.modeReforme, tip= u"Différence entre la situation simulée et la situation actuelle") mode_group = QActionGroup(self) mode_group.addAction(action_bareme) mode_group.addAction(action_cas_type) self.mode = 'bareme' action_bareme.trigger() simulation_actions = [ self.action_refresh_bareme, self.action_refresh_aggregate, None, self.action_calibrate, None, action_bareme, action_cas_type, None, action_mode_reforme ] add_actions(self.simulation_menu, simulation_actions) # Menu Help help_menu = self.menuBar().addMenu("&Aide") action_about = create_action(self, u"&About OpenFisca", triggered=self.helpAbout) action_help = create_action(self, "&Aide", QKeySequence.HelpContents, triggered=self.helpHelp) help_actions = [action_about, action_help] add_actions(help_menu, help_actions) # Display Menu view_menu = self.createPopupMenu() view_menu.setTitle("&Affichage") self.menuBar().insertMenu(help_menu.menuAction(), view_menu) # Toolbar self.main_toolbar = self.create_toolbar(u"Barre d'outil", 'main_toolbar') toolbar_actions = [ action_export_png, action_export_csv, None, self.action_refresh_bareme, self.action_refresh_aggregate, None, self.action_calibrate, None, action_bareme, action_cas_type, None, action_mode_reforme ] add_actions(self.main_toolbar, toolbar_actions) self.connect(self._menage, SIGNAL('changed()'), self.changed_bareme) self.connect(self._parametres, SIGNAL('changed()'), self.changed_param) self.connect(self._aggregate_output, SIGNAL('calculated()'), self.calculated) self.connect(self, SIGNAL('weights_changed()'), self.refresh_aggregate) self.connect(self, SIGNAL('bareme_only()'), self.switch_bareme_only) # Window settings self.splash.showMessage( "Restoring settings...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) settings = QSettings() size = settings.value('MainWindow/Size', QVariant(QSize(800, 600))).toSize() self.resize(size) position = settings.value('MainWindow/Position', QVariant(QPoint(0, 0))).toPoint() self.move(position) self.restoreState(settings.value("MainWindow/State").toByteArray()) self.splash.showMessage( "Loading survey data...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.enable_aggregate(True) self.refresh_bareme() self.isLoaded = True self.splash.hide()
def main(): QLocale.setDefault(QLocale(QLocale.C)) app = QApplication(sys.argv) transit = TransitGUI() sys.exit(app.exec_())
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'volum_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) ## Create the dialog (after translation) and keep reference self.dlg = volumDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Volumator') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'volum') self.toolbar.setObjectName(u'volum') ##################################################################### INIT self.dlg.hCalc.setMaximum(100000.0) self.dlg.espac.setMinimum(0.1) #botao "BOTH" self.dlg.both.setChecked(True) # self.dlg.lineEdit.clear() # self.dlg.pushButton.clicked.connect(self.select_output_file) ##botao input self.dlg.input2.clear() self.dlg.botaoinput.clicked.connect(self.select_input_file) ##botao output self.dlg.outputTxt.clear() self.dlg.botaoOutput.clicked.connect(self.select_output_file) #botao minmax self.dlg.obMaxMin.clicked.connect(self.obtain_max_min) #botao ids self.dlg.obIDs.clicked.connect(self.obtain_ids) #botao clear self.dlg.clearAll.clicked.connect(self.clearFields) ###botao de seleciona CRS #31982 #32614 temp = QgsCoordinateReferenceSystem() # temp.createFromId(31982) temp.createFromId(32614) self.dlg.crsSel.setCrs(temp) # self.dlg.crsSel.setCrs(crsOrt) #muda seletor de CRS caso seja selecionado o orto self.dlg.defProjButton.clicked.connect(self.set_orto_crs) ## definição do "sobre" self.dlg.aboutDefProj.setOpenExternalLinks(True) #trocando virgula (argh) por ponto self.dlg.hCalc.setLocale(QLocale("UnitedStates")) #LANGUAGE self.dlg.hEquip.setLocale(QLocale("UnitedStates")) #LANGUAGE self.dlg.hBast.setLocale(QLocale("UnitedStates")) #LANGUAGE self.dlg.espac.setLocale(QLocale("UnitedStates")) #LANGUAGE self.dlg.hEquip.setValue(1.5) #hiding everithing that is not useful at the beggining #DO # self.dlg.hEquip.hide() ################################################################## # ####################### LINHAS A VIRAR COMENTARIO self.dlg.input2.setText(homedir+"/Documents/epsg32614.csv") #COMMENT self.dlg.outputTxt.setText(homedir+"/report.txt") #COMMENT