def setResultPoint(self, point): if self.sectionIsGeographic[CoordinatorDockWidget.SectionOutput]: if (self.resultAsDec.isChecked()): f = QgsCoordinateFormatter.FormatDecimalDegrees precision = 9 else: f = QgsCoordinateFormatter.FormatDegreesMinutesSeconds precision = 3 transformedX = QgsCoordinateFormatter.formatX( point.x(), f, precision) transformedY = QgsCoordinateFormatter.formatY( point.y(), f, precision) # if we use FormatDecimalDegrees QgsCoordinateFormatter produces # a string just with a QString::number(). Therefore the string is NOT # localized. But QgsCoordinateFormatter provides coordinate wrapping already # so we just hack the correct decimal sign into the string and should be # fine... juuust fine! decPoint = QLocale().decimalPoint() #coordinatorLog("Decimal Point: %s" % decPoint) if (decPoint != "."): #coordinatorLog("replace!!") transformedX = transformedX.replace(".", decPoint) transformedY = transformedY.replace(".", decPoint) else: #self.log(" -> using decimal output") transformedX = QLocale().toString(point.x(), 'f', 2) transformedY = QLocale().toString(point.y(), 'f', 2) self.setResult(transformedX, transformedY)
def _init_translation(qt_app): """Sets up translation data for the application. qt_app -- The QApplication that is being set up. """ # Set up translation for Qt's built-in strings. qt_translator = QTranslator(qt_app) if not qt_translator.load( 'qt_' + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)): # TODO: Log the failure to load translation information. pass elif not qt_app.installTranslator(qt_translator): # TODO: Log the failure to install translation information. pass # Set up translation for app-specific strings. app_translator = QTranslator(qt_app) app_translations_path = QDir.toNativeSeparators('./qt_qm/translations') if not app_translator.load('scriptaseq_' + QLocale.system().name(), app_translations_path): # TODO: Log the failure to load translation information. pass elif not qt_app.installTranslator(app_translator): # TODO: Log the failure to load translation information. pass
def __inputFieldsChangedInternal(self): #coordinatorLog("fields changed internal triggered") self._setToolsEnabled(self.hasInput()) if (self.hasInput()): if (self.leftDMS.isVisible()): (leftValue, rightValue) = self.calculateDecimalDegreesFromDMS() self.inLeftDec.setText(QLocale().toString(leftValue, "f", 9)) self.inRightDec.setText(QLocale().toString(rightValue, "f", 9)) else: # calculate DMS Values leftValue = QLocale().toFloat(self.inLeftDec.text())[0] rightValue = QLocale().toFloat(self.inRightDec.text())[0] x = leftValue if self._eastingLeftNorthingRight else rightValue y = rightValue if self._eastingLeftNorthingRight else leftValue self.setDmsInputFromDecimal(x, y, False) else: if (self.leftDMS.isVisible()): self.inLeftDec.setText(None) self.inRightDec.setText(None) else: for f in self._widgetlistInputDms: f.setText(None) self.inputChanged.emit()
def _onLanguagesReceived(self, languages): loc = QLocale.system() sysLang = QLocale.languageToString(loc.language()) preferredLanguages = self._getPreferredLanguages() self._langList.clear() firstCheckedItem = None for lang in sorted(languages, key=lambda x: x['name']): langName = lang['name'] langCode = lang['code'] nativeLang = self._getNativeLanguageName(langName) text = langName isSystemLang = langName == sysLang if nativeLang and not isSystemLang: text += " (" + nativeLang + ")" item = QListWidgetItem(text) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setData(Qt.UserRole, langCode) if (preferredLanguages and langCode in preferredLanguages) \ or isSystemLang: item.setCheckState(Qt.Checked) firstCheckedItem = item else: item.setCheckState(Qt.Unchecked) self._langList.addItem(item) self._langList.setMinimumWidth(self._langList.sizeHintForColumn(0)) if firstCheckedItem: self._langList.scrollToItem(firstCheckedItem)
def __init__(self, args, force_calibre_style=False, override_program_name=None, headless=False, color_prefs=gprefs): self.file_event_hook = None if override_program_name: args = [override_program_name] + args[1:] if headless: if not args: args = sys.argv[:1] args.extend(['-platformpluginpath', sys.extensions_location, '-platform', 'headless']) qargs = [i.encode('utf-8') if isinstance(i, unicode) else i for i in args] self.pi = plugins['progress_indicator'][0] QApplication.__init__(self, qargs) self.setup_styles(force_calibre_style) f = QFont(QApplication.font()) if (f.family(), f.pointSize()) == ('Sans Serif', 9): # Hard coded Qt settings, no user preference detected f.setPointSize(10) QApplication.setFont(f) f = QFontInfo(f) self.original_font = (f.family(), f.pointSize(), f.weight(), f.italic(), 100) if not self.using_calibre_style and self.style().objectName() == 'fusion': # Since Qt is using the fusion style anyway, specialize it self.load_calibre_style() fi = gprefs['font'] if fi is not None: font = QFont(*(fi[:4])) s = gprefs.get('font_stretch', None) if s is not None: font.setStretch(s) QApplication.setFont(font) dl = QLocale(get_lang()) if unicode(dl.bcp47Name()) != u'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() self._translator = None self.load_translations() qt_app = self self._file_open_paths = [] self._file_open_lock = RLock() if not isosx: # OS X uses a native color dialog that does not support custom # colors self.color_prefs = color_prefs self.read_custom_colors() self.lastWindowClosed.connect(self.save_custom_colors) if isxp: error_dialog(None, _('Windows XP not supported'), '<p>' + _( 'calibre versions newer than 2.0 do not run on Windows XP. This is' ' because the graphics toolkit calibre uses (Qt 5) crashes a lot' ' on Windows XP. We suggest you stay with <a href="%s">calibre 1.48</a>' ' which works well on Windows XP.') % 'http://download.calibre-ebook.com/1.48.0/', show=True) raise SystemExit(1)
def __rawInputCoordinates(self): if (self.leftDMS.isVisible()): return (self.calculateDecimalDegreesFromDMS()) else: valueLeft = 0.0 valueRight = 0.0 if (len(self.inLeftDec.text())): valueLeft = QLocale().toFloat(self.inLeftDec.text())[0] if (len(self.inRightDec.text())): valueRight = QLocale().toFloat(self.inRightDec.text())[0] return (valueLeft, valueRight)
def __init__(self, args, force_calibre_style=False, override_program_name=None, headless=False): self.file_event_hook = None if override_program_name: args = [override_program_name] + args[1:] if headless: if not args: args = sys.argv[:1] args.extend([ '-platformpluginpath', sys.extensions_location, '-platform', 'headless' ]) qargs = [ i.encode('utf-8') if isinstance(i, unicode) else i for i in args ] self.pi = plugins['progress_indicator'][0] self.setup_styles(force_calibre_style) QApplication.__init__(self, qargs) f = QFont(QApplication.font()) if (f.family(), f.pointSize()) == ( 'Sans Serif', 9): # Hard coded Qt settings, no user preference detected f.setPointSize(10) QApplication.setFont(f) f = QFontInfo(f) self.original_font = (f.family(), f.pointSize(), f.weight(), f.italic(), 100) if not self.using_calibre_style and self.style().objectName( ) == 'fusion': # Since Qt is using the fusion style anyway, specialize it self.load_calibre_style() fi = gprefs['font'] if fi is not None: font = QFont(*(fi[:4])) s = gprefs.get('font_stretch', None) if s is not None: font.setStretch(s) QApplication.setFont(font) dl = QLocale(get_lang()) if unicode(dl.bcp47Name()) != u'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() self._translator = None self.load_translations() qt_app = self self._file_open_paths = [] self._file_open_lock = RLock()
def _initLocales(self): locales = QLocale.matchingLocales(QLocale.AnyLanguage, QLocale.AnyScript, QLocale.AnyCountry) localeDict = {} for loc in locales: langName = QLocale.languageToString(loc.language()) if langName == "C": continue if langName in localeDict: continue localeDict[langName] = loc self._localeDict = localeDict
def testCaptureWest4326(self): CANVAS.setDestinationCrs(QgsCoordinateReferenceSystem("EPSG:4326")) #self.dw.setMinimumWidth(self.dw.width() + 50) QTest.qWait(100) CANVAS.zoomToFeatureExtent(QgsRectangle(-99.7, 70.3, -99.3, 70.7)) QTest.qWait(100) QTest.mouseClick(self.dw.captureCoordButton, Qt.LeftButton) QTest.qWait(100) testPosition = QgsPointXY(-99.5, 70.5) self.clickCanvasCoordinate(testPosition) QTest.qWait(100) # recalculate and click again, because the GUI might have moved a bit: self.clickCanvasCoordinate(testPosition) QTest.qWait(100) self.assertEqual("99", self.dw.inLeft.text()) self.assertTextFieldBetween(28, 31, self.dw.inLeftMin) #self.assertEqual(helperFormatCoordinates("0.00"), self.dw.inLeftSec.text()) self.assertEqual("W", self.dw.leftDirButton.text()) self.assertEqual("70", self.dw.inRight.text()) self.assertTextFieldBetween(28, 31, self.dw.inRightMin) #self.assertEqual(helperFormatCoordinates("0.00"), self.dw.inRightSec.text()) self.assertEqual("N", self.dw.rightDirButton.text()) QTest.mouseClick(self.dw.inputAsDec, Qt.LeftButton) self.assertAlmostEqual(99.5, QLocale().toFloat(self.dw.inLeftDec.text())[0], places=2) self.assertEqual("W", self.dw.leftDirButton.text()) self.assertAlmostEqual(70.5, QLocale().toFloat(self.dw.inRightDec.text())[0], places=2) self.assertEqual("N", self.dw.rightDirButton.text()) # repeat test while in decimal mode: self.clickCanvasCoordinate(testPosition) QTest.qWait(100) self.assertAlmostEqual(99.5, QLocale().toFloat(self.dw.inLeftDec.text())[0], places=2) self.assertEqual("W", self.dw.leftDirButton.text()) self.assertAlmostEqual(70.5, QLocale().toFloat(self.dw.inRightDec.text())[0], places=2) self.assertEqual("N", self.dw.rightDirButton.text())
def doStepwiseIncrement(self, direction): value = QLocale().toFloat(self._leField.text())[0] overflow = 0 if (direction < 0): newValue = value - 1 elif (direction > 0): newValue = value + 1 else: return False #coordinatorLog("new value : %s" % newValue) if self._doOverflow: if newValue < self._min: newValue = self._max overflow = ValueIncrementor.IS_UNDERFLOW elif newValue > self._max: newValue = self._min overflow = ValueIncrementor.IS_OVERFLOW else: if newValue < self._min: newValue = self._min overflow = ValueIncrementor.IS_UNDERFLOW elif newValue > self._max: newValue = self._max overflow = ValueIncrementor.IS_OVERFLOW # important to call the overflow before we edit the minor # field because subsequent validators (like DmsHandler.minorFieldDidChange) # may depend on an already correct DegreeField if (overflow != 0): # we do overflow. check if we are allowed to overflow: if (self._wrapCallback): if not self._wrapCallback(self._leField, direction): return True self.fieldDidOverflow.emit(self._leField, overflow) textValidator = self._leField.validator() if isinstance(textValidator, QIntValidator): newValueString = QLocale().toString(newValue, "f", 0) else: precision = textValidator.decimals() newValueString = QLocale().toString(newValue, "f", precision) self._leField.clear() self._leField.insert(newValueString) return True
def addLanguage(self): dialog = QDialog(self) ui = uic.loadUi('mc/preferences/AddAcceptLanguage.ui', dialog) ui.listWidget.setLayoutDirection(Qt.LeftToRight) allLanguages = [] for idx in range(1 + QLocale.C, QLocale.LastLanguage + 1): allLanguages.extend(self._expand(QLocale.Language(idx))) ui.listWidget.addItems(allLanguages) ui.listWidget.itemDoubleClicked.connect(dialog.accept) if dialog.exec_() == QDialog.Rejected: return ownText = ui.ownDefinition.text() if ownText: title = _('Personal [%s]' % ownText) self._ui.listWidget.addItem(title) else: c = ui.listWidget.currentItem() if not c: return self._ui.listWidget.addItem(c.text())
def on_bridge_ready(self): f = QApplication.instance().font() fi = QFontInfo(f) family = f.family() if family in ('.AppleSystemUIFont', 'MS Shell Dlg 2'): family = 'system-ui' ui_data = { 'all_font_families': QFontDatabase().families(), 'ui_font_family': family, 'ui_font_sz': '{}px'.format(fi.pixelSize()), 'show_home_page_on_ready': self.show_home_page_on_ready, 'system_colors': system_colors(), 'QT_VERSION': QT_VERSION, 'short_time_fmt': QLocale.system().timeFormat(QLocale.FormatType.ShortFormat), } self.bridge.create_view(vprefs['session_data'], vprefs['local_storage'], field_metadata.all_metadata(), ui_data) for func, args in iteritems(self.pending_bridge_ready_actions): getattr(self.bridge, func)(*args)
class Runner(): _window = None _application = None def __init__(self): self._application = QApplication(sys.argv) self._window = None # Main Window Initialized.. try: self._window = yali.gui.YaliWindow.Widget() except yali.Error, msg: ctx.logger.debug(msg) sys.exit(1) self._translator = QTranslator() self._translator.load( "qt_" + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)) ctx.mainScreen = self._window screens = self._get_screens(ctx.flags.install_type) self._set_steps(screens) # These shorcuts for developers :) prevScreenShortCut = QShortcut(QKeySequence(Qt.SHIFT + Qt.Key_F1), self._window) nextScreenShortCut = QShortcut(QKeySequence(Qt.SHIFT + Qt.Key_F2), self._window) prevScreenShortCut.activated.connect(self._window.slotBack) nextScreenShortCut.activated.connect(self._window.slotNext) # VBox utils ctx.logger.debug("Starting VirtualBox tools..") #FIXME:sh /etc/X11/Xsession.d/98-vboxclient.sh yali.util.run_batch("VBoxClient", ["--autoresize"]) yali.util.run_batch("VBoxClient", ["--clipboard"]) # Cp Reboot, ShutDown yali.util.run_batch("cp", ["/sbin/reboot", "/tmp/reboot"]) yali.util.run_batch("cp", ["/sbin/shutdown", "/tmp/shutdown"]) # base connections self._application.lastWindowClosed.connect(self._application.quit) self._window.signalProcessEvents.connect( self._application.processEvents) #hata olabilir self._application.desktop().resized[int].connect( self._reinit_screen) #hata olabilir # Font Resize fontMinusShortCut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Minus), self._window) fontPlusShortCut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Plus), self._window) fontMinusShortCut.activated.connect(self._window.setFontMinus) fontPlusShortCut.activated.connect(self._window.setFontPlus)
def test_get_current_language(self): install_translators("ru_RU") self.assertEqual(get_current_language(), "ru_RU") install_translators("en_EN") self.assertEqual(get_current_language(), "en_EN") install_translators() if QLocale.system().name() == "ru_RU": self.assertEqual(get_current_language(), "ru_RU")
def __init__(self, parent=None): super().__init__(parent) self._ui = uic.loadUi('mc/preferences/AcceptLanguage.ui', self) self.setAttribute(Qt.WA_DeleteOnClose) self._ui.listWidget.setLayoutDirection(Qt.LeftToRight) settings = Settings() settings.beginGroup('Language') # QStringList langs = settings.value('acceptLanguage', self.defaultLanguage(), type=list) settings.endGroup() for code in langs: loc = QLocale(code.replace('-', '_')) label = '' if loc.language() == QLocale.C: label = _('Personal [%s]') % code else: label = '%s/%s [%s]' % (loc.languageToString( loc.language()), loc.countryToString(loc.country()), code) self._ui.listWidget.addItem(label) self._ui.add.clicked.connect(self.addLanguage) self._ui.remove.clicked.connect(self.removeLanguage) self._ui.up.clicked.connect(self.upLanguage) self._ui.down.clicked.connect(self.downLanguage)
def assertTextFieldBetween(self, lower, upper, textField, msg = None): textFieldValue = QLocale().toFloat(textField.text())[0] result = (lower < textFieldValue < upper) if msg == None: msg = "value '%f' of QTextField is not between %f and %f)" % (textFieldValue, lower, upper) self.assertTrue(result, msg)
def isWrapAllowedFor(self, field, direction): if (field == self._minField): degrees = QLocale().toInt(self._degField.text())[0] res = degrees + direction return 0 <= res <= self._maxDegrees elif (field == self._secField): minutes = QLocale().toInt(self._minField.text())[0] res = minutes + direction if not (0 <= res < 60): return self.isWrapAllowedFor(self._minField, direction) else: return True elif (field == self._degField): degrees = QLocale().toInt(self._degField.text())[0] res = degrees + direction return 0 <= res <= self._maxDegrees return True
def assertTextFieldCloseTo(self, expected, textField, tolerance = 1, msg = None): textFieldValue = QLocale().toFloat(textField.text())[0] result = ( (expected - tolerance) <= textFieldValue <= (expected + tolerance) ) if(not result): if msg == None: msg = "value '%f' of QTextField is not close to %f±%f)" % (textFieldValue, expected, tolerance) raise AssertionError(msg)
def __init__(self, parent: QWidget, config, **params): super(TextEditor, self).__init__(None) self._parent = parent # add keys for local vars for p in ["PlainText", "Font", "FontSize", "ShowLineNumbers", "WordWrap", "HighlightCurrentLine", "ShowToolBar", "ShowStatusBar", "AutoSave"]: params["TextEditor/" + p] = "" textmode = "format" in params and params["format"].upper() != "HTML" self._load = params["load"] if "load" in params else lambda: "" self._save = params["save"] if "save" in params else lambda x: True self._cfg = ConfigHelper(config, **params) self._init_params_in_cfg() self._set_vars(textmode) self._doc = Doc(self._cfg) margins = params["margins"] if "margins" in params else None self._view = View(self, self._cfg, margins) self._spell = params["spell"] if "spell" in params else None if not self._spell: self._spell = SpellChecker() self._spell.change_enabled.connect(self._rehighlight) auto_key_switch = "auto_key_switch" in params cond1 = auto_key_switch and not params["auto_key_switch"] cond2 = not auto_key_switch and QLocale.system().name() == "en_EN" if cond1 or cond2: self._keyswitcher = None # pragma: no cover else: self._keyswitcher = KeySwitcher(self._view.text, self._spell) self._highlighter = "" self._highlighter_cls = None self._set_highlighter(self._highlighter) self._view.text.setAcceptRichText( not self._cfg.get("TextEditor/PlainText", 0)) self._actions: Dict[str, QAction] = {} self._make_actions() self._bind_controls() # code for copying text format self._current_format = self._view.text.currentCharFormat() self._copy_format_mode = TextEditor.NORMAL_MODE self._cursor_to_change_word = None if "layout" in params: params["layout"].addWidget(self) # pragma: no cover if "auto_load" in params and params["auto_load"]: self.load()
def defaultLanguage(cls): ''' @return: QStringList ''' longCode = QLocale.system().name().replace('_', '-') if len(longCode) == 5: ret = [longCode, longCode[:2]] return ret return [longCode]
def test_install_translators(self): install_translators("ru_RU") txt = QCoreApplication.translate("@default", "Question") self.assertEqual(txt, "Вопрос") # i18n install_translators("en_EN") txt = QCoreApplication.translate("@default", "Question") self.assertEqual(txt, "Question") install_translators() if QLocale.system().name() == "ru_RU": txt = QCoreApplication.translate("@default", "Question") self.assertEqual(txt, "Вопрос") # i18n
def __init__(self, args, force_calibre_style=False, override_program_name=None, headless=False): self.file_event_hook = None if override_program_name: args = [override_program_name] + args[1:] if headless: if not args: args = sys.argv[:1] args.extend(['-platformpluginpath', sys.extensions_location, '-platform', 'headless']) qargs = [i.encode('utf-8') if isinstance(i, unicode) else i for i in args] self.pi = plugins['progress_indicator'][0] self.setup_styles(force_calibre_style) QApplication.__init__(self, qargs) f = QFont(QApplication.font()) if (f.family(), f.pointSize()) == ('Sans Serif', 9): # Hard coded Qt settings, no user preference detected f.setPointSize(10) QApplication.setFont(f) f = QFontInfo(f) self.original_font = (f.family(), f.pointSize(), f.weight(), f.italic(), 100) if not self.using_calibre_style and self.style().objectName() == 'fusion': # Since Qt is using the fusion style anyway, specialize it self.load_calibre_style() fi = gprefs['font'] if fi is not None: font = QFont(*(fi[:4])) s = gprefs.get('font_stretch', None) if s is not None: font.setStretch(s) QApplication.setFont(font) dl = QLocale(get_lang()) if unicode(dl.bcp47Name()) != u'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() self._translator = None self.load_translations() qt_app = self self._file_open_paths = [] self._file_open_lock = RLock()
def setInputPoint(self, point): #QgsMessageLog.logMessage("%s/%s" % (point.x(), point.y())) if self.sectionIsGeographic[self.SectionInput]: precision = 9 # remove leading minus when setting decimal fields. The correct state for # the hemisphere buttons is applied in setDmsInputFromDecimal() later. xDec = abs(point.x()) yDec = abs(point.y()) else: precision = 3 xDec = point.x() yDec = point.y() self.inLeftDec.setText(QLocale().toString( xDec if self._eastingLeftNorthingRight else yDec, "f", precision)) self.inRightDec.setText(QLocale().toString( yDec if self._eastingLeftNorthingRight else xDec, "f", precision)) self.setDmsInputFromDecimal(point.x(), point.y()) self.__inputFieldsChangedInternal()
def value(self, key, localized=False): if not self._settings: return None if localized: locale = QLocale.system() localeKey = '%s[%s]' % (key, locale.name()) if self._settings.contains(localeKey): return self._settings.value(localeKey) localeKey = '%s[%s]' % (key, locale.bcp47Name()) if self._settings.contains(localeKey): return self._settings.value(localeKey) idx = locale.name().index('_') if idx > 0: localeKey = '%s[%s]' % (key, locale.name()[:idx]) if self._settings.contains(localeKey): return self._settings.value(localeKey) return self._settings.value(key)
def setDmsInputFromDecimal(self, x, y, setEastingNorthingInversion=True): xDMS = coordinatorDecimalToDms(x) yDMS = coordinatorDecimalToDms(y) #QgsMessageLog.logMessage(str(xDMS)) if (setEastingNorthingInversion): self.setEastingInverted(xDMS[0]) self.setNorthingInverted(yDMS[0]) leftDMS = xDMS if self._eastingLeftNorthingRight else yDMS rightDMS = yDMS if self._eastingLeftNorthingRight else xDMS self.inLeft.setText(QLocale().toString(leftDMS[1])) self.inLeftMin.setText(QLocale().toString(leftDMS[2])) self.inLeftSec.setText(QLocale().toString(leftDMS[3], "f", 2)) self.inRight.setText(QLocale().toString(rightDMS[1])) self.inRightMin.setText(QLocale().toString(rightDMS[2])) self.inRightSec.setText(QLocale().toString(rightDMS[3], "f", 2))
def _expand(self, language): ''' @param: QLocale::Language @return: QStringList ''' allLanguages = [] countries = QLocale.matchingLocales(language, QLocale.AnyScript, QLocale.AnyCountry) for jdx in range(0, len(countries)): languageString = '' country = countries[jdx].country() if len(countries) == 1: languageString = '%s [%s]' % (QLocale.languageToString( language), QLocale(language).name().split('_')[0]) else: languageString = '%s/%s [%s]' % (QLocale.languageToString( language), QLocale.countryToString(country), ('-'.join( QLocale(language, country).name().split('_'))).lower()) if languageString not in allLanguages: allLanguages.append(languageString) return allLanguages
def minorFieldDidChange(self, field): degrees = QLocale().toInt(self._degField.text())[0] if degrees == self._maxDegrees: field.setText("0") self.inputDidChange.emit()
def helperFormatCoordinates(coordinate): # if the locale does not use grouping, we need to remove the grouping # separator before translation: if QLocale.OmitGroupSeparator & QLocale().numberOptions(): coordinate = coordinate.replace(",", "") return coordinate.translate(TRANSLATION)
def __init__(self, iface, mainWindow=None): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # store references to important stuff from QGIS self.iface = iface self.canvas = iface.mapCanvas() self._project = QgsProject.instance() self._observingLayer = None self._uiHook = mainWindow if isinstance(mainWindow, QMainWindow) else iface # region: LOCALE - UNUSED # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # #initialize locale localeString = QSettings().value('locale/userLocale') if (localeString): locale = localeString[0:2] else: locale = QLocale().language() locale_path = os.path.join(self.plugin_dir, 'i18n', 'coordinator_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # endregion # plugin housekeeping: self.openPanelAction = None self.pluginIsActive = False self.dockwidget = None # Init CRS Transformation: self._inputCrs = None self._outputCrs = None # self._transform : input -> output transformation # self._canvasTransform: input -> canvas transformation self.__initTransformers() # initialize canvas marker icon: self.marker = QgsVertexMarker(self.canvas) self.marker.hide() self.marker.setColor(QColor(255, 0, 0)) self.marker.setIconSize(14) self.marker.setIconType( QgsVertexMarker.ICON_CIRCLE ) # See the enum IconType from http://www.qgis.org/api/classQgsVertexMarker.html self.marker.setPenWidth(3) # init point picker: self.mapTool = QgsMapToolEmitPoint(self.canvas)
def __init__(self, args, force_calibre_style=False, override_program_name=None, headless=False, color_prefs=gprefs): self.file_event_hook = None if override_program_name: args = [override_program_name] + args[1:] if headless: if not args: args = sys.argv[:1] args.extend(['-platformpluginpath', sys.extensions_location, '-platform', 'headless']) self.headless = headless qargs = [i.encode('utf-8') if isinstance(i, unicode) else i for i in args] self.pi = plugins['progress_indicator'][0] if not isosx and not headless: # On OS X high dpi scaling is turned on automatically by the OS, so we dont need to set it explicitly setup_hidpi() QApplication.setOrganizationName('calibre-ebook.com') QApplication.setOrganizationDomain(QApplication.organizationName()) QApplication.setApplicationVersion(__version__) QApplication.setApplicationName(APP_UID) QApplication.__init__(self, qargs) self.setAttribute(Qt.AA_UseHighDpiPixmaps) self.setAttribute(Qt.AA_SynthesizeTouchForUnhandledMouseEvents, False) try: base_dir() except EnvironmentError as err: if not headless: show_temp_dir_error(err) raise SystemExit('Failed to create temporary directory') if DEBUG and not headless: prints('devicePixelRatio:', self.devicePixelRatio()) s = self.primaryScreen() if s: prints('logicalDpi:', s.logicalDotsPerInchX(), 'x', s.logicalDotsPerInchY()) prints('physicalDpi:', s.physicalDotsPerInchX(), 'x', s.physicalDotsPerInchY()) if not iswindows: self.setup_unix_signals() if islinux or isbsd: self.setAttribute(Qt.AA_DontUseNativeMenuBar, 'CALIBRE_NO_NATIVE_MENUBAR' in os.environ) self.setup_styles(force_calibre_style) self.setup_ui_font() if not self.using_calibre_style and self.style().objectName() == 'fusion': # Since Qt is using the fusion style anyway, specialize it self.load_calibre_style() fi = gprefs['font'] if fi is not None: font = QFont(*(fi[:4])) s = gprefs.get('font_stretch', None) if s is not None: font.setStretch(s) QApplication.setFont(font) self.line_height = max(12, QFontMetrics(self.font()).lineSpacing()) dl = QLocale(get_lang()) if unicode(dl.bcp47Name()) != u'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() self._translator = None self.load_translations() qt_app = self self._file_open_paths = [] self._file_open_lock = RLock() if not isosx: # OS X uses a native color dialog that does not support custom # colors self.color_prefs = color_prefs self.read_custom_colors() self.lastWindowClosed.connect(self.save_custom_colors) if isxp: error_dialog(None, _('Windows XP not supported'), '<p>' + _( 'calibre versions newer than 2.0 do not run on Windows XP. This is' ' because the graphics toolkit calibre uses (Qt 5) crashes a lot' ' on Windows XP. We suggest you stay with <a href="%s">calibre 1.48</a>' ' which works well on Windows XP.') % 'http://download.calibre-ebook.com/1.48.0/', show=True) raise SystemExit(1) if iswindows: # On windows the highlighted colors for inactive widgets are the # same as non highlighted colors. This is a regression from Qt 4. # https://bugreports.qt-project.org/browse/QTBUG-41060 p = self.palette() for role in (p.Highlight, p.HighlightedText, p.Base, p.AlternateBase): p.setColor(p.Inactive, role, p.color(p.Active, role)) self.setPalette(p) # Prevent text copied to the clipboard from being lost on quit due to # Qt 5 bug: https://bugreports.qt-project.org/browse/QTBUG-41125 self.aboutToQuit.connect(self.flush_clipboard)
def updateEditorGeometry(self, editor, option, index): if editor is None: return fm = editor.fontMetrics() # get the original size of the edit widget opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) opt.showDecorationSelected = True opt.decorationSize = QSize( 0, 0) # We want the editor to cover the decoration style = QApplication.style() initial_geometry = style.subElementRect(style.SE_ItemViewItemText, opt, None) orig_width = initial_geometry.width() # Compute the required width: the width that can show all of the current value if hasattr(self, 'get_required_width'): new_width = self.get_required_width(editor, style, fm) else: # The line edit box seems to extend by the space consumed by an 'M'. # So add that to the text text = self.displayText(index.data(Qt.DisplayRole), QLocale()) + u'M' srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignLeft, False, text) new_width = srect.width() # Now get the size of the combo/spinner arrows and add them to the needed width if isinstance(editor, (QComboBox, QDateTimeEdit)): r = style.subControlRect(QStyle.CC_ComboBox, QStyleOptionComboBox(), QStyle.SC_ComboBoxArrow, editor) new_width += r.width() elif isinstance(editor, (QSpinBox, QDoubleSpinBox)): r = style.subControlRect(QStyle.CC_SpinBox, QStyleOptionSpinBox(), QStyle.SC_SpinBoxUp, editor) new_width += r.width() # Compute the maximum we can show if we consume the entire viewport max_width = ( self.table_widget.horizontalScrollBar().geometry().width() - self.table_widget.verticalHeader().width()) # What we have to display might not fit. If so, adjust down new_width = new_width if new_width < max_width else max_width # See if we need to change the editor's geometry if new_width <= orig_width: delta_x = 0 delta_width = 0 else: # Compute the space available from the left edge of the widget to # the right edge of the displayed table (the viewport) and the left # edge of the widget to the left edge of the viewport. These are # used to position the edit box space_left = initial_geometry.x() space_right = max_width - space_left if editor.layoutDirection() == Qt.RightToLeft: # If language is RtL, align to the cell's right edge if possible cw = initial_geometry.width() consume_on_left = min(space_left, new_width - cw) consume_on_right = max(0, new_width - (consume_on_left + cw)) delta_x = -consume_on_left delta_width = consume_on_right else: # If language is LtR, align to the left if possible consume_on_right = min(space_right, new_width) consume_on_left = max(0, new_width - consume_on_right) delta_x = -consume_on_left delta_width = consume_on_right - initial_geometry.width() initial_geometry.adjust(delta_x, 0, delta_width, 0) editor.setGeometry(initial_geometry)
def __init__(self, args, force_calibre_style=False, override_program_name=None, headless=False, color_prefs=gprefs): self.file_event_hook = None if override_program_name: args = [override_program_name] + args[1:] if headless: if not args: args = sys.argv[:1] args.extend(['-platformpluginpath', sys.extensions_location, '-platform', 'headless']) self.headless = headless qargs = [i.encode('utf-8') if isinstance(i, unicode) else i for i in args] self.pi = plugins['progress_indicator'][0] QApplication.__init__(self, qargs) if islinux or isbsd: self.setAttribute(Qt.AA_DontUseNativeMenuBar, 'CALIBRE_NO_NATIVE_MENUBAR' in os.environ) self.setup_styles(force_calibre_style) f = QFont(QApplication.font()) if (f.family(), f.pointSize()) == ('Sans Serif', 9): # Hard coded Qt settings, no user preference detected f.setPointSize(10) QApplication.setFont(f) f = QFontInfo(f) self.original_font = (f.family(), f.pointSize(), f.weight(), f.italic(), 100) if not self.using_calibre_style and self.style().objectName() == 'fusion': # Since Qt is using the fusion style anyway, specialize it self.load_calibre_style() fi = gprefs['font'] if fi is not None: font = QFont(*(fi[:4])) s = gprefs.get('font_stretch', None) if s is not None: font.setStretch(s) QApplication.setFont(font) dl = QLocale(get_lang()) if unicode(dl.bcp47Name()) != u'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() self._translator = None self.load_translations() qt_app = self self._file_open_paths = [] self._file_open_lock = RLock() if not isosx: # OS X uses a native color dialog that does not support custom # colors self.color_prefs = color_prefs self.read_custom_colors() self.lastWindowClosed.connect(self.save_custom_colors) if isxp: error_dialog(None, _('Windows XP not supported'), '<p>' + _( 'calibre versions newer than 2.0 do not run on Windows XP. This is' ' because the graphics toolkit calibre uses (Qt 5) crashes a lot' ' on Windows XP. We suggest you stay with <a href="%s">calibre 1.48</a>' ' which works well on Windows XP.') % 'http://download.calibre-ebook.com/1.48.0/', show=True) raise SystemExit(1) if iswindows: # On windows the highlighted colors for inactive widgets are the # same as non highlighted colors. This is a regression from Qt 4. # https://bugreports.qt-project.org/browse/QTBUG-41060 p = self.palette() for role in (p.Highlight, p.HighlightedText, p.Base, p.AlternateBase): p.setColor(p.Inactive, role, p.color(p.Active, role)) self.setPalette(p) # Prevent text copied to the clipboard from being lost on quit due to # Qt 5 bug: https://bugreports.qt-project.org/browse/QTBUG-41125 self.aboutToQuit.connect(self.flush_clipboard)