Example #1
0
    def __init__(self,parent,config):
        super(Newsfeed,self).__init__(parent)
        self.locale = config["locale"]
        QLocale.setDefault(self.locale)
        self.config = config
        self.all_head_lines = []
        self.timerFeed = QtCore.QTimer(self)
        self.timerNews = QtCore.QTimer(self)
        self.date_pub = QtWidgets.QLabel()
        self.title_pub = QtWidgets.QLabel()
        self.date_pub.setObjectName("datePub")
        self.title_pub.setObjectName("titlePub")
        self.layout = QtWidgets.QGridLayout(self)
        self.layout.addWidget(self.date_pub)
        self.layout.addWidget(self.title_pub)
        self.layout.setAlignment(Ressources.getAlignment("bottom_left"))
        self.setStyleSheet("""
                           #datePub,#titlePub {
                               color:white; 
                               padding: 6px;
                            } 
                            #titlePub {
                               font: bold 35px;
                            } 
                            #datePub {
                               font: 25px;
                            } 
                            """)



        self.connect(self.timerFeed,QtCore.SIGNAL('timeout()'),self.getNewsFedd)
        self.timerFeed.start(6*60*60*1000)
        self.getNewsFedd()      
Example #2
0
 def showNews(self):
     random_items = random.choices(population=self.all_head_lines, k=1)[0]
     date = parser.parse(random_items["date"])
     str_date = QLocale().toString(date) 
     self.date_pub.setText(str_date.capitalize())
     self.title_pub.setText(random_items["title"])
     print(random_items)
Example #3
0
    def __init__(self, parent, config):
        super(Clock, self).__init__(parent)
        self.locale = config["locale"]

        QLocale.setDefault(self.locale)
        self.curTime = QtWidgets.QLabel()
        self.curTime.setObjectName("curTime")
        curDate = QtWidgets.QLabel(QLocale().toString(
            QtCore.QDate.currentDate()).capitalize())
        curDate.setObjectName("curdate")
        self.layout = QtWidgets.QGridLayout(self)
        self.layout.addWidget(curDate)
        self.layout.addWidget(self.curTime)
        self.layout.setAlignment(Ressources.getAlignment(config["alignment"]))
        self.setStyleSheet("""
                           #curdate,#curTime {
                               color:white; 
                               font: bold 35px;
                               padding: 6px;
                            } 
                            """)
        self.curTime.setAlignment(Ressources.getAlignment("center"))
        timer = QtCore.QTimer(self)
        self.connect(timer, QtCore.SIGNAL('timeout()'), self.showTime)
        timer.start(1000)
        self.showTime()
Example #4
0
 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
Example #5
0
 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
Example #6
0
 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
Example #7
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())
Example #8
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     QLocale.setDefault(QLocale.English)
     self.__central_widget = None
     self.__menu_bar = None
     self.__status_bar = None
     self.__g_code_sender = GCodeSender()
     self.__init_central_widget()
     # self.__init_menu_bar_widget()
     layout = QVBoxLayout(self)
     layout.addWidget(self.__central_widget)
Example #9
0
    def createLanguageMenu(self):
        langPath = self.own_path + "languages" + os.sep

        langDirectory = QDir(langPath)
        for language_file in langDirectory.entryList(['*.qm']):
            language_code = language_file.split('.')[0]
            language = QLocale.languageToString(QLocale(language_code).language())
            language_icon = QIcon(langPath + language_code + '.png')
            action = QAction(language_icon, language, self)
            action.setCheckable(True)
            action.setData(language_code)
            self.menuLanguage.addAction(action)
            self.langGroup.addAction(action)
Example #10
0
 def onLanguageChanged(self, action):
     language_code = action.data()
     if language_code != self.currentLanguage:
         executeSQL(self.db,
                    "UPDATE settings "
                    "SET value=(SELECT id FROM languages WHERE language = :new_language) WHERE name ='Language'",
                    [(':new_language', language_code)])
         QMessageBox().information(self, g_tr('MainWindow', "Restart required"),
                                   g_tr('MainWindow', "Language was changed to ") +
                                   QLocale.languageToString(QLocale(language_code).language()) + "\n" +
                                   g_tr('MainWindow', "You should restart application to apply changes\n"
                                        "Application will be terminated now"),
                                   QMessageBox.Ok)
         self.close()
Example #11
0
 def onLanguageChanged(self, action):
     language_code = action.data()
     if language_code != self.currentLanguage:
         JalSettings().setValue('Language',
                                JalDB().get_language_id(language_code))
         QMessageBox().information(
             self, g_tr('MainWindow', "Restart required"),
             g_tr('MainWindow', "Language was changed to ") +
             QLocale.languageToString(QLocale(language_code).language()) +
             "\n" + g_tr(
                 'MainWindow',
                 "You should restart application to apply changes\n"
                 "Application will be terminated now"), QMessageBox.Ok)
         self.close()
Example #12
0
 def __init__(self, parent=None):
     QLocale.setDefault(QLocale.English)
     QMainWindow.__init__(self, parent)
     self.setWindowTitle("AMLab Software v1.0")
     self.supported_printers = ['DLP', 'Metal']
     self.selected_printer = self.supported_printers[0]
     self.__init_setup__()
     self.dlp_gui = None
     self.metal_gui = None
     # self.dlp_gui.hide()
     # self.metal_gui.hide()
     self.setup_widget.hide()
     self.__init_menu_bar__()
     if not self.__load_settings__():
         self.__select_setup_widget__()
Example #13
0
    def __init__(self, *args):
        super().__init__()

        self.setFixedSize(930, 631)
        self.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.setWindowTitle(
            QCoreApplication.translate("MainWindow", "PyInspect"))

        self.central_widget = QWidget(self)

        self.comboBox = QComboBox(self.central_widget)
        self.comboBox.setGeometry(QRect(10, 10, 451, 22))
        self.comboBox.setMouseTracking(False)
        self.comboBox.setMaxVisibleItems(5)
        self.comboBox.setObjectName("comboBox")

        for _backend in backend.registry.backends.keys():
            self.comboBox.addItem(_backend)

        self.tree_view = QTreeView(self.central_widget)
        self.tree_view.setGeometry(QRect(10, 40, 451, 581))
        self.tree_view.setColumnWidth(0, 150)

        self.comboBox.setCurrentText('uia')
        self.__show_tree()

        self.table_view = QTableView(self.central_widget)
        self.table_view.setGeometry(QRect(470, 40, 451, 581))

        self.comboBox.activated[str].connect(self.__show_tree)
        self.tree_view.clicked.connect(self.__show_property)
    def setupFilterLayout(self):
        filterLayout = QVBoxLayout(self)
        filterSettLayout = QHBoxLayout()

        self.filterBandChooser = QComboBox()
        self.filterTypeChooser = QComboBox()
        filterTypeLayout = QFormLayout()

        filterTypeLayout.addWidget(QLabel('Type'))
        filterTypeLayout.addWidget(self.filterBandChooser)
        bandTypes = {
            'Low Pass': '******',
            'Band Pass': '******',
            'High Pass': '******',
            'Band Stop': 'bandstop'
        }
        [self.filterBandChooser.addItem(i, bandTypes[i]) for i in bandTypes]
        self.filterBandChooser.setCurrentText('Band Pass')
        filterTypeLayout.addWidget(self.filterTypeChooser)
        filterTypes = {'Butter': 'butter', 'Bessel': 'bessel'}
        [
            self.filterTypeChooser.addItem(i, filterTypes[i])
            for i in filterTypes
        ]

        self.lowFreqEdit = QDoubleSpinBox()
        self.lowFreqEdit.setSuffix(' Hz')
        self.lowFreqEdit.setDecimals(1)
        self.lowFreqEdit.setRange(0.1, self.fs / 2 - 0.1)
        self.highFreqEdit = QDoubleSpinBox()
        self.highFreqEdit.setSuffix(' Hz')
        self.highFreqEdit.setDecimals(1)
        self.highFreqEdit.setLocale(
            QLocale(QLocale.Polish, QLocale.EuropeanUnion))
        self.highFreqEdit.setRange(0.1, self.fs / 2 - 0.1)
        self.filterBandChooser.currentTextChanged.connect(self.setFilterBand)
        filterFreqLayout = QFormLayout()
        filterFreqLayout.addRow(QLabel('Cutoff Frequencies'))
        filterFreqLayout.addRow('Low', self.lowFreqEdit)
        filterFreqLayout.addRow('High', self.highFreqEdit)

        filterOrdLayout = QFormLayout()
        self.filterOrdEdit = QSpinBox()
        self.filterOrdEdit.setMinimum(1)
        self.filterOrdEdit.setValue(5)
        filterOrdLayout.addRow(QLabel('Order'))
        filterOrdLayout.addRow(self.filterOrdEdit)

        filterSettLayout.addLayout(filterTypeLayout)
        filterSettLayout.addSpacing(10)
        filterSettLayout.addLayout(filterFreqLayout)
        filterSettLayout.addSpacing(10)
        filterSettLayout.addLayout(filterOrdLayout)

        btn = QPushButton('Show filter response')
        btn.clicked.connect(self.showFilterResponse)

        filterLayout.addLayout(filterSettLayout)
        filterLayout.addWidget(btn, 0, Qt.AlignRight)
Example #15
0
    def __init__(self, parent=None, cutoff_value=0.01, limit_type="percent"):
        super().__init__(parent)
        self.cutoff_value = cutoff_value
        self.limit_type = limit_type

        locale = QLocale(QLocale.English, QLocale.UnitedStates)
        locale.setNumberOptions(QLocale.RejectGroupSeparator)
        self.validators = Types(QDoubleValidator(0.001, 100.0, 1, self),
                                QIntValidator(0, 50, self))
        self.validators.relative.setLocale(locale)
        self.validators.topx.setLocale(locale)
        self.buttons = Types(QRadioButton("Relative"), QRadioButton("Top #"))
        self.buttons.relative.setChecked(True)
        self.buttons.relative.setToolTip(
            "This cut-off type shows the selected top percentage of contributions (for example the \
top 10% contributors)")
        self.buttons.topx.setToolTip(
            "This cut-off type shows the selected top number of contributions (for example the top \
5 contributors)")
        self.button_group = QButtonGroup()
        self.button_group.addButton(self.buttons.relative, 0)
        self.button_group.addButton(self.buttons.topx, 1)
        self.sliders = Types(LogarithmicSlider(self),
                             QSlider(Qt.Horizontal, self))
        self.sliders.relative.setToolTip(
            "This slider sets the selected percentage of contributions\
 to be shown")
        self.sliders.topx.setToolTip(
            "This slider sets the selected number of contributions to be \
shown")
        self.units = Types("% of total", "top #")
        self.labels = Labels(QLabel(), QLabel(), QLabel())
        self.cutoff_slider_line = QLineEdit()
        self.cutoff_slider_line.setToolTip(
            "This box can set a precise cut-off value for the \
contributions to be shown")
        self.cutoff_slider_line.setLocale(locale)
        self.cutoff_slider_lft_btn = QPushButton("<")
        self.cutoff_slider_lft_btn.setToolTip(
            "This button moves the cut-off value one increment")
        self.cutoff_slider_rght_btn = QPushButton(">")
        self.cutoff_slider_rght_btn.setToolTip(
            "This button moves the cut-off value one increment")

        self.make_layout()
        self.connect_signals()
Example #16
0
 def validate(self, inputString: str, pos: int) -> QValidator.State:
     self.__numValidator.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
     inputString = inputString.strip(' ')
     stringList: List[str] = inputString.split(' ')
     for string in stringList:
         if self.__numValidator.validate(string, 0)[0] == QValidator.Invalid:
             return QValidator.Invalid
     return QValidator.Acceptable
Example #17
0
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"]
Example #18
0
 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)
Example #19
0
    def __init__(self,
                 title: str = '',
                 value: float = 0,
                 min_value: float = 0,
                 max_value: float = 100,
                 displayed_value_factor: float = 1,
                 parent: QWidget = None):
        super().__init__(parent)

        self._value = value
        self._min_value = min_value
        self._max_value = max_value
        self._displayed_value_factor = displayed_value_factor

        self._title_label = QLabel(title)

        self._color = DEFAULT_BAR_COLOR

        self._locale = QLocale(QLocale.English)
        self._locale.setNumberOptions(self._locale.numberOptions()
                                      | QLocale.RejectGroupSeparator)

        validator = QDoubleValidator(self._min_value, self._max_value, 2)
        validator.setNotation(QDoubleValidator.StandardNotation)
        validator.setLocale(self._locale)

        self._value_line_edit = SliderValueLineEdit()
        self._value_line_edit.setValidator(validator)
        max_label_width = self._value_line_edit.fontMetrics().width(
            self._value_to_str(self.max_value))
        self._value_line_edit.setFixedWidth(6 + max_label_width)
        self._value_line_edit.editingFinished.connect(
            self._on_value_line_edit_editing_finished)

        h_layout = QHBoxLayout(self)
        h_layout.setContentsMargins(4, 0, 4, 0)
        # h_layout.setSpacing(0)

        h_layout.addWidget(self._title_label, 0, Qt.AlignLeft)
        h_layout.addWidget(self._value_line_edit, 0, Qt.AlignRight)

        self._update_value_line_edit()
Example #20
0
 def __init__(self, objname, parent=None):
     QObjectListModel.__init__(self, parent)
     self.setObjectName(str(objname))
     self.m_locale = QLocale("es")  #temp, auto changue when login
     #self.m_proxy = ProxyModelJson()
     self.m_order = ""
     self.boolMetadata = False
     self.m_fields = QJsonArray()  #[]#QJsonArray
     self.m_fieldsPoint = []  #5.2up
     self.m_maxLimit = 100
     self.m_domain = QJsonArray()  #[]#QJsonArray
     self.m_orderTryton = QJsonArray()  #[]#QJsonArray
     self.m_preferences = {}
     self.m_qjsonnetwork = QJsonNetwork()
     self.m_fieldsFormatDecimal = []  #QJsonArray
     self.m_fieldsFormatDateTime = []  #QJsonArray
     self.m_model_method_search = ""
     self.m_hasIndexOfId = {}
     self.m_engine = None  #QQmlApplicationEngine()
     self.autoBusy = True
     self.boolSynchro = True  # add synchronous call (calldirect), best performance!
    def setupUi(self, Dialog):
        if not Dialog.objectName():
            Dialog.setObjectName(u"Dialog")
        Dialog.resize(320, 260)
        self.buttonBox = QDialogButtonBox(Dialog)
        self.buttonBox.setObjectName(u"buttonBox")
        self.buttonBox.setGeometry(QRect(20, 210, 280, 30))
        self.buttonBox.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Save)
        self.edit_row_line = QLineEdit(Dialog)
        self.edit_row_line.setObjectName(u"edit_row_line")
        self.edit_row_line.setEnabled(False)
        self.edit_row_line.setGeometry(QRect(20, 20, 100, 30))
        self.edit_row_line.setAlignment(Qt.AlignCenter)
        self.edit_row_value = QLineEdit(Dialog)
        self.edit_row_value.setObjectName(u"edit_row_value")
        self.edit_row_value.setEnabled(False)
        self.edit_row_value.setGeometry(QRect(140, 20, 160, 30))
        self.edit_column_line = QLineEdit(Dialog)
        self.edit_column_line.setObjectName(u"edit_column_line")
        self.edit_column_line.setEnabled(False)
        self.edit_column_line.setGeometry(QRect(20, 60, 100, 30))
        self.edit_column_line.setAlignment(Qt.AlignCenter)
        self.edit_column_value = QLineEdit(Dialog)
        self.edit_column_value.setObjectName(u"edit_column_value")
        self.edit_column_value.setEnabled(False)
        self.edit_column_value.setGeometry(QRect(140, 60, 160, 30))
        self.edit_x_line = QLineEdit(Dialog)
        self.edit_x_line.setObjectName(u"edit_x_line")
        self.edit_x_line.setEnabled(False)
        self.edit_x_line.setGeometry(QRect(20, 100, 100, 30))
        self.edit_x_line.setAlignment(Qt.AlignCenter)
        self.edit_x_value = QLineEdit(Dialog)
        self.edit_x_value.setObjectName(u"edit_x_value")
        self.edit_x_value.setGeometry(QRect(140, 100, 160, 30))
        self.edit_y_line = QLineEdit(Dialog)
        self.edit_y_line.setObjectName(u"edit_y_line")
        self.edit_y_line.setEnabled(False)
        self.edit_y_line.setGeometry(QRect(20, 140, 100, 30))
        self.edit_y_line.setAlignment(Qt.AlignCenter)
        self.edit_y_value = QLineEdit(Dialog)
        self.edit_y_value.setObjectName(u"edit_y_value")
        self.edit_y_value.setGeometry(QRect(140, 140, 160, 30))

        self.retranslateUi(Dialog)
        # self.buttonBox.accepted.connect(Dialog.accept)
        # self.buttonBox.rejected.connect(Dialog.reject)

        QMetaObject.connectSlotsByName(Dialog)
Example #22
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))
Example #23
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()
    def accept(self):

        surfType = []
        radius = []
        thick = []
        semid = []
        matcat = []
        matref = []

        lo = QLocale()

        X = self.form.Xpos.value()
        Y = self.form.Ypos.value()
        Z = self.form.Zpos.value()
        Xrot = self.form.Xrot.value()
        Yrot = self.form.Yrot.value()
        Zrot = self.form.Zrot.value()

        for r in range(self.form.surfTable.rowCount()):
            surfType.append(self.form.surfTable.item(r, 0).text())
            radius.append(lo.toFloat(self.form.surfTable.item(r, 1).text())[0])
            thick.append(lo.toFloat(self.form.surfTable.item(r, 2).text())[0])
            semid.append(lo.toFloat(self.form.surfTable.item(r, 3).text())[0])
            matcat.append(self.form.surfTable.item(r, 4).text())
            matref.append(self.form.surfTable.item(r, 5).text())

        datalist = (surfType, radius, thick, semid, matcat, matref)

        obj = InsertLD(datalist, ID="L")
        m = FreeCAD.Matrix()
        m.rotateX(radians(Xrot))
        m.rotateY(radians(Yrot))
        m.rotateZ(radians(Zrot))
        m.move((X, Y, Z))
        p1 = FreeCAD.Placement(m)
        obj.Placement = p1
        FreeCADGui.Control.closeDialog()
Example #25
0
    def testMimeTypeForName(self):
        db = QMimeDatabase()

        s0 = db.mimeTypeForName("application/x-zerosize")
        self.assertTrue(s0.isValid())
        self.assertEqual(s0.name(), "application/x-zerosize")
        if "en" in QLocale().name():
            self.assertEqual(s0.comment(), "empty document")

        s0Again = db.mimeTypeForName("application/x-zerosize")
        self.assertEqual(s0Again.name(), s0.name())

        s1 = db.mimeTypeForName("text/plain")
        self.assertTrue(s1.isValid())
        self.assertEqual(s1.name(), "text/plain")

        krita = db.mimeTypeForName("application/x-krita")
        self.assertTrue(krita.isValid())

        rdf = db.mimeTypeForName("application/rdf+xml")
        self.assertTrue(rdf.isValid())
        self.assertEqual(rdf.name(), "application/rdf+xml")
        if "en" in QLocale().name():
            self.assertEqual(rdf.comment(), "RDF file")

        bzip2 = db.mimeTypeForName("application/x-bzip2")
        self.assertTrue(bzip2.isValid())
        if "en" in QLocale().name():
            self.assertEqual(bzip2.comment(), "Bzip archive")

        defaultMime = db.mimeTypeForName("application/octet-stream")
        self.assertTrue(defaultMime.isValid())
        self.assertEqual(defaultMime.name(), "application/octet-stream")
        self.assertTrue(defaultMime.isDefault())

        doesNotExist = db.mimeTypeForName("foobar/x-doesnot-exist")
        self.assertTrue(not doesNotExist.isValid())
Example #26
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.")
Example #27
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_())
Example #28
0
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
Example #29
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
Example #30
0
    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)
Example #31
0
 def testToNumberShort(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((ctypes.c_short(37).value, True),
                      obj.toShort('37'))
Example #32
0
 def testToNumberInt(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((37, True), obj.toInt('37'))
Example #33
0
 def testToNumberFloat(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((ctypes.c_float(37.109).value, True),
                      obj.toFloat('37.109'))
Example #34
0
 def testToNumberULongLongNegative(self):
     obj = QLocale(QLocale.C)
     self.assert_(not obj.toULongLong('-37')[1])
Example #35
0
 def testToNumberDouble(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((ctypes.c_double(37.109).value, True),
                      obj.toDouble('37.109'))
Example #36
0
 def testToNumberULongLong(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((ctypes.c_ulonglong(37).value, True),
                      obj.toULongLong('37'))