Exemple #1
0
    def set_viewport(self, size, raise_if_empty=False):
        """
        Set viewport size.
        If size is "full" viewport size is detected automatically.
        If can also be "<width>x<height>".

        .. note::

           This will update all JS geometry variables, but window resize event
           is delivered asynchronously and so ``window.resize`` will not be
           invoked until control is yielded to the event loop.

        """
        if size == 'full':
            size = self.web_page.mainFrame().contentsSize()
            self.logger.log("Contents size: %s" % size, min_level=2)
            if size.isEmpty():
                if raise_if_empty:
                    raise RuntimeError("Cannot detect viewport size")
                else:
                    size = defaults.VIEWPORT_SIZE
                    self.logger.log("Viewport is empty, falling back to: %s" %
                                    size)

        if not isinstance(size, QSize):
            validate_size_str(size)
            w, h = map(int, size.split('x'))
            size = QSize(w, h)
        self.web_page.setViewportSize(size)
        self._force_relayout()
        w, h = int(size.width()), int(size.height())
        self.logger.log("viewport size is set to %sx%s" % (w, h), min_level=2)
        return w, h
Exemple #2
0
    def setScrolls(self):
        """
        Currently not being used...
        """
        self.horizontalScrollBar().setVisible(True)
        self.verticalScrollBar().setVisible(True)

        self.__prevZoomFactor = 1.0

        # nasty code here...
        shouldZoom = True
        while shouldZoom:
            w = self.width()
            h = self.height()
            imgSize = self.__glWidget.GetImageSize()
            if imgSize.width() == 0 or imgSize.height() == 0:
                imgSize = QSize(100, 100)

            zoomFactor = self.__glWidget.GetZoomFactor()

            if w < imgSize.width() * zoomFactor or h < imgSize.height() * zoomFactor:
                self.__glWidget.ZoomOut()
            else:
                shouldZoom = False

        self.UpdateViewport(True)
Exemple #3
0
class NotificationServer(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self.notifications = set()
        self.size = QSize(300, 100)
        self.margin = QPoint(10, 10)

    def notify(self, html):
        note = Notification(html)
        self.connect(note, SIGNAL("done"), self.noteDestroyed)

        desktop = QApplication.desktop().availableGeometry(note)
        me = QRect(QPoint(0, 0), self.size)
        me.moveBottomRight(desktop.bottomRight() - self.margin)
        while self.notePosTaken(me):
            me.translate(0, 0 - (self.size.height() + (self.margin.y() * 2)))
            if not desktop.contains(me):
                me.moveBottom(desktop.bottom() - self.margin.y())
                me.translate(0 - (self.size.width() + self.margin.x() * 2), 0)

        note.setGeometry(me)
        self.notifications.add(note)
        note.display()

    def notePosTaken(self, rect):
        for note in self.notifications:
            if note.geometry().intersects(rect):
                return True
        return False

    def noteDestroyed(self, note):
        self.notifications.remove(note)
Exemple #4
0
    def get_favicon(self):
        """
        Get favicon for the site.

        This is called when the site_url can't be loaded or when that
        page doesn't contain a link tag with rel set to icon (the new
        way of doing site icons.)
        """
        if self.site_icon:
            return
        if not with_pyqt:
            self.site_icon = None
            return
        ico_url = urlparse.urljoin(self.icon_url, "/favicon.ico")
        ico_request = urllib2.Request(ico_url)
        if self.user_agent:
            ico_request.add_header('User-agent', self.user_agent)
        ico_response = urllib2.urlopen(ico_request)
        if 200 != ico_response.code:
            self.site_icon = None
            return
        self.site_icon = QImage.fromData(ico_response.read())
        max_size = QSize(self.max_icon_size, self.max_icon_size)
        ico_size = self.site_icon.size()
        if ico_size.width() > max_size.width() \
                or ico_size.height() > max_size.height():
            self.site_icon = self.site_icon.scaled(
                max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
Exemple #5
0
 def pixmapFromSvg(self, pmapSize=None, withBorders=None):
     """returns a pixmap with default size as given in SVG and optional borders/shadows"""
     if withBorders is None:
         withBorders = Preferences.showShadows
     if withBorders:
         wantSize = self.tileset.tileSize.toSize()
     else:
         wantSize = self.tileset.faceSize.toSize()
     if not pmapSize:
         pmapSize = wantSize
     result = QPixmap(pmapSize)
     result.fill(Qt.transparent)
     painter = QPainter(result)
     if not painter.isActive():
         logException('painter is not active. Wanted size: %s' % str(pmapSize))
     try:
         xScale = float(pmapSize.width()) / wantSize.width()
         yScale = float(pmapSize.height()) / wantSize.height()
     except ZeroDivisionError:
         xScale = 1
         yScale = 1
     if not withBorders:
         painter.scale(*self.tileset.tileFaceRelation())
         painter.translate(-self.facePos())
     renderer = self.tileset.renderer()
     renderer.render(painter, self.elementId())
     painter.resetTransform()
     self._drawDarkness(painter)
     if self.showFace():
         faceSize = self.tileset.faceSize.toSize()
         faceSize = QSize(faceSize.width() * xScale, faceSize.height() * yScale)
         painter.translate(self.facePos())
         renderer.render(painter, self.tileset.svgName[self.tile.element.lower()],
                 QRectF(QPointF(), QSizeF(faceSize)))
     return result
Exemple #6
0
 def __fillLastTileComboWith(self, lastTiles, winnerTiles):
     """fill last meld combo with prepared content"""
     self.comboTilePairs = lastTiles
     idx = self.cbLastTile.currentIndex()
     if idx < 0:
         idx = 0
     indexedTile = str(self.cbLastTile.itemData(idx).toPyObject())
     restoredIdx = None
     self.cbLastTile.clear()
     if not winnerTiles:
         return
     pmSize = winnerTiles[0].board.tileset.faceSize
     pmSize = QSize(pmSize.width() * 0.5, pmSize.height() * 0.5)
     self.cbLastTile.setIconSize(pmSize)
     QPixmapCache.clear()
     self.__tilePixMaps = []
     shownTiles = set()
     for tile in winnerTiles:
         if tile.element in lastTiles and tile.element not in shownTiles:
             shownTiles.add(tile.element)
             self.cbLastTile.addItem(QIcon(tile.graphics.pixmapFromSvg(pmSize, withBorders=False)),
                     '', QVariant(tile.element))
             if indexedTile == tile.element:
                 restoredIdx = self.cbLastTile.count() - 1
     if not restoredIdx and indexedTile:
         # try again, maybe the tile changed between concealed and exposed
         indexedTile = indexedTile.lower()
         for idx in range(self.cbLastTile.count()):
             if indexedTile == str(self.cbLastTile.itemData(idx).toPyObject()).lower():
                 restoredIdx = idx
                 break
     if not restoredIdx:
         restoredIdx = 0
     self.cbLastTile.setCurrentIndex(restoredIdx)
     self.prevLastTile = self.computeLastTile()
Exemple #7
0
 def _setViewportSize(self, size):
     if not isinstance(size, QSize):
         w, h = map(int, size.split('x'))
         size = QSize(w, h)
     self.web_page.setViewportSize(size)
     w, h = int(size.width()), int(size.height())
     self.log("viewport size for %s is set to %sx%s" % (id(self.splash_request), w, h))
Exemple #8
0
    def sizeHint(self):
        """
        Reimplemented from `QPushButton.sizeHint`.

        Returns
        -------
        sh : QSize
        """
        sh = super().sizeHint()
        option = QStyleOptionButton()
        self.initStyleOption(option)
        style = self.style()
        fm = option.fontMetrics
        if option.iconSize.isValid():
            icsize = option.iconSize
            icsize.setWidth(icsize.width() + 4)
        else:
            icsize = QSize()

        for text in self.__textChoiceList:
            option.text = text
            size = fm.size(Qt.TextShowMnemonic, text)

            if not icsize.isNull():
                size.setWidth(size.width() + icsize.width())
                size.setHeight(max(size.height(), icsize.height()))

            sh = sh.expandedTo(
                style.sizeFromContents(QStyle.CT_PushButton, option,
                                       size, self))
        return sh
    def paintEvent(self, event):
        crect = self.rect()
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        painter.setBrush(QBrush(Qt.white))
        painter.setPen(QPen(Qt.lightGray, 1.2))
        painter.drawRoundedRect(QRectF(crect).adjusted(2, 2, -2, -2), 2, 2,
                                Qt.AbsoluteSize)

        if self._selected:
            painter.setPen(QPen(QBrush(Qt.red), 2))
        if self._highlighted:
            painter.setBrush(QBrush(Qt.gray,  Qt.FDiagPattern))
        else:
            painter.setBrush(Qt.NoBrush)

        painter.drawRoundedRect(QRectF(crect).adjusted(2, 2, -2, -2), 2, 2,
                                Qt.AbsoluteSize)

        defsize = self.renderer().defaultSize()
        margin = 5

        bound = QSize(defsize)
        bound.scale(crect.width() - margin, crect.height() - margin,
                    Qt.KeepAspectRatio)

        svgrect = QRectF(0, 0, bound.width(), bound.height())
        svgrect.moveCenter(crect.center())
        self.renderer().render(painter, svgrect)
Exemple #10
0
 def viewportSize(self):
     size = QSize(self.m_page.viewportSize())
     result = {
         'width': size.width(),
         'height': size.height()
     }
     return result
Exemple #11
0
    def __updatePixmap(self):
        """
        Update the cached shadow pixmap.
        """
        rect_size = QSize(50, 50)
        left = top = right = bottom = self.radius_

        # Size of the pixmap.
        pixmap_size = QSize(rect_size.width() + left + right,
                            rect_size.height() + top + bottom)
        shadow_rect = QRect(QPoint(left, top), rect_size)
        pixmap = QPixmap(pixmap_size)
        pixmap.fill(QColor(0, 0, 0, 0))
        rect_fill_color = self.palette().color(QPalette.Window)

        pixmap = render_drop_shadow_frame(
                      pixmap,
                      QRectF(shadow_rect),
                      shadow_color=self.color_,
                      offset=QPointF(0, 0),
                      radius=self.radius_,
                      rect_fill_color=rect_fill_color
                      )

        self.__shadowPixmap = pixmap
        self.update()
Exemple #12
0
 def __init__(self, *args):
     QComboBox.__init__(self, *args)
     self.paletteImg = []
     self.cachedPalettes = []
     ##        self.setItemDelegate(PaletteItemDelegate(self, self))
     size = self.sizeHint()
     size = QSize(size.width() * 2 / 3, size.height() * 2 / 3)
     self.setIconSize(size)
Exemple #13
0
    def minimumSize(self):
        size = QSize()
        for item in self.items:
            size = size.expandedTo(item.minimumSize())

        margin = self.margin()
        size += QSize(2*margin, 2*margin)
        return size
 def sizeHint(self, option, index):
     size = QStyledItemDelegate.sizeHint(self,  option, index)
     parent = self.parent()
     item = parent.itemFromIndex(index)
     widget = parent.itemWidget(item, 0)
     if widget:
         size = QSize(size.width(), widget.sizeHint().height() / 2)
     return size
    def sizeHint(self):
        hint = QLabel.sizeHint(self)

        if self.maximum_size_hint != None:
            hint = QSize(max(hint.width(), self.maximum_size_hint.width()),
                         max(hint.height(), self.maximum_size_hint.height()))

        self.maximum_size_hint = hint

        return hint
Exemple #16
0
    def invalidate(self):
        """ Invalidate the internal cached data for this widget item.

        The invalidation will only have an effect if the layout data
        associate with this item is marked as dirty.

        """
        if self.data.dirty:
            self._cached_hint = QSize()
            self._cached_min = QSize()
            self.data.dirty = False
Exemple #17
0
 def sizeHint(self):
     # The default sizeHint method returns (-1, 3) or (3, -1) when
     # the frame is used as a separator, regardless of the computed
     # frame width. This override corrects that behavior.
     hint = super(QSeparator, self).sizeHint()
     if self.frameShadow() in (QFrame.Raised, QFrame.Sunken):
         shape = self.frameShape()
         if shape == QFrame.HLine:
             hint = QSize(hint.width(), max(3, self.frameWidth() * 2))
         elif shape == QFrame.VLine:
             hint = QSize(max(3, self.frameWidth() * 2), hint.height())
     return hint
class FeatureTableWidgetHHeader(QTableWidgetItem):
    def __init__(self, sigma, window_size, name=None):
        QTableWidgetItem.__init__(self)
        # init
        # ------------------------------------------------
        self.sigma = sigma
        self.window_size = window_size
        self.pixmapSize = QSize(61, 61)
        if not name:
            self.setNameAndBrush(self.sigma)
        else:
            self.setText(name)

    @property
    def brushSize(self):
        return int(3.0 * self.sigma + 0.5) * 2 + 1

    def setNameAndBrush(self, sigma, color=Qt.black):
        self.sigma = sigma
        self.setText(
            decode_to_qstring("σ=%.1fpx" % self.sigma, "utf-8")
        )  # This file is encoded as utf-8, so this string should be decoded as such.
        total_window = 1 + 2 * int(self.sigma * self.window_size + 0.5)
        self.setToolTip("sigma = {:.1f} pixels, window diameter = {:.1f}".format(self.sigma, total_window))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        self.setFont(font)
        self.setForeground(color)

        pixmap = QPixmap(self.pixmapSize)
        pixmap.fill(Qt.transparent)
        painter = QPainter()
        painter.begin(pixmap)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setPen(color)
        brush = QBrush(color)
        painter.setBrush(brush)
        painter.drawEllipse(
            QRect(
                self.pixmapSize.width() / 2 - self.brushSize / 2,
                self.pixmapSize.height() / 2 - self.brushSize / 2,
                self.brushSize,
                self.brushSize,
            )
        )
        painter.end()
        self.setIcon(QIcon(pixmap))
        self.setTextAlignment(Qt.AlignVCenter)

    def setIconAndTextColor(self, color):
        self.setNameAndBrush(self.sigma, color)
Exemple #19
0
    def sizeHint(self):
        hint = self.__contentsLayout.sizeHint()

        if self.count():
            # Compute max width of hidden widgets also.
            scroll = self.__scrollArea
            scroll_w = scroll.verticalScrollBar().sizeHint().width()
            frame_w = self.frameWidth() * 2 + scroll.frameWidth() * 2
            max_w = max([p.widget.sizeHint().width() for p in self.__pages])
            hint = QSize(max(max_w, hint.width()) + scroll_w + frame_w,
                         hint.height())

        return QSize(200, 200).expandedTo(hint)
Exemple #20
0
    def restoreWindowState(self):
        # GUI settings
        history = util.readConfigString(GeneralConfig, "Url History", '')\
            .split(',')
        self.characterCombo.insertItems(history)
        self.historyLength = util.readConfigInt(GeneralConfig, "History Length",
            20)
        self.autoLookup = util.readConfigString(GeneralConfig,
            "Auto-Lookup clipboard", str(False)) != "False"
        self.autoLookupAction.setChecked(self.autoLookup)
        self.onlyAutoLookupCJKCharacters = util.readConfigString(GeneralConfig,
            "Auto-Lookup only Chinese characters", str(False)) != "False"

        self.splitterFrame.restoreState(QByteArray.fromBase64(
            str(util.readConfigString(GeneralConfig, "Splitter", ""))))
        self.splitterSizes = [int(i) for i \
            in util.readConfigString(GeneralConfig, "Splitter sizes",
                "220,426").split(',')]

        self.toolbarOriginalState = QByteArray.fromBase64(
            str(util.readConfigString(GeneralConfig, "Toolbar original state",
                "")))
        self.restoreState(self.toolbarOriginalState)
        self.menuBar().setVisible(True)

        self.characterChooser.setCurrentIndex(util.readConfigInt(GeneralConfig,
            "Toolbox current", 0))

        visible = GeneralConfig.readEntry("Toolbox visibile", str(True))
        if visible == "False":
            self.characterChooserOriginalVisibility = False
        else:
            self.splitterFrame.setSizes(self.splitterSizes)
            self.characterChooserOriginalVisibility = True
        self.characterChooser.setVisible(
            self.characterChooserOriginalVisibility)
        self.toggleToolboxAction.setChecked(
            self.characterChooserOriginalVisibility)

        w = util.readConfigInt(GeneralConfig, "Width", 640)
        h = util.readConfigInt(GeneralConfig, "Height", 420)
        self.defaultWindowSize = QSize(w, h)
        x = util.readConfigInt(GeneralConfig, "LastX", 0)
        y = util.readConfigInt(GeneralConfig, "LastY", 0)

        mini_w = util.readConfigInt(GeneralConfig, "Mini-mode Width", 400)
        mini_h = util.readConfigInt(GeneralConfig, "Mini-mode Height", 200)
        self.miniModeWindowSize = QSize(mini_w, mini_h)

        self.setGeometry(x, y, w, h)
Exemple #21
0
	def paintEvent(self, event):
		painter = QPainter(self)
		painter.setRenderHint(QPainter.Antialiasing)
		size = QSize(1, 1)
		size.scale(self.width() - 1, self.height() - 1, Qt.KeepAspectRatio)

		matrix = QMatrix()
		matrix.translate((self.width() - size.width()) / 2, (self.height() - size.height()) / 2)
		painter.setMatrix(matrix)
		self.__startAngle = 0
		for polozka in self.__polozky:
			self.kresliPolozku(painter, size, polozka[0], polozka[1], polozka[2])
		self.__startAngle = 0
		for polozka in self.__polozky:
			self.kresliText(painter, size, polozka[0], polozka[1], polozka[2])
Exemple #22
0
    def __init__(self):
        """ The Settings constructor initializes the default settings
        values, which is provided as a fallback, should the config file
        somehow go missing. We use the ``qApp`` instance of The running
        ``QApplication`` to register organization and application name,
        as well as the application version.
        """
        QSettings.__init__(self)

        # This is the path prefix where we store all luma related
        # files (serverlist, templates, filter bookmarks etc.)
        self.__configPrefix = ''

        # Defaults for section: mainwindow
        self.__maximize = False
        self.__size = QSize(750, 500)
        screen = QDesktopWidget().screenGeometry()
        self.__position = QPoint((screen.width() - self.__size.width()) / 2,
                                 (screen.height() - self.__size.height()) / 2)
        # Defaults for section: i18n
        self.__language = u'en'
        # Defaults for section: logger
        self.__showLoggerOnStart = False
        self.__showLogger = False
        self.__showErrors = True
        self.__showDebug = True
        self.__showInfo = True
class FeatureTableWidgetHHeader(QTableWidgetItem):
    def __init__(self, sigma, name=None):
        QTableWidgetItem.__init__(self)
        # init
        # ------------------------------------------------
        self.sigma = sigma
        self.pixmapSize = QSize(61, 61)
        if not name:
            self.setNameAndBrush(self.sigma)
        else:
            self.setText(name)

    @property
    def brushSize(self):
        return int(3.0 * self.sigma + 0.5) * 2 + 1

    def setNameAndBrush(self, sigma, color=Qt.black):
        self.sigma = sigma
        self.setText(str(self.brushSize))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        self.setFont(font)
        self.setForeground(color)

        pixmap = QPixmap(self.pixmapSize)
        pixmap.fill(Qt.transparent)
        painter = QPainter()
        painter.begin(pixmap)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setPen(color)
        brush = QBrush(color)
        painter.setBrush(brush)
        painter.drawEllipse(
            QRect(
                self.pixmapSize.width() / 2 - self.brushSize / 2,
                self.pixmapSize.height() / 2 - self.brushSize / 2,
                self.brushSize,
                self.brushSize,
            )
        )
        painter.end()
        self.setIcon(QIcon(pixmap))
        self.setTextAlignment(Qt.AlignVCenter)

    def setIconAndTextColor(self, color):
        self.setNameAndBrush(self.sigma, color)
Exemple #24
0
  def test01_export_empty(self):
    """test exporting with empty export settings"""
    # map settings
    canvasSize = QSize(600, 600)
    width = 1000.
    height = width * canvasSize.height() / canvasSize.width()
    crs = QgsCoordinateReferenceSystem(3099, QgsCoordinateReferenceSystem.EpsgCrsId)  # JGD2000 / UTM zone 53N

    mapSettings = QgsMapSettings()
    mapSettings.setOutputSize(canvasSize)
    mapSettings.setExtent(QgsRectangle(0, 0, width, height))
    mapSettings.setDestinationCrs(crs)

    exporter = Exporter()
    exporter.setMapSettings(mapSettings)
    err = exporter.export(outputPath(os.path.join("empty", "empty.html")))
    assert err == Exporter.NO_ERROR, err
Exemple #25
0
    def __init__(self, widget, data):
        """ Initialize a QFlowWidgetItem.

        Parameters
        ----------
        widget : QWidget
            The widget to manage with this item.

        data : FlowLayoutData
            The layout data struct associated with this item.

        """
        super(QFlowWidgetItem, self).__init__(widget)
        self.data = data
        self._cached_hint = QSize()
        self._cached_max = QSize()
        self._cached_min = QSize()
Exemple #26
0
    def __init__(self, parent=None, **kwargs):
        QFrame.__init__(self, parent, **kwargs)

        self.__pages = []
        self.__tabButtonHeight = -1
        self.__tabIconSize = QSize()
        self.__exclusive = False
        self.__setupUi()
 def setIconSize(self, size):
     """
     Set the icon (and this item's) size (:class:`QSize`).
     """
     if self.__iconSize != size:
         self.prepareGeometryChange()
         self.__iconSize = QSize(size)
         self.update()
Exemple #28
0
 def __init__(self):
   QDeclarativeImageProvider.__init__(self, QDeclarativeImageProvider.Image)
   self.size = QSize(2631/4, 1860/4)
   self.image = QImage(self.size, QImage.Format_RGB32)
   self.image.fill(QColor(255,255,255))
   self.p = QPainter()
   self.p.begin(self.image)
   self.p.setPen(QPen(QColor(0,0,0), 5));
Exemple #29
0
    def maybe_get_icon(self):
        """
        Get icon for the site as a QImage if we haven't already.

        Get the site icon, either the 'rel="icon"' or the favicon, for
        the web page at url or passed in as page_html and store it as
        a QImage. This function can be called repeatedly and loads the
        icon only once.
        """
        if self.site_icon:
            return
        if not with_pyqt:
            self.site_icon = None
            return
        page_request = urllib2.Request(self.icon_url)
        if self.user_agent:
            page_request.add_header('User-agent', self.user_agent)
        page_response = urllib2.urlopen(page_request)
        if 200 != page_response.code:
            self.get_favicon()
            return
        page_soup = soup(page_response)
        try:
            icon_url = page_soup.find(
                name='link', attrs={'rel': 'icon'})['href']
        except (TypeError, KeyError):
            self.get_favicon()
            return
        # The url may be absolute or relative.
        if not urlparse.urlsplit(icon_url).netloc:
            icon_url = urlparse.urljoin(
                self.url, urllib.quote(icon_url.encode('utf-8')))
        icon_request = urllib2.Request(icon_url)
        if self.user_agent:
            icon_request.add_header('User-agent', self.user_agent)
        icon_response = urllib2.urlopen(icon_request)
        if 200 != icon_response.code:
            self.site_icon = None
            return
        self.site_icon = QImage.fromData(icon_response.read())
        max_size = QSize(self.max_icon_size, self.max_icon_size)
        icon_size = self.site_icon.size()
        if icon_size.width() > max_size.width() \
                or icon_size.height() > max_size.height():
            self.site_icon = self.site_icon.scaled(
                max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
Exemple #30
0
	def readSettings(self):
		self.imageFolder = os.path.normpath(str(self.settings.value("imageFolder").toString()))
		self.ui.actionIgnore_Transparent_Pixels.setChecked( self.settings.value("ignoreAlpha", True).toBool())
		self.ui.actionCheck_for_update_at_start.setChecked( self.settings.value("checkupdate", True).toBool())
		self.ui.tolerance_le.setText( self.settings.value("tolerance").toString())
		self.settings.beginGroup("/geometry")
		p = QPoint()  # position
		s = QSize()  # size

		x = self.settings.value("X", -1).toInt()[0]
		y = self.settings.value("Y", -1).toInt()[0]
		# don't position outside current screen
		qRect = QtGui.QDesktopWidget.availableGeometry(app.desktop())
		if x > qRect.right():
			x = 10
		if y > qRect.bottom():
			y = 10
		p.setX(x)
		p.setY(y)
		s.setWidth(self.settings.value("W", -1).toInt()[0])
		s.setHeight(self.settings.value("H", -1).toInt()[0])
		self.settings.endGroup()
		if p.x() > 0 and p.y() > 0 and s.width() > 0 and s.height() > 0:
			self.resize(s)  # restore size
			self.move(p)  # restore position
Exemple #31
0
    def __createLayout(self):
        " Creates the toolbar and layout "

        # Buttons
        self.__printButton = QAction(PixmapCache().getIcon('printer.png'),
                                     'Print', self)
        self.__printButton.triggered.connect(self.__onPrint)
        self.__printButton.setEnabled(False)
        self.__printButton.setVisible(False)

        self.__printPreviewButton = QAction(
            PixmapCache().getIcon('printpreview.png'), 'Print preview', self)
        self.__printPreviewButton.triggered.connect(self.__onPrintPreview)
        self.__printPreviewButton.setEnabled(False)
        self.__printPreviewButton.setVisible(False)

        # self.__sendUpButton = QAction( PixmapCache().getIcon('sendioup.png'),
        #                                'Send to Main Editing Area', self )
        # self.__sendUpButton.triggered.connect( self.__sendUp )

        self.__filterMenu = QMenu(self)
        self.__filterMenu.aboutToShow.connect(self.__filterAboutToShow)
        self.__filterGroup = QActionGroup(self)
        self.__filterShowAllAct = self.__filterMenu.addAction("Show all")
        self.__filterShowAllAct.setCheckable(True)
        self.__filterShowAllAct.setActionGroup(self.__filterGroup)
        self.__filterShowAllAct.triggered.connect(self.__onFilterShowAll)
        self.__filterShowStdoutAct = self.__filterMenu.addAction(
            "Show stdin and stdout")
        self.__filterShowStdoutAct.setCheckable(True)
        self.__filterShowStdoutAct.setActionGroup(self.__filterGroup)
        self.__filterShowStdoutAct.triggered.connect(self.__onFilterShowStdout)
        self.__filterShowStderrAct = self.__filterMenu.addAction(
            "Show stdin and stderr")
        self.__filterShowStderrAct.setCheckable(True)
        self.__filterShowStderrAct.setActionGroup(self.__filterGroup)
        self.__filterShowStderrAct.triggered.connect(self.__onFilterShowStderr)
        self.__filterButton = QToolButton(self)
        self.__filterButton.setIcon(PixmapCache().getIcon('iofilter.png'))
        self.__filterButton.setToolTip('Filtering settings')
        self.__filterButton.setPopupMode(QToolButton.InstantPopup)
        self.__filterButton.setMenu(self.__filterMenu)
        self.__filterButton.setFocusPolicy(Qt.NoFocus)

        self.__settingsMenu = QMenu(self)
        self.__settingsMenu.aboutToShow.connect(self.__settingsAboutToShow)
        self.__wrapLongLinesAct = self.__settingsMenu.addAction(
            "Wrap long lines")
        self.__wrapLongLinesAct.setCheckable(True)
        self.__wrapLongLinesAct.triggered.connect(self.__onWrapLongLines)
        self.__showEOLAct = self.__settingsMenu.addAction("Show EOL")
        self.__showEOLAct.setCheckable(True)
        self.__showEOLAct.triggered.connect(self.__onShowEOL)
        self.__showWhitespacesAct = self.__settingsMenu.addAction(
            "Show whitespaces")
        self.__showWhitespacesAct.setCheckable(True)
        self.__showWhitespacesAct.triggered.connect(self.__onShowWhitespaces)
        self.__autoscrollAct = self.__settingsMenu.addAction("Autoscroll")
        self.__autoscrollAct.setCheckable(True)
        self.__autoscrollAct.triggered.connect(self.__onAutoscroll)
        self.__showMarginAct = self.__settingsMenu.addAction(
            "Show timestamp margin")
        self.__showMarginAct.setCheckable(True)
        self.__showMarginAct.triggered.connect(self.__onShowMargin)

        self.__settingsButton = QToolButton(self)
        self.__settingsButton.setIcon(PixmapCache().getIcon('iosettings.png'))
        self.__settingsButton.setToolTip('View settings')
        self.__settingsButton.setPopupMode(QToolButton.InstantPopup)
        self.__settingsButton.setMenu(self.__settingsMenu)
        self.__settingsButton.setFocusPolicy(Qt.NoFocus)

        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.__clearButton = QAction(PixmapCache().getIcon('trash.png'),
                                     'Clear', self)
        self.__clearButton.triggered.connect(self.clear)

        # The toolbar
        toolbar = QToolBar(self)
        toolbar.setOrientation(Qt.Vertical)
        toolbar.setMovable(False)
        toolbar.setAllowedAreas(Qt.RightToolBarArea)
        toolbar.setIconSize(QSize(16, 16))
        toolbar.setFixedWidth(28)
        toolbar.setContentsMargins(0, 0, 0, 0)

        # toolbar.addAction( self.__sendUpButton )
        toolbar.addAction(self.__printPreviewButton)
        toolbar.addAction(self.__printButton)
        toolbar.addWidget(self.__filterButton)
        toolbar.addWidget(self.__settingsButton)
        toolbar.addWidget(spacer)
        toolbar.addAction(self.__clearButton)

        hLayout = QHBoxLayout()
        hLayout.setContentsMargins(0, 0, 0, 0)
        hLayout.setSpacing(0)
        hLayout.addWidget(toolbar)
        hLayout.addWidget(self.__viewer)

        self.setLayout(hLayout)
        return
        if self._tc1:
            self._tc1.stop()
        if self._tc2:
            self._tc2.stop()

    def _on_finished(self):
        #only enable start button when both threads have stopped...
        stopped = True
        if self._tc1.is_running or self._tc2.is_running:
            stopped = False

        if stopped:
            self.btnStart.setEnabled(True)
            self.btnStop.setEnabled(False)

    def _onTc1Change(self, data):
        self.lblOne.setText(data['result'])

    def _onTc2Change(self, data):
        self.lblTwo.setText(data['result'])


if __name__ == '__main__':
    app = QApplication(sys.argv)

    gui = MyGUI()
    gui.resize(QSize(500, 100))
    gui.show()

    app.exec_()
    sys.exit()
Exemple #33
0
 def __init__(self, parent=None):
     super(WebWidget, self).__init__(parent)
     self.web = QWebView()
     self.web.setMinimumSize(QSize(500, 500))
     self.web.setUrl(QUrl(r'http://www.google.com/'))
 def sizeHint(self):
     return QSize(500, 300)  # TODO better size handling
Exemple #35
0
    def __init__(self, parent=None):
        super(MapWidget, self).__init__(parent)
        self.setupUi(self)
        self.snapping = True

        icon = roam_style.iconsize()
        self.projecttoolbar.setIconSize(QSize(icon, icon))

        self.current_form = None
        self.last_form = None
        self.firstshow = True
        self.layerbuttons = []
        self.editfeaturestack = []
        self.lastgpsposition = None
        self.project = None
        self.gps = None
        self.gpslogging = None
        self.selectionbands = defaultdict(partial(QgsRubberBand, self.canvas))

        self.bridge = QgsLayerTreeMapCanvasBridge(
            QgsProject.instance().layerTreeRoot(), self.canvas)
        self.bridge.setAutoSetupOnFirstLayer(False)
        QgsProject.instance().writeProject.connect(self.bridge.writeProject)
        QgsProject.instance().readProject.connect(self.bridge.readProject)

        # self.canvas.setInteractive(False)
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.enableAntiAliasing(True)
        self.canvas.setWheelAction(QgsMapCanvas.WheelZoomToMouseCursor)

        self.snappingutils = SnappingUtils(self.canvas, self)
        self.canvas.setSnappingUtils(self.snappingutils)
        QgsProject.instance().readProject.connect(
            self.snappingutils.readConfigFromProject)

        if hasattr(self.canvas, 'setParallelRenderingEnabled'):
            threadcount = QThread.idealThreadCount()
            threadcount = 2 if threadcount > 2 else 1
            QgsApplication.setMaxThreads(threadcount)
            self.canvas.setParallelRenderingEnabled(True)

        pal = QgsPalLabeling()
        self.canvas.mapRenderer().setLabelingEngine(pal)
        self.canvas.setFrameStyle(QFrame.NoFrame)

        self.editgroup = QActionGroup(self)
        self.editgroup.setExclusive(True)
        self.editgroup.addAction(self.actionPan)
        self.editgroup.addAction(self.actionZoom_In)
        self.editgroup.addAction(self.actionZoom_Out)
        self.editgroup.addAction(self.actionInfo)

        self.actionGPS = GPSAction(":/icons/gps", self.canvas, self)
        self.projecttoolbar.addAction(self.actionGPS)

        if roam.config.settings.get('north_arrow', False):
            self.northarrow = NorthArrow(":/icons/north", self.canvas)
            self.northarrow.setPos(10, 10)
            self.canvas.scene().addItem(self.northarrow)

        smallmode = roam.config.settings.get("smallmode", False)
        self.projecttoolbar.setSmallMode(smallmode)

        self.scalebar_enabled = roam.config.settings.get('scale_bar', False)
        if self.scalebar_enabled:
            self.scalebar = ScaleBarItem(self.canvas)
            self.canvas.scene().addItem(self.scalebar)

        self.projecttoolbar.setContextMenuPolicy(Qt.CustomContextMenu)

        gpsspacewidget = QWidget()
        gpsspacewidget.setMinimumWidth(30)
        gpsspacewidget.setSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)

        self.topspaceraction = self.projecttoolbar.insertWidget(
            self.actionGPS, gpsspacewidget)

        self.dataentryselection = QAction(self.projecttoolbar)
        self.dataentryaction = self.projecttoolbar.insertAction(
            self.topspaceraction, self.dataentryselection)
        self.dataentryselection.triggered.connect(self.select_data_entry)

        self.marker = GPSMarker(self.canvas)
        self.marker.hide()

        self.currentfeatureband = CurrentSelection(self.canvas)
        self.currentfeatureband.setIconSize(30)
        self.currentfeatureband.setWidth(10)
        self.currentfeatureband.setColor(QColor(186, 93, 212, 50))
        self.currentfeatureband.setOutlineColour(QColor(186, 93, 212))

        self.gpsband = QgsRubberBand(self.canvas)
        self.gpsband.setColor(QColor(165, 111, 212, 75))
        self.gpsband.setWidth(5)

        RoamEvents.editgeometry.connect(self.queue_feature_for_edit)
        RoamEvents.selectioncleared.connect(self.clear_selection)
        RoamEvents.selectionchanged.connect(self.highlight_selection)
        RoamEvents.openfeatureform.connect(self.feature_form_loaded)
        RoamEvents.sync_complete.connect(self.refresh_map)
        RoamEvents.snappingChanged.connect(self.snapping_changed)

        self.snappingbutton = QToolButton()
        self.snappingbutton.setText("Snapping: On")
        self.snappingbutton.setAutoRaise(True)
        self.snappingbutton.pressed.connect(self.toggle_snapping)

        spacer = QWidget()
        spacer2 = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        spacer2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        self.scalewidget = QgsScaleComboBox()

        self.scalebutton = QToolButton()
        self.scalebutton.setAutoRaise(True)
        self.scalebutton.setMaximumHeight(self.statusbar.height())
        self.scalebutton.pressed.connect(self.selectscale)
        self.scalebutton.setText("Scale")

        self.scalelist = BigList(parent=self.canvas,
                                 centeronparent=True,
                                 showsave=False)
        self.scalelist.hide()
        self.scalelist.setlabel("Map Scale")
        self.scalelist.setmodel(self.scalewidget.model())
        self.scalelist.closewidget.connect(self.scalelist.close)
        self.scalelist.itemselected.connect(self.update_scale_from_item)
        self.scalelist.itemselected.connect(self.scalelist.close)

        self.positionlabel = QLabel('')
        self.gpslabel = QLabel("GPS: Not active")
        self.gpslabelposition = QLabel("")

        self.statusbar.addWidget(self.snappingbutton)
        self.statusbar.addWidget(spacer2)
        self.statusbar.addWidget(self.gpslabel)
        self.statusbar.addWidget(self.gpslabelposition)
        self.statusbar.addPermanentWidget(self.scalebutton)

        self.canvas.extentsChanged.connect(self.updatestatuslabel)
        self.canvas.scaleChanged.connect(self.updatestatuslabel)

        GPS.gpsposition.connect(self.update_gps_label)
        GPS.gpsdisconnected.connect(self.gps_disconnected)

        self.connectButtons()
Exemple #36
0
 def sizeHint(self):
     w, h = self.get_width_height()
     return QSize(w, h)
Exemple #37
0
 def sizeHint(self):
     return QSize(780, 1)
Exemple #38
0
    def __init__(self, parent=None):
        Qwt.QwtPlot.__init__(self, parent)
        self.setAutoReplot(False)
        self.setTitle("Frequency Response of a Second-Order System")
        canvas = Qwt.QwtPlotCanvas()
        canvas.setBorderRadius(10)
        self.setCanvas(canvas)
        self.setCanvasBackground(QColor("MidnightBlue"))
        # legend
        legend = Qwt.QwtLegend()
        self.insertLegend(legend, Qwt.QwtPlot.BottomLegend)

        # grid
        grid = Qwt.QwtPlotGrid()
        grid.enableXMin(True)
        grid.setMajorPen(Qt.white, 0, Qt.DotLine)
        grid.setMinorPen(Qt.gray, 0, Qt.DotLine)
        grid.attach(self)

        # axes
        self.enableAxis(Qwt.QwtPlot.yRight)
        self.setAxisTitle(Qwt.QwtPlot.xBottom, "Normalized Frequency")
        self.setAxisTitle(Qwt.QwtPlot.yLeft, "Amplitude [dB]")
        self.setAxisTitle(Qwt.QwtPlot.yRight, "Phase [deg]")

        self.setAxisMaxMajor(Qwt.QwtPlot.xBottom, 6)
        self.setAxisMaxMinor(Qwt.QwtPlot.xBottom, 9)
        self.setAxisScaleEngine(Qwt.QwtPlot.xBottom, Qwt.QwtLogScaleEngine())

        # curves
        self.d_curve1 = Qwt.QwtPlotCurve("Amplitude")
        self.d_curve1.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased)
        self.d_curve1.setPen(Qt.yellow)
        self.d_curve1.setLegendAttribute(Qwt.QwtPlotCurve.LegendShowLine)
        self.d_curve1.setYAxis(Qwt.QwtPlot.yLeft)
        self.d_curve1.attach(self)

        self.d_curve2 = Qwt.QwtPlotCurve("Phase")
        self.d_curve2.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased)
        self.d_curve2.setPen(Qt.cyan)
        self.d_curve2.setLegendAttribute(Qwt.QwtPlotCurve.LegendShowLine)
        self.d_curve2.setYAxis(Qwt.QwtPlot.yRight)
        self.d_curve2.attach(self)

        # marker
        self.d_marker1 = Qwt.QwtPlotMarker()
        self.d_marker1.setValue(0.0, 0.0)
        self.d_marker1.setLineStyle(Qwt.QwtPlotMarker.VLine)
        self.d_marker1.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        self.d_marker1.setLinePen(Qt.green, 0, Qt.DashDotLine)
        self.d_marker1.attach(self)

        self.d_marker2 = Qwt.QwtPlotMarker()
        self.d_marker2.setLineStyle(Qwt.QwtPlotMarker.HLine)
        self.d_marker2.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        self.d_marker2.setLinePen(QColor(200, 150, 0), 0, Qt.DashDotLine)
        self.d_marker2.setSymbol(
            Qwt.QwtSymbol(Qwt.QwtSymbol.Diamond, QColor(Qt.yellow),
                          QColor(Qt.green), QSize(8, 8)))
        self.d_marker2.attach(self)

        self.setDamp(0)

        self.setAutoReplot(True)
Exemple #39
0
 def sizeHint(self, *args):
     size = super().sizeHint(*args)
     return QSize(size.width(), size.height() + 6)
Exemple #40
0
    def __init__(self, mainwindow):
        super(Dialog, self).__init__(mainwindow)
        self._document = None

        layout = QGridLayout()
        self.setLayout(layout)

        self.versionLabel = QLabel()
        self.lilyChooser = lilychooser.LilyChooser()

        self.outputLabel = QLabel()
        self.outputCombo = QComboBox()

        self.resolutionLabel = QLabel()
        self.resolutionCombo = QComboBox(editable=True)

        self.antialiasLabel = QLabel()
        self.antialiasSpin = QSpinBox(minimum=1, maximum=128, value=1)

        self.modeLabel = QLabel()
        self.modeCombo = QComboBox()

        self.englishCheck = QCheckBox()
        self.deleteCheck = QCheckBox()

        self.commandLineLabel = QLabel()
        self.commandLine = QTextEdit(acceptRichText=False)

        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.buttons.button(QDialogButtonBox.Ok).setIcon(
            icons.get("lilypond-run"))
        userguide.addButton(self.buttons, "engrave_custom")

        self.resolutionCombo.addItems(['100', '200', '300', '600', '1200'])
        self.resolutionCombo.setCurrentIndex(2)

        self.modeCombo.addItems(['preview', 'publish', 'debug'])
        layout.addWidget(self.versionLabel, 0, 0)
        layout.addWidget(self.lilyChooser, 0, 1, 1, 3)
        layout.addWidget(self.outputLabel, 1, 0)
        layout.addWidget(self.outputCombo, 1, 1, 1, 3)
        layout.addWidget(self.resolutionLabel, 2, 0)
        layout.addWidget(self.resolutionCombo, 2, 1)
        layout.addWidget(self.antialiasLabel, 2, 2, Qt.AlignRight)
        layout.addWidget(self.antialiasSpin, 2, 3)
        layout.addWidget(self.modeLabel, 3, 0)
        layout.addWidget(self.modeCombo, 3, 1, 1, 3)
        layout.addWidget(self.englishCheck, 4, 0, 1, 4)
        layout.addWidget(self.deleteCheck, 5, 0, 1, 4)
        layout.addWidget(self.commandLineLabel, 6, 0, 1, 4)
        layout.addWidget(self.commandLine, 7, 0, 1, 4)
        layout.addWidget(widgets.Separator(), 8, 0, 1, 4)
        layout.addWidget(self.buttons, 9, 0, 1, 4)

        app.translateUI(self)
        qutil.saveDialogSize(self, "engrave/custom/dialog/size",
                             QSize(480, 260))
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

        model = listmodel.ListModel(formats,
                                    display=lambda f: f.title(),
                                    icon=lambda f: icons.file_type(f.type))
        self.outputCombo.setModel(model)

        s = QSettings()
        s.beginGroup("lilypond_settings")
        self.englishCheck.setChecked(s.value("no_translation", False, bool))
        self.deleteCheck.setChecked(
            s.value("delete_intermediate_files", True, bool))

        if s.value("default_output_target", "pdf", type("")) == "svg":
            self.outputCombo.setCurrentIndex(3)

        app.jobFinished.connect(self.slotJobFinished)
        self.outputCombo.currentIndexChanged.connect(self.makeCommandLine)
        self.modeCombo.currentIndexChanged.connect(self.makeCommandLine)
        self.deleteCheck.toggled.connect(self.makeCommandLine)
        self.resolutionCombo.editTextChanged.connect(self.makeCommandLine)
        self.antialiasSpin.valueChanged.connect(self.makeCommandLine)
        self.makeCommandLine()
        panelmanager.manager(
            mainwindow).layoutcontrol.widget().optionsChanged.connect(
                self.makeCommandLine)
Exemple #41
0
 def __init__(self, parent=None):
     QPushButton.__init__(self, parent)
     self.setFixedSize(20, 20)
     self.setIconSize(QSize(12, 12))
     self.connect(self, SIGNAL("clicked()"), self.choose_color)
     self._color = QColor()
Exemple #42
0
 def sizeHint(self):
     height = super(FeatureTableWidget, self).sizeHint().height()
     width = self.horizontalHeader().sizeHint().width() * self.columnCount(
     ) + self.verticalHeader().sizeHint().width() + 22
     return QSize(width, height)
Exemple #43
0
 def sizeHint(self):
     return QSize(20, 20)
Exemple #44
0
 def cursor(name):
     pix = QPixmap(name)
     pix = pix.scaled(QSize(24, 24))
     return QCursor(pix)
Exemple #45
0
def SWProxyStart(ip, port, log):
    # parser = argparse.ArgumentParser(description='SWParser')
    # parser.add_argument('-d', '--debug', action="store_true", default=False)
    # parser.add_argument('-g', '--no-gui', action="store_true", default=False)
    # parser.add_argument('-p', '--port', type=int, default=8080)
    # options, unknown_args = parser.parse_known_args()
    unknown_args = ''

    options = Option(ip=ip, port=port, debug=log, no_gui=True)

    # Set up logger
    level = "DEBUG" if options.debug else "INFO"
    logging.basicConfig(
        level=level,
        filename="proxy.log",
        format='%(asctime)s: %(name)s - %(levelname)s - %(message)s')
    logger.setLevel(logging.INFO)

    print get_usage_text()

    # Check if a PCAP file was passed in
    pcap_filename = None
    for arg in unknown_args:
        if arg.endswith('.pcap'):
            pcap_filename = arg
            break

    if pcap_filename:
        # Parse a PCAP file
        print "Parsing PCAP file..."
        parse_pcap(sys.argv[1])
        raw_input("Press Enter to exit...")
    else:
        # Run the proxy
        # attempt to load gui; fallback if import error
        if not options.no_gui:
            try:
                # Import here to avoid importing QT in CLI mode
                from SWParser.gui import gui
                from PyQt4.QtGui import QApplication, QIcon
                from PyQt4.QtCore import QSize
            except ImportError:
                print "Failed to load GUI dependencies. Switching to CLI mode"
                options.no_gui = True

        if options.no_gui:
            logger.addHandler(logging.StreamHandler())
            start_proxy_server(options)
        else:
            app = QApplication(sys.argv)
            # set the icon
            icons_path = os.path.join(os.getcwd(), resource_path("icons/"))
            app_icon = QIcon()
            app_icon.addFile(icons_path + '16x16.png', QSize(16, 16))
            app_icon.addFile(icons_path + '24x24.png', QSize(24, 24))
            app_icon.addFile(icons_path + '32x32.png', QSize(32, 32))
            app_icon.addFile(icons_path + '48x48.png', QSize(48, 48))
            app_icon.addFile(icons_path + '256x256.png', QSize(256, 256))
            app.setWindowIcon(app_icon)
            win = gui.MainWindow(options.ip, options.port)
            logger.addHandler(gui.GuiLogHandler(win))
            win.show()
            sys.exit(app.exec_())
Exemple #46
0
 def sizeHint(self):
     return QSize(300, 400)
Exemple #47
0
 def sizeHint(self):
     return QSize(1024, 720)
Exemple #48
0
 def sizeHint(self):
     return QSize(320, 40)
Exemple #49
0
 def sizeHint(self):
     return QSize(480, 272)
Exemple #50
0
 def resizeEvent(self, event):
     super().resizeEvent(event)
     size = self.size()
     self.setIconSize(size - QSize(20, 14))
     self.setIcon(self._paletteicon(self.colors, self.iconSize()))
Exemple #51
0
 def sizeHint(self):
     return QSize(100, 100)
Exemple #52
0
 def sizeHint(self):
     metrics = QFontMetrics(self.font())
     rect = metrics.boundingRect(self.text())
     size = QSize(rect.height() + self.margin(),
                  rect.width() + self.margin())
     return size
 def sizeHint(self):
     return QSize(800, 500)
Exemple #54
0
 def minimumSizeHint(self):
     return QSize(10, 10)
Exemple #55
0
        # Run the proxy
        # attempt to load gui; fallback if import error
        if not options.no_gui:
            try:
                # Import here to avoid importing QT in CLI mode
                from SWParser.gui import gui
                from PyQt4.QtGui import QApplication, QIcon
                from PyQt4.QtCore import QSize
            except ImportError:
                print "Failed to load GUI dependencies. Switching to CLI mode"
                options.no_gui = True

        if options.no_gui:
            logger.addHandler(logging.StreamHandler())
            start_proxy_server(options)
        else:
            app = QApplication(sys.argv)
            # set the icon
            icons_path = os.path.join(os.getcwd(), resource_path("icons/"))
            app_icon = QIcon()
            app_icon.addFile(icons_path + '16x16.png', QSize(16, 16))
            app_icon.addFile(icons_path + '24x24.png', QSize(24, 24))
            app_icon.addFile(icons_path + '32x32.png', QSize(32, 32))
            app_icon.addFile(icons_path + '48x48.png', QSize(48, 48))
            app_icon.addFile(icons_path + '256x256.png', QSize(256, 256))
            app.setWindowIcon(app_icon)
            win = gui.MainWindow(get_external_ip(), options.port)
            logger.addHandler(gui.GuiLogHandler(win))
            win.show()
            sys.exit(app.exec_())
Exemple #56
0
 def __init__(self, parent, container):
     QPushButton.__init__(self, QIcon(":del_dump.png"), "", parent)
     self.setIconSize(QSize(16, 16))
     self.container = container
     self.manager = parent
     self.connect(self, SIGNAL("clicked()"), self.rm)
Exemple #57
0
 def _setSizeHintToTableWidgetItems(self):
     width = self.horizontalHeader().sizeHint().width()
     height = self.verticalHeader().sizeHint().height()
     for r, c in self._tableEntries():
         self.item(r, c).setSizeHint(QSize(width, height))
Exemple #58
0
 def minimumSizeHint(self):
     if self.model is None:
         return QSize(BarGraphView.WIDTH * 10, 100)
     return QSize(BarGraphView.WIDTH * self.model.rowCount(), 100)
Exemple #59
0
 def __setup_ui(self):
     self.setTabsClosable(True)
     self.setIconSize(QSize(15, 15))
    def __init__(self, layers, legend, iface, parent=None):
        """Constructor."""
        super(CityExplorerDockWidget, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.layers = layers
        self.iface = iface
        self.districts = getLayerByName(self.layers[0])
        self.buildings = getLayerByName(self.layers[1])
        self.streets = getLayerByName(self.layers[2])
        self.plots = getLayerByName(self.layers[3])
        self.tranform_idx = getLayerByName(self.layers[4])
        self.legend = legend
        self.districts_statistics = getLayerByName(self.layers[5])
        self.buildings_statistics = getLayerByName(self.layers[6])
        self.streets_statistics = getLayerByName(self.layers[7])

        self.chart_data = None

        # setup info icons on pushbuttons
        info_icon = QtGui.QPixmap(
            os.path.dirname(__file__) + "/raster/info_icon.png")

        for icon in [
                self.cityInfo, self.buildInfo, self.strInfo, self.vacantInfo,
                self.transformInfo
        ]:
            icon.setIcon(QtGui.QIcon(info_icon))
            icon.setIconSize(QSize(18, 18))

        logo = QtGui.QPixmap(
            os.path.dirname(__file__) + '/raster/Space_Syntax_logo.png')
        logo = logo.scaled(100, 15, Qt.KeepAspectRatio,
                           Qt.SmoothTransformation)
        self.logoLabel.setPixmap(logo)

        self.settings = []

        # add items to combos
        self.cpscombo.clear()
        kpi_list = [i + " index" for i in tier2.keys()]
        self.cpscombo.addItems(kpi_list)
        self.updatekpicombo()
        self.updatemodecombo()
        self.strcombo.addItems(streets)

        # enable only city index
        self.cityCheckBox.setChecked(True)
        self.districtsRadio.setChecked(True)
        self.allRadio.setChecked(True)
        self.buildCheckBox.setChecked(True)
        self.strCheckBox.setChecked(True)

        # signals to disable/enable layers
        self.cityCheckBox.stateChanged.connect(self.disable_cpscombo)
        self.buildCheckBox.stateChanged.connect(self.disable_kpicombo)
        self.strCheckBox.stateChanged.connect(self.disable_strcombo)

        # disable kpi & str combo - the signal needs the state to be changed to be called
        self.disable_kpicombo()
        self.disable_strcombo()
        self.kpi2combo.setDisabled(True)

        # signals to update combos based on selected indices (only city and building scales)
        # & to emit user input selection
        self.cpscombo.currentIndexChanged.connect(self.updatekpicombo)
        self.kpicombo.currentIndexChanged.connect(self.updatemodecombo)
        self.modecombo.currentIndexChanged.connect(self.updatemodeinput)
        self.strcombo.currentIndexChanged.connect(self.updatestrinput)
        self.kpi2combo.currentIndexChanged.connect(self.updatekpi2combo)

        # visualise additional layers
        self.vacantCheckBox.stateChanged.connect(self.make_plots_visible)
        self.transformCheckBox.stateChanged.connect(
            self.make_transform_idx_visible)

        # exports
        self.imageExport.clicked.connect(self.saveOutput)

        # info buttons
        self.cityInfo.clicked.connect(self.getCityInfo)
        self.strInfo.clicked.connect(self.getStreetInfo)
        self.buildInfo.clicked.connect(self.getBuildInfo)