def data(self, index, role): source_index = self.mapToSource(index) source_data = self.sourceModel().data(source_index, role) expiration_col = self.sourceModel().columns_ids.index('expiration') expiration_index = self.sourceModel().index(source_index.row(), expiration_col) expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole) current_time = QDateTime().currentDateTime().toMSecsSinceEpoch() sig_validity = self.community.parameters['sigValidity'] warning_expiration_time = int(sig_validity / 3) #logging.debug("{0} > {1}".format(current_time, expiration_data)) if expiration_data is not None: will_expire_soon = (current_time > expiration_data*1000 - warning_expiration_time*1000) if role == Qt.DisplayRole: if source_index.column() == self.sourceModel().columns_ids.index('renewed') \ or source_index.column() == self.sourceModel().columns_ids.index('expiration'): if source_data is not None: return QLocale.toString( QLocale(), QDateTime.fromTime_t(source_data).date(), QLocale.dateFormat(QLocale(), QLocale.ShortFormat) ) else: return "" if source_index.column() == self.sourceModel().columns_ids.index('pubkey'): return "pub:{0}".format(source_data[:5]) if role == Qt.ForegroundRole: if expiration_data: if will_expire_soon: return QColor(Qt.red) else: return QColor(Qt.blue) return source_data
def expand(cls, language): """ Class method to expand a language enum to a readable languages list. @param language language number (QLocale.Language) @return list of expanded language names (list of strings) """ allLanguages = [] countries = [l.country() for l in QLocale.matchingLocales( language, QLocale.AnyScript, QLocale.AnyCountry)] languageString = "{0} [{1}]"\ .format(QLocale.languageToString(language), QLocale(language).name().split('_')[0]) allLanguages.append(languageString) for country in countries: languageString = "{0}/{1} [{2}]"\ .format(QLocale.languageToString(language), QLocale.countryToString(country), '-'.join(QLocale(language, country).name() .split('_')).lower()) if languageString not in allLanguages: allLanguages.append(languageString) return allLanguages
def setUp(self): self.setUpQuamash() QLocale.setDefault(QLocale("en_GB")) self.identities_registry = IdentitiesRegistry({}) self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False self.endpoint = BMAEndpoint(PyBMAEndpoint("", "127.0.0.1", "", 50000)) self.node = Node("test_currency", [self.endpoint], "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", nice_blockchain.bma_blockchain_current, Node.ONLINE, time.time(), {}, "ucoin", "0.14.0", 0) self.network = Network.create(self.node) self.bma_access = BmaAccess.create(self.network) self.community = Community("test_currency", self.network, self.bma_access) self.wallet = Wallet(0, "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", "Wallet 1", self.identities_registry) self.wallet.init_cache(self.application, self.community) # Salt/password : "******" # Pubkey : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ self.account = Account("testsakia", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", "john", [self.community], [self.wallet], [], self.identities_registry)
def parseTemplate(cls, searchTerm, searchTemplate): """ Class method to parse a search template. @param searchTerm term to search for (string) @param searchTemplate template to be parsed (string) @return parsed template (string) """ locale = QLocale(Preferences.getHelp("SearchLanguage")) language = locale.name().split("_")[0] country = language.lower() result = searchTemplate result = result.replace("{count}", "20") result = result.replace("{startIndex}", "0") result = result.replace("{startPage}", "0") result = result.replace("{language}", language) result = result.replace("{country}", country) result = result.replace("{inputEncoding}", "UTF-8") result = result.replace("{outputEncoding}", "UTF-8") result = result.replace( "{searchTerms}", bytes(QUrl.toPercentEncoding(searchTerm)).decode()) result = re.sub(r"""\{([^\}]*:|)source\??\}""", Program, result) return result
def __init__(self, parent, dict, persepolis_setting): super().__init__(persepolis_setting) self.persepolis_setting = persepolis_setting self.dict = dict self.parent = parent # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # connecting buttons self.open_pushButtun.clicked.connect(self.openFile) self.open_folder_pushButtun.clicked.connect(self.openFolder) self.ok_pushButton.clicked.connect(self.okButtonPressed) # labels # find gid gid = self.dict['gid'] # get file_path from data base self.add_link_dict = self.parent.persepolis_db.searchGidInAddLinkTable(gid) file_path = self.add_link_dict['download_path'] # save_as self.save_as_lineEdit.setText(file_path) self.save_as_lineEdit.setToolTip(file_path) # link link = str(self.dict['link']) self.link_lineEdit.setText(link) self.link_lineEdit.setToolTip(link) # file_name window_title = str(self.dict['file_name']) file_name = QCoreApplication.translate("after_download_src_ui_tr", "<b>File name</b>: ") + \ window_title self.setWindowTitle(window_title) self.file_name_label.setText(file_name) # size size = QCoreApplication.translate("after_download_src_ui_tr", "<b>Size</b>: ") + str(self.dict['size']) self.size_label.setText(size) # disable link_lineEdit and save_as_lineEdit self.link_lineEdit.setEnabled(False) self.save_as_lineEdit.setEnabled(False) # set window size and position size = self.persepolis_setting.value( 'AfterDownloadWindow/size', QSize(570, 290)) position = self.persepolis_setting.value( 'AfterDownloadWindow/position', QPoint(300, 300)) self.resize(size) self.move(position)
def setUp(self): self.setUpQuamash() QLocale.setDefault(QLocale("en_GB")) self.identities_registry = IdentitiesRegistry() self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False self.mock_nice_blockchain = nice_blockchain.get_mock(self.lp) self.node = Node(self.mock_nice_blockchain.peer(), "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", None, Node.ONLINE, time.time(), {}, "ucoin", "0.14.0", 0) self.network = Network.create(self.node) self.bma_access = BmaAccess.create(self.network) self.community = Community("test_currency", self.network, self.bma_access) self.wallet = Wallet(0, "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", "Wallet 1", self.identities_registry) # Salt/password : "******" # Pubkey : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ self.account = Account("testsakia", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", "john", [self.community], [self.wallet], [], self.identities_registry) self.password_asker = PasswordAskerDialog(self.account) self.password_asker.password = "******" self.password_asker.remember = True
async def exec_test(): value = await referential.localized(units=True, international_system=True) self.assertEqual(value, "1.011000 mUD({0}) TC".format(QLocale.toString( QLocale(), QDateTime.fromTime_t(1452663088792).date(), QLocale.dateFormat(QLocale(), QLocale.ShortFormat) )))
async def exec_test(): value = await referential.diff_localized(units=True) self.assertEqual(value, "0.101100 UD({0}) TC".format(QLocale.toString( QLocale(), QDateTime.fromTime_t(1452663088792).date(), QLocale.dateFormat(QLocale(), QLocale.ShortFormat) )))
def setUp(self): self.setUpQuamash() QLocale.setDefault(QLocale("en_GB")) self.identity = Mock(spec='sakia.core.registry.Identity') self.identity.pubkey = "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk" self.identity.uid = "A" self.app = MagicMock(autospec='sakia.core.Application') self.account_joe = Mock(spec='sakia.core.Account') self.account_joe.contacts_changed = Mock() self.account_joe.contacts_changed.disconnect = Mock() self.account_joe.contacts_changed.connect = Mock() self.account_doe = Mock(spec='sakia.core.Account') self.account_doe.contacts_changed = Mock() self.account_doe.contacts_changed.disconnect = Mock() self.account_doe.contacts_changed.connect = Mock() def change_current_account(account_name): type(self.app).current_account = PropertyMock(return_value=self.account_doe) self.app.get_account = Mock(side_effect=lambda name: self.app.accounts[name]) self.app.change_current_account = Mock(side_effect=change_current_account) type(self.app).current_account = PropertyMock(return_value=self.account_joe) self.app.accounts = {'joe':self.account_joe, 'doe': self.account_doe} self.homescreen = MagicMock(autospec='sakia.gui.homescreen.Homescreen') self.community_view = MagicMock(autospec='sakia.gui.community_view.CommunityView') self.password_asker = MagicMock(autospec='sakia.gui.password_asker.PasswordAsker') self.node_manager = MagicMock(autospec='sakia.gui.node_manager.NodeManager')
def setUp(self): self.setUpQuamash() QLocale.setDefault(QLocale("en_GB")) self.identities_registry = Mock(spec='sakia.core.registry.IdentitiesRegistry') self.community = Mock(spec='sakia.core.Community') self.community.name = "test_brouzouf" self.community.bma_access = Mock(spec='sakia.core.net.api.bma.BmaAccess')
def main(): global app # register representation factories baseRepresentationFactories.registerAllFactories() representationFactories.registerAllFactories() # initialize the app app = Application(sys.argv) app.setOrganizationName("TruFont") app.setOrganizationDomain("trufont.github.io") app.setApplicationName("TruFont") app.setApplicationVersion(__version__) app.setWindowIcon(QIcon(":app.png")) app.setAttribute(Qt.AA_UseHighDpiPixmaps, True) # Install stream redirection app.outputWindow = OutputWindow() # Exception handling sys.excepthook = exceptionCallback # Qt's translation for itself. May not be installed. qtTranslator = QTranslator() qtTranslator.load("qt_" + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) appTranslator = QTranslator() appTranslator.load("trufont_" + QLocale.system().name(), os.path.dirname(os.path.realpath(__file__)) + "/resources") app.installTranslator(appTranslator) # parse options and open fonts parser = QCommandLineParser() parser.setApplicationDescription(QApplication.translate( "Command-line parser", "The TruFont font editor.")) parser.addHelpOption() parser.addVersionOption() parser.addPositionalArgument(QApplication.translate( "Command-line parser", "files"), QApplication.translate( "Command-line parser", "The UFO files to open.")) parser.process(app) args = parser.positionalArguments() if not args: fontPath = None # maybe load recent file settings = QSettings() loadRecentFile = settings.value("misc/loadRecentFile", False, bool) if loadRecentFile: recentFiles = settings.value("core/recentFiles", [], type=str) if len(recentFiles) and os.path.exists(recentFiles[0]): fontPath = recentFiles[0] app.openFile(fontPath) # otherwise, create a new file if fontPath is None: app.newFile() else: for fontPath in args: app.openFile(fontPath) sys.exit(app.exec_())
def data(self, index, role): source_index = self.mapToSource(index) model = self.sourceModel() source_data = model.data(source_index, role) state_col = model.columns_types.index('state') state_index = model.index(source_index.row(), state_col) state_data = model.data(state_index, Qt.DisplayRole) if role == Qt.DisplayRole: if source_index.column() == model.columns_types.index('uid'): return source_data if source_index.column() == model.columns_types.index('date'): return QLocale.toString( QLocale(), QDateTime.fromTime_t(source_data).date(), QLocale.dateFormat(QLocale(), QLocale.ShortFormat) ) if source_index.column() == model.columns_types.index('payment') or \ source_index.column() == model.columns_types.index('deposit'): if source_data is not "": amount_ref = self.account.units_to_diff_ref(source_data, self.community) # if referential type is quantitative... if self.account.ref_type() == 'q': # display int values return QLocale().toString(float(amount_ref), 'f', 0) else: # display float values return QLocale().toString(amount_ref, 'f', 6) if role == Qt.FontRole: font = QFont() if state_data == Transfer.AWAITING: font.setItalic(True) elif state_data == Transfer.REFUSED: font.setItalic(True) elif state_data == Transfer.TO_SEND: font.setBold(True) else: font.setItalic(False) return font if role == Qt.ForegroundRole: if state_data == Transfer.REFUSED: return QColor(Qt.red) elif state_data == Transfer.TO_SEND: return QColor(Qt.blue) if role == Qt.TextAlignmentRole: if source_index.column() == self.sourceModel().columns_types.index( 'deposit') or source_index.column() == self.sourceModel().columns_types.index('payment'): return Qt.AlignRight | Qt.AlignVCenter if source_index.column() == self.sourceModel().columns_types.index('date'): return Qt.AlignCenter if role == Qt.ToolTipRole: if source_index.column() == self.sourceModel().columns_types.index('date'): return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate) return source_data
def refresh_status(self): """ Refresh status bar """ logging.debug("Refresh status") if self.community: text = "" current_block_number = self.community.network.current_blockid.number if current_block_number: text += self.tr(" Block {0}").format(current_block_number) try: block = yield from self.community.get_block(current_block_number) text += " ({0})".format(QLocale.toString( QLocale(), QDateTime.fromTime_t(block['medianTime']), QLocale.dateTimeFormat(QLocale(), QLocale.NarrowFormat) )) except NoPeerAvailable as e: logging.debug(str(e)) text += " ( ### ) " except ValueError as e: logging.debug(str(e)) if len(self.community.network.synced_nodes) == 0: self.button_membership.setEnabled(False) self.button_certification.setEnabled(False) self.button_send_money.setEnabled(False) else: self.button_membership.setEnabled(True) self.button_certification.setEnabled(True) self.button_send_money.setEnabled(True) if self.community.network.quality > 0.66: icon = '<img src=":/icons/connected" width="12" height="12"/>' elif self.community.network.quality > 0.33: icon = '<img src=":/icons/weak_connect" width="12" height="12"/>' else: icon = '<img src=":/icons/disconnected" width="12" height="12"/>' status_infotext = " - ".join([self.app.notifications[info][0] for info in self.status_info]) label_text = "{0}{1}".format(icon, text) if status_infotext != "": label_text += " - {0}".format(status_infotext) if self.app.preferences['expert_mode']: try: members_pubkeys = yield from self.community.members_pubkeys() label_text += self.tr(" - Median fork window : {0}")\ .format(self.community.network.fork_window(members_pubkeys)) except NoPeerAvailable as e: logging.debug(str(e)) label_text += self.tr(" - Median fork window : {0}")\ .format("#") self.status_label.setText(label_text)
def switch_language(self): translator = QTranslator(self.qapp) logging.debug("Loading translations") locale = self.preferences["lang"] QLocale.setDefault(QLocale(locale)) if translator.load(":/i18n/{0}".format(locale)): if QCoreApplication.installTranslator(translator): logging.debug("Loaded i18n/{0}".format(locale)) else: logging.debug("Couldn't load translation")
def update_time(self): dateTime = QDateTime.currentDateTime() self.label_time.setText("{0}".format(QLocale.toString( QLocale(), QDateTime.currentDateTime(), QLocale.dateTimeFormat(QLocale(), QLocale.NarrowFormat) ))) timer = QTimer() timer.timeout.connect(self.update_time) timer.start(1000)
def data(self, index, role): source_index = self.mapToSource(index) if source_index.isValid(): source_data = self.sourceModel().data(source_index, role) expiration_col = self.sourceModel().columns_ids.index('expiration') expiration_index = self.sourceModel().index(source_index.row(), expiration_col) STATUS_NOT_MEMBER = 0 STATUS_MEMBER = 1 STATUS_EXPIRE_SOON = 3 status = STATUS_NOT_MEMBER expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole) current_time = QDateTime().currentDateTime().toMSecsSinceEpoch() sig_validity = self.sourceModel().sig_validity() warning_expiration_time = int(sig_validity / 3) #logging.debug("{0} > {1}".format(current_time, expiration_data)) if expiration_data is not None: status = STATUS_MEMBER if current_time > (expiration_data*1000): status = STATUS_NOT_MEMBER elif current_time > ((expiration_data*1000) - (warning_expiration_time*1000)): status = STATUS_EXPIRE_SOON if role == Qt.DisplayRole: if source_index.column() in (self.sourceModel().columns_ids.index('renewed'), self.sourceModel().columns_ids.index('expiration'), self.sourceModel().columns_ids.index('publication')): if source_data is not None: return QLocale.toString( QLocale(), QDateTime.fromTime_t(source_data).date(), QLocale.dateFormat(QLocale(), QLocale.ShortFormat) ) else: return "" if source_index.column() == self.sourceModel().columns_ids.index('pubkey'): return "pub:{0}".format(source_data[:5]) if role == Qt.ForegroundRole: if status == STATUS_EXPIRE_SOON: return QColor("darkorange").darker(120) elif status == STATUS_NOT_MEMBER: return QColor(Qt.red) else: return QColor(Qt.blue) if role == Qt.DecorationRole and source_index.column() == self.sourceModel().columns_ids.index('uid'): if status == STATUS_NOT_MEMBER: return QIcon(":/icons/not_member") elif status == STATUS_MEMBER: return QIcon(":/icons/member") elif status == STATUS_EXPIRE_SOON: return QIcon(":/icons/member_warning") return source_data
def add_certifier_list(self, certifier_list, person, person_account): """ Add list of certifiers to graph :param list certifier_list: List of certifiers from api :param Person person: Person instance which is certified :param Person person_account: Account person instance :return: """ # add certifiers of uid for certifier in tuple(certifier_list): # add only valid certification... if (time.time() - certifier['cert_time']['medianTime']) > self.signature_validity: continue # new node if certifier['pubkey'] not in self._graph.keys(): node_status = 0 if certifier['pubkey'] == person_account.pubkey: node_status += NODE_STATUS_HIGHLIGHTED if certifier['isMember'] is False: node_status += NODE_STATUS_OUT self._graph[certifier['pubkey']] = { 'id': certifier['pubkey'], 'arcs': list(), 'text': certifier['uid'], 'tooltip': certifier['pubkey'], 'status': node_status, 'connected': [person.pubkey] } # keep only the latest certification if self._graph[certifier['pubkey']]['arcs']: if certifier['cert_time']['medianTime'] < self._graph[certifier['pubkey']]['arcs'][0]['cert_time']: continue # display validity status if (time.time() - certifier['cert_time']['medianTime']) > self.ARC_STATUS_STRONG_time: arc_status = ARC_STATUS_WEAK else: arc_status = ARC_STATUS_STRONG arc = { 'id': person.pubkey, 'status': arc_status, 'tooltip': QLocale.toString( QLocale(), QDateTime.fromTime_t(certifier['cert_time']['medianTime'] + self.signature_validity).date(), QLocale.dateFormat(QLocale(), QLocale.ShortFormat) ), 'cert_time': certifier['cert_time']['medianTime'] } # add arc to certifier self._graph[certifier['pubkey']]['arcs'].append(arc) # if certifier node not in person nodes if certifier['pubkey'] not in tuple(self._graph[person.pubkey]['connected']): # add certifier node to person node self._graph[person.pubkey]['connected'].append(certifier['pubkey'])
def __init__(self, parent, gid, persepolis_setting): super().__init__(persepolis_setting) self.persepolis_setting = persepolis_setting self.parent = parent self.gid = gid self.status = None self.resume_pushButton.clicked.connect(self.resumePushButtonPressed) self.stop_pushButton.clicked.connect(self.stopPushButtonPressed) self.pause_pushButton.clicked.connect(self.pausePushButtonPressed) self.download_progressBar.setValue(0) self.limit_pushButton.clicked.connect(self.limitPushButtonPressed) self.limit_frame.setEnabled(False) self.limit_checkBox.toggled.connect(self.limitCheckBoxToggled) self.after_frame.setEnabled(False) self.after_checkBox.toggled.connect(self.afterCheckBoxToggled) self.after_pushButton.clicked.connect(self.afterPushButtonPressed) # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # check if limit speed actived by user or not add_link_dictionary = self.parent.persepolis_db.searchGidInAddLinkTable(gid) limit = str(add_link_dictionary['limit_value']) if limit != '0': limit_number = limit[:-1] limit_unit = limit[-1] self.limit_spinBox.setValue(float(limit_number)) if limit_unit == 'K': self.after_comboBox.setCurrentIndex(0) else: self.after_comboBox.setCurrentIndex(1) self.limit_checkBox.setChecked(True) self.after_comboBox.currentIndexChanged.connect(self.afterComboBoxChanged) self.limit_comboBox.currentIndexChanged.connect(self.limitComboBoxChanged) self.limit_spinBox.valueChanged.connect(self.limitComboBoxChanged) # set window size and position size = self.persepolis_setting.value( 'ProgressWindow/size', QSize(595, 274)) position = self.persepolis_setting.value( 'ProgressWindow/position', QPoint(300, 300)) self.resize(size) self.move(position)
def setUp(self): self.setUpQuamash() QLocale.setDefault(QLocale("en_GB")) self.identity = Mock(specs='sakia.core.registry.Identity') self.identity.pubkey = "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk" self.identity.uid = "A" self.app = MagicMock(specs='sakia.core.Application') self.account = MagicMock(specs='sakia.core.Account') self.community = MagicMock(specs='sakia.core.Community') self.password_asker = MagicMock(specs='sakia.gui.password_asker.PasswordAsker')
def data(self, index, role): source_index = self.mapToSource(index) if source_index.isValid(): source_data = self.sourceModel().data(source_index, role) publication_col = CertifiersTableModel.columns_ids.index('publication') publication_index = self.sourceModel().index(source_index.row(), publication_col) expiration_col = CertifiersTableModel.columns_ids.index('expiration') expiration_index = self.sourceModel().index(source_index.row(), expiration_col) written_col = CertifiersTableModel.columns_ids.index('written') written_index = self.sourceModel().index(source_index.row(), written_col) publication_data = self.sourceModel().data(publication_index, Qt.DisplayRole) expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole) written_data = self.sourceModel().data(written_index, Qt.DisplayRole) current_time = QDateTime().currentDateTime().toMSecsSinceEpoch() warning_expiration_time = int((expiration_data - publication_data) / 3) #logging.debug("{0} > {1}".format(current_time, expiration_data)) if role == Qt.DisplayRole: if source_index.column() == CertifiersTableModel.columns_ids.index('expiration'): if source_data: ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data) return QLocale.toString( QLocale(), QDateTime.fromTime_t(ts), QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat) ) + " BAT" else: return "" if source_index.column() == CertifiersTableModel.columns_ids.index('publication'): if source_data: ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data) return QLocale.toString( QLocale(), QDateTime.fromTime_t(ts), QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat) ) + " BAT" else: return "" if source_index.column() == CertifiersTableModel.columns_ids.index('pubkey'): return source_data if role == Qt.FontRole: font = QFont() if not written_data: font.setItalic(True) return font if role == Qt.ForegroundRole: if current_time > ((expiration_data*1000) - (warning_expiration_time*1000)): return QColor("darkorange").darker(120) return source_data
def loadLanguage(self, language): if not self.language == language: self.language = language locale = QLocale(language) QLocale.setDefault(locale) self.switchTranslator(self.qtTl, "qtbase", language) self.switchTranslator(self.appTl, "wuchshuellenrechner", language) # update gui self.retranslateUi() self.dataWidget.retranslateUi()
def switch_language(self): logging.debug("Loading translations") locale = self.preferences['lang'] QLocale.setDefault(QLocale(locale)) QCoreApplication.removeTranslator(self._translator) self._translator = QTranslator(self.qapp) if locale == "en_GB": QCoreApplication.installTranslator(self._translator) elif self._translator.load(":/i18n/{0}".format(locale)): if QCoreApplication.installTranslator(self._translator): logging.debug("Loaded i18n/{0}".format(locale)) else: logging.debug("Couldn't load translation")
def setUp(self): self.setUpQuamash() QLocale.setDefault(QLocale("en_GB")) self.identities_registry = IdentitiesRegistry({}) self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False # Salt/password : "******" # Pubkey : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ self.account = Account("testsakia", "B7J4sopyfqzi3uh4Gzsdnp1XHc87NaxY7rqW2exgivCa", "test", [], [], [], self.identities_registry) self.password_asker = PasswordAskerDialog(self.account) self.password_asker.password = "******" self.password_asker.remember = True
def main(): locale = QLocale(QLocale.C) locale.setNumberOptions(QLocale.RejectGroupSeparator) QLocale.setDefault(locale) config = Config() config.removeOldFiles() app = QApplication([]) window = MainWindow() window.show() sys.exit(app.exec_())
async def refresh(self): if self.identity and self.identity.local_state != LocalState.NOT_FOUND: self.ui.busy.show() self.ui.label_uid.setText(self.identity.uid) self.ui.label_properties.setText("") try: identity_selfcert = await self.identity.selfcert(self.community) publish_time = await self.community.time(identity_selfcert.timestamp.number) join_date = await self.identity.get_join_date(self.community) if join_date is None: join_date = self.tr('not a member') else: join_date = datetime.datetime.fromtimestamp(join_date).strftime("%d/%m/%Y %I:%M") except MembershipNotFoundError: join_date = "###" except (LookupFailureError, NoPeerAvailable): publish_time = None join_date = "###" if publish_time: uid_publish_date = QLocale.toString( QLocale(), QDateTime.fromTime_t(publish_time), QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat) ) else: uid_publish_date = "###" text = self.tr(""" <table cellpadding="5"> <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr> <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr> <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr> """).format( self.tr('Public key'), self.identity.pubkey, self.tr('UID Published on'), uid_publish_date, self.tr('Join date'), join_date ) # close html text text += "</table>" # set text in label self.ui.label_properties.setText(text) self.ui.busy.hide()
def __init__(self, filepath=None): QObject.__init__(self) QTimer.singleShot(0, self.__launchTimerTimedOut) self.prefs = Preferences() self.prefs.load() global APP_PREFS APP_PREFS = self.prefs locale = QLocale.system() dateFormat = self.prefs.dateFormat decimalSep = locale.decimalPoint() groupingSep = locale.groupSeparator() cachePath = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)[0] DateEdit.DATE_FORMAT = dateFormat self.model = MoneyGuruModel( view=self, date_format=dateFormat, decimal_sep=decimalSep, grouping_sep=groupingSep, cache_path=cachePath ) self.mainWindow = MainWindow(app=self) self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self) self.aboutBox = AboutBox(self.mainWindow, self) self.initialFilePath = None if filepath and op.exists(filepath): self.initialFilePath = filepath elif self.prefs.recentDocuments: self.initialFilePath = self.prefs.recentDocuments[0] self.finishedLaunching.connect(self.applicationFinishedLaunching) QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
def getExportExtensionsList(self): extensions = [] for extsprefix in datadirs: extsdir = QDir(extsprefix+'/export-extensions/') if extsdir.exists(): for fileInfo in extsdir.entryInfoList(['*.desktop', '*.ini'], QDir.Files | QDir.Readable): extensions.append(self.readExtension(fileInfo.filePath())) locale = QLocale.system().name() self.extensionActions = [] for extension in extensions: try: if ('Name[%s]' % locale) in extension: name = extension['Name[%s]' % locale] elif ('Name[%s]' % locale.split('_')[0]) in extension: name = extension['Name[%s]' % locale.split('_')[0]] else: name = extension['Name'] data = {} for prop in ('FileFilter', 'DefaultExtension', 'Exec'): if 'X-ReText-'+prop in extension: data[prop] = extension['X-ReText-'+prop] elif prop in extension: data[prop] = extension[prop] else: data[prop] = '' action = self.act(name, trig=self.extensionFunction(data)) if 'Icon' in extension: action.setIcon(self.actIcon(extension['Icon'])) mimetype = extension['MimeType'] if 'MimeType' in extension else None except KeyError: print('Failed to parse extension: Name is required', file=sys.stderr) else: self.extensionActions.append((action, mimetype))
def __init__(self, filepath=None): ApplicationBase.__init__(self) self.prefs = Preferences() self.prefs.load() global APP_PREFS APP_PREFS = self.prefs locale = QLocale.system() dateFormat = self.prefs.dateFormat decimalSep = locale.decimalPoint() groupingSep = locale.groupSeparator() cachePath = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)[0] appdata = getAppData() DateEdit.DATE_FORMAT = dateFormat self.model = MoneyGuruModel( view=self, date_format=dateFormat, decimal_sep=decimalSep, grouping_sep=groupingSep, cache_path=cachePath, appdata_path=appdata, ) # on the Qt side, we're single document based, so it's one doc per app. self.doc = Document(app=self) self.doc.model.connect() self.mainWindow = MainWindow(doc=self.doc) self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self) self.aboutBox = AboutBox(self.mainWindow, self) self.initialFilePath = None if filepath and op.exists(filepath): self.initialFilePath = filepath elif self.prefs.recentDocuments: self.initialFilePath = self.prefs.recentDocuments[0] self.finishedLaunching.connect(self.applicationFinishedLaunching) QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
def __init__(self): """ Constructor """ super(SnapshotFreehandGrabber, self).__init__( None, Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool) self.__selection = QPolygon() self.__mouseDown = False self.__newSelection = False self.__handleSize = 10 self.__showHelp = True self.__grabbing = False self.__dragStartPoint = QPoint() self.__selectionBeforeDrag = QPolygon() self.__locale = QLocale() self.__helpTextRect = QRect() self.__helpText = self.tr( "Select a region using the mouse. To take the snapshot," " press the Enter key or double click. Press Esc to quit.") self.__pixmap = QPixmap() self.__pBefore = QPoint() self.setMouseTracking(True) QTimer.singleShot(200, self.__initialize)
def save(self): """ Public slot to save the Help Viewers configuration. """ Preferences.setHelp("SingleHelpWindow", self.singleHelpWindowCheckBox.isChecked()) Preferences.setHelp("SaveGeometry", self.saveGeometryCheckBox.isChecked()) Preferences.setHelp("WebSearchSuggestions", self.webSuggestionsCheckBox.isChecked()) Preferences.setHelp("ShowPreview", self.showTabPreviews.isChecked()) Preferences.setHelp("AccessKeysEnabled", self.accessKeysCheckBox.isChecked()) Preferences.setHelp("JavaEnabled", self.javaCheckBox.isChecked()) Preferences.setHelp("JavaScriptEnabled", self.javaScriptCheckBox.isChecked()) Preferences.setHelp("JavaScriptCanOpenWindows", self.jsOpenWindowsCheckBox.isChecked()) Preferences.setHelp("JavaScriptCanAccessClipboard", self.jsClipboardCheckBox.isChecked()) Preferences.setHelp("PluginsEnabled", self.pluginsCheckBox.isChecked()) Preferences.setHelp("ClickToFlashEnabled", self.clickToFlashCheckBox.isChecked()) Preferences.setHelp("DoNotTrack", self.doNotTrackCheckBox.isChecked()) Preferences.setHelp("SendReferer", self.sendRefererCheckBox.isChecked()) Preferences.setHelp("DiskCacheEnabled", self.diskCacheCheckBox.isChecked()) Preferences.setHelp("DiskCacheSize", self.cacheSizeSpinBox.value()) if self.cacheKeepButton.isChecked(): Preferences.setHelp("CachePolicy", QNetworkRequest.PreferNetwork) elif self.cachePreferButton.isChecked(): Preferences.setHelp("CachePolicy", QNetworkRequest.PreferCache) elif self.cacheOfflineButton.isChecked(): Preferences.setHelp("CachePolicy", QNetworkRequest.AlwaysCache) Preferences.setHelp("PrintBackgrounds", self.printBackgroundsCheckBox.isChecked()) Preferences.setHelp("StartupBehavior", self.startupCombo.currentIndex()) Preferences.setHelp("HomePage", self.homePageEdit.text()) Preferences.setHelp("DefaultScheme", self.defaultSchemeCombo.currentText()) idx = self.expireHistory.currentIndex() if idx == 0: historyLimit = 1 elif idx == 1: historyLimit = 7 elif idx == 2: historyLimit = 14 elif idx == 3: historyLimit = 30 elif idx == 4: historyLimit = 365 elif idx == 5: historyLimit = -1 elif idx == 6: historyLimit = -2 Preferences.setHelp("HistoryLimit", historyLimit) languageIndex = self.languageCombo.currentIndex() if languageIndex > -1: language = self.languageCombo.itemData(languageIndex) else: # fall back to system default language = QLocale.system().language() Preferences.setHelp("SearchLanguage", language) if hasattr(QWebSettings, "SpatialNavigationEnabled"): Preferences.setHelp("SpatialNavigationEnabled", self.spatialCheckBox.isChecked()) if hasattr(QWebSettings, "LinksIncludedInFocusChain"): Preferences.setHelp("LinksIncludedInFocusChain", self.linksInFocusChainCheckBox.isChecked()) if hasattr(QWebSettings, "XSSAuditingEnabled"): Preferences.setHelp("XSSAuditingEnabled", self.xssAuditingCheckBox.isChecked()) if hasattr(QWebSettings, "SiteSpecificQuirksEnabled"): Preferences.setHelp("SiteSpecificQuirksEnabled", self.quirksCheckBox.isChecked())
t1 = QTime(18, 50, 59) dt1 = QDateTime(d1, t1, Qt.LocalTime) print("Datetime: {0}".format(dt1.toString())) print("Date: {0}".format(d1.toString())) print("Time: {0}".format(t1.toString())) now = QDate.currentDate() print(now.toString(Qt.ISODate)) print(now.toString(Qt.DefaultLocaleLongDate)) datetime = QDateTime.currentDateTime() print(datetime.toString()) dayOfWeek = now.dayOfWeek() print(QDate.shortDayName(dayOfWeek)) print(QDate.longDayName(dayOfWeek)) locale = QLocale(QLocale.Russian, QLocale.RussianFederation) print(locale.toString(now, 'dddd')) # prints current time time = QTime.currentTime() print(time.toString(Qt.DefaultLocaleLongDate)) now = QDateTime.currentDateTime() print("Local datetime: ", now.toString(Qt.ISODate)) print("Universal datetime: ", now.toUTC().toString(Qt.ISODate)) print("The offset from UTC is: {0} seconds".format(now.offsetFromUtc())) # comparing two dates d1 = QDate(2017, 4, 5) d2 = QDate(2016, 4, 5) if d1 < d2:
def __init__(self, parent, title="pymodaq Move", preset=None, init=False, controller_ID=-1): # DAQ_Move object is a module used to control one motor from a specified list. # managers is an optional list of dicts used to managers programatically settings such as the name of the controller from the list of possible controllers, COM address... # init is a boolean to tell the programm to initialize the controller at the start of the programm given the managers options # controller_ID is a unique random integer generated by the parent caller. To differenciate various instance of this class self.logger = utils.set_logger(f'{logger.name}.{title}') self.logger.info(f'Initializing DAQ_Move: {title}') QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates)) super(DAQ_Move, self).__init__() self.ui = Ui_Form() self.ui.setupUi(parent) self.ui.Moveto_pb_bis_2.setVisible(False) self.parent = parent self.ui.title_label.setText(title) self.title = title self.ui.statusbar = QtWidgets.QStatusBar(parent) self.ui.StatusBarLayout.addWidget(self.ui.statusbar) self.ui.statusbar.setMaximumHeight(20) self.send_to_tcpip = False self.tcpclient_thread = None self.wait_time = 1000 self.ui.Ini_state_LED self.ui.Ini_state_LED.clickable = False self.ui.Ini_state_LED.set_as_false() self.ui.Move_Done_LED.clickable = False self.ui.Move_Done_LED.set_as_false() self.initialized_state = False self.ui.Current_position_sb.setReadOnly(False) self.move_done_bool = True ############IMPORTANT############################ self.controller = None # the hardware controller/set after initialization and to be used by other modules ################################################# self.current_position = 0 self.target_position = 0 self.wait_position_flag = True self.ui.Current_position_sb.setValue(self.current_position) self.set_enabled_move_buttons(enable=False) self.ui.groupBox.hide() self.parent.resize(150, 200) ##Setting stages types self.stage_types = DAQ_Move_Stage_type.names('daq_move') self.ui.Stage_type_combo.clear() self.ui.Stage_type_combo.addItems(self.stage_types) #create main parameter tree self.ui.settings_tree = ParameterTree() self.ui.verticalLayout_2.addWidget(self.ui.settings_tree) self.ui.settings_tree.setMinimumWidth(300) self.settings = Parameter.create(name='Settings', type='group', children=self.params) self.ui.settings_tree.setParameters(self.settings, showTop=False) #connecting from tree self.settings.sigTreeStateChanged.connect( self.parameter_tree_changed ) #any changes on the settings will update accordingly the detector self.ui.settings_tree.setVisible(False) self.set_setting_tree() self.settings.child('main_settings', 'controller_ID').setValue(controller_ID) QtWidgets.QApplication.processEvents() ##Connecting buttons: self.ui.Stage_type_combo.currentIndexChanged.connect( self.set_setting_tree) self.ui.Stage_type_combo.currentIndexChanged.connect( self.stage_changed) self.ui.Quit_pb.clicked.connect(self.quit_fun) self.ui.IniStage_pb.clicked.connect(self.ini_stage_fun) self.update_status("Ready", wait_time=self.wait_time) self.ui.Move_Abs_pb.clicked.connect( lambda: self.move_Abs(self.ui.Abs_position_sb.value())) self.ui.Move_Rel_plus_pb.clicked.connect( lambda: self.move_Rel(self.ui.Rel_position_sb.value())) self.ui.Move_Rel_minus_pb.clicked.connect( lambda: self.move_Rel(-self.ui.Rel_position_sb.value())) self.ui.Find_Home_pb.clicked.connect(self.move_Home) self.ui.Get_position_pb.clicked.connect(self.get_position) self.ui.Stop_pb.clicked.connect(self.stop_Motion) self.ui.parameters_pb.clicked.connect(self.show_settings) self.ui.fine_tuning_pb.clicked.connect(self.show_fine_tuning) self.ui.Abs_position_sb.valueChanged.connect( self.ui.Abs_position_sb_bis.setValue) self.ui.Abs_position_sb_bis.valueChanged.connect( self.ui.Abs_position_sb.setValue) self.ui.Moveto_pb_bis.clicked.connect( lambda: self.move_Abs(self.ui.Abs_position_sb_bis.value())) # set managers options if preset is not None: for preset_dict in preset: # fo instance preset_dict=dict(object='Stage_type_combo',method='setCurrentIndex',value=1) if hasattr(self.ui, preset_dict['object']): obj = getattr(self.ui, preset_dict['object']) if hasattr(obj, preset_dict['method']): setattr(obj, preset_dict['method'], preset_dict['value']) QtWidgets.QApplication.processEvents() #initialize the controller if init=True if init: self.ui.IniStage_pb.click()
def init_language(): """ Find the current locale, and install the correct translators """ # Get app instance app = QCoreApplication.instance() # Setup of our list of translators and paths translator_types = ( { "type": 'QT', "prefix": 'qt_', # Older versions of Qt use this file (built-in translations) "path": QLibraryInfo.location(QLibraryInfo.TranslationsPath) }, { "type": 'QT', "prefix": 'qtbase_', # Newer versions of Qt use this file (built-in translations) "path": QLibraryInfo.location(QLibraryInfo.TranslationsPath) }, { "type": 'QT', "prefix": 'qt_', "path": os.path.join(info.PATH, 'language') }, # Optional path where we package QT translations { "type": 'QT', "prefix": 'qtbase_', "path": os.path.join(info.PATH, 'language') }, # Optional path where we package QT translations { "type": 'OpenShot', "prefix": 'OpenShot_', # Our custom translations "path": language_path }, ) # Determine the environment locale, or default to system locale name locale_names = [ os.environ.get('LANG', QLocale().system().name()), os.environ.get('LOCALE', QLocale().system().name()) ] # Get the user's configured language preference settings = app.get_settings() if settings: preference_lang = settings.get('default-language') else: preference_lang = "Default" # Output all languages detected from various sources log.info("Qt Detected Languages: {}".format( QLocale().system().uiLanguages())) log.info("LANG Environment Variable: {}".format(os.environ.get('LANG', ""))) log.info("LOCALE Environment Variable: {}".format( os.environ.get('LOCALE', ""))) log.info("OpenShot Preference Language: {}".format(preference_lang)) # Check if the language preference is something other than "Default" if preference_lang == "en_US": # Override language list with en_US, don't add to it locale_names = ["en_US"] elif preference_lang != "Default": # Prepend preference setting to list locale_names.insert(0, preference_lang) # If the user has used the --lang command line arg, override with that # (We've already checked that it's in SUPPORTED_LANGUAGES) if info.CMDLINE_LANGUAGE: locale_names = [info.CMDLINE_LANGUAGE] log.info("Language overridden on command line, using: {}".format( info.CMDLINE_LANGUAGE)) # Default the locale to C, for number formatting locale.setlocale(locale.LC_ALL, 'C') # Loop through environment variables found_language = False for locale_name in locale_names: # Go through each translator and try to add for current locale for type in translator_types: trans = QTranslator(app) if find_language_match(type["prefix"], type["path"], trans, locale_name): # Install translation app.installTranslator(trans) found_language = True # Exit if found language for type: "OpenShot" if found_language: log.debug( "Exiting translation system (since we successfully loaded: {})" .format(locale_name)) info.CURRENT_LANGUAGE = locale_name break
def __init__(self, persepolis_setting): super().__init__() self.persepolis_setting = persepolis_setting # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) # get icons name icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setMinimumSize(QtCore.QSize(520, 425)) self.setWindowIcon( QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) window_verticalLayout = QVBoxLayout() # add link tab widget self.add_link_tabWidget = QTabWidget(self) window_verticalLayout.addWidget(self.add_link_tabWidget) # link tab self.link_tab = QWidget() link_tab_verticalLayout = QVBoxLayout(self.link_tab) link_tab_verticalLayout.setContentsMargins(21, 21, 21, 81) self.link_frame = QFrame(self.link_tab) self.link_frame.setFrameShape(QFrame.StyledPanel) self.link_frame.setFrameShadow(QFrame.Raised) horizontalLayout_2 = QHBoxLayout(self.link_frame) self.link_verticalLayout = QVBoxLayout() # link -> self.link_horizontalLayout = QHBoxLayout() self.link_label = QLabel(self.link_frame) self.link_horizontalLayout.addWidget(self.link_label) self.link_lineEdit = QLineEdit(self.link_frame) self.link_horizontalLayout.addWidget(self.link_lineEdit) self.link_verticalLayout.addLayout(self.link_horizontalLayout) horizontalLayout_2.addLayout(self.link_verticalLayout) link_tab_verticalLayout.addWidget(self.link_frame) # add change_name field -> change_name_horizontalLayout = QHBoxLayout() self.change_name_checkBox = QCheckBox(self.link_frame) change_name_horizontalLayout.addWidget(self.change_name_checkBox) self.change_name_lineEdit = QLineEdit(self.link_frame) change_name_horizontalLayout.addWidget(self.change_name_lineEdit) self.link_verticalLayout.addLayout(change_name_horizontalLayout) # add_category -> queue_horizontalLayout = QHBoxLayout() self.queue_frame = QFrame(self) self.queue_frame.setFrameShape(QFrame.StyledPanel) self.queue_frame.setFrameShadow(QFrame.Raised) add_queue_horizontalLayout = QHBoxLayout(self.queue_frame) self.add_queue_label = QLabel(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_label) self.add_queue_comboBox = QComboBox(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_comboBox) queue_horizontalLayout.addWidget(self.queue_frame) queue_horizontalLayout.addStretch(1) self.size_label = QLabel(self) queue_horizontalLayout.addWidget(self.size_label) link_tab_verticalLayout.addLayout(queue_horizontalLayout) self.add_link_tabWidget.addTab(self.link_tab, '') # proxy tab self.proxy_tab = QWidget(self) proxy_verticalLayout = QVBoxLayout(self.proxy_tab) proxy_verticalLayout.setContentsMargins(21, 21, 21, 171) proxy_horizontalLayout = QHBoxLayout() self.proxy_checkBox = QCheckBox(self.proxy_tab) self.detect_proxy_pushButton = QPushButton(self.proxy_tab) self.detect_proxy_label = QLabel(self.proxy_tab) proxy_horizontalLayout.addWidget(self.proxy_checkBox) proxy_horizontalLayout.addWidget(self.detect_proxy_label) proxy_horizontalLayout.addWidget(self.detect_proxy_pushButton) proxy_verticalLayout.addLayout(proxy_horizontalLayout) self.proxy_frame = QFrame(self.proxy_tab) self.proxy_frame.setFrameShape(QFrame.StyledPanel) self.proxy_frame.setFrameShadow(QFrame.Raised) gridLayout = QGridLayout(self.proxy_frame) self.ip_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.ip_label, 0, 0, 1, 1) self.ip_lineEdit = QLineEdit(self.proxy_frame) self.ip_lineEdit.setInputMethodHints(QtCore.Qt.ImhNone) gridLayout.addWidget(self.ip_lineEdit, 0, 1, 1, 1) self.port_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.port_label, 0, 2, 1, 1) self.port_spinBox = QSpinBox(self.proxy_frame) self.port_spinBox.setMaximum(65535) self.port_spinBox.setSingleStep(1) gridLayout.addWidget(self.port_spinBox, 0, 3, 1, 1) self.proxy_user_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_user_label, 2, 0, 1, 1) self.proxy_user_lineEdit = QLineEdit(self.proxy_frame) gridLayout.addWidget(self.proxy_user_lineEdit, 2, 1, 1, 1) self.proxy_pass_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_pass_label, 2, 2, 1, 1) self.proxy_pass_lineEdit = QLineEdit(self.proxy_frame) self.proxy_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout.addWidget(self.proxy_pass_lineEdit, 2, 3, 1, 1) proxy_verticalLayout.addWidget(self.proxy_frame) self.add_link_tabWidget.addTab(self.proxy_tab, '') # more options tab self.more_options_tab = QWidget(self) more_options_tab_verticalLayout = QVBoxLayout(self.more_options_tab) # download UserName & Password -> download_horizontalLayout = QHBoxLayout() download_horizontalLayout.setContentsMargins(-1, 10, -1, -1) download_verticalLayout = QVBoxLayout() self.download_checkBox = QCheckBox(self.more_options_tab) download_verticalLayout.addWidget(self.download_checkBox) self.download_frame = QFrame(self.more_options_tab) self.download_frame.setFrameShape(QFrame.StyledPanel) self.download_frame.setFrameShadow(QFrame.Raised) gridLayout_2 = QGridLayout(self.download_frame) self.download_user_lineEdit = QLineEdit(self.download_frame) gridLayout_2.addWidget(self.download_user_lineEdit, 0, 1, 1, 1) self.download_user_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_user_label, 0, 0, 1, 1) self.download_pass_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_pass_label, 1, 0, 1, 1) self.download_pass_lineEdit = QLineEdit(self.download_frame) self.download_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout_2.addWidget(self.download_pass_lineEdit, 1, 1, 1, 1) download_verticalLayout.addWidget(self.download_frame) download_horizontalLayout.addLayout(download_verticalLayout) # select folder -> self.folder_frame = QFrame(self.more_options_tab) self.folder_frame.setFrameShape(QFrame.StyledPanel) self.folder_frame.setFrameShadow(QFrame.Raised) gridLayout_3 = QGridLayout(self.folder_frame) self.download_folder_lineEdit = QLineEdit(self.folder_frame) gridLayout_3.addWidget(self.download_folder_lineEdit, 2, 0, 1, 1) self.folder_pushButton = QPushButton(self.folder_frame) gridLayout_3.addWidget(self.folder_pushButton, 3, 0, 1, 1) self.folder_pushButton.setIcon(QIcon(icons + 'folder')) self.folder_label = QLabel(self.folder_frame) self.folder_label.setAlignment(QtCore.Qt.AlignCenter) gridLayout_3.addWidget(self.folder_label, 1, 0, 1, 1) download_horizontalLayout.addWidget(self.folder_frame) more_options_tab_verticalLayout.addLayout(download_horizontalLayout) # start time -> time_limit_horizontalLayout = QHBoxLayout() time_limit_horizontalLayout.setContentsMargins(-1, 10, -1, -1) start_verticalLayout = QVBoxLayout() self.start_checkBox = QCheckBox(self.more_options_tab) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self.more_options_tab) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) horizontalLayout_5 = QHBoxLayout(self.start_frame) self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame) self.start_time_qDataTimeEdit.setDisplayFormat('H:mm') horizontalLayout_5.addWidget(self.start_time_qDataTimeEdit) start_verticalLayout.addWidget(self.start_frame) time_limit_horizontalLayout.addLayout(start_verticalLayout) # end time -> end_verticalLayout = QVBoxLayout() self.end_checkBox = QCheckBox(self.more_options_tab) end_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self.more_options_tab) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) horizontalLayout_6 = QHBoxLayout(self.end_frame) self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame) self.end_time_qDateTimeEdit.setDisplayFormat('H:mm') horizontalLayout_6.addWidget(self.end_time_qDateTimeEdit) end_verticalLayout.addWidget(self.end_frame) time_limit_horizontalLayout.addLayout(end_verticalLayout) # limit Speed -> limit_verticalLayout = QVBoxLayout() self.limit_checkBox = QCheckBox(self.more_options_tab) limit_verticalLayout.addWidget(self.limit_checkBox) self.limit_frame = QFrame(self.more_options_tab) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) horizontalLayout_4 = QHBoxLayout(self.limit_frame) self.limit_spinBox = QDoubleSpinBox(self.limit_frame) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) horizontalLayout_4.addWidget(self.limit_spinBox) self.limit_comboBox = QComboBox(self.limit_frame) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") horizontalLayout_4.addWidget(self.limit_comboBox) limit_verticalLayout.addWidget(self.limit_frame) time_limit_horizontalLayout.addLayout(limit_verticalLayout) more_options_tab_verticalLayout.addLayout(time_limit_horizontalLayout) # number of connections -> connections_horizontalLayout = QHBoxLayout() connections_horizontalLayout.setContentsMargins(-1, 10, -1, -1) self.connections_frame = QFrame(self.more_options_tab) self.connections_frame.setFrameShape(QFrame.StyledPanel) self.connections_frame.setFrameShadow(QFrame.Raised) horizontalLayout_3 = QHBoxLayout(self.connections_frame) self.connections_label = QLabel(self.connections_frame) horizontalLayout_3.addWidget(self.connections_label) self.connections_spinBox = QSpinBox(self.connections_frame) self.connections_spinBox.setMinimum(1) self.connections_spinBox.setMaximum(16) self.connections_spinBox.setProperty("value", 16) horizontalLayout_3.addWidget(self.connections_spinBox) connections_horizontalLayout.addWidget(self.connections_frame) connections_horizontalLayout.addStretch(1) more_options_tab_verticalLayout.addLayout(connections_horizontalLayout) self.add_link_tabWidget.addTab(self.more_options_tab, '') # advance options self.advance_options_tab = QWidget(self) advance_options_tab_verticalLayout = QVBoxLayout( self.advance_options_tab) # referer referer_horizontalLayout = QHBoxLayout() self.referer_label = QLabel(self.advance_options_tab) referer_horizontalLayout.addWidget(self.referer_label) self.referer_lineEdit = QLineEdit(self.advance_options_tab) referer_horizontalLayout.addWidget(self.referer_lineEdit) advance_options_tab_verticalLayout.addLayout(referer_horizontalLayout) # header header_horizontalLayout = QHBoxLayout() self.header_label = QLabel(self.advance_options_tab) header_horizontalLayout.addWidget(self.header_label) self.header_lineEdit = QLineEdit(self.advance_options_tab) header_horizontalLayout.addWidget(self.header_lineEdit) advance_options_tab_verticalLayout.addLayout(header_horizontalLayout) # user_agent user_agent_horizontalLayout = QHBoxLayout() self.user_agent_label = QLabel(self.advance_options_tab) user_agent_horizontalLayout.addWidget(self.user_agent_label) self.user_agent_lineEdit = QLineEdit(self.advance_options_tab) user_agent_horizontalLayout.addWidget(self.user_agent_lineEdit) advance_options_tab_verticalLayout.addLayout( user_agent_horizontalLayout) # load_cookies load_cookies_horizontalLayout = QHBoxLayout() self.load_cookies_label = QLabel(self.advance_options_tab) load_cookies_horizontalLayout.addWidget(self.load_cookies_label) self.load_cookies_lineEdit = QLineEdit(self.advance_options_tab) load_cookies_horizontalLayout.addWidget(self.load_cookies_lineEdit) advance_options_tab_verticalLayout.addLayout( load_cookies_horizontalLayout) self.add_link_tabWidget.addTab(self.advance_options_tab, '') # ok cancel download_later buttons -> buttons_horizontalLayout = QHBoxLayout() buttons_horizontalLayout.addStretch(1) self.download_later_pushButton = QPushButton(self) self.download_later_pushButton.setIcon(QIcon(icons + 'stop')) self.cancel_pushButton = QPushButton(self) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) self.ok_pushButton = QPushButton(self) self.ok_pushButton.setIcon(QIcon(icons + 'ok')) buttons_horizontalLayout.addWidget(self.download_later_pushButton) buttons_horizontalLayout.addWidget(self.cancel_pushButton) buttons_horizontalLayout.addWidget(self.ok_pushButton) window_verticalLayout.addLayout(buttons_horizontalLayout) self.setLayout(window_verticalLayout) # labels -> self.setWindowTitle( QCoreApplication.translate("addlink_ui_tr", "Enter Your Link")) self.link_label.setText( QCoreApplication.translate("addlink_ui_tr", "Download Link : ")) self.add_queue_label.setText( QCoreApplication.translate("addlink_ui_tr", "Add to category : ")) self.change_name_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Change File Name : ")) self.detect_proxy_pushButton.setText( QCoreApplication.translate("addlink_ui_tr", "Detect system proxy setting")) self.proxy_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Proxy")) self.proxy_pass_label.setText( QCoreApplication.translate("addlink_ui_tr", "Proxy PassWord : "******"addlink_ui_tr", "IP : ")) self.proxy_user_label.setText( QCoreApplication.translate("addlink_ui_tr", "Proxy UserName : "******"addlink_ui_tr", "Port:")) self.download_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Download UserName and PassWord")) self.download_user_label.setText( QCoreApplication.translate("addlink_ui_tr", "Download UserName : "******"addlink_ui_tr", "Download PassWord : "******"addlink_ui_tr", "Change Download Folder")) self.folder_label.setText( QCoreApplication.translate("addlink_ui_tr", "Download Folder : ")) self.start_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Start Time")) self.end_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "End Time")) self.limit_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Limit Speed")) self.limit_comboBox.setItemText( 0, QCoreApplication.translate("addlink_ui_tr", "KB/S")) self.limit_comboBox.setItemText( 1, QCoreApplication.translate("addlink_ui_tr", "MB/S")) self.connections_label.setText( QCoreApplication.translate("addlink_ui_tr", "Number Of Connections :")) self.cancel_pushButton.setText( QCoreApplication.translate("addlink_ui_tr", "Cancel")) self.ok_pushButton.setText( QCoreApplication.translate("addlink_ui_tr", "OK")) self.download_later_pushButton.setText( QCoreApplication.translate("addlink_ui_tr", "Download later")) self.add_link_tabWidget.setTabText( self.add_link_tabWidget.indexOf(self.link_tab), QCoreApplication.translate("addlink_ui_tr", "Link")) self.add_link_tabWidget.setTabText( self.add_link_tabWidget.indexOf(self.proxy_tab), QCoreApplication.translate("addlink_ui_tr", "Proxy")) self.add_link_tabWidget.setTabText( self.add_link_tabWidget.indexOf(self.more_options_tab), QCoreApplication.translate("addlink_ui_tr", "More Options")) self.add_link_tabWidget.setTabText( self.add_link_tabWidget.indexOf(self.advance_options_tab), QCoreApplication.translate("addlink_ui_tr", "Advanced Options")) self.referer_label.setText( QCoreApplication.translate("addlink_ui_tr", 'Referrer: ')) self.header_label.setText( QCoreApplication.translate("addlink_ui_tr", 'Header: ')) self.load_cookies_label.setText( QCoreApplication.translate("addlink_ui_tr", 'Load cookies: ')) self.user_agent_label.setText( QCoreApplication.translate("addlink_ui_tr", 'User agent: '))
def __init__(self, persepolis_setting): super().__init__() self.persepolis_setting = persepolis_setting icons = ':/' + str(persepolis_setting.value('settings/icons')) + '/' # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) # window self.setMinimumSize(QtCore.QSize(595, 284)) self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) self.setWindowTitle(QCoreApplication.translate("progress_ui_tr", "Persepolis Download Manager")) verticalLayout = QVBoxLayout(self) # progress_tabWidget self.progress_tabWidget = QTabWidget(self) # information_tab self.information_tab = QWidget() information_verticalLayout = QVBoxLayout(self.information_tab) # link_label self.link_label = QLabel(self.information_tab) information_verticalLayout.addWidget(self.link_label) # status_label self.status_label = QLabel(self.information_tab) information_verticalLayout.addWidget(self.status_label) # downloaded_label self.downloaded_label = QLabel(self.information_tab) information_verticalLayout.addWidget(self.downloaded_label) # rate_label self.rate_label = QLabel(self.information_tab) information_verticalLayout.addWidget(self.rate_label) # time_label self.time_label = QLabel(self.information_tab) information_verticalLayout.addWidget(self.time_label) # connections_label self.connections_label = QLabel(self.information_tab) information_verticalLayout.addWidget(self.connections_label) # add information_tab to progress_tabWidget self.progress_tabWidget.addTab(self.information_tab, "") # options_tab self.options_tab = QWidget() options_tab_horizontalLayout = QHBoxLayout(self.options_tab) options_tab_horizontalLayout.setContentsMargins(11, 11, 11, 11) # limit_checkBox self.limit_checkBox = QCheckBox(self.options_tab) limit_verticalLayout = QVBoxLayout() limit_verticalLayout.addWidget(self.limit_checkBox) # limit_frame self.limit_frame = QFrame(self.options_tab) self.limit_frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.limit_frame.setFrameShadow(QtWidgets.QFrame.Raised) limit_frame_verticalLayout = QVBoxLayout(self.limit_frame) limit_frame_horizontalLayout = QHBoxLayout() # limit_spinBox self.limit_spinBox = QDoubleSpinBox(self.options_tab) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) limit_frame_horizontalLayout.addWidget(self.limit_spinBox) # limit_comboBox self.limit_comboBox = QComboBox(self.options_tab) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") limit_frame_horizontalLayout.addWidget(self.limit_comboBox) # limit_pushButton self.limit_pushButton = QPushButton(self.options_tab) limit_frame_verticalLayout.addLayout(limit_frame_horizontalLayout) limit_frame_verticalLayout.addWidget(self.limit_pushButton) limit_verticalLayout.addWidget(self.limit_frame) limit_verticalLayout.setContentsMargins(11, 11, 11, 11) options_tab_horizontalLayout.addLayout(limit_verticalLayout) # after_checkBox self.after_checkBox = QCheckBox(self.options_tab) after_verticalLayout = QVBoxLayout() after_verticalLayout.addWidget(self.after_checkBox) # after_frame self.after_frame = QFrame(self.options_tab) self.after_frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.after_frame.setFrameShadow(QtWidgets.QFrame.Raised) after_frame_verticalLayout = QVBoxLayout(self.after_frame) # after_comboBox self.after_comboBox = QComboBox(self.options_tab) self.after_comboBox.addItem("") after_frame_verticalLayout.addWidget(self.after_comboBox) # after_pushButton self.after_pushButton = QPushButton(self.options_tab) after_frame_verticalLayout.addWidget(self.after_pushButton) after_verticalLayout.addWidget(self.after_frame) after_verticalLayout.setContentsMargins(11, 11, 11, 11) options_tab_horizontalLayout.addLayout(after_verticalLayout) self.progress_tabWidget.addTab(self.options_tab, "") verticalLayout.addWidget(self.progress_tabWidget) # download_progressBar self.download_progressBar = QProgressBar(self) verticalLayout.addWidget(self.download_progressBar) # buttons button_horizontalLayout = QHBoxLayout() button_horizontalLayout.addStretch(1) # resume_pushButton self.resume_pushButton = QPushButton(self) self.resume_pushButton.setIcon(QIcon(icons + 'play')) button_horizontalLayout.addWidget(self.resume_pushButton) # pause_pushButton self.pause_pushButton = QtWidgets.QPushButton(self) self.pause_pushButton.setIcon(QIcon(icons + 'pause')) button_horizontalLayout.addWidget(self.pause_pushButton) # stop_pushButton self.stop_pushButton = QtWidgets.QPushButton(self) self.stop_pushButton.setIcon(QIcon(icons + 'stop')) button_horizontalLayout.addWidget(self.stop_pushButton) verticalLayout.addLayout(button_horizontalLayout) self.progress_tabWidget.setCurrentIndex(0) # labels self.link_label.setText(QCoreApplication.translate("progress_ui_tr", "Link:")) self.status_label.setText(QCoreApplication.translate("progress_ui_tr", "Status: ")) self.downloaded_label.setText(QCoreApplication.translate("progress_ui_tr", "Downloaded:")) self.rate_label.setText(QCoreApplication.translate("progress_ui_tr", "Transfer rate: ")) self.time_label.setText(QCoreApplication.translate("progress_ui_tr", "Estimated time left:")) self.connections_label.setText(QCoreApplication.translate("progress_ui_tr", "Number of connections: ")) self.progress_tabWidget.setTabText(self.progress_tabWidget.indexOf( self.information_tab), QCoreApplication.translate("progress_ui_tr", "Download Information")) self.limit_checkBox.setText(QCoreApplication.translate("progress_ui_tr", "Limit Speed")) self.after_checkBox.setText(QCoreApplication.translate("progress_ui_tr", "After download")) self.limit_comboBox.setItemText(0, "KiB/s") self.limit_comboBox.setItemText(1, "MiB/s") self.limit_pushButton.setText(QCoreApplication.translate("progress_ui_tr", "Apply")) self.after_comboBox.setItemText(0, QCoreApplication.translate("progress_ui_tr", "Shut Down")) self.progress_tabWidget.setTabText( self.progress_tabWidget.indexOf(self.options_tab), QCoreApplication.translate("progress_ui_tr", "Download Options")) self.resume_pushButton.setText(QCoreApplication.translate("progress_ui_tr", "Resume")) self.pause_pushButton.setText(QCoreApplication.translate("progress_ui_tr", "Pause")) self.stop_pushButton.setText(QCoreApplication.translate("progress_ui_tr", "Stop")) self.after_pushButton.setText(QCoreApplication.translate("progress_ui_tr", "Apply"))
def data(self, index, role): source_index = self.mapToSource(index) source_model = self.sourceModel() if not source_index.isValid(): return QVariant() source_data = source_model.data(source_index, role) if role == Qt.DisplayRole: if index.column() == NetworkTableModel.columns_types.index( 'is_member'): value = { True: QT_TRANSLATE_NOOP("NetworkTableModel", 'yes'), False: QT_TRANSLATE_NOOP("NetworkTableModel", 'no'), None: QT_TRANSLATE_NOOP("NetworkTableModel", 'offline') } return value[source_data] if index.column() == NetworkTableModel.columns_types.index( 'pubkey'): return source_data[:5] if index.column() == NetworkTableModel.columns_types.index( 'current_block'): if source_data == -1: return "" else: return source_data if index.column() == NetworkTableModel.columns_types.index('address') \ or index.column() == NetworkTableModel.columns_types.index('port'): return "<p>" + source_data.replace('\n', "<br>") + "</p>" if index.column() == NetworkTableModel.columns_types.index( 'current_hash'): return source_data[:10] if index.column() == NetworkTableModel.columns_types.index( 'current_time') and source_data: ts = self.blockchain_processor.adjusted_ts( self.app.currency, source_data) return QLocale.toString( QLocale(), QDateTime.fromTime_t(ts), QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)) if role == Qt.TextAlignmentRole: if source_index.column() == NetworkTableModel.columns_types.index( 'address') or source_index.column() == self.sourceModel( ).columns_types.index('current_block'): return Qt.AlignRight | Qt.AlignVCenter if source_index.column() == NetworkTableModel.columns_types.index( 'is_member'): return Qt.AlignCenter if role == Qt.FontRole: is_root_col = NetworkTableModel.columns_types.index('is_root') index_root_col = source_model.index(source_index.row(), is_root_col) if source_model.data(index_root_col, Qt.DisplayRole): font = QFont() font.setBold(True) return font return source_data
def __init__(self, datadir=None, logdir=None): DistUpgradeView.__init__(self) get_telemetry().set_updater_type('KDE') # silence the PyQt4 logger logger = logging.getLogger("PyQt4") logger.setLevel(logging.INFO) if not datadir or datadir == '.': localedir=os.path.join(os.getcwd(),"mo") else: localedir="/usr/share/locale/ubuntu-release-upgrader" # FIXME: i18n must be somewhere relative do this dir try: gettext.bindtextdomain("ubuntu-release-upgrader", localedir) gettext.textdomain("ubuntu-release-upgrader") except Exception as e: logging.warning("Error setting locales (%s)" % e) # we test for DISPLAY here, QApplication does not throw a # exception when run without DISPLAY but dies instead if not "DISPLAY" in os.environ: raise Exception("No DISPLAY in os.environ found") # Force environment to make sure Qt uses suitable theming and UX. os.environ["QT_PLATFORM_PLUGIN"] = "kde" # For above settings to apply automatically we need to indicate that we # are inside a full KDE session. os.environ["KDE_FULL_SESSION"] = "TRUE" # We also need to indicate version as otherwise KDElibs3 compatibility # might kick in such as in QIconLoader.cpp:QString fallbackTheme. os.environ["KDE_SESSION_VERSION"] = "5" # Pretty much all of the above but for Qt5 os.environ["QT_QPA_PLATFORMTHEME"] = "kde" self.app = QApplication(["ubuntu-release-upgrader"]) # Try to load default Qt translations so we don't have to worry about # QStandardButton translations. translator = QTranslator(self.app) if type(PYQT_VERSION) == int: translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt5/translations') else: translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt4/translations') self.app.installTranslator(translator) QUrlOpener().setupUrlHandles() messageIcon = _icon("system-software-update", fallbacks=["/usr/share/icons/oxygen/48x48/apps/system-software-update.png", "/usr/share/icons/hicolor/48x48/apps/adept_manager.png"]) self.app.setWindowIcon(messageIcon) self.window_main = UpgraderMainWindow() self.window_main.setParent(self) self.window_main.show() self.prev_step = None # keep a record of the latest step self._opCacheProgress = KDEOpProgress(self.window_main.progressbar_cache, self.window_main.progress_text) self._acquireProgress = KDEAcquireProgressAdapter(self) self._cdromProgress = KDECdromProgressAdapter(self) self._installProgress = KDEInstallProgressAdapter(self) # reasonable fault handler sys.excepthook = self._handleException self.window_main.showTerminalButton.setEnabled(False) self.window_main.showTerminalButton.clicked.connect(self.showTerminal) # init gettext gettext.bindtextdomain("ubuntu-release-upgrader",localedir) gettext.textdomain("ubuntu-release-upgrader") self.translate_widget_children() name = _OSRelease().result["PRETTY_NAME"] if not name or name == "Ubuntu": name = "Kubuntu" title_string = self.window_main.label_title.text() title_string = title_string.replace("Ubuntu", name) title_string = title_string.replace("%s", "19.10") self.window_main.label_title.setText(title_string) # setup terminal text in hidden by default spot self.window_main.konsole_frame.hide() self.konsole_frame_layout = QHBoxLayout(self.window_main.konsole_frame) self.window_main.konsole_frame.setMinimumSize(600, 400) self.terminal_text = DumbTerminal(self._installProgress, self.window_main.konsole_frame) self.konsole_frame_layout.addWidget(self.terminal_text) self.terminal_text.show() self.inhibitScreenlock() atexit.register(self.uninhibitScreenlock) # for some reason we need to start the main loop to get everything displayed # this app mostly works with processEvents but run main loop briefly to keep it happily displaying all widgets QTimer.singleShot(10, self.exitMainLoopMidFlight) self.app.exec_()
labelVersion = QLabel(self) labelVersion.setText(" Vima versión beta: 1.0 ") self.statusBar = self.statusBar() self.statusBar.addPermanentWidget(labelVersion, 0) # ================================================================== if __name__ == '__main__': import sys aplicacion = QApplication(sys.argv) traductor = QTranslator(aplicacion) lugar = QLocale.system().name() path = QLibraryInfo.location(QLibraryInfo.TranslationsPath) traductor.load("qtbase_%s" % lugar, path) aplicacion.installTranslator(traductor) fuente = QFont() fuente.setPointSize(10) aplicacion.setFont(fuente) ventana = visorImagenes() ventana.show() sys.exit(aplicacion.exec_())
import proyectoFINAL proyectoFINAL.mainFunction() def AboutMessage(self): alert = QMessageBox() alert.setWindowIcon(QIcon('C:/PROYECTO FINAL/coche.png')) alert.setWindowTitle('Saliendo...') alert.setText('¡HASTA PRONTO!') alert.exec_() sys.exit() # ******************************************************************** if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) app.setStyle('Fusion') # Traducimos al idioma del SO qt_traductor = QTranslator() qt_traductor.load("qtbase_" + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qt_traductor) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) # Icono de aplicación MainWindow.setWindowIcon(QIcon('C:/PROYECTO FINAL/coche.png')) MainWindow.show() sys.exit(app.exec_())
def __init__(self, *args, **kwargs): QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates)) super().__init__(*args, **kwargs) self.setupview()
import os import sys import json import signal import weakref from PyQt5 import QtCore from PyQt5.QtCore import QCoreApplication if os.name == 'posix': QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads, True) # from PyQt5.QtGui import QFont from PyQt5.QtCore import pyqtSlot, QObject, QTranslator, QLocale, QLibraryInfo from PyQt5.QtWidgets import QApplication appTranslator = QTranslator() translationsPath = "qt_" + QLocale.system().name() appTranslator.load("qt_zh_CN.qm", QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app = QApplication(sys.argv) app.setApplicationVersion("2.1") app.installTranslator(appTranslator) app.setQuitOnLastWindowClosed(True) from window import Window from database import database from config import config from movie_info import movie_info from browser import Browser from utils import utils, FindVideoThreadManager from constant import MAIN_QML from menu_controller import MenuController
class ImapServer(QObject): socket.setdefaulttimeout(1) imap_signal = pyqtSignal() def __init__(self): super().__init__() self.serverIMAP = None self.mailbox = 'INBOX' self.is_connected = False self.is_first_connection = True self.running = False self.log = "?" self.server_id = -1 self.thread = None self.db = DataBaseConnection(init_table=True) self.locale = QLocale(QLocale.English, QLocale.UnitedStates) self.start_sync = None self.last_mail_datetime = None def __del__(self): # with self.lock: self.running = False if (threading.active_count() != 0 and self.thread != None): self.thread.join() self.close_server() def start_server(self): # with self.lock: self.running = True self.thread = threading.Thread(target=self.update_imap, daemon=True) self.thread.start() def stop_server(self): # with self.lock: if (self.running == True): self.running = False if (self.thread != None): self.thread.join() def close_server(self): if self.is_connected == True: self.is_connected = False self.is_first_connection = True try: self.serverIMAP.close() self.serverIMAP.logout() except imaplib.IMAP4.error as err: print(err, flush=True) def update_imap(self): self.db = DataBaseConnection(init_table=True) while self.running: if (not self.is_connected): self.connect_imap() if (self.is_connected and self.is_first_connection): self.update_first_connection() if (self.is_connected and not self.is_first_connection): self.update_recent() time.sleep(5.0) def set_server_id(self, server_id): self.server_id = server_id def connect_imap(self): print("Try connect") try: # Retreive data from DB login_data = self.db.get_server_data(self.server_id) if (len(login_data) == 0): raise Exception('wrong server_id ', self.server_id) self.serverIMAP = imaplib.IMAP4_SSL(login_data["server_ip"], login_data["server_port"]) rsp = self.serverIMAP.login(login_data["email"], login_data["password"]) if (rsp[1][0].decode() == "LOGIN completed."): self.is_connected = True self.is_first_connection = True rsp, nb_message_inbox = self.serverIMAP.select( mailbox=self.mailbox, readonly=False) print("select rsp = ", rsp, " nb_message = ", nb_message_inbox[0].decode()) self.log = "Connected" else: raise Exception('Failed to select') return True except imaplib.IMAP4.error as err: print("Error imap ", err) self.log = "Error IMAP" self.close_server() return False except sqlite3.Error as error: print("Error sqlite ", error) self.log = "Error SQLITE" self.close_server() return False except: print("Error ", sys.exc_info()) self.log = "Error - No connection" self.close_server() return False def process_msg(self, msgnums): if (msgnums[0] != None): k = 1 list_msg_num = msgnums[0].split() for num in list_msg_num: if (not self.download_msg(num.decode())): return False self.log = "Update " + str(k) + "/" + str( len(list_msg_num)) + " (" + str(num.decode()) + ")" k += 1 self.imap_signal.emit() return True def update_recent(self): self.log = "Update " + str( datetime.datetime.now().replace(microsecond=0)) try: t = datetime.datetime.now() rsp, msgnums = self.serverIMAP.recent() if (not self.process_msg(msgnums)): return False self.db.update_last_sync( self.server_id, t.replace(microsecond=0).isoformat()) # without microsecond return True except imaplib.IMAP4.error as err: self.close_server() print(err, flush=True) self.log = "Error imaplib" return False except: print("Error ", sys.exc_info()) self.close_server() self.log = "Error (timeout)" return False def update_first_connection(self): print("Try update_first_connection") t = datetime.datetime.now() try: # Search for email since last sync date self.start_sync = self.db.get_last_sync(self.server_id) date_string = self.locale.toString(self.start_sync, "dd-MMM-yyyy") print(date_string) typ, msgnums = self.serverIMAP.search( None, 'SINCE {date}'.format(date=date_string), 'FROM "*****@*****.**"') if (not self.process_msg(msgnums)): return False self.is_first_connection = False self.db.update_last_sync(self.server_id, t) self.log = "Connected" return True except imaplib.IMAP4.error as err: self.close_server() self.log = "Error IMAP" print(err) return False except sqlite3.Error as error: self.close_server() self.log = "Error SQLITE" print(error) return False except: print("Error ", sys.exc_info()) self.close_server() self.log = "Error - No connection" return False def download_msg(self, msgnum): if (msgnum == "0"): return True print("Download msg ", msgnum) try: typ, data_msg = self.serverIMAP.fetch(msgnum, '(BODY.PEEK[])') except imaplib.IMAP4.error as err: self.close_server() self.log = "Error IMAP" print(err) return False # Parse received part (starting with "Received: ") mail = email.message_from_bytes(data_msg[0][1], policy=default) if (mail["From"] == "*****@*****.**"): # imei = mail["Subject"].split(": ")[1] print(mail["Subject"]) imei = re.search("SBD (.*): (.*)", mail["Subject"]).group(2) time_connection = calendar.timegm(parsedate(mail["Date"])) # Check timed received mail_datetime = QDateTime.fromString(mail["Date"], Qt.RFC2822Date) # if(self.last_mail_datetime>=mail_datetime): # print("Before last mail datetime") # return True if mail.get_content_maintype() != 'multipart': print("No attachment") return True self.db.add_new_robot(imei) # Add new robot if not existing ## Extract enclosed file for part in mail.iter_attachments(): if part.get_content_maintype() == 'application': # Extract momsn from attached file print(part.get_filename()) momsn = int( re.search("_(.*)\.", part.get_filename()).group(1)) # Add new entry to the database with the association of the imei and momsn message_id = self.db.add_sbd_received( imei, momsn, time_connection) # Test if message is already saved if (message_id != None): msg_data = part.get_payload(decode=True) IridiumMessageParser(msg_data, self.db, message_id, time_connection) return True def get_log(self): return self.log def get_is_connected(self): return self.is_connected
def ajoutRechercheBonDeTravail(self): # Recuperation des differents attributs self.bonDeTravailManager = BonTravailManager(pathBonTravailDatabase) try: fichierConf = open(pathFichierConf, 'r') # try: ouvrir le fichier et le lire with fichierConf: self._conf = yaml.load(fichierConf) except IOError: # attrape l'erreur IOError si elle se présente et renvoie print("Could not read file: ", pathFichierConf) # définir ce qu'il faut faire pour corriger self.listeCategorieEquipement = list(self._conf['CategorieEquipement']) self.listeCategorieEquipement.sort() self.listeUnite = list(self._conf['Unite']) self.listeUnite.sort() self.listeEtatService = list(self._conf['EtatService']) self.listeEtatService.sort() #Mise a jour des differentes listes deroulantes self.comboBoxCategorieEquipement.clear() self.comboBoxCategorieEquipement.addItem("") self.comboBoxCategorieEquipement.addItems( self.listeCategorieEquipement) self.comboBoxEtat.clear() self.comboBoxEtat.addItem("") self.comboBoxEtat.addItems(self.listeEtatService) self.comboBoxUnite.clear() self.comboBoxUnite.addItem("") self.comboBoxUnite.addItems(self.listeUnite) fichierConf.close() self.signalRechercheBon = Communicate() self.signalRechercheBon.aucunResultat.connect(self.aucunResultat) self.signalRechercheBon.remplirTableau.connect(self.remplirTableau) self.signalRechercheBon.nouvelleRecherche.connect( self.nouvelleRecherche) #modification calendrier calendrierApres = QCalendarWidget() calendrierApres.setStyleSheet("background :#F5F5F5;\n color: black;") calendrierApres.setGridVisible(True) self.calendrierApres.setCalendarWidget(calendrierApres) calendrierApres.setVerticalHeaderFormat( QCalendarWidget.NoVerticalHeader) self.calendrierApres.setLocale(QLocale(QLocale.French, QLocale.France)) calendrierAvant = QCalendarWidget() calendrierAvant.setStyleSheet("background :#F5F5F5;\n color: black;") calendrierAvant.setVerticalHeaderFormat( QCalendarWidget.NoVerticalHeader) calendrierAvant.setGridVisible(True) self.calendrierAvant.setCalendarWidget(calendrierAvant) self.calendrierAvant.setLocale(QLocale(QLocale.French, QLocale.France)) self.calendrierAvant.setDate(QDate.currentDate()) self.calendrierApres.setDate(QDate.currentDate()) #Creation des differents colonnes pour le tableau de resultat self.listeCleDonnees = list([ "IdEquipement", "NumeroBonTravail", "CategorieEquipement", "Modele", "Unite", "EtatBDT", "Date", "DescriptionSituation" ]) #liste contenant les bons résultant de la recherche self.listeResultat = list() #liste contenant les informations des bons a afficher self.listeDonnees = list() self.tableResultats.setColumnCount(len(self.listeCleDonnees)) self.listeHeaders = [ "Id de l'équipement", "Numero du bon de travail", "Catégorie d'équipement", "Modèle", "Unité", "État BDT", "Date", "Description de la situation" ] self.tableResultats.setHorizontalHeaderLabels(self.listeHeaders) self.tableResultats.resizeColumnsToContents() self.tableResultats.setRowCount(0) self.dictionnaireRecherche = dict() #Connexion des differentes recherches pour la mise a jour automatique self.comboBoxCategorieEquipement.currentTextChanged.connect( self.rechercheCategorieEquipement) self.comboBoxEtat.currentTextChanged.connect( self.rechercheEtatDeService) self.comboBoxUnite.currentTextChanged.connect(self.rechercheUnite) self.calendrierAvant.dateChanged.connect(self.rechercheDateAvant) self.lineEditDescriptionSituation.returnPressed.connect( self.rechercheDescriptionSituation) self.calendrierApres.dateChanged.connect(self.rechercheDateApres) self.boutonNouvelleRecherche.clicked.connect( self.signalRechercheBon.nouvelleRecherche.emit) self.tableResultats.horizontalHeader().sectionClicked.connect( self.trier) self.boutonActualiser.clicked.connect(self.rechercherBonTravailThread) self.colonneClique = None self.nombreClique = 0 # Empeche la modification de la table self.tableResultats.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) self.tableResultats.setSelectionBehavior( QtWidgets.QAbstractItemView.SelectRows) self.tableResultats.cellDoubleClicked.connect(self.choisirBonDeTravail) self.bonDeTravailSelectionne = None
def get_default_language(): name = QLocale.system().name() return name if name in languages else 'en_UK'
def __init__(self, parent, persepolis_setting): super().__init__(persepolis_setting) self.persepolis_setting = persepolis_setting self.parent = parent self.grandparent = parent.persepolis_main self.persepolis_setting.beginGroup('settings') # initialization self.tries_spinBox.setValue( int(self.persepolis_setting.value('max-tries'))) self.wait_spinBox.setValue( int(self.persepolis_setting.value('retry-wait'))) self.time_out_spinBox.setValue( int(self.persepolis_setting.value('timeout'))) self.connections_spinBox.setValue( int(self.persepolis_setting.value('connections'))) self.rpc_port_spinbox.setValue( int(self.persepolis_setting.value('rpc-port'))) # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # wait_queue wait_queue_list = self.persepolis_setting.value('wait-queue') q_time = QTime(int(wait_queue_list[0]), int(wait_queue_list[1])) self.wait_queue_time.setTime(q_time) # change aria2 path self.aria2_path_pushButton.clicked.connect(self.changeAria2Path) self.aria2_path_checkBox.toggled.connect(self.ariaCheckBoxToggled) aria2_path = self.persepolis_setting.value('settings/aria2_path') self.aria2_path_lineEdit.setEnabled(False) if aria2_path != None: self.aria2_path_checkBox.setChecked(True) self.aria2_path_lineEdit.setText(str(aria2_path)) self.ariaCheckBoxToggled('aria2') if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD': for widget in self.aria2_path_checkBox, self.aria2_path_lineEdit, self.aria2_path_pushButton: widget.hide() # save_as_tab self.download_folder_lineEdit.setText( str(self.persepolis_setting.value('download_path'))) self.temp_download_lineEdit.setText( str(self.persepolis_setting.value('download_path_temp'))) # subfolder if str(self.persepolis_setting.value('subfolder')) == 'yes': self.subfolder_checkBox.setChecked(True) else: self.subfolder_checkBox.setChecked(False) # notifications_tab self.volume_label.setText( 'Volume : ' + str(self.persepolis_setting.value('sound-volume'))) self.volume_dial.setValue( int(self.persepolis_setting.value('sound-volume'))) # set style # if style_comboBox is changed, self.styleComboBoxChanged is called. self.style_comboBox.currentIndexChanged.connect( self.styleComboBoxChanged) # find available styles(It's depends on operating system and desktop environments). available_styles = QStyleFactory.keys() for style in available_styles: # 'GTK' or 'gtk' styles may cause to crashing! Eliminate them! if 'gtk' not in str(style) and 'GTK' not in str(style): self.style_comboBox.addItem(style) # System >> for system default style # when user select System for style section, the default system style is using. self.style_comboBox.addItem('System') current_style_index = self.style_comboBox.findText( str(self.persepolis_setting.value('style'))) if current_style_index != -1: self.style_comboBox.setCurrentIndex(current_style_index) # available language available_language = [ 'en_US', 'fa_IR', 'zh_CN', 'fr_FR', 'pl_PL', 'nl_NL' ] for lang in available_language: self.lang_comboBox.addItem(str(QLocale(lang).nativeLanguageName()), lang) current_locale = self.lang_comboBox.findData( str(self.persepolis_setting.value('locale'))) self.lang_comboBox.setCurrentIndex(current_locale) self.lang_comboBox.currentIndexChanged.connect( self.styleComboBoxChanged) self.styleComboBoxChanged() current_color_index = self.color_comboBox.findText( str(self.persepolis_setting.value('color-scheme'))) self.color_comboBox.setCurrentIndex(current_color_index) self.current_icon = self.persepolis_setting.value('icons') # icon size size = ['128', '64', '48', '32', '24', '16'] self.icons_size_comboBox.addItems(size) current_icons_size_index = self.icons_size_comboBox.findText( str(self.persepolis_setting.value('toolbar_icon_size'))) self.icons_size_comboBox.setCurrentIndex(current_icons_size_index) # call iconSizeComboBoxCanged if index is changed self.icons_size_comboBox.currentIndexChanged.connect( self.iconSizeComboBoxCanged) self.iconSizeComboBoxCanged(1) # set notification notifications = ['Native notification', 'QT notification'] self.notification_comboBox.addItems(notifications) current_notification_index = self.notification_comboBox.findText( str(self.persepolis_setting.value('notification'))) self.notification_comboBox.setCurrentIndex(current_notification_index) # set font font_setting = QFont() font_setting.setFamily(str(self.persepolis_setting.value('font'))) self.fontComboBox.setCurrentFont(font_setting) self.font_size_spinBox.setValue( int(self.persepolis_setting.value('font-size'))) # sound frame self.sound_frame.setEnabled(False) self.enable_notifications_checkBox.toggled.connect(self.soundFrame) if str(self.persepolis_setting.value('sound')) == 'yes': self.enable_notifications_checkBox.setChecked(True) else: self.enable_notifications_checkBox.setChecked(False) # connect folder buttons self.download_folder_lineEdit.setEnabled(False) self.download_folder_pushButton.clicked.connect( self.downloadFolderPushButtonClicked) self.temp_download_lineEdit.setEnabled(False) self.temp_download_pushButton.clicked.connect( self.tempDownloadPushButtonClicked) # dial self.volume_dial.setNotchesVisible(True) self.volume_dial.valueChanged.connect(self.dialChanged) # start_persepolis_if_browser_executed_checkBox if str(self.persepolis_setting.value('browser-persepolis')) == 'yes': self.start_persepolis_if_browser_executed_checkBox.setChecked(True) else: self.start_persepolis_if_browser_executed_checkBox.setChecked( False) # hide window if str(self.persepolis_setting.value('hide-window')) == 'yes': self.hide_window_checkBox.setChecked(True) else: self.hide_window_checkBox.setChecked(False) # tray icon if str(self.persepolis_setting.value('tray-icon')) == 'yes': self.enable_system_tray_checkBox.setChecked(True) else: self.enable_notifications_checkBox.setChecked(False) # show_menubar if str(self.persepolis_setting.value('show-menubar')) == 'yes': self.show_menubar_checkbox.setChecked(True) else: self.show_menubar_checkbox.setChecked(False) if platform.system() == 'Darwin': self.show_menubar_checkbox.setChecked(True) self.show_menubar_checkbox.hide() # show_sidepanel if str(self.persepolis_setting.value('show-sidepanel')) == 'yes': self.show_sidepanel_checkbox.setChecked(True) else: self.show_sidepanel_checkbox.setChecked(False) # show ProgressWindow if str(self.persepolis_setting.value('show-progress')) == 'yes': self.show_progress_window_checkbox.setChecked(True) else: self.show_progress_window_checkbox.setChecked(False) # after download dialog if str(self.persepolis_setting.value('after-dialog')) == 'yes': self.after_download_checkBox.setChecked(True) else: self.after_download_checkBox.setChecked(False) # run persepolis at startup checkBox if str(self.persepolis_setting.value('startup')) == 'yes': self.startup_checkbox.setChecked(True) else: self.startup_checkbox.setChecked(False) # font_checkBox if str(self.persepolis_setting.value('custom-font')) == 'yes': self.font_checkBox.setChecked(True) else: self.font_checkBox.setChecked(False) self.fontCheckBoxState(self.font_checkBox) # keep_awake_checkBox if str(self.persepolis_setting.value('awake')) == 'yes': self.keep_awake_checkBox.setChecked(True) else: self.keep_awake_checkBox.setChecked(False) # columns_tab if str(self.persepolis_setting.value('column0')) == 'yes': self.column0_checkBox.setChecked(True) else: self.column0_checkBox.setChecked(False) if str(self.persepolis_setting.value('column1')) == 'yes': self.column1_checkBox.setChecked(True) else: self.column1_checkBox.setChecked(False) if str(self.persepolis_setting.value('column2')) == 'yes': self.column2_checkBox.setChecked(True) else: self.column2_checkBox.setChecked(False) if str(self.persepolis_setting.value('column3')) == 'yes': self.column3_checkBox.setChecked(True) else: self.column3_checkBox.setChecked(False) if str(self.persepolis_setting.value('column4')) == 'yes': self.column4_checkBox.setChecked(True) else: self.column4_checkBox.setChecked(False) if str(self.persepolis_setting.value('column5')) == 'yes': self.column5_checkBox.setChecked(True) else: self.column5_checkBox.setChecked(False) if str(self.persepolis_setting.value('column6')) == 'yes': self.column6_checkBox.setChecked(True) else: self.column6_checkBox.setChecked(False) if str(self.persepolis_setting.value('column7')) == 'yes': self.column7_checkBox.setChecked(True) else: self.column7_checkBox.setChecked(False) if str(self.persepolis_setting.value('column10')) == 'yes': self.column10_checkBox.setChecked(True) else: self.column10_checkBox.setChecked(False) if str(self.persepolis_setting.value('column11')) == 'yes': self.column11_checkBox.setChecked(True) else: self.column11_checkBox.setChecked(False) if str(self.persepolis_setting.value('column12')) == 'yes': self.column12_checkBox.setChecked(True) else: self.column12_checkBox.setChecked(False) # video_finder try: # Integer casting may raise exception. self.max_links_spinBox.setValue( int(persepolis_setting.value('video_finder/max_links', 3))) except: pass # shortcuts self.qshortcuts_list = [ self.parent.exitAction_shortcut, self.parent.minimizeAction_shortcut, self.parent.removeSelectedAction_shortcut, self.parent.deleteSelectedAction_shortcut, self.parent.moveUpSelectedAction_shortcut, self.parent.moveDownSelectedAction_shortcut, self.parent.addlinkAction_shortcut, self.parent.videoFinderAddLinkAction_shortcut, self.parent.addtextfileAction_shortcut ] self.shortcuts_list = [ self.parent.exitAction_shortcut.key().toString(), self.parent.minimizeAction_shortcut.key().toString(), self.parent.removeSelectedAction_shortcut.key().toString(), self.parent.deleteSelectedAction_shortcut.key().toString(), self.parent.moveUpSelectedAction_shortcut.key().toString(), self.parent.moveDownSelectedAction_shortcut.key().toString(), self.parent.addlinkAction_shortcut.key().toString(), self.parent.videoFinderAddLinkAction_shortcut.key().toString(), self.parent.addtextfileAction_shortcut.key().toString() ] # add shortcuts to the shortcut_table j = 0 for shortcut in self.shortcuts_list: item = QTableWidgetItem(shortcut) # align center item.setTextAlignment(0x0004 | 0x0080) # insert item in shortcut_table self.shortcut_table.setItem(j, 1, item) j = j + 1 # If user doubleclicks on a row, then run showCaptureKeyboardWindow method self.shortcut_table.itemDoubleClicked.connect( self.showCaptureKeyboardWindow) # ok cancel default button self.cancel_pushButton.clicked.connect(self.close) self.defaults_pushButton.clicked.connect( self.defaultsPushButtonPressed) self.ok_pushButton.clicked.connect(self.okPushButtonPressed) # font_checkBox connect self.font_checkBox.stateChanged.connect(self.fontCheckBoxState) # saving initial value of self.persepolis_setting in self.first_key_value_dict # at the end! in the okPushButtonPressed method, first_key_value_dict will compared with second_key_value_dict. # if any thing changed , then a message box notify user about "some changes take effect after restarting persepolis". self.first_key_value_dict = {} for member in self.persepolis_setting.allKeys(): self.first_key_value_dict[member] = str( self.persepolis_setting.value(member)) self.persepolis_setting.endGroup() # setting window size and position size = self.persepolis_setting.value('PreferencesWindow/size', QSize(578, 565)) position = self.persepolis_setting.value('PreferencesWindow/position', QPoint(300, 300)) self.resize(size) self.move(position)
def l10nDecimal(dec, digits=2): from PyQt5.QtCore import QLocale l=QLocale() return l.toCurrencyString(float(dec))
def createGeneralOptionsGroupBox(self): self.generalOptionsGroupBox = QGroupBox("General Options") self.localeCombo = QComboBox() curLocaleIndex = -1 index = 0 for lid in range(QLocale.C, QLocale.LastLanguage + 1): lang = QLocale.Language(lid) countries = QLocale.countriesForLanguage(lang) for country in countries: label = "%s/%s" % (QLocale.languageToString(lang), QLocale.countryToString(country)) locale = QLocale(lang, country) if self.locale().language() == lang and self.locale().country( ) == country: curLocaleIndex = index self.localeCombo.addItem(label, locale) index += 1 if curLocaleIndex != -1: self.localeCombo.setCurrentIndex(curLocaleIndex) self.localeLabel = QLabel("&Locale") self.localeLabel.setBuddy(self.localeCombo) self.firstDayCombo = QComboBox() self.firstDayCombo.addItem("Sunday", Qt.Sunday) self.firstDayCombo.addItem("Monday", Qt.Monday) self.firstDayCombo.addItem("Tuesday", Qt.Tuesday) self.firstDayCombo.addItem("Wednesday", Qt.Wednesday) self.firstDayCombo.addItem("Thursday", Qt.Thursday) self.firstDayCombo.addItem("Friday", Qt.Friday) self.firstDayCombo.addItem("Saturday", Qt.Saturday) self.firstDayLabel = QLabel("Wee&k starts on:") self.firstDayLabel.setBuddy(self.firstDayCombo) self.selectionModeCombo = QComboBox() self.selectionModeCombo.addItem("Single selection", QCalendarWidget.SingleSelection) self.selectionModeCombo.addItem("None", QCalendarWidget.NoSelection) self.selectionModeLabel = QLabel("&Selection mode:") self.selectionModeLabel.setBuddy(self.selectionModeCombo) self.gridCheckBox = QCheckBox("&Grid") self.gridCheckBox.setChecked(self.calendar.isGridVisible()) self.navigationCheckBox = QCheckBox("&Navigation bar") self.navigationCheckBox.setChecked(True) self.horizontalHeaderCombo = QComboBox() self.horizontalHeaderCombo.addItem( "Single letter day names", QCalendarWidget.SingleLetterDayNames) self.horizontalHeaderCombo.addItem("Short day names", QCalendarWidget.ShortDayNames) self.horizontalHeaderCombo.addItem("Long day names", QCalendarWidget.LongDayNames) self.horizontalHeaderCombo.addItem("None", QCalendarWidget.NoHorizontalHeader) self.horizontalHeaderCombo.setCurrentIndex(1) self.horizontalHeaderLabel = QLabel("&Horizontal header:") self.horizontalHeaderLabel.setBuddy(self.horizontalHeaderCombo) self.verticalHeaderCombo = QComboBox() self.verticalHeaderCombo.addItem("ISO week numbers", QCalendarWidget.ISOWeekNumbers) self.verticalHeaderCombo.addItem("None", QCalendarWidget.NoVerticalHeader) self.verticalHeaderLabel = QLabel("&Vertical header:") self.verticalHeaderLabel.setBuddy(self.verticalHeaderCombo) self.localeCombo.currentIndexChanged.connect(self.localeChanged) self.firstDayCombo.currentIndexChanged.connect(self.firstDayChanged) self.selectionModeCombo.currentIndexChanged.connect( self.selectionModeChanged) self.gridCheckBox.toggled.connect(self.calendar.setGridVisible) self.navigationCheckBox.toggled.connect( self.calendar.setNavigationBarVisible) self.horizontalHeaderCombo.currentIndexChanged.connect( self.horizontalHeaderChanged) self.verticalHeaderCombo.currentIndexChanged.connect( self.verticalHeaderChanged) checkBoxLayout = QHBoxLayout() checkBoxLayout.addWidget(self.gridCheckBox) checkBoxLayout.addStretch() checkBoxLayout.addWidget(self.navigationCheckBox) outerLayout = QGridLayout() outerLayout.addWidget(self.localeLabel, 0, 0) outerLayout.addWidget(self.localeCombo, 0, 1) outerLayout.addWidget(self.firstDayLabel, 1, 0) outerLayout.addWidget(self.firstDayCombo, 1, 1) outerLayout.addWidget(self.selectionModeLabel, 2, 0) outerLayout.addWidget(self.selectionModeCombo, 2, 1) outerLayout.addLayout(checkBoxLayout, 3, 0, 1, 2) outerLayout.addWidget(self.horizontalHeaderLabel, 4, 0) outerLayout.addWidget(self.horizontalHeaderCombo, 4, 1) outerLayout.addWidget(self.verticalHeaderLabel, 5, 0) outerLayout.addWidget(self.verticalHeaderCombo, 5, 1) self.generalOptionsGroupBox.setLayout(outerLayout) self.firstDayChanged(self.firstDayCombo.currentIndex()) self.selectionModeChanged(self.selectionModeCombo.currentIndex()) self.horizontalHeaderChanged(self.horizontalHeaderCombo.currentIndex()) self.verticalHeaderChanged(self.verticalHeaderCombo.currentIndex())
def data(self, index, role): source_index = self.mapToSource(index) if source_index.isValid(): source_data = self.sourceModel().data(source_index, role) publication_col = CertifiersTableModel.columns_ids.index( 'publication') publication_index = self.sourceModel().index( source_index.row(), publication_col) expiration_col = CertifiersTableModel.columns_ids.index( 'expiration') expiration_index = self.sourceModel().index( source_index.row(), expiration_col) written_col = CertifiersTableModel.columns_ids.index('written') written_index = self.sourceModel().index(source_index.row(), written_col) publication_data = self.sourceModel().data(publication_index, Qt.DisplayRole) expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole) written_data = self.sourceModel().data(written_index, Qt.DisplayRole) current_time = QDateTime().currentDateTime().toMSecsSinceEpoch() warning_expiration_time = int( (expiration_data - publication_data) / 3) #logging.debug("{0} > {1}".format(current_time, expiration_data)) if role == Qt.DisplayRole: if source_index.column( ) == CertifiersTableModel.columns_ids.index('expiration'): if source_data: ts = self.blockchain_processor.adjusted_ts( self.app.currency, source_data) return QLocale.toString( QLocale(), QDateTime.fromTime_t(ts), QLocale.dateTimeFormat( QLocale(), QLocale.ShortFormat)) + " BAT" else: return "" if source_index.column( ) == CertifiersTableModel.columns_ids.index('publication'): if source_data: ts = self.blockchain_processor.adjusted_ts( self.app.currency, source_data) return QLocale.toString( QLocale(), QDateTime.fromTime_t(ts), QLocale.dateTimeFormat( QLocale(), QLocale.ShortFormat)) + " BAT" else: return "" if source_index.column( ) == CertifiersTableModel.columns_ids.index('pubkey'): return source_data if role == Qt.FontRole: font = QFont() if not written_data: font.setItalic(True) return font if role == Qt.ForegroundRole: if current_time > ((expiration_data * 1000) - (warning_expiration_time * 1000)): return QColor("darkorange").darker(120) return source_data
# You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Main_hydra_dev.ui' # # Created by: PyQt4 UI code generator 4.12.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui from PyQt5.QtCore import QLocale QLocale.setDefault(QLocale(QLocale.C)) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("KerberosSDR") MainWindow.resize(1366, 870) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.verticalLayout_6 = QtGui.QVBoxLayout() self.verticalLayout_6.setObjectName("verticalLayout_6") self.stackedWidget_config = QtGui.QStackedWidget(self.centralwidget) self.stackedWidget_config.setMaximumSize(QtCore.QSize(290, 16777215)) self.stackedWidget_config.setObjectName("stackedWidget_config")
if res == True: return True elif res == "UNIQUE constraint failed: fournisseurs.NOM": QMessageBox.warning(self, "Erreur", "Ce nom existe déjà.") else: QMessageBox.warning(self, "Erreur", "Erreur de requette inconnue!") def add_code_compta(self): name, code, ok = CodeComptaDialog.getCode() if ok and name != "": datas = {'code': code, 'nom': name} response = self.model.add(datas, 'codecompta') if response == "UNIQUE constraint failed: codecompta.CODE": QMessageBox.warning(self, "Erreur", "Ce code existe déjà") def add_input(self): res = AddInputDialog(self) def about_d(self): QMessageBox.information(self, "Diabolik Compta", "version 0.0.4") app = QApplication(sys.argv) translator = QTranslator() translator.load('qt_' + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(translator) main_window = MainWindow() sys.exit(app.exec_())
def __init__(self, configDialog): """ Constructor @param configDialog reference to the configuration dialog (ConfigurationDialog) """ super(HelpWebBrowserPage, self).__init__() self.setupUi(self) self.setObjectName("HelpWebBrowserPage") self.__configDlg = configDialog mw = configDialog.parent().parent() if hasattr(mw, "helpWindow") and mw.helpWindow is not None: self.__helpWindow = mw.helpWindow elif hasattr(mw, "currentBrowser"): self.__helpWindow = mw else: self.__helpWindow = None self.setCurrentPageButton.setEnabled(self.__helpWindow is not None) defaultSchemes = ["file://", "http://", "https://"] self.defaultSchemeCombo.addItems(defaultSchemes) self.clickToFlashCheckBox.setIcon( UI.PixmapCache.getIcon("flashBlock.png")) # set initial values self.singleHelpWindowCheckBox.setChecked( Preferences.getHelp("SingleHelpWindow")) self.saveGeometryCheckBox.setChecked( Preferences.getHelp("SaveGeometry")) self.webSuggestionsCheckBox.setChecked( Preferences.getHelp("WebSearchSuggestions")) self.showTabPreviews.setChecked(Preferences.getHelp("ShowPreview")) self.accessKeysCheckBox.setChecked( Preferences.getHelp("AccessKeysEnabled")) self.javaCheckBox.setChecked(Preferences.getHelp("JavaEnabled")) self.javaScriptCheckBox.setChecked( Preferences.getHelp("JavaScriptEnabled")) self.jsOpenWindowsCheckBox.setChecked( Preferences.getHelp("JavaScriptCanOpenWindows")) self.jsClipboardCheckBox.setChecked( Preferences.getHelp("JavaScriptCanAccessClipboard")) self.pluginsCheckBox.setChecked(Preferences.getHelp("PluginsEnabled")) self.clickToFlashCheckBox.setChecked( Preferences.getHelp("ClickToFlashEnabled")) self.doNotTrackCheckBox.setChecked(Preferences.getHelp("DoNotTrack")) self.sendRefererCheckBox.setChecked(Preferences.getHelp("SendReferer")) self.diskCacheCheckBox.setChecked( Preferences.getHelp("DiskCacheEnabled")) self.cacheSizeSpinBox.setValue(Preferences.getHelp("DiskCacheSize")) cachePolicy = Preferences.getHelp("CachePolicy") if cachePolicy == QNetworkRequest.PreferNetwork: self.cacheKeepButton.setChecked(True) elif cachePolicy == QNetworkRequest.PreferCache: self.cachePreferButton.setChecked(True) elif cachePolicy == QNetworkRequest.AlwaysCache: self.cacheOfflineButton.setChecked(True) self.printBackgroundsCheckBox.setChecked( Preferences.getHelp("PrintBackgrounds")) self.startupCombo.setCurrentIndex( Preferences.getHelp("StartupBehavior")) self.homePageEdit.setText(Preferences.getHelp("HomePage")) self.defaultSchemeCombo.setCurrentIndex( self.defaultSchemeCombo.findText( Preferences.getHelp("DefaultScheme"))) historyLimit = Preferences.getHelp("HistoryLimit") idx = 0 if historyLimit == 1: idx = 0 elif historyLimit == 7: idx = 1 elif historyLimit == 14: idx = 2 elif historyLimit == 30: idx = 3 elif historyLimit == 365: idx = 4 elif historyLimit == -1: idx = 5 elif historyLimit == -2: idx = 6 else: idx = 5 self.expireHistory.setCurrentIndex(idx) for language in range(2, QLocale.LastLanguage + 1): countries = [ l.country() for l in QLocale.matchingLocales( language, QLocale.AnyScript, QLocale.AnyCountry) ] if len(countries) > 0: self.languageCombo.addItem(QLocale.languageToString(language), language) self.languageCombo.model().sort(0) self.languageCombo.insertSeparator(0) self.languageCombo.insertItem(0, QLocale.languageToString(0), 0) index = self.languageCombo.findData( Preferences.getHelp("SearchLanguage")) if index > -1: self.languageCombo.setCurrentIndex(index) if hasattr(QWebSettings, "SpatialNavigationEnabled"): self.spatialCheckBox.setChecked( Preferences.getHelp("SpatialNavigationEnabled")) else: self.spatialCheckBox.setEnabled(False) if hasattr(QWebSettings, "LinksIncludedInFocusChain"): self.linksInFocusChainCheckBox.setChecked( Preferences.getHelp("LinksIncludedInFocusChain")) else: self.linksInFocusChainCheckBox.setEnabled(False) if hasattr(QWebSettings, "XSSAuditingEnabled"): self.xssAuditingCheckBox.setChecked( Preferences.getHelp("XSSAuditingEnabled")) else: self.xssAuditingCheckBox.setEnabled(False) if hasattr(QWebSettings, "SiteSpecificQuirksEnabled"): self.quirksCheckBox.setChecked( Preferences.getHelp("SiteSpecificQuirksEnabled")) else: self.quirksCheckBox.setEnabled(False)
def get_default_locale(): return QLocale.system()
def init_language(): """ Find the current locale, and install the correct translators """ # Get app instance app = QCoreApplication.instance() # Setup of our list of translators and paths translator_types = ( { "type": 'QT', "pattern": 'qt_%s', # Older versions of Qt use this file (built-in translations) "path": QLibraryInfo.location(QLibraryInfo.TranslationsPath) }, { "type": 'QT', "pattern": 'qtbase_%s', # Newer versions of Qt use this file (built-in translations) "path": QLibraryInfo.location(QLibraryInfo.TranslationsPath) }, { "type": 'QT', "pattern": 'qt_%s', "path": os.path.join(info.PATH, 'locale', 'QT') }, # Optional path where we package QT translations { "type": 'QT', "pattern": 'qtbase_%s', "path": os.path.join(info.PATH, 'locale', 'QT') }, # Optional path where we package QT translations { "type": 'OpenShot', "pattern": os.path.join('%s', 'LC_MESSAGES', 'OpenShot'), # Our custom translations "path": os.path.join(info.PATH, 'locale') }, ) # Determine the environment locale, or default to system locale name locale_names = [ os.environ.get('LANG', QLocale().system().name()), os.environ.get('LOCALE', QLocale().system().name()) ] # Determine if the user has overwritten the language (in the preferences) preference_lang = settings.get_settings().get('default-language') if preference_lang != "Default": # Append preference lang to top of list locale_names.insert(0, preference_lang) # Output all system languages detected log.info("Qt Detected Languages: {}".format( QLocale().system().uiLanguages())) log.info("LANG Environment Variable: {}".format( os.environ.get('LANG', QLocale().system().name()))) log.info("LOCALE Environment Variable: {}".format( os.environ.get('LOCALE', QLocale().system().name()))) # Default the locale to C, for number formatting locale.setlocale(locale.LC_ALL, 'C') # Loop through environment variables found_language = False for locale_name in locale_names: # Don't try on default locale, since it fails to load what is the default language if 'en_US' in locale_name: log.info("Skipping English language (no need for translation): {}". format(locale_name)) continue # Go through each translator and try to add for current locale for type in translator_types: trans = QTranslator(app) if find_language_match(type["pattern"], type["path"], trans, locale_name): # Install translation app.installTranslator(trans) found_language = True # Exit if found language if found_language: log.info( "Exiting translation system (since we successfully loaded: {})" .format(locale_name)) info.CURRENT_LANGUAGE = locale_name break
def __init__(self, parent, receiver_slot, settings, video_dict={}): super().__init__(parent, receiver_slot, settings, video_dict) self.setWindowTitle( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video Finder')) self.size_label.hide() # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # Fetch Button self.url_submit_button = QPushButton(self.link_frame) self.link_horizontalLayout.addWidget(self.url_submit_button) # Status Box self.status_box = QTextEdit(self.link_frame) self.status_box.setMaximumHeight(150) self.link_verticalLayout.addWidget(self.status_box) # Select format horizontal layout select_format_hl = QHBoxLayout() # Selection Label select_format_label = QLabel(self.link_frame) select_format_hl.addWidget(select_format_label) # Selection combobox self.media_combo = QComboBox(self.link_frame) self.media_combo.setMinimumWidth(200) select_format_hl.addWidget(self.media_combo) # Duration label self.duration_label = QLabel(self.link_frame) select_format_hl.addWidget(self.duration_label) self.selection_line = QFrame(self) self.selection_line.setLayout(select_format_hl) self.link_verticalLayout.addWidget(self.selection_line) # Set Texts self.url_submit_button.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Fetch Media List')) self.ok_pushButton.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Download Now')) select_format_label.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Select a format')) # Add Slot Connections self.url_submit_button.setEnabled(False) self.change_name_lineEdit.setEnabled(False) self.ok_pushButton.setEnabled(False) self.download_later_pushButton.setEnabled(False) self.url_submit_button.clicked.connect(self.submit_clicked) self.media_combo.currentIndexChanged.connect( self.media_selection_changed) self.link_lineEdit.textChanged.disconnect( super().linkLineChanged) # Should be disconnected. self.link_lineEdit.textChanged.connect(self.linkLineChangedHere) self.setMinimumSize(500, 400) self.status_box.hide() self.selection_line.hide() if 'link' in video_dict.keys() and video_dict['link']: self.link_lineEdit.setText(video_dict['link']) self.url_submit_button.setEnabled(True) else: # check clipboard clipboard = QApplication.clipboard() text = clipboard.text() if (("tp:/" in text[2:6]) or ("tps:/" in text[2:7])): self.link_lineEdit.setText(str(text)) self.url_submit_button.setEnabled(True)
def __init__(self, parent=None): super().__init__() self.parent = parent self.setWindowTitle(self.tr("Welcome")) self.setLayout(QVBoxLayout()) self.layout().setAlignment(Qt.AlignCenter) titleLabel = QLabel() titleLabel.setAlignment(Qt.AlignCenter) titleLabel.setText(self.tr("<h1>Welcome to Lime GNU/Linux System Installer.</h1>")) self.layout().addWidget(titleLabel) descLabel = QLabel() descLabel.setAlignment(Qt.AlignCenter) descLabel.setText(self.tr("This program is going to ask you some questions and then will install the Lime GNU/Linux to your device.")) self.layout().addWidget(descLabel) lLayout = QHBoxLayout() lLayout.setAlignment(Qt.AlignCenter) self.layout().addLayout(lLayout) imageLabel = QLabel() imageLabel.setPixmap(QPixmap(":/images/welcome.svg")) imageLabel.setScaledContents(True) imageLabel.setFixedSize(256, 256) lLayout.addWidget(imageLabel) langLayout = QHBoxLayout() langLayout.setAlignment(Qt.AlignCenter) self.layout().addLayout(langLayout) langLabel = QLabel() langLabel.setText(self.tr("Language:")) langLayout.addWidget(langLabel) langComboBox = QComboBox() langComboBox.setFixedWidth(250) langLayout.addWidget(langComboBox) linkLayout = QHBoxLayout() linkLayout.setAlignment(Qt.AlignCenter) self.layout().addLayout(linkLayout) aboutButton = QPushButton() aboutButton.setFlat(True) aboutButton.setText(self.tr("About")) aboutButton.setIcon(QIcon(":/images/about.svg")) aboutButton.setIconSize(QSize(18, 18)) linkLayout.addWidget(aboutButton) bugButton = QPushButton() bugButton.setFlat(True) bugButton.setText(self.tr("Found Bugs")) bugButton.setIcon(QIcon(":/images/bug.svg")) bugButton.setIconSize(QSize(18, 18)) linkLayout.addWidget(bugButton) releaseButton = QPushButton() releaseButton.setFlat(True) releaseButton.setText(self.tr("Release Notes")) releaseButton.setIcon(QIcon(":/images/release-note.svg")) releaseButton.setIconSize(QSize(18, 18)) linkLayout.addWidget(releaseButton) langComboBox.addItems(["Català", "Deutsch", "English (US)", "Español", "Français", "Magyar", "Italiano", "Nederlands", "Polski", "Português (Brasil)", "Pусский", "Svenska", "Türkçe"]) for k, v in self.lang_list.items(): if QLocale.system().name()+".UTF-8" == k: langComboBox.setCurrentText(v) self.parent.lilii_settings["lang"] = k langComboBox.currentTextChanged.connect(self.langSelect) aboutButton.clicked.connect(self.aboutDialog) bugButton.clicked.connect(self.bugAdressConnect) releaseButton.clicked.connect(self.releaseInfoConnect)
'highlightCurrentLine': False, 'iconTheme': '', 'lineNumbersEnabled': False, 'livePreviewByDefault': False, 'markdownDefaultFileExtension': '.mkd', 'pygmentsStyle': 'default', 'restDefaultFileExtension': '.rst', 'rightMargin': 0, 'saveWindowGeometry': False, 'spellCheck': False, 'spellCheckLocale': '', 'styleSheet': '', 'syncScroll': True, 'tabInsertsSpaces': True, 'tabWidth': 4, 'uiLanguage': QLocale.system().name(), 'useFakeVim': False, 'useWebKit': False, 'windowGeometry': QByteArray(), } def readFromSettings(key, keytype, settings=settings, default=None): if isinstance(default, QFont): family = readFromSettings(key, str, settings, default.family()) size = readFromSettings(key + 'Size', int, settings, 0) return QFont(family, size) if not settings.contains(key): return default try: value = settings.value(key, type=keytype)
def value_updated(self, item, interpolation=-1, value=None, interpolation_details=[]): """ Table cell change event - also handles context menu to update interpolation value """ if self.ignore_update_signal: return # Get translation method _ = get_app()._tr # Determine what was changed property = self.model.item(item.row(), 0).data() property_name = property[1]["name"] closest_point_x = property[1]["closest_point_x"] previous_point_x = property[1]["previous_point_x"] property_type = property[1]["type"] property_key = property[0] clip_id, item_type = item.data() # Get value (if any) if item.text(): # Set and format value based on property type if value != None: # Override value new_value = value elif property_type == "string": # Use string value new_value = item.text() elif property_type == "bool": # Use boolean value if item.text() == _("False"): new_value = False else: new_value = True elif property_type == "int": # Use int value new_value = QLocale().system().toInt(item.text())[0] else: # Use decimal value new_value = QLocale().system().toFloat(item.text())[0] else: new_value = None log.info("%s for %s changed to %s at frame %s with interpolation: %s at closest x: %s" % (property_key, clip_id, new_value, self.frame_number, interpolation, closest_point_x)) # Find this clip c = None clip_updated = False if item_type == "clip": # Get clip object c = Clip.get(id=clip_id) elif item_type == "transition": # Get transition object c = Transition.get(id=clip_id) elif item_type == "effect": # Get effect object c = Effect.get(id=clip_id) if c: # Update clip attribute if property_key in c.data: log.info("value updated: %s" % c.data) # Check the type of property (some are keyframe, and some are not) if type(c.data[property_key]) == dict: # Keyframe # Loop through points, find a matching points on this frame found_point = False point_to_delete = None for point in c.data[property_key]["Points"]: log.info("looping points: co.X = %s" % point["co"]["X"]) if interpolation == -1 and point["co"]["X"] == self.frame_number: # Found point, Update value found_point = True clip_updated = True # Update or delete point if new_value != None: point["co"]["Y"] = float(new_value) log.info("updating point: co.X = %s to value: %s" % (point["co"]["X"], float(new_value))) else: point_to_delete = point break elif interpolation > -1 and point["co"]["X"] == previous_point_x: # Only update interpolation type (and the LEFT side of the curve) found_point = True clip_updated = True point["interpolation"] = interpolation if interpolation == 0: point["handle_right"] = point.get("handle_right") or {"Y": 0.0, "X": 0.0} point["handle_right"]["X"] = interpolation_details[0] point["handle_right"]["Y"] = interpolation_details[1] log.info("updating interpolation mode point: co.X = %s to %s" % (point["co"]["X"], interpolation)) log.info("use interpolation preset: %s" % str(interpolation_details)) elif interpolation > -1 and point["co"]["X"] == closest_point_x: # Only update interpolation type (and the RIGHT side of the curve) found_point = True clip_updated = True point["interpolation"] = interpolation if interpolation == 0: point["handle_left"] = point.get("handle_left") or {"Y": 0.0, "X": 0.0} point["handle_left"]["X"] = interpolation_details[2] point["handle_left"]["Y"] = interpolation_details[3] log.info("updating interpolation mode point: co.X = %s to %s" % (point["co"]["X"], interpolation)) log.info("use interpolation preset: %s" % str(interpolation_details)) # Delete point (if needed) if point_to_delete: clip_updated = True log.info("Found point to delete at X=%s" % point_to_delete["co"]["X"]) c.data[property_key]["Points"].remove(point_to_delete) # Create new point (if needed) elif not found_point and new_value != None: clip_updated = True log.info("Created new point at X=%s" % self.frame_number) c.data[property_key]["Points"].append({'co': {'X': self.frame_number, 'Y': new_value}, 'interpolation': 1}) elif property_type == "int": # Integer clip_updated = True c.data[property_key] = int(new_value) elif property_type == "float": # Float clip_updated = True c.data[property_key] = new_value elif property_type == "bool": # Boolean clip_updated = True c.data[property_key] = bool(new_value) elif property_type == "string": # String clip_updated = True c.data[property_key] = str(new_value) # Reduce # of clip properties we are saving (performance boost) c.data = {property_key: c.data.get(property_key)} # Save changes if clip_updated: # Save c.save() # Update the preview get_app().window.refreshFrameSignal.emit() # Clear selection self.parent.clearSelection()
def createEditor(self, userType, parent): if userType == QVariant.Double: doubleSpinBox = QtWidgets.QDoubleSpinBox(parent) doubleSpinBox.setDecimals(4) doubleSpinBox.setMaximum(-10000000) doubleSpinBox.setMaximum( 10000000) # The default maximum value is 99.99.所以要设置一下 return doubleSpinBox else: return super().createEditor(userType, parent) if __name__ == '__main__': import sys app = QtWidgets.QApplication([]) QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates)) w = QtWidgets.QMainWindow() table = TableView(w) styledItemDelegate = QtWidgets.QStyledItemDelegate() styledItemDelegate.setItemEditorFactory(SpinBoxDelegate()) table.setItemDelegate(styledItemDelegate) table.setModel( TableModel([[name, 0., 1., 0.1] for name in ['X_axis', 'Y_axis', 'theta_axis']], header=['Actuator', 'Start', 'Stop', 'Step'], editable=[False, True, True, True])) w.setCentralWidget(table) w.show() sys.exit(app.exec_())
def update_model(self, filter=""): log.info("updating clip properties model.") app = get_app() _ = app._tr # Stop QTimer self.update_timer.stop() # Check for a selected clip if self.selected and self.selected[0]: c, item_type = self.selected[0] # Skip blank clips # TODO: Determine why c is occasional = None if not c: return # Get raw unordered JSON properties raw_properties = json.loads(c.PropertiesJSON(self.frame_number)) all_properties = OrderedDict(sorted(raw_properties.items(), key=lambda x: x[1]['name'])) log.info("Getting properties for frame %s: %s" % (self.frame_number, str(all_properties))) # Check if filter was changed (if so, wipe previous model data) if self.previous_filter != filter: self.previous_filter = filter self.new_item = True # filter changed, so we need to regenerate the entire model # Ignore any events from this method self.ignore_update_signal = True # Clear previous model data (if item is different) if self.new_item: # Prepare for new properties self.items = {} self.model.clear() # Add Headers self.model.setHorizontalHeaderLabels([_("Property"), _("Value")]) # Loop through properties, and build a model for property in all_properties.items(): label = property[1]["name"] name = property[0] value = property[1]["value"] type = property[1]["type"] memo = property[1]["memo"] readonly = property[1]["readonly"] keyframe = property[1]["keyframe"] points = property[1]["points"] interpolation = property[1]["interpolation"] closest_point_x = property[1]["closest_point_x"] choices = property[1]["choices"] # Adding Transparency to translation file transparency_label = _("Transparency") selected_choice = None if choices: selected_choice = [c for c in choices if c["selected"] == True][0]["name"] # Hide filtered out properties if filter and filter.lower() not in name.lower(): continue # Hide unused base properties (if any) if name in self.filter_base_properties: continue # Insert new data into model, or update existing values row = [] if self.new_item: # Append Property Name col = QStandardItem("Property") col.setText(_(label)) col.setData(property) if keyframe and points > 1: col.setBackground(QColor("green")) # Highlight keyframe background elif points > 1: col.setBackground(QColor(42, 130, 218)) # Highlight interpolated value background if readonly: col.setFlags(Qt.ItemIsEnabled) else: col.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) row.append(col) # Append Value col = QStandardItem("Value") if selected_choice: col.setText(_(selected_choice)) elif type == "string": # Use string value col.setText(memo) elif type == "bool": # Use boolean value if value: col.setText(_("True")) else: col.setText(_("False")) elif type == "color": # Don't output a value for colors col.setText("") elif type == "int": col.setText("%d" % value) else: # Use numeric value col.setText(QLocale().system().toString(float(value), "f", precision=2)) col.setData((c.Id(), item_type)) if points > 1: # Apply icon to cell my_icon = QPixmap(os.path.join(info.IMAGES_PATH, "keyframe-%s.png" % interpolation)) col.setData(my_icon, Qt.DecorationRole) log.info(os.path.join(info.IMAGES_PATH, "keyframe-%s.png" % interpolation)) # Set the background color of the cell if keyframe: col.setBackground(QColor("green")) # Highlight keyframe background else: col.setBackground(QColor(42, 130, 218)) # Highlight interpolated value background if type == "color": # Color needs to be handled special red = property[1]["red"]["value"] green = property[1]["green"]["value"] blue = property[1]["blue"]["value"] col.setBackground(QColor(red, green, blue)) if readonly or type == "color" or choices: col.setFlags(Qt.ItemIsEnabled) else: col.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsEditable) row.append(col) # Append ROW to MODEL (if does not already exist in model) self.model.appendRow(row) else: # Update the value of the existing model # Get 1st Column col = self.items[name]["row"][0] col.setData(property) # For non-color types, update the background color if keyframe and points > 1: col.setBackground(QColor("green")) # Highlight keyframe background elif points > 1: col.setBackground(QColor(42, 130, 218)) # Highlight interpolated value background else: col.setBackground(QStandardItem("Empty").background()) # Update helper dictionary row.append(col) # Get 2nd Column col = self.items[name]["row"][1] if selected_choice: col.setText(_(selected_choice)) elif type == "string": # Use string value col.setText(memo) elif type == "bool": # Use boolean value if value: col.setText(_("True")) else: col.setText(_("False")) elif type == "color": # Don't output a value for colors col.setText("") elif type == "int": col.setText("%d" % value) else: # Use numeric value col.setText(QLocale().system().toString(float(value), "f", precision=2)) if points > 1: # Apply icon to cell my_icon = QPixmap(os.path.join(info.IMAGES_PATH, "keyframe-%s.png" % interpolation)) col.setData(my_icon, Qt.DecorationRole) # Set the background color of the cell if keyframe: col.setBackground(QColor("green")) # Highlight keyframe background else: col.setBackground(QColor(42, 130, 218)) # Highlight interpolated value background else: # clear background color col.setBackground(QStandardItem("Empty").background()) # clear icon my_icon = QPixmap() col.setData(my_icon, Qt.DecorationRole) if type == "color": # Update the color based on the color curves red = property[1]["red"]["value"] green = property[1]["green"]["value"] blue = property[1]["blue"]["value"] col.setBackground(QColor(red, green, blue)) # Update helper dictionary row.append(col) # Keep track of items in a dictionary (for quick look up) self.items[name] = {"row": row, "property": property} # Update the values on the next call to this method (instead of adding rows) self.new_item = False else: # Clear previous properties hash self.previous_hash = "" # Clear previous model data (if any) self.model.clear() # Add Headers self.model.setHorizontalHeaderLabels([_("Property"), _("Value")]) # Done updating model self.ignore_update_signal = False
def __init__(self, argv, qapp): ''' Create a new "cutecoin" application :param argv: The argv parameters of the call ''' super().__init__() self.accounts = {} self.current_account = None self.monitor = None self.available_version = (True, __version__, "") config.parse_arguments(argv) self._network_manager = QNetworkAccessManager() self._network_manager.finished.connect(self.read_available_version) self.preferences = {'account': "", 'lang': 'en_GB', 'ref': 0 } self.load() translator = QTranslator(qapp) logging.debug("Loading translations") locale = self.preferences['lang'] QLocale.setDefault(QLocale(locale)) if translator.load(":/i18n/{0}".format(locale)): if QCoreApplication.installTranslator(translator): logging.debug("Loaded i18n/{0}".format(locale)) else: logging.debug("Couldn't load translation")