Exemplo n.º 1
0
 def sizeHint(self):
     q = self.parentWidget()
     mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
     fw = q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q)
     closeSize = QSize(0, 0)
     if self.closeButton:
         closeSize = self.closeButton.sizeHint()
     floatSize = QSize(0, 0)
     if self.floatButton:
         floatSize = self.floatButton.sizeHint()
     hideSize = QSize(0, 0)
     if self.collapseButton:
         hideSize = self.collapseButton.sizeHint()
     pinSize = QSize(0, 0)
     if self.pinButton:
         pinSize = self.pinButton.sizeHint()
     buttonHeight = max(max(closeSize.height(), floatSize.height()), 
                         hideSize.height(), pinSize.height()) + 2
     buttonWidth = closeSize.width() + floatSize.width() + hideSize.width() + pinSize.width()
     titleFontMetrics = q.fontMetrics()
     fontHeight = titleFontMetrics.lineSpacing() + 2 * mw
     height = max(buttonHeight, fontHeight)
     width = buttonWidth + height + 4 * mw + 2 * fw
     if hasFeature(q, QDockWidget.DockWidgetVerticalTitleBar):
         width, height = height, width
     return QSize(width, height)
Exemplo n.º 2
0
 def sizeHint(self):
     q = self.parentWidget()
     mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
     fw = q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q)
     closeSize = QSize(0, 0)
     if self.closeButton:
         closeSize = self.closeButton.sizeHint()
     floatSize = QSize(0, 0)
     if self.floatButton:
         floatSize = self.floatButton.sizeHint()
     hideSize = QSize(0, 0)
     if self.collapseButton:
         hideSize = self.collapseButton.sizeHint()
     pinSize = QSize(0, 0)
     if self.pinButton:
         pinSize = self.pinButton.sizeHint()
     buttonHeight = max(max(closeSize.height(), floatSize.height()),
                        hideSize.height(), pinSize.height()) + 2
     buttonWidth = closeSize.width() + floatSize.width() + hideSize.width(
     ) + pinSize.width()
     titleFontMetrics = q.fontMetrics()
     fontHeight = titleFontMetrics.lineSpacing() + 2 * mw
     height = max(buttonHeight, fontHeight)
     width = buttonWidth + height + 4 * mw + 2 * fw
     if hasFeature(q, QDockWidget.DockWidgetVerticalTitleBar):
         width, height = height, width
     return QSize(width, height)
Exemplo n.º 3
0
 def __init__(self,ressource_directory, dim: QSize, clock_dim_ratio: tuple=(0.9, 0.35), clock_color="#FFFFFF", dev_mode=False):
     super().__init__()
     self.setMaximumSize(dim)
     self.setMinimumSize(dim)
     self.font_color = clock_color
     # Setup clock background
     self._load_timer_picture(ressource_directory)
     #self.setPixmap(self.fond_pixmap.scaled(dim, Qt.KeepAspectRatio))
     self.setPixmap(self.fond_pixmap.scaled(QSize(dim.width()-5,dim.height()-5), Qt.KeepAspectRatio))
     self.setContentsMargins((dim.width() - self.pixmap().width()) * 0.5,
                             (dim.height() - self.pixmap().height()) * 0.5,
                             (dim.width() - self.pixmap().width()) * 0.5,
                             (dim.height() - self.pixmap().height()) * 0.5)
     if dev_mode:
         self.setStyleSheet("background-color:yellow")
     else:
         self.setAttribute(Qt.WA_TranslucentBackground, True)
     # Setup clock foreground
     self.clock_layout = QtGui.QGridLayout()
     self.setLayout(self.clock_layout)
     self.clock_layout.setContentsMargins(0,0,0,0)
     self.clock_label = QLabel()
     self.clock_layout.addWidget(self.clock_label)
     self.clock_label.setAlignment(Qt.AlignCenter)
     #self.default_font = self.font() #TODO set custom font
     font = self.clock_label.font()
     font.setBold(True)
     self.clock_label.setFont(font)
     bound = self.clock_label.fontMetrics().boundingRect("00")
     font_size_ratio = min(dim.width() * clock_dim_ratio[0] / bound.width() * 0.5,
                           dim.height() * clock_dim_ratio[1] / bound.height())
     font.setPointSizeF(font_size_ratio * self.clock_label.font().pointSize()+10)
     self.clock_label.setFont(font)
     self.clock_label.setAttribute(Qt.WA_TranslucentBackground, True)
     self.set_timer_value(0)
Exemplo n.º 4
0
 def __init__(self,
              ressource_directory,
              dim: QSize,
              nbr_life,
              dev_mode=False):
     """
     Generate a Widget displaying lifes.
     :param ressource_directory: String, the path to ressource directory
     :param dim: QtCore.QSize, the dimension of the space allocated to LifeWidget.
     :param nbr_life: int, the number of heart to display.
     :param dev_mode: boolean [Facultative (default False)], if True debug informations are displayed.
     """
     super().__init__()
     self.setMaximumSize(dim)
     self.setMinimumSize(dim)
     self._load_life_picture(ressource_directory)
     # Setup grid layout
     self.main_grid_layout = QtGui.QGridLayout(self)
     ratio_h_w = (dim.height() * self.life_picture.width()) / (
         dim.width() * self.life_picture.height())
     self.nbr_columns = math.ceil((nbr_life / ratio_h_w)**0.5)
     self.nbr_lines = math.ceil(nbr_life / self.nbr_columns)
     self.column_size = dim.width() / self.nbr_columns
     self.line_size = dim.height() / self.nbr_lines
     self.main_grid_layout.setSpacing(0)
     # Resize pictures
     self.life_picture = self.life_picture.scaled(self.line_size,
                                                  self.column_size,
                                                  Qt.KeepAspectRatio)
     self.dead_picture = self.dead_picture.scaled(self.line_size,
                                                  self.column_size,
                                                  Qt.KeepAspectRatio)
     # Setup heart images
     self.life_labels = []
     for k in range(nbr_life):
         self.life_labels.append(QtGui.QLabel())
         self.main_grid_layout.addWidget(self.life_labels[-1],
                                         k // self.nbr_columns,
                                         k % self.nbr_columns)
         if dev_mode:
             self.life_labels[-1].setStyleSheet("background-color:pink")
     if dev_mode:
         self.setStyleSheet("background-color:purple")
         print(
             "LifeWidget Dimensions:\n | screen_size : %s, %s\n | ratio : %s \n | lines : %s\n | rows : %s"
             % (dim.height(), dim.width(), ratio_h_w, self.nbr_lines,
                self.nbr_columns))
     # Adjust border for centering
     horizontal_space = dim.width(
     ) - self.life_picture.width() * self.nbr_columns
     vertical_space = dim.height(
     ) - self.life_picture.height() * self.nbr_lines
     self.setContentsMargins(
         math.floor(horizontal_space * 0.5 - self.DEFAULT_FUCKING_MARGIN),
         math.ceil(vertical_space * 0.5 - self.DEFAULT_FUCKING_MARGIN),
         math.ceil(horizontal_space * 0.5 - self.DEFAULT_FUCKING_MARGIN),
         math.floor(vertical_space * 0.5 - self.DEFAULT_FUCKING_MARGIN))
     self.set_alive(0)
Exemplo n.º 5
0
    def __init__(self,
                 ressource_directory,
                 dim: QSize,
                 player_size: QSize,
                 player_ratio_spacing: float = 0.33,
                 alpha_color="#FF00FF",
                 vertical_random_ratio=0.1,
                 key_press_event_callback=None,
                 dev_mode=False):
        """
        :param ressource_directory: String, chemin du dossier ressource.
        :param dim: QSize, taille alloué au widget.
        :param dev_mode: boolean [facultatif (defaut False)], active le mode developpement.
        """
        # Setup widget
        super().__init__()
        if dev_mode:
            self.setStyleSheet("background-color:blue")
        else:
            self.setStyleSheet("background-color:" + alpha_color)
        self.setMaximumSize(dim)
        self.setMinimumSize(dim)

        # Setup poses
        self.current_silhouette = None
        self.colors = list(self.default_colors)
        self.player_rect = QRect((dim.width() - player_size.width()) * 0.5,
                                 (dim.height() - player_size.height()) * 0.5,
                                 player_size.width(), player_size.height())
        self.player_ratio_spacing = player_ratio_spacing
        self.vertical_random_ratio = vertical_random_ratio
        self.player_pixel_spacing = 0
        self.pose_dict = {}
        self._load_all_poses(ressource_directory,
                             load_all_images=True,
                             verbose=False,
                             filter_valid=True,
                             dev_mode=dev_mode)

        # Init constant for pose drawing
        exemple_sil_pixmap = self.pose_dict[list(
            self.pose_dict.keys())[1]].get_silhouette().pixmap
        vertical_scale = self.player_rect.height() / exemple_sil_pixmap.height(
        )
        self.pose_hauteur = round(exemple_sil_pixmap.height() * vertical_scale)
        self.pose_largeur = round(exemple_sil_pixmap.width() * vertical_scale)
        self.player_pixel_spacing = self.player_ratio_spacing * self.pose_largeur

        # Event callback
        self.key_press_event_callback = key_press_event_callback
Exemplo n.º 6
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
Exemplo n.º 7
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)
Exemplo n.º 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
Exemplo n.º 9
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()
Exemplo n.º 10
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
Exemplo n.º 11
0
    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)
Exemplo n.º 12
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)
Exemplo n.º 13
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()
Exemplo n.º 14
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
Exemplo n.º 15
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
Exemplo n.º 16
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
Exemplo n.º 17
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)
Exemplo n.º 18
0
    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)
Exemplo n.º 19
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))
Exemplo n.º 20
0
 def viewportSize(self):
     size = QSize(self.m_page.viewportSize())
     result = {
         'width': size.width(),
         'height': size.height()
     }
     return result
Exemplo n.º 21
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)
Exemplo n.º 22
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)
Exemplo n.º 23
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)
Exemplo n.º 24
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)
Exemplo n.º 25
0
 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
Exemplo n.º 26
0
 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
Exemplo n.º 27
0
    def calculateSize(self, sizeType):
        totalSize = QSize()

        for wrapper in self.list:
            position = wrapper.position
            itemSize = QSize()

            if sizeType == self.MinimumSize:
                itemSize = wrapper.item.minimumSize()
            else:  # sizeType == self.SizeHint
                itemSize = wrapper.item.sizeHint()

            if position in (self.North, self.South, self.Center):
                totalSize.setHeight(totalSize.height() + itemSize.height())

            if position in (self.West, self.East, self.Center):
                totalSize.setWidth(totalSize.width() + itemSize.width())

        return totalSize
Exemplo n.º 28
0
    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
Exemplo n.º 29
0
    def __layoutActions(self):
        left, right = self.__actions

        contents = self.contentsRect()
        buttonSize = QSize(contents.height(), contents.height())

        margins = self.textMargins()

        if left:
            geom = QRect(contents.topLeft(), buttonSize)
            left.button.setGeometry(geom)
            margins.setLeft(buttonSize.width())

        if right:
            geom = QRect(contents.topRight(), buttonSize)
            right.button.setGeometry(geom.translated(-buttonSize.width(), 0))
            margins.setLeft(buttonSize.width())

        self.setTextMargins(margins)
Exemplo n.º 30
0
    def sizeHint(self):
        q = self.parentWidget()
        mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
        fw = q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q)
        closeSize = QSize(0, 0)
        if self.closeButton:
            closeSize = self.closeButton.sizeHint()

        floatSize = QSize(0, 0)
        if self.floatButton:
            floatSize = self.floatButton.sizeHint()
        hideSize = self.hideSizeHint()

        buttonHeight = max(max(closeSize.height(), floatSize.height()), hideSize.height()) + 2
        buttonWidth = closeSize.width() + floatSize.width() + hideSize.width()
        titleFontMetrics = q.fontMetrics()
        fontHeight = titleFontMetrics.lineSpacing() + 2 * mw
        height = max(buttonHeight, fontHeight)
        return QSize(buttonWidth + height + 4 * mw + 2 * fw, height)
Exemplo n.º 31
0
    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
Exemplo n.º 32
0
    def sizeHint(self):
        q = self.parentWidget()
        mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
        fw = q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q)
        closeSize = QSize(0, 0)
        if self.closeButton:
            closeSize = self.closeButton.sizeHint()

        floatSize = QSize(0, 0)
        if self.floatButton:
            floatSize = self.floatButton.sizeHint()
        hideSize = self.hideSizeHint()

        buttonHeight = max(max(closeSize.height(), floatSize.height()),
                           hideSize.height()) + 2
        buttonWidth = closeSize.width() + floatSize.width() + hideSize.width()
        titleFontMetrics = q.fontMetrics()
        fontHeight = titleFontMetrics.lineSpacing() + 2 * mw
        height = max(buttonHeight, fontHeight)
        return QSize(buttonWidth + height + 4 * mw + 2 * fw, height)
Exemplo n.º 33
0
class ImageProvider(QDeclarativeImageProvider):
  
  image = None
  size = None
  p = None
  
  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));
    #p.end()
    
  def draw(self, x1, y1, x2, y2):
    self.p.drawLine(x1*self.size.width(), y1*self.size.height(), x2*self.size.width(), y2*self.size.height())
    
  def requestImage(self, id, size, requestedSize):
    return self.image
Exemplo n.º 34
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
Exemplo n.º 35
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
Exemplo n.º 36
0
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)
Exemplo n.º 37
0
    def minimumSize(self):
        """ A reimplemented method which returns the minimum size hint
        of the layout item widget as the minimum size of the window.

        """
        if self._cached_min is None:
            size = QSize(0, 0)
            for item in self._items:
                size = size.expandedTo(item.minimumSize())
            left, top, right, bottom = self.getContentsMargins()
            size.setWidth(size.width() + left + right)
            size.setHeight(size.height() + top + bottom)
            self._cached_min = size
        # XXX hack! We really need hasWidthForHeight! This doesn't quite
        # work because a QScrollArea internally caches the min size.
        d = self._options.direction
        if d == self.TopToBottom or d == self.BottomToTop:
            m = QSize(self._cached_min)
            if m.width() < self._cached_wfh:
                m.setWidth(self._cached_wfh)
            return m
        return self._cached_min
Exemplo n.º 38
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)
Exemplo n.º 39
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)
Exemplo n.º 40
0
    def sizeHint(self):
        """ A virtual method implementation which returns the size hint
        for the layout.

        """
        if self._cached_hint is None:
            size = QSize(0, 0)
            for item in self._items:
                size = size.expandedTo(item.sizeHint())
            left, top, right, bottom = self.getContentsMargins()
            size.setWidth(size.width() + left + right)
            size.setHeight(size.height() + top + bottom)
            self._cached_hint = size
        return self._cached_hint
Exemplo n.º 41
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])
Exemplo n.º 42
0
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)
Exemplo n.º 43
0
    def maybe_get_icon(self):
        u"""
        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)
Exemplo n.º 44
0
    def renderPdf(self, fileName):
        p = QPrinter()
        p.setOutputFormat(QPrinter.PdfFormat)
        p.setOutputFileName(fileName)
        p.setResolution(pdf_dpi)
        paperSize = self.m_paperSize

        if not len(paperSize):
            pageSize = QSize(self.m_page.mainFrame().contentsSize())
            paperSize['width'] = str(pageSize.width()) + 'px'
            paperSize['height'] = str(pageSize.height()) + 'px'
            paperSize['border'] = '0px'

        if paperSize.get('width') and paperSize.get('height'):
            sizePt = QSizeF(ceil(self.stringToPointSize(paperSize['width'])),
                            ceil(self.stringToPointSize(paperSize['height'])))
            p.setPaperSize(sizePt, QPrinter.Point)
        elif 'format' in paperSize:
            orientation = QPrinter.Landscape if paperSize.get(
                'orientation') and paperSize['orientation'].lower(
                ) == 'landscape' else QPrinter.Portrait
            orientation = QPrinter.Orientation(orientation)
            p.setOrientation(orientation)

            formats = {
                'A3': QPrinter.A3,
                'A4': QPrinter.A4,
                'A5': QPrinter.A5,
                'Legal': QPrinter.Legal,
                'Letter': QPrinter.Letter,
                'Tabloid': QPrinter.Tabloid
            }

            p.setPaperSize(QPrinter.A4)  # fallback
            for format, size in formats.items():
                if format.lower() == paperSize['format'].lower():
                    p.setPaperSize(size)
                    break
        else:
            return False

        border = floor(self.stringToPointSize(
            paperSize['border'])) if paperSize.get('border') else 0
        p.setPageMargins(border, border, border, border, QPrinter.Point)

        self.m_page.mainFrame().print_(p)
        return True
Exemplo n.º 45
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
Exemplo n.º 46
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)
Exemplo n.º 47
0
 def maybe_get_icon(self):
     if self.site_icon:
         return
     if not with_pyqt:
         self.site_icon = None
         return
     try:
         icon_data = self.get_data_from_url(self.full_icon_url)
     except:
         AudioDownloader.maybe_get_icon(self)
     else:
         self.site_icon = QImage.fromData(icon_data)
         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)
Exemplo n.º 48
0
 def maybe_get_icon(self):
     if self.site_icon:
         return
     if not with_pyqt:
         self.site_icon = None
         return
     try:
         icon_data = self.get_data_from_url(self.full_icon_url)
     except:
         AudioDownloader.maybe_get_icon(self)
     else:
         self.site_icon = QImage.fromData(icon_data)
         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)
Exemplo n.º 49
0
 def sectionSizeFromContents(self, logicalIndex: int) -> QSize:
     if self._pd.headerModel:
         curLeafIndex = QModelIndex(self._pd.leafIndex(logicalIndex))
         if curLeafIndex.isValid():
             styleOption = QStyleOptionHeader(
                 self.styleOptionForCell(logicalIndex))
             s = QSize(self._pd.cellSize(curLeafIndex, self, styleOption))
             curLeafIndex = curLeafIndex.parent()
             while curLeafIndex.isValid():
                 if self.orientation() == Qt.Horizontal:
                     s.setHeight(s.height() + self._pd.cellSize(
                         curLeafIndex, self, styleOption).height())
                 else:
                     s.setWidth(s.width() + self._pd.cellSize(
                         curLeafIndex, self, styleOption).width())
                 curLeafIndex = curLeafIndex.parent()
             return s
     return super().sectionSizeFromContents(logicalIndex)
Exemplo n.º 50
0
    def renderPdf(self, fileName):
        p = QPrinter()
        p.setOutputFormat(QPrinter.PdfFormat)
        p.setOutputFileName(fileName)
        p.setResolution(pdf_dpi)
        paperSize = self.m_paperSize

        if not len(paperSize):
            pageSize = QSize(self.m_page.mainFrame().contentsSize())
            paperSize['width'] = str(pageSize.width()) + 'px'
            paperSize['height'] = str(pageSize.height()) + 'px'
            paperSize['border'] = '0px'

        if paperSize.get('width') and paperSize.get('height'):
            sizePt = QSizeF(ceil(self.stringToPointSize(paperSize['width'])),
                            ceil(self.stringToPointSize(paperSize['height'])))
            p.setPaperSize(sizePt, QPrinter.Point)
        elif 'format' in paperSize:
            orientation = QPrinter.Landscape if paperSize.get('orientation') and paperSize['orientation'].lower() == 'landscape' else QPrinter.Portrait
            orientation = QPrinter.Orientation(orientation)
            p.setOrientation(orientation)

            formats = {
                'A3': QPrinter.A3,
                'A4': QPrinter.A4,
                'A5': QPrinter.A5,
                'Legal': QPrinter.Legal,
                'Letter': QPrinter.Letter,
                'Tabloid': QPrinter.Tabloid
            }

            p.setPaperSize(QPrinter.A4) # fallback
            for format, size in formats.items():
                if format.lower() == paperSize['format'].lower():
                    p.setPaperSize(size)
                    break
        else:
            return False

        border = floor(self.stringToPointSize(paperSize['border'])) if paperSize.get('border') else 0
        p.setPageMargins(border, border, border, border, QPrinter.Point)

        self.m_page.mainFrame().print_(p)
        return True
Exemplo n.º 51
0
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)
Exemplo n.º 52
0
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)
Exemplo n.º 53
0
    def set_viewport(self, size):
        """
        Set viewport size.
        If size is "full" viewport size is detected automatically.
        If can also be "<width>x<height>".
        """
        if size == 'full':
            size = self.web_page.mainFrame().contentsSize()
            if size.isEmpty():
                self.logger.log("contentsSize method doesn't work %s",
                                min_level=1)
                size = defaults.VIEWPORT_FALLBACK

        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.logger.log("viewport size is set to %sx%s" % (w, h), min_level=2)
        return w, h
Exemplo n.º 54
0
    def _updateShadowPixmap(self):
        """Update the cached drop shadow pixmap.
        """
        # Rectangle casting the shadow
        rect_size = QSize(*CACHED_SHADOW_RECT_SIZE)
        left, top, right, bottom = self.getContentsMargins()
        # 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=self.offset,
                                          radius=self.radius,
                                          rect_fill_color=rect_fill_color)

        self._shadowPixmap = pixmap
Exemplo n.º 55
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