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 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 __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)
Пример #4
0
    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
Пример #6
0
    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 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
Пример #8
0
 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)
Пример #9
0
 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)
Пример #10
0
 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
Пример #11
0
    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 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))
Пример #14
0
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)
Пример #15
0
    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)
Пример #16
0
    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)
Пример #17
0
            CANVAS = IFACE.mapCanvas()
            QGIS_APP = QgsApplication.instance()
            PARENT = CANVAS.parentWidget()
        else:
            try:
                sysargsUtf8 = [sysarg.encode("utf-8") for sysarg in sys.argv]
            except AttributeError:
                sysargsUtf8 = []
            QGIS_APP = QgsApplication(sysargsUtf8, True)
            QGIS_APP.initQgis()
            PARENT = QWidget()
            CANVAS = QgsMapCanvas(PARENT)
            CANVAS.resize(QtCore.QSize(400, 400))
            CANVAS.setDestinationCrs(QgsCoordinateReferenceSystem("EPSG:4326"))
            IFACE = QgisStubInterface(CANVAS)

    return QGIS_APP, IFACE, CANVAS


DEC_POINT = QLocale().decimalPoint()
GROUP_SEPARATOR = QLocale().groupSeparator()
TRANSLATION = str.maketrans(".,", "%s%s" % (DEC_POINT, GROUP_SEPARATOR))


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 minorFieldDidChange(self, field):
        degrees = QLocale().toInt(self._degField.text())[0]
        if degrees == self._maxDegrees:
            field.setText("0")

        self.inputDidChange.emit()
Пример #19
0
    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)
Пример #20
0
    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)
Пример #21
0
def coordinatorDmsStringsToDecimal(deg, minute, sec):
    result = 0.0
    if (len(deg) > 0): result += QLocale().toFloat(deg)[0]
    if (len(minute) > 0): result += QLocale().toFloat(minute)[0] / 60
    if (len(sec) > 0): result += QLocale().toFloat(sec)[0] / 3600
    return result