Beispiel #1
0
    def __updateGeometry(self):
        """
        Update the shadow geometry to fit the widget's changed
        geometry.

        """
        widget = self.__widget
        parent = self.__widgetParent
        radius = self.radius_
        pos = widget.pos()
        if parent != widget.parentWidget():
            pos = widget.parentWidget().mapTo(parent, pos)

        geom = QRect(pos, widget.size())
        geom.adjust(-radius, -radius, radius, radius)
        if geom != self.geometry():
            self.setGeometry(geom)

        # Set the widget mask (punch a hole through to the `widget` instance.
        rect = self.rect()

        mask = QRegion(rect)
        transparent = QRegion(rect.adjusted(radius, radius, -radius, -radius))

        mask = mask.subtracted(transparent)
        self.setMask(mask)
Beispiel #2
0
class MovingMessage(FadeMessage):
    def __init__(self, message, str = None, pos = None):
        cfg = Config('messages', message)
        
        if (pos is None):
            self.pos = QPoint(*cfg.get('position'))
        else:
            self.pos = QPoint(*pos)
        
        self.velocity = cfg.get('velocity') 
        
        FadeMessage.__init__(self, message, str)
    
    def with_controller(self):
        self.rect = QRect(0, 0, self.controller.width(), self.controller.height())
        self.rect.moveCenter(self.pos)

    def tick(self, elapsed):        
        FadeMessage.tick(self, elapsed)

        self.pos.setX(self.pos.x() + self.velocity[0] * elapsed)
        self.pos.setY(self.pos.y() + self.velocity[1] * elapsed)
        
        self.rect.moveCenter(self.pos)
    
    def draw(self):
        FadeMessage.draw(self)
        
        if (self.color.alpha() == 0):
            self.rect = self.bounding_text_rect
Beispiel #3
0
    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        if not self.showRegionMap:
            painter.drawPixmap(0, 0, self.scaledOwnershipMap)
        rect = self.imageRect()
        if self.isEnabled():
            if self.showRegionMap:
                painter.drawPixmap(0, 0, self.scaledRegionMap)
            else:
                if self.currentTerritory:
                    painter.drawPixmap(0, 0, self.coloredMask(self.currentTerritory, QColor(*self.game.clientPlayer.color)))
                #draw active animations
                for a in self.animations:
                    painter.save()
                    a.paint(painter)
                    painter.restore()
                painter.drawPixmap(0, 0, self.scaledTroopCountMap)
        else:
            painter.fillRect(rect, QColor(0, 0, 0, 200))
            painter.drawText(rect, Qt.AlignCenter, "Waiting for the game to start.")

        #remaining troops
        if self.game.yourTurn() and self.game.remainingTroops:
            troopText = "Remaining troops: %d" % self.game.remainingTroops
            troopRect = QRect(0, 0, painter.fontMetrics().width(troopText) + 8, painter.fontMetrics().height() + 8)
            troopRect.moveBottomLeft(rect.bottomLeft())
            painter.setPen(Qt.white)
            painter.setBrush(QColor(0, 0, 0, 200))
            painter.drawRect(troopRect)
            painter.drawText(troopRect, Qt.AlignCenter, troopText)

        painter.end()
Beispiel #4
0
    def draw_color_bar(self, painter, rect):
        h1, s1, v1, _ = self.light.getHsv()
        h2, s2, v2, _ = self.dark.getHsv()

        painter.save()
        painter.setClipRect(rect)
        painter.setClipping(True)
        # painter.fillRect(rect, QBrush(self.dark))

        if self.orientation == Qt.Horizontal:
            num_intervalls = rect.width()
        else:
            num_intervalls = rect.height()

        section = QRect()

        num_intervalls_shown = num_intervalls * self.height / 100
        l = range(num_intervalls - num_intervalls_shown, num_intervalls)
        l.reverse()
        for i in l:
            if self.orientation == Qt.Horizontal:
                section.setRect(rect.x() + i, rect.y(), 1, rect.heigh())
            else:
                section.setRect(rect.x(), rect.y() + i, rect.width(), 1)

            ratio = float(i) / float(num_intervalls)
            color = QColor()
            color.setHsv(
                h1 + int(ratio * (h2 - h1) + 0.5), s1 + int(ratio * (s2 - s1) + 0.5), v1 + int(ratio * (v2 - v1) + 0.5)
            )

            painter.fillRect(section, color)

        painter.restore()
	def paintEvent( self, event ):
		"""
		Das automatisch ausgelöste paintEvent, das das Widget bei jeder Fensterveränderung neu zeichnet.
		"""

		if self.__maximum > 0:
			frameWidth = 1
			separatorWidth = 1

			# Damit der Rahmen nicht irgendwie abgeschnitten wird, muß das Quadrat entsprechend kleiner sein.
			squareSideLength = 10
			framePen = QPen( frameWidth )
			framePen.setColor( self.__colorFrame )

			squareSideLengthPlus = squareSideLength + 2 * frameWidth

			painter = QPainter( self )

			windowWidth = self.width() / min( self.__maximum, self.__columnMax )
			windowHeight = self.__maximum / self.__columnMax
			windowHeight = math.ceil( windowHeight )
			windowHeight = self.height() / windowHeight
			side = min( windowWidth, windowHeight )

			painter.setRenderHint( QPainter.Antialiasing )

			# Wenn das Widget disabled ist, muß ich den Alphakanal meiner Farben verändern.
			if ( not self.isEnabled() ):
				painter.setOpacity( .5 )

			#painter.translate( float( windowWidth ), float( windowHeight ) )

			painter.scale( side / squareSideLengthPlus, side / squareSideLengthPlus )
			painter.setPen( framePen )
			painter.setBrush( self.__colorEmpty )

			painter.save()

			squareColumnIter = 0
			squareLineIter = 0
			squareCount = 0
			for squareCount in range(self.__maximum):
				square = QRect(
					( squareSideLength + separatorWidth ) * squareColumnIter + frameWidth * ( squareColumnIter + 1 ),
					( squareSideLength + separatorWidth ) * squareLineIter + frameWidth * ( squareLineIter + 1 ), squareSideLength, squareSideLength
				)
				painter.drawRect( square )

				# Wir zeichnen die ausgekreuzten Quadrate
				if (self.__value > (self.__columnMax * squareLineIter + squareColumnIter)):
					painter.drawLine(square.bottomLeft(), square.topRight())
					painter.drawLine(square.topLeft(), square.bottomRight())

				squareColumnIter += 1

				if ( squareColumnIter >= self.__columnMax ):
					squareColumnIter = 0
					squareLineIter += 1

			painter.restore()
Beispiel #6
0
 def mouseMoveEvent (self, event):
     '''Overrides QWidget's mouseMoveEvent. Handles resizing
     and dragging operations on selection'''
     # pylint: disable=C0103
     sel_rect = self._selection_rect
     if self._resize_start:
         resize_end = event.pos() / self._zoom
         sel_rect.setBottomRight(sel_rect.bottomRight() +
                                 (resize_end - self._resize_start))
         self._resize_start = resize_end
         self.make_selection_square()
         self.update()
     elif self._drag_start is not None:
         drag_end = event.pos() / self._zoom
         sel_rect.translate(drag_end - self._drag_start)
         self._drag_start = drag_end
         self.update()
         
     # cursor shape:
     mouse_pos = event.pos() / self._zoom
     if (not sel_rect.isNull()) and sel_rect.contains(mouse_pos, True):
         handle_rect = QRect(sel_rect.bottomRight(), self._handle_size)
         if handle_rect.contains(mouse_pos):
             self.setCursor(Qt.SizeFDiagCursor)
         else:
             self.setCursor(Qt.OpenHandCursor)
             
     else:
         self.setCursor(Qt.CrossCursor)
Beispiel #7
0
def ensure_on_screen(rect):
    """ Ensure that the given rect is contained on screen.

    If the origin of the rect is not contained within the closest
    desktop screen, the rect will be moved so that it is fully on the
    closest screen. If the rect is larger than the closest screen, the
    origin will never be less than the screen origin.

    Parameters
    ----------
    rect : QRect
        The geometry rect of interest.

    """
    d = QApplication.desktop()
    pos = rect.topLeft()
    drect = d.screenGeometry(pos)
    if not drect.contains(pos):
        x = pos.x()
        if x < drect.x() or x > drect.right():
            dw = drect.width() - rect.width()
            x = max(drect.x(), drect.x() + dw)
        y = pos.y()
        if x < drect.top() or y > drect.bottom():
            dh = drect.height() - rect.height()
            y = max(drect.y(), drect.y() + dh)
        rect = QRect(x, y, rect.width(), rect.height())
    return rect
Beispiel #8
0
 def request( self, qrect, along_through=None ):
     assert isinstance(qrect, QRect)
     # Widen request with a 1-pixel halo, to make sure edges on the tile borders are shown.
     qrect = QRect( qrect.x(), qrect.y(), qrect.width()+1, qrect.height()+1 )
     s = rect2slicing(qrect)
     arrayreq = self._arraySource2D.request(s, along_through)
     return SegmentationEdgesItemRequest(arrayreq, self._layer, qrect)
    def mouseReleaseEvent(self, event):
        """ 
        Обрабатываем нажатие на иконку 'Интересно/Скучно' как нажатие на обычный чекбокс
        
        Решение достаточно грубое, но в данной ситуации вполне себе работает. Перехватывать нужно 
        отпускание мыши, потому что в QAbstractItemView редактирование запускается именно по 
        отпусканию. 
        
        """

        if event.pos().x() < settings.entryIconWidth():
            item = self.itemAt(event.pos())
            item.setSelected(True)
            rect = self.visualItemRect(item)
            iconRect = QRect(rect.left(),
                             rect.top(),
                             settings.entryIconWidth(),
                             settings.entryIconHeight())
            if iconRect.contains(event.pos()):
                if item.checkState() == Qt.Checked:
                    item.setCheckState(Qt.Unchecked)
                else:
                    item.setCheckState(Qt.Checked)
        else:
            QListWidget.mousePressEvent(self, event)
Beispiel #10
0
 def paint(self, painter):
     opacity = 1.0 - float(self.anim.currentTime()) / self.anim.duration()
     pen = QPen(QColor(255, 0, 0, opacity * 255))
     pen.setWidth(3)
     painter.setPen(pen)
     painter.setBrush(Qt.transparent)
     rect = QRect(0, 0, self.radius * 2, self.radius * 2)
     rect.moveCenter(self.center)
     painter.drawEllipse(rect)
Beispiel #11
0
    def paintEvent(self, event):
        painter = QPainter(self)
        rect = self.geometry()
        text_rect = QRect(0, 0, rect.width(), rect.height())

        painter.translate(text_rect.bottomLeft())
        painter.rotate(-90)
        painter.drawText(QRect(QPoint(0, 0), QSize(rect.height(), rect.width())), Qt.AlignCenter, self.text())
        painter.end()
    def _runImpl(self):

        processed = set()
        self._dataPending.wait()
        if self._numLayers == 0:
            return
        bbox = QRect()
        toUpdate = numpy.zeros((len(self._tiling),), dtype=numpy.uint8)
        while len(self._queue) > 0:
            self._dataPending.clear()

            layerNr, patchNr, image, tiling, numLayers = self._queue.popleft()
            if tiling != self._tiling or numLayers != self._numLayers:
                continue            
            if (layerNr, patchNr) in processed:
                continue
            processed.add((layerNr, patchNr))

            rect = self._tiling._imageRect[patchNr]
            bbox = bbox.united(rect)

            self._imageLayersNext[layerNr,patchNr] = image
            toUpdate[patchNr] = 1


        firstOpaqueLayer = 1000000000000000000
        for i, (visible, layerOpacity, layerImageSource) in enumerate(self._stackedIms):
            if visible and layerOpacity == 1.0 and layerImageSource.isOpaque():
                firstOpaqueLayer = i
                break

        for patchNr in toUpdate.nonzero()[0]: 
            self._compositeNext[patchNr] = QImage(self._tiling._imageRect[patchNr].size(), QImage.Format_ARGB32_Premultiplied)
            self._compositeNext[patchNr].fill(Qt.white)
            p = QPainter(self._compositeNext[patchNr])

            for i, v in enumerate(reversed(self._stackedIms)):
                visible, layerOpacity, layerImageSource = v
                if not visible:
                    continue

                layerNr = len(self._stackedIms) - i - 1
                if layerNr > firstOpaqueLayer:
                    continue

                patch = self._imageLayersNext[layerNr, patchNr]
                p.setOpacity(layerOpacity)
                if patch is not None:
                    p.drawImage(0,0, patch)
            p.end()

        w = numpy.equal(self._compositeNext, None)
        self._compositeCurrent = numpy.where(numpy.equal(self._compositeNext, None), self._compositeCurrent, self._compositeNext)
        self._compositeNext[:] = None

        self.patchAvailable.emit(bbox)
Beispiel #13
0
 def destinationsRect(self, destinations):
     """Return the rectangle containing all destinations."""
     layout = self.view.surface().pageLayout()
     rect = QRect()
     for dest in destinations:
         for pageNum, r in dest:
             rect = rect.united(layout[pageNum].linkRect(r.normalized()))
     # not larger than viewport
     rect.setSize(rect.size().boundedTo(self.view.viewport().size()))
     return rect
Beispiel #14
0
 def setGeometry(self, rect):
     QStackedLayout.setGeometry(self, rect)
     for i in range(self.count()):
         w = self.widget(i)
         hint = w.sizeHint()
         geom = QRect(rect)
         size = clipMinMax(rect.size(), w.minimumSize(), w.maximumSize())
         size = fixSizePolicy(size, hint, w.sizePolicy())
         geom.setSize(size)
         if geom != w.geometry():
             w.setGeometry(geom)
Beispiel #15
0
 def paintEvent(self, ev):
     image = self.viewer.image()
     painter = QPainter(self)
     if self.size() == image.size():
         painter.drawImage(ev.rect(), image, ev.rect())
     else:
         s = image.size()
         s.scale(self.size(), Qt.KeepAspectRatio)
         r = QRect()
         r.setSize(s)
         r.moveCenter(self.rect().center())
         painter.drawPixmap(r, self.viewer.pixmap(s))
Beispiel #16
0
 def paint (self, painter, option, index):
     if not (QStyle.State_Selected & option.state):
         r = QRect(option.rect)
         r.setX(0)
         # test if item/device is in use
         if index.data(Qt.UserRole).toBool():
             painter.setBrush(QColor(255, 0, 0, 32))
         else:
             painter.setBrush(QColor(0, 255, 0, 128))
         painter.setPen(Qt.lightGray)
         painter.drawRect(r)
     QItemDelegate.paint(self, painter, option, index)
Beispiel #17
0
 def rearangeDescriptionWidgets(self):
     self._activeSize = QSize(0.3 * self.width(), 0.1 * self.height())
     self._prototypingRect = QRect(QPoint(0.5 * (self.width() - self._activeSize.width()), 0), self._activeSize)
     self._executionRect = QRect(QPoint(0, 0.635 * self.height()), self._activeSize)
     self._verifyingRect = QRect(QPoint(self.width() -self._activeSize.width(), 0.635 * self.height()), self._activeSize)
     self._descriptionActiveRects[0] = self._prototypingRect
     self._descriptionActiveRects[1] = self._executionRect 
     self._descriptionActiveRects[2] = self._verifyingRect
     
     self._prototypingDescriptionWidget.move(self.mapToParent(self._prototypingRect.topLeft()) + QPoint((self._prototypingRect.width() - self._prototypingDescriptionWidget.width()) * 0.5, - self._prototypingDescriptionWidget.height()))
     self._executionDescriptionWidget.move(self.mapToParent(self._executionRect.topLeft()) - QPoint(self._executionDescriptionWidget.width(), - 0.5 * (self._executionRect.height() - self._executionDescriptionWidget.height())))
     self._verifyingDescriptionWidget.move(self.mapToParent(self._verifyingRect.topRight()) - QPoint(0, - 0.5 * (self._verifyingRect.height() - self._verifyingDescriptionWidget.height())))
 def mousePressEvent(self, event):
 
     if event.button() != Qt.LeftButton:
         return
     
     size = self.height() / 2.0
     rect = QRect(self.width() - size, size * 0.5, size, size)
     
     if rect.contains(event.pos()):
         self.clear()
         self.valid = True
         event.accept()
Beispiel #19
0
	def createOnlineIcon(self,color):
		dim = QRect(0,0,32,32)
		img = QImage(dim.size(),QImage.Format_ARGB32)
		p = QPainter(img)
		p.setCompositionMode(QPainter.CompositionMode_Source)
		p.fillRect(dim,Qt.transparent)
		p.setCompositionMode(QPainter.CompositionMode_SourceOver)
		p.setRenderHints(QPainter.Antialiasing)
		p.setPen(Qt.black)
		p.setBrush(color)
		p.drawEllipse(dim.adjusted(1,1,-2,-2))
		return img
Beispiel #20
0
 def calculateLogicalRect(self, physicalRect):
     gridX = self.parent().width() / 40
     gridY = self.parent().height() / 30
     logicalRect = QRect()
     logicalRect.setTop(round(physicalRect.top() / gridY))
     logicalRect.setLeft(round(physicalRect.left() / gridX))
     logicalRect.setWidth(round(physicalRect.width() / gridX))
     logicalRect.setHeight(round(physicalRect.height() / gridY))
     return logicalRect
Beispiel #21
0
 def fitRect(rect, targetrect):
     size = rect.size().boundedTo(targetgeom.size())
     newrect = QRect(rect.topLeft(), size)
     dx, dy = 0, 0
     if newrect.left() < targetrect.left():
         dx = targetrect.left() - newrect.left()
     if newrect.top() < targetrect.top():
         dy = targetrect.top() - newrect.top()
     if newrect.right() > targetrect.right():
         dx = targetrect.right() - newrect.right()
     if newrect.bottom() > targetrect.bottom():
         dy = targetrect.bottom() - newrect.bottom()
     return newrect.translated(dx, dy)
Beispiel #22
0
    def mouseMoveEvent(self, event):
        if self._interaction.moving:
            mouse_position = event.globalPos()
            offset = mouse_position - self._interaction.mouse_last_position
            if self.parent() is not None:
                parent_rect = self.parent().rect()
                old_geometry = self.geometry()
                new_geometry = old_geometry.translated(offset)
                if new_geometry.left() < 0:
                    new_geometry.moveLeft(0)
                if new_geometry.top() < 0:
                    new_geometry.moveTop(0)
                if new_geometry.right() > parent_rect.right():
                    new_geometry.moveRight(parent_rect.right())
                if new_geometry.bottom() > parent_rect.bottom():
                    new_geometry.moveBottom(parent_rect.bottom())
                offset = new_geometry.topLeft() - old_geometry.topLeft()
            self.move(self.pos() + offset)
            self._interaction.mouse_last_position += offset
        elif self._interaction.resizing:
            mouse_position = event.globalPos()
            delta_y = mouse_position.y() - self._interaction.mouse_last_position.y()
            geometry = self.geometry()

            if self._interaction.resize_corner is self.TopLeftCorner:
                delta_x = -(self.width_for_height(geometry.height() - delta_y) - geometry.width())
                geometry.setTopLeft(geometry.topLeft() + QPoint(delta_x, delta_y))
            elif self._interaction.resize_corner is self.TopRightCorner:
                delta_x =  (self.width_for_height(geometry.height() - delta_y) - geometry.width())
                geometry.setTopRight(geometry.topRight() + QPoint(delta_x, delta_y))
            elif self._interaction.resize_corner is self.BottomLeftCorner:
                delta_x = -(self.width_for_height(geometry.height() + delta_y) - geometry.width())
                geometry.setBottomLeft(geometry.bottomLeft() + QPoint(delta_x, delta_y))
            else:
                delta_x =  (self.width_for_height(geometry.height() + delta_y) - geometry.width())
                geometry.setBottomRight(geometry.bottomRight() + QPoint(delta_x, delta_y))

            if self.minimumHeight() <= geometry.height() <= self.maximumHeight() and (self.parent() is None or self.parent().rect().contains(geometry)):
                self.setGeometry(geometry)
                self._interaction.mouse_last_position = mouse_position
        elif self.interactive:
            mouse_position = event.pos()
            topbar_rect = QRect(0, 0, self.width(), 10)

            if self.rect().adjusted(0, 10, 0, -10).contains(mouse_position):
                self.setCursor(Qt.ArrowCursor)
            elif topbar_rect.contains(mouse_position):
                self.setCursor(self.cursors.resize_top)
            else:
                self.setCursor(self.cursors.resize_bottom)
Beispiel #23
0
 def _handleMousePressEvent(self, event, superMethod):
     pos = event.pos()
     index = self.indexAt(pos)
     selected = index in self.selectedIndexes()
     superMethod(self, event)
     if not index.isValid():
         return
     rect = self.visualRect(index)
     relativePos = QPoint(pos.x()-rect.x(), pos.y()-rect.y())
     delegate = self.itemDelegate(index)
     # handleClick(index, relativePos, itemRect, selected)
     if hasattr(delegate, 'handleClick'):
         rect = QRect(0, 0, rect.width(), rect.height())
         delegate.handleClick(index, relativePos, rect, selected)
Beispiel #24
0
 def _handleMousePressEvent(self, event, superMethod):
     callsuper = True
     pos = event.pos()
     index = self.indexAt(pos)
     if index.isValid():
         selected = index in self.selectedIndexes()
         rect = self.visualRect(index)
         relativePos = QPoint(pos.x()-rect.x(), pos.y()-rect.y())
         delegate = self.itemDelegate(index)
         if hasattr(delegate, 'handleClick'):
             rect = QRect(0, 0, rect.width(), rect.height())
             if delegate.handleClick(index, relativePos, rect, selected):
                 callsuper = False
     if callsuper:
         superMethod(self, event)
Beispiel #25
0
 def linkRect(self, linkarea):
     """Returns a QRect encompassing the linkArea (of a link) in coordinates of our rect()."""
     left, top, right, bottom = linkarea.normalized().getCoords()
     # rotate
     if self._rotation:
         if self._rotation == popplerqt4.Poppler.Page.Rotate90:
             left, top, right, bottom = 1-bottom, left, 1-top, right
         elif self._rotation == popplerqt4.Poppler.Page.Rotate180:
             left, top, right, bottom = 1-right, 1-bottom, 1-left, 1-top
         else: # 270
             left, top, right, bottom = top, 1-right, bottom, 1-left
     rect = QRect()
     rect.setCoords(left * self.width(), top * self.height(), right * self.width(), bottom * self.height())
     rect.translate(self.pos())
     return rect
Beispiel #26
0
    def paint(self, painter, option, index):
        """ Draw a button-style on root items """
        model = index.model()
        assert model


        if not model.parent(index).isValid():
            # this is a top-level item.
            buttonOption = QStyleOptionButton()

            buttonOption.state = option.state
            buttonOption.state &= ~QStyle.State_HasFocus

            buttonOption.rect = option.rect
            buttonOption.palette = option.palette
            buttonOption.features = QStyleOptionButton.None

            self.m_view.style().drawControl(QStyle.CE_PushButton, buttonOption, painter, self.m_view)

            branchOption = QStyleOption()
            i = 15  ### hardcoded in qcommonstyle.cpp
            r = option.rect
            branchOption.rect = QRect(r.left() + i/2, r.top() + (r.height() - i)/2, i, i)
            branchOption.palette = option.palette
#            branchOption.state = QStyle.State_Children

            if self.m_view.isExpanded(index):
                branchOption.state |= QStyle.State_Open

            self.m_view.style().drawPrimitive(QStyle.PE_IndicatorBranch, branchOption, painter, self.m_view)

            # draw text
            textrect = QRect(r.left() + i*2, r.top(), r.width() - ((5*i)/2), r.height())
            text = self.elidedText(option.fontMetrics, textrect.width(), Qt.ElideMiddle,
                              model.data(index, Qt.DisplayRole).toString())
            self.m_view.style().drawItemText(painter, textrect,Qt.AlignLeft|Qt.AlignVCenter,
                                             option.palette, self.m_view.isEnabled(), text)

            icon_variant = index.data(Qt.DecorationRole)
            icon = QIcon(icon_variant)
            self.m_view.style().drawItemPixmap(
                                               painter, option.rect,
                                               Qt.AlignLeft,
                                               icon.pixmap(icon.actualSize(QSize(20 ,20)))
                                               )

        else:
            QItemDelegate.paint(self, painter, option, index)
Beispiel #27
0
    def __updateWindowGeometry(self):
        if not self.isWindow() or self.__hasExplicitSize:
            return

        def framemargins(widget):
            frame, geom = widget.frameGeometry(), widget.geometry()
            return QMargins(geom.left() - frame.left(),
                            geom.top() - frame.top(),
                            geom.right() - frame.right(),
                            geom.bottom() - frame.bottom())

        def fitRect(rect, targetrect):
            size = rect.size().boundedTo(targetgeom.size())
            newrect = QRect(rect.topLeft(), size)
            dx, dy = 0, 0
            if newrect.left() < targetrect.left():
                dx = targetrect.left() - newrect.left()
            if newrect.top() < targetrect.top():
                dy = targetrect.top() - newrect.top()
            if newrect.right() > targetrect.right():
                dx = targetrect.right() - newrect.right()
            if newrect.bottom() > targetrect.bottom():
                dy = targetrect.bottom() - newrect.bottom()
            return newrect.translated(dx, dy)

        margins = framemargins(self)
        minsize = QSize(120, 120)
        pixsize = self.__pixmap.size()
        available = QApplication.desktop().availableGeometry(self)
        available = available.adjusted(margins.left(), margins.top(),
                                       -margins.right(), -margins.bottom())
        # extra adjustment so the preview does not cover the whole desktop
        available = available.adjusted(10, 10, -10, -10)
        targetsize = pixsize.boundedTo(available.size()).expandedTo(minsize)
        pixsize.scale(targetsize, Qt.KeepAspectRatio)

        if not self.testAttribute(Qt.WA_WState_Created) or \
                self.testAttribute(Qt.WA_WState_Hidden):
            center = available.center()
        else:
            center = self.geometry().center()
        targetgeom = QRect(QPoint(0, 0), pixsize)
        targetgeom.moveCenter(center)
        if not available.contains(targetgeom):
            targetgeom = fitRect(targetgeom, available)
        self.__inUpdateWindowGeometry = True
        self.setGeometry(targetgeom)
        self.__inUpdateWindowGeometry = False
Beispiel #28
0
    def __testaxis(self, event):
        viewbox = self.parent()
        widget = event.widget()
        assert widget is not None
        view = widget.parent()
        assert isinstance(view, QtGui.QGraphicsView)
        pos = view.mapFromGlobal(event.screenPos())
        hitarea = view.mapToScene(QRect(pos - QPoint(2, 2), QSize(4, 4)))
        hitarea = viewbox.mapFromScene(hitarea)
        hitarea = viewbox.mapToView(hitarea).boundingRect()
        center = hitarea.center()

        if center.x() < 0:
            hitarea.moveCenter(QPointF(-center.x(), center.y()))

        cx = self.selection[1][1].x()
        cy = self.selection[1][1].y()
        if hitarea.contains(QPointF(cx, cy)):
            axes = Qt.Horizontal | Qt.Vertical
        elif hitarea.bottom() > cy > hitarea.top() and hitarea.left() > cx:
            axes = Qt.Vertical
        elif hitarea.left() < cx < hitarea.right() and hitarea.bottom() > cy:
            axes = Qt.Horizontal
        else:
            axes = 0
        return axes
Beispiel #29
0
    def handleMousePressEvent(self, ev):
        """Handle mouse press for various operations
            - links to source,
            - magnifier, 
            - selection highlight,
            
            If event was used, return true to indicate processing should stop.
        """
        
        # As the event comes from the view, we need to map it locally.
        pos = self.mapFromParent(ev.pos())
               
        # selecting?
        if self._selectionEnabled:
            if self.hasSelection():
                edge = selectionEdge(pos, self.selection())
                if edge == _OUTSIDE:
                    self.clearSelection()
                else:
                    if ev.button() != Qt.RightButton or edge != _INSIDE:
                        self._selecting = True
                        self._selectionEdge = edge
                        self._selectionRect = self.selection()
                        self._selectionPos = pos
                        if edge == _INSIDE:
                            self.setCursor(Qt.SizeAllCursor)
                    return True
            if not self._selecting:
                if ev.modifiers() & Qt.ShiftModifier and ev.button() == Qt.LeftButton and self._linksEnabled:
                    page, link = self.pageLayout().linkAt(pos)
                    if link:
                        self.linkClickEvent(ev, page, link)
                        return True
                if ev.button() == Qt.RightButton or int(ev.modifiers()) & _SCAM:
                    if not (int(ev.modifiers()) & _SCAM == self._magnifierModifiers 
                            and  ev.button() == Qt.LeftButton):
                        self._selecting = True
                        self._selectionEdge = _RIGHT | _BOTTOM
                        self._selectionRect = QRect(pos, QSize(0, 0))
                        self._selectionPos = pos
                        return True
        
        # link?
        if self._linksEnabled:
            page, link = self.pageLayout().linkAt(pos)
            if link:
                self.linkClickEvent(ev, page, link)
                return True
        # magnifier?
        if (self._magnifier and
            int(ev.modifiers()) & _SCAM == self._magnifierModifiers and
            ev.button() == Qt.LeftButton):
            self._magnifier.moveCenter(pos)
            self._magnifier.show()
            self._magnifier.raise_()
            self._magnifying = True
            self.setCursor(QCursor(Qt.BlankCursor))
            return True

        return False
def splash_screen():
    """
    """
    pm = QPixmap(
        pkg_resources.resource_filename(__name__,
                                        "icons/orange-splash-screen.png"))

    version = QCoreApplication.applicationVersion()
    size = 21 if len(version) < 5 else 16
    font = QFont("Helvetica")
    font.setPixelSize(size)
    font.setBold(True)
    font.setItalic(True)
    font.setLetterSpacing(QFont.AbsoluteSpacing, 2)
    metrics = QFontMetrics(font)
    br = metrics.boundingRect(version).adjusted(-5, 0, 5, 0)
    br.moveCenter(QPoint(436, 224))

    p = QPainter(pm)
    p.setRenderHint(QPainter.Antialiasing)
    p.setRenderHint(QPainter.TextAntialiasing)
    p.setFont(font)
    p.setPen(QColor("#231F20"))
    p.drawText(br, Qt.AlignCenter, version)
    p.end()
    return pm, QRect(88, 193, 200, 20)
Beispiel #31
0
    def print_results(self):
        printer = QtGui.QPrinter()
        printer.setCreator(self.o_results.toHtml())
        printer.setDocName(_(u"Results") + "-" + str(self.o_page.value()))
        printer.setPageSize(printer.A4)

        dialog = QtGui.QPrintDialog(printer, None)
        if dialog.exec_():
            pass

        painter = QtGui.QPainter(printer)

        painter.drawText(
            10, 10,
            _("This is not a bug,Printing will be available in next releases insha'allah"
              ))
        painter.setFont(QtGui.QFont("Arabeyesqr"))
        metrics = (painter.device().width(), painter.device().height())
        marginHeight = 6
        marginWidth = 8
        body = QRect(marginWidth, marginHeight, metrics[0] - 2 * marginWidth,
                     metrics[1] - 2 * marginHeight)
        #painter.drawRect(body)
        i = 0
        for line in self.o_results.toPlainText().split("\n"):
            i += 1
            if "[" not in line:
                painter.drawText(10, 30 + 10 * i, line)

        painter.end()
Beispiel #32
0
 def __init__(self, parent):
     QThread.__init__(self)
     self.result = None
     self.parent = parent
     self._stopped = False
     self.mutex = QMutex()
     self.filePrefix = None
     self.fileFormat = None
     self.wallColoring = None
     self.cellColoring = None
     self.pointColoring = None
     self.extraDrawing = []
     self.pointSize = None
     self.pointLineColor = None
     self.pointLineThickness = None
     self.ellipsisDraw = None
     self.overSampling = None
     self.wallThickness = None
     self.bgColor = None
     self.loading = False
     self._crop = QRect(0,0,1,1)
     self._pix = None
     self._end_image_plot = False
     self._loading_arguments = {}
     self.retryObject = None
Beispiel #33
0
 def editorEvent(self, event, model, option, index):
     """edit right aligned checkbox"""
     flags = model.flags(index)
     # make sure that the item is checkable
     if (not (flags & Qt.ItemIsUserCheckable)
             or not (flags & Qt.ItemIsEnabled)):
         return False
     # make sure that we have a check state
     value = index.data(Qt.CheckStateRole)
     if not value.isValid():
         return False
     # make sure that we have the right event type
     if event.type() == QEvent.MouseButtonRelease:
         textMargin = self.__textMargin()
         checkRect = QStyle.alignedRect(
             option.direction, Qt.AlignRight, option.decorationSize,
             QRect(option.rect.x() + (2 * textMargin), option.rect.y(),
                   option.rect.width() - (2 * textMargin),
                   option.rect.height()))
         if not checkRect.contains(event.pos()):
             return False
     elif event.type() == QEvent.KeyPress:
         if event.key() not in (Qt.Key_Space, Qt.Key_Select):
             return False
     else:
         return False
     if value.toInt()[0] == Qt.Checked:
         state = Qt.Unchecked
     else:
         state = Qt.Checked
     return model.setData(index, state, Qt.CheckStateRole)
Beispiel #34
0
    def setupLayout(self):
        self.containerWidget = QWidget(self)
        self.widgetHeight = 0
        self.containerWidget.setGeometry(QRect(0,0,451,self.widgetHeight))

        self.layout = QVBoxLayout()
        self.containerWidget.setLayout(self.layout)
Beispiel #35
0
    def _layoutChildren(self, rect, appl=True):
        left, top, right, bottom = self.getContentsMargins()
        r = rect.adjusted(+left, +top, -right, -bottom)
        x, y = r.x(), r.y()
        lineHeight = 0

        for item in self._items:
            wid = item.widget()
            spaceX = wid.style().layoutSpacing(QSizePolicy.PushButton,
                                               QSizePolicy.PushButton,
                                               Qt.Horizontal)
            spaceY = wid.style().layoutSpacing(QSizePolicy.PushButton,
                                               QSizePolicy.PushButton,
                                               Qt.Vertical)

            sz_hint = item.sizeHint()
            if x != r.x() and x + sz_hint.width() >= r.right():
                # start new line
                x = r.x()
                y += lineHeight + spaceY
                lineHeight = 0
            if appl:
                item.setGeometry(QRect(QPoint(x, y), sz_hint))

            x += sz_hint.width() + spaceX
            lineHeight = max(lineHeight, sz_hint.height())

        return y + lineHeight - r.y() + top + bottom
Beispiel #36
0
class SlicingToolsTest(unittest.TestCase):
    slicing = (slice(5, 7), slice(10, 18))
    qrect = QRect(5, 10, 2, 8)

    def test_slicing2rect(self):
        qrect = st.slicing2rect(self.slicing)
        self.assertEquals(qrect, self.qrect)

    def test_rect2slicing(self):
        slicing = st.rect2slicing(self.qrect)
        self.assertEquals(slicing, self.slicing)

    def test_slicing_rect_inversion(self):
        """Ensures that slicing2rect and rect2slicing are inverse
        operations.

        """
        a = self.slicing
        b = st.slicing2rect(a)
        c = st.rect2slicing(b)

        self.assertEquals(a, c)

        a = self.qrect
        b = st.rect2slicing(a)
        c = st.slicing2rect(b)

        self.assertEquals(a, c)
Beispiel #37
0
        def paintEvent(self, event):
            painter = QPainter(self)
            painter.fillRect(event.rect(), self.numberBarColor)

            block = self.editor.firstVisibleBlock()

            # Iterate over all visible text blocks in the document.
            while block.isValid():
                blockNumber = block.blockNumber()
                block_top = self.editor.blockBoundingGeometry(block).translated(self.editor.contentOffset()).top()

                # Check if the position of the block is outside of the visible area.
                if not block.isVisible() or block_top >= event.rect().bottom():
                    break

                # We want the line number for the selected line to be bold.
                if blockNumber == self.editor.textCursor().blockNumber():
                    self.font.setBold(True)
                    painter.setPen(QColor("#000000"))
                else:
                    self.font.setBold(False)
                    painter.setPen(QColor("#717171"))
                painter.setFont(self.font)

                # Draw the line number right justified at the position of the line.
                paint_rect = QRect(0, block_top, self.width(), self.editor.fontMetrics().height())
                painter.drawText(paint_rect, Qt.AlignRight, str(blockNumber + 1))

                block = block.next()

            painter.end()

            QWidget.paintEvent(self, event)
Beispiel #38
0
    def __init__(self, tileSource, parent=None):
        """Constructor.

        Args:
            tileSource(MapTileSource): Source for loading the tiles.
            parent(QObject): Parent object, default `None`
        """
        QGraphicsScene.__init__(self)

        self._zoom = 15

        self._tileSource = tileSource
        self._tileSource.setParent(self)
        self._tileSource.tileReceived.connect(self.setTilePixmap)
        tdim = self._tileSource.tileSize()

        self._emptyTile = QPixmap(tdim, tdim)
        self._emptyTile.fill(Qt.lightGray)

        self._tilesRect = QRect()
        self._tilePixmaps = {}

        self._tileInDownload = list()

        self.setSceneRect(0.0, 0.0, 400, 300)
        self.sceneRectChanged.connect(self.onSceneRectChanged)
 def mouseMoveEvent(self, ev):
     """
     On mouse move event
     """
     if self.state == 1:
         self.rb.setGeometry(
             QRect(self.origin, ev.globalPos()).normalized())
def get_sprite(sprite_id):

    sprite_file = get_sprite_file(sprite_id)

    if sprite_file == None:
        return None

    sprite_file = os.path.join(SPRITE_DIR, sprite_file)

    if not os.path.isfile(sprite_file):
        sprite_file = os.path.join(SPRITE_DIR,
                                   "bustup_%02d_%02d.png" % (99, 99))

    out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
    out.fill(QColor(0, 0, 0, 0).rgba())
    painter = QPainter(out)

    sprite = QImage(sprite_file)

    # Center the sprite on our image.
    sprite_x = (out.width() - sprite.width()) / 2
    sprite_y = 0

    painter.drawImage(
        QRect(sprite_x, sprite_y, sprite.width(), sprite.height()), sprite,
        sprite.rect())
    painter.end()

    return out
Beispiel #41
0
	def draw(self,p,source,target,subsource = None):
		#这里很难写,回头还要看看写的对不对
		'''Draw image using QPainter
		@param p painter used to draw image
		@param source source rectangle - which part of image to draw
		@param target destination rectangle - which area to draw to
		@param subsource subpixel-accurate subset of source'''	
		wx=source.width()
		wy=source.height()
		x0=source.left()
		y0=source.top()
		source0 = QRect(0,0,wx,wy)
		theBytes=wx*wy*4 #RGBA
		if  self.d.pix_w !=wx or self.d.pix_h !=wy:
			#Size was changed since last time
			del self.d.pixdata
			self.d.pixdata=None
		if not self.d.pixdata:
		        #self.d.pixdata=(int *)malloc(theBytes)
		        self.d.pix_x=x0
		        self.d.pix_y=y0
		        self.d.pix_w=wx
		        self.d.pix_h=wy

		if subsource == None:
			p.drawImage(target,self.d.i,source0)
		else:
			subsource0 = QtCore.QRectF(frac(subsource.left()),frac(subsource.top()),subsource.width(),subsource.height())
			p.drawImage(target,self.d.i,subsource0)
 def __init__(self):
     super(NotificationPresenter, self).__init__()
     rect = QApplication.desktop().availableGeometry()
     self.setGeometry(QRect(rect.width() - 300, 0, 300, rect.height()))
     self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
                         | Qt.Popup | Qt.Tool)
     self.setAttribute(Qt.WA_TranslucentBackground, True)
     self.webview = QWebView(self)
     self.webview.settings().setAttribute(QWebSettings.JavascriptEnabled,
                                          True)
     self.webview.settings().setAttribute(
         QWebSettings.DeveloperExtrasEnabled, True)
     self.webview.settings().setAttribute(
         QWebSettings.LocalContentCanAccessRemoteUrls, True)
     self.webview.settings().setAttribute(QWebSettings.LocalStorageEnabled,
                                          True)
     self.webview.settings().setLocalStoragePath(AppProperty.HomeDir +
                                                 "/data")
     self.webview.setContextMenuPolicy(Qt.NoContextMenu)
     self.webview.settings().setDefaultTextEncoding("utf-8")
     self.webview.setGeometry(0, 0, self.width(), self.height())
     self.webview.setStyleSheet(
         "QWebView{background-color: rgba(255, 193, 245, 0%); }")
     self.webview.load(
         QUrl.fromLocalFile(AppProperty.HomeDir +
                            "/html/notification.html"))
     self.webview.page().linkClicked.connect(self.linkClicked)
     self.webview.page().mainFrame().javaScriptWindowObjectCleared.connect(
         self.setJavaScriptObject)
     self.webview.page().setLinkDelegationPolicy(
         self.webview.page().DelegateAllLinks)
Beispiel #43
0
    def paintEvent(self, paint_event):
        """Paints the box"""
        painter = QPainter(self)
        rect = self.contentsRect()
        tile_count = 3
        tile_size = rect.width() / tile_count
        painter.save()
        painter.translate(rect.x(), rect.y())

        color_index = 0
        for y in range(tile_count):

            if y % 2 == 1:
                color_index = 1
            else:
                color_index = 0

            for x in range(tile_count):
                tile_rect = QRect(x * tile_size, y * tile_size, tile_size,
                                  tile_size)
                painter.fillRect(tile_rect, self.tile_colors[color_index])

                color_index += 1
                if color_index >= len(self.tile_colors):
                    color_index = 0

        painter.restore()
        painter.fillRect(rect, self.color)

        QFrame.paintEvent(self, paint_event)
Beispiel #44
0
    def _onLayerDirty(self, dirtyImgSrc, dataRect):
        sceneRect = self.tiling.data2scene.mapRect(dataRect)
        if dirtyImgSrc not in self._sims.viewImageSources():
            return

        visibleAndNotOccluded = self._sims.isVisible( dirtyImgSrc ) \
                                and not self._sims.isOccluded( dirtyImgSrc )

        # Is EVERYTHING dirty?
        if not sceneRect.isValid() or dataRect == QRect(
                0, 0, *self.tiling.sliceShape):
            # Everything is dirty.
            # This is a FAST PATH for quickly setting all tiles dirty.
            # (It makes a HUGE difference for very large tiling scenes.)
            with self._cache:
                for ims in self._sims.viewImageSources():
                    self._cache.setLayerDirtyAllTiles(ims)
                if visibleAndNotOccluded:
                    self._cache.setAllTilesDirty()
        else:
            # Slow path: Mark intersecting tiles as dirty.
            with self._cache:
                for tile_no in self.tiling.intersected(sceneRect):
                    for ims in self._sims.viewImageSources():
                        self._cache.setLayerDirtyAllStacks(ims, tile_no, True)
                    if visibleAndNotOccluded:
                        self._cache.setTileDirtyAllStacks(tile_no, True)
        if visibleAndNotOccluded:
            self.sceneRectChanged.emit(QRectF(sceneRect))
Beispiel #45
0
    def paintEvent(self, ev):
        painter = QtGui.QPainter()
        painter.begin(self)

        rect = self.rect()
        gs = self._gridSize
        brushT = QColor('#795122')
        brushF = Qt.black
        penG = Qt.darkGray
        penT = Qt.white
        penF = Qt.darkGray
        value = int(self._value)
        tflag = Qt.AlignCenter | Qt.AlignVCenter
        for i in range(self._bitSize):
            col = i % 8
            row = int(i / 8)
            x0 = gs * col
            y0 = gs * row
            gridRect = QRect(x0, y0, gs, gs)
            bit = bool(value & (1 << i))
            if bit:
                painter.setBrush(brushT)
                painter.setPen(penG)
            else:
                painter.setBrush(brushF)
                painter.setPen(penG)

            painter.drawRect(gridRect)
            if bit:
                painter.setPen(penT)
            else:
                painter.setPen(penF)
            painter.drawText(gridRect, tflag, '%d' % i)
        painter.end()
    def testRequest( self ):
        imr = self.ims.request(QRect(0,0,512,512))
        def check(result, codon):
            self.assertEqual(codon, "unique")
            self.assertTrue(type(result) == QImage)

        imr.notify(check, codon="unique")
    def paint(self, painter, option, index):
        # if item selected, override default theme
        # Keeps verdict color for cells and use a bold font
        if option.state & QStyle.State_Selected:
            option.state &= ~QStyle.State_Selected
            option.font.setBold(True)

        QStyledItemDelegate.paint(self, painter, option, index)

        item = index.model().get_item(index)
        if item and item.downloading:
            # Draw progress bar
            progressBarOption = QStyleOptionProgressBarV2()
            progressBarHeight = option.rect.height() / 4
            progressBarOption.rect = QRect(
                option.rect.x(),
                option.rect.y() + (option.rect.height() - progressBarHeight),
                option.rect.width(), progressBarHeight)
            progressBarOption.minimum = 0
            progressBarOption.maximum = 100
            progressBarOption.textAlignment = Qt.AlignCenter

            progressBarOption.progress = item.progress

            QApplication.style().drawControl(QStyle.CE_ProgressBar,
                                             progressBarOption, painter)
Beispiel #48
0
    def drawIcon(self, colorRamp):
        # input color ramp object: QgsVectorColorRampV2 object.
        # QgsVectorColorRampV2 is a virtual object, the real object name in
        # this case is QgsVectorGradientColorRampV2 object.
        mStops = colorRamp.stops()
        linearGradient = QLinearGradient(0.0, 50.0, 200.0, 50.0)
        for item in mStops:
            linearGradient.setColorAt(item.offset, item.color)
        linearGradient.setSpread(QGradient.PadSpread)

        svgName = os.path.join(os.path.dirname(__file__), self.text() + '.svg')
        pix = QSvgGenerator()
        pix.setFileName(svgName)
        pix.setSize(QSize(200, 100))
        painter = QPainter()
        painter.begin(pix)
        br = QBrush(linearGradient)
        painter.setBrush(br)
        painter.drawRect(QRect(0, 0, 200, 100))
        painter.end()

        pixmap = QPixmap(svgName)
        icon = QIcon(pixmap)
        self.svgName = svgName

        return icon
Beispiel #49
0
 def __visualRectForSelection(self, rect):
     h, w = self.image.shape
     rect = rect.normalized()
     rect = rect.intersected(QRect(0, 0, w, h))
     r1, r2 = rect.top(), rect.bottom() + 1
     c1, c2 = rect.left(), rect.right() + 1
     return QRectF(QPointF(c1, r1), QPointF(c2, r2))
    def draw_filled_polygon(self, outline_pen_with=0):
        if not self.scale_polygon_colors == None:
            painter_filled_polygon = QPainter(self)
            painter_filled_polygon.setRenderHint(QPainter.Antialiasing)
            # Koordinatenursprung in die Mitte der Flaeche legen
            painter_filled_polygon.translate(self.width() / 2, self.height() / 2)

            painter_filled_polygon.setPen(Qt.NoPen)

            self.pen.setWidth(outline_pen_with)
            if outline_pen_with > 0:
                painter_filled_polygon.setPen(self.pen)

            colored_scale_polygon = self.create_polygon_pie(
                ((self.widget_diameter / 2) - (self.pen.width() / 2)) * self.gauge_color_outer_radius_factor,
                (((self.widget_diameter / 2) - (self.pen.width() / 2)) * self.gauge_color_inner_radius_factor),
                self.scale_angle_start_value, self.scale_angle_size)

            gauge_rect = QRect(QPoint(0, 0), QSize(self.widget_diameter / 2 - 1, self.widget_diameter - 1))
            grad = QConicalGradient(QPointF(0, 0), - self.scale_angle_size - self.scale_angle_start_value +
                                    self.angle_offset - 1)

            # todo definition scale color as array here
            for eachcolor in self.scale_polygon_colors:
                grad.setColorAt(eachcolor[0], eachcolor[1])
            # grad.setColorAt(.00, Qt.red)
            # grad.setColorAt(.1, Qt.yellow)
            # grad.setColorAt(.15, Qt.green)
            # grad.setColorAt(1, Qt.transparent)
            painter_filled_polygon.setBrush(grad)
            # self.brush = QBrush(QColor(255, 0, 255, 255))
            # painter_filled_polygon.setBrush(self.brush)
            painter_filled_polygon.drawPolygon(colored_scale_polygon)
Beispiel #51
0
    def __init__(self, canvas, forms, snapradius = 2):
        MapTool.__init__(self, canvas, [])
        self.canvas = canvas
        self.radius = snapradius
        self.forms = forms
        
        self.band = QgsRubberBand(self.canvas)
        self.band.setColor(QColor.fromRgb(224,162,16))
        self.band.setWidth(3)
        
        self.selectband = None
        
        self.selectrect = QRect()
        self.dragging = False

        self.cursor = QCursor(QPixmap(["16 16 3 1",
            "      c None",
            ".     c #FF0000",
            "+     c #FFFFFF",
            "                ",
            "       +.+      ",
            "      ++.++     ",
            "     +.....+    ",
            "    +.     .+   ",
            "   +.   .   .+  ",
            "  +.    .    .+ ",
            " ++.    .    .++",
            " ... ...+... ...",
            " ++.    .    .++",
            "  +.    .    .+ ",
            "   +.   .   .+  ",
            "   ++.     .+   ",
            "    ++.....+    ",
            "      ++.++     ",
            "       +.+      "]))
Beispiel #52
0
    def __init__(self, parent, args):
        super(WebPage, self).__init__(parent)

        # variable declarations
        self.m_paperSize = {}
        self.m_clipRect = QRect()
        self.m_libraryPath = ''
        self.m_scrollPosition = QPoint()

        self.setObjectName('WebPage')
        self.m_webPage = CustomPage(self)
        self.m_mainFrame = self.m_webPage.mainFrame()

        self.m_mainFrame.javaScriptWindowObjectCleared.connect(self.initialized)
        self.m_webPage.loadStarted.connect(self.loadStarted)
        self.m_webPage.loadFinished.connect(self.finish)

        # Start with transparent background
        palette = self.m_webPage.palette()
        palette.setBrush(QPalette.Base, Qt.transparent)
        self.m_webPage.setPalette(palette)

        # Page size does not need to take scrollbars into account
        self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)

        self.m_webPage.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True)
        self.m_webPage.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation))
        self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageDatabaseEnabled, True)
        self.m_webPage.settings().setAttribute(QWebSettings.OfflineWebApplicationCacheEnabled, True)
        self.m_webPage.settings().setOfflineWebApplicationCachePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation))
        self.m_webPage.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True)
        self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageEnabled, True)
        self.m_webPage.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation))

        # Ensure we have a document.body.
        self.m_webPage.mainFrame().setHtml(self.blankHtml)

        # Custom network access manager to allow traffic monitoring
        self.m_networkAccessManager = NetworkAccessManager(self.parent(), args)
        self.m_webPage.setNetworkAccessManager(self.m_networkAccessManager)
        self.m_networkAccessManager.resourceRequested.connect(self.resourceRequested)
        self.m_networkAccessManager.resourceReceived.connect(self.resourceReceived)

        self.m_webPage.setViewportSize(QSize(400, 300))

        do_action('WebPageInit')
 def initUI(self):
     self.setWindowIcon(QIcon(':/icon/export'))
     self.setWindowTitle("Export Well")
     self.layout = QGridLayout(self)
     # add QLabel
     self.label_0 = QLabel(self)
     self.label_0.setGeometry(QRect(0, 24, 31, 20))
     self.label_0.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                               | Qt.AlignVCenter)
     self.label_0.setText("Well to export:")
     self.layout.addWidget(self.label_0, 0, 0)
     # add QComboBox
     self.well_comboBox = QComboBox(self)
     self.well_comboBox.setGeometry(QRect(10, 10, 101, 24))
     self.layout.addWidget(self.well_comboBox, 0, 1, 1, 1)
     # add QCheckBox
     self.checkbox = QCheckBox(self)
     self.checkbox.setText("Full LAS")
     self.checkbox.setCheckState(Qt.Unchecked)
     self.layout.addWidget(self.checkbox, 0, 2)
     # add QListWidget
     self.logs_listWidget = QListWidget(self)
     self.logs_listWidget.setGeometry(QRect(0, 0, 101, 201))
     # self.well_comboBox.setMaximumHeight(151)
     self.layout.addWidget(self.logs_listWidget, 1, 1)
     # add QLabel
     self.label_1 = QLabel(self)
     self.label_1.setGeometry(QRect(0, 24, 31, 20))
     self.label_1.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                               | Qt.AlignVCenter)
     self.label_1.setText("Output File:")
     self.layout.addWidget(self.label_1, 2, 0)
     # add QLineEdit
     self.file_path_lineEdit = QLineEdit(self)
     self.file_path_lineEdit.setGeometry(QRect(50, 24, 81, 20))
     self.layout.addWidget(self.file_path_lineEdit, 2, 1)
     # add Button
     self.select_Button = QPushButton(self)
     self.select_Button.setMaximumSize(QSize(61, 24))
     self.select_Button.setText("Select")
     self.layout.addWidget(self.select_Button, 2, 2)
     # add QDialogButtonBox
     self.button_box = QDialogButtonBox(self)
     self.export_Button = self.button_box.addButton(
         "Export", QDialogButtonBox.ApplyRole)
     self.button_box.addButton(QDialogButtonBox.Cancel)
     self.layout.addWidget(self.button_box, 3, 0, 1, 3)
Beispiel #54
0
    def _partition_data(self, zone):

        subzone_width = zone.rect.width() / 2
        subzone_height = zone.rect.height() / 2

        if subzone_width < 100 or subzone_height < 100 or len(
                zone.lines) <= 10:
            return

        subzones = [
            Zone(
                QRect(zone.rect.x(), zone.rect.y(), subzone_width,
                      subzone_height), zone.colour_item),
            Zone(
                QRect(zone.rect.x() + subzone_width, zone.rect.y(),
                      subzone_width, subzone_height), zone.colour_item),
            Zone(
                QRect(zone.rect.x(),
                      zone.rect.y() + subzone_height, subzone_width,
                      subzone_height), zone.colour_item),
            Zone(
                QRect(zone.rect.x() + subzone_width,
                      zone.rect.y() + subzone_height, subzone_width,
                      subzone_height), zone.colour_item)
        ]

        lines = []

        for line in zone.lines:
            for subzone in subzones:
                # If a line is completely within a subzone, add it to the
                # subzone and ignore all other subzones.
                if subzone.rect.contains(line.p1()) and subzone.rect.contains(
                        line.p2()):
                    subzone.lines.append(line)
                    break
            else:
                # If a line is not completely within a zone, add it to the list
                # of lines to keep in the zone.
                lines.append(line)

        zone.lines = lines

        for subzone in subzones:
            if subzone.lines:
                zone.subzones.append(subzone)
                self._partition_data(subzone)
Beispiel #55
0
    def _onLayerDirty(self, dirtyImgSrc, dataRect ):
        """
        Called when one of the image sources we depend on has become dirty.
        Mark the appropriate entries in our tile/layer caches as dirty.
        """
        # Clip the dataRect to the boundaries of the tiling, to ensure 
        # that the 'fast path' below is active when appropriate.
        # (datasources are permitted to mark wider dirty regions than the
        # scene boundaries, but the roi outside the scene bounds is just ignored.)
        tileshape = self.tiling.sliceShape

        datastart = ( max(0, dataRect.left()),
                      max(0, dataRect.top()) )

        datastop = ( min(tileshape[0], dataRect.x() + dataRect.width()),  # Don't use right()!
                     min(tileshape[1], dataRect.y() + dataRect.height())) # Don't use bottom()!

        dataRect = QRect( datastart[0],
                          datastart[1],
                          datastop[0] - datastart[0],
                          datastop[1] - datastart[1] )
        
        sceneRect = self.tiling.data2scene.mapRect(dataRect)
        if dirtyImgSrc not in self._sims.viewImageSources():
            return
        
        visibleAndNotOccluded = self._sims.isVisible( dirtyImgSrc ) \
                                and not self._sims.isOccluded( dirtyImgSrc )

        # Is EVERYTHING dirty?
        if not sceneRect.isValid() or dataRect == QRect(0,0,*self.tiling.sliceShape):
            # Everything is dirty.
            # This is a FAST PATH for quickly setting all tiles dirty.
            # (It makes a HUGE difference for very large tiling scenes.)
            with self._cache:
                self._cache.setLayerDirtyAllTiles(dirtyImgSrc)
                if visibleAndNotOccluded:
                    self._cache.setAllTilesDirty()
        else:
            # Slow path: Mark intersecting tiles as dirty.
            with self._cache:
                for tile_no in self.tiling.intersected(sceneRect):
                    self._cache.setLayerDirtyAllStacks(dirtyImgSrc, tile_no, True)
                    if visibleAndNotOccluded:
                        self._cache.setTileDirtyAllStacks(tile_no, True)
        if visibleAndNotOccluded:
            self.sceneRectChanged.emit( QRectF(sceneRect) )
    def __init__(self):
        super().__init__()

        self.runaction = OWAction("Compute", self)
        self.runaction.triggered.connect(self.compute)
        self.addAction(self.runaction)

        geom = QApplication.desktop().availableGeometry()
        self.setGeometry(QRect(round(geom.width()*0.05),
                               round(geom.height()*0.05),
                               round(min(geom.width()*0.98, self.MAX_WIDTH)),
                               round(min(geom.height()*0.95, self.MAX_HEIGHT))))

        self.setMaximumHeight(self.geometry().height())
        self.setMaximumWidth(self.geometry().width())

        self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH)

        box0 = gui.widgetBox(self.controlArea, "", orientation="horizontal")
        #widget buttons: compute, set defaults, help
        gui.button(box0, self, "Compute", callback=self.compute)
        gui.button(box0, self, "Defaults", callback=self.defaults)
        gui.button(box0, self, "Help", callback=self.help1)

        gui.separator(self.controlArea, height=10)

        self.build_gui()

        self.process_showers()

        gui.rubber(self.controlArea)

        self.main_tabs = gui.tabWidget(self.mainArea)
        plot_tab = gui.createTabPage(self.main_tabs, "Results")
        out_tab = gui.createTabPage(self.main_tabs, "Output")

        view_box = oasysgui.widgetBox(plot_tab, "Results Options", addSpace=False, orientation="horizontal")
        view_box_1 = oasysgui.widgetBox(view_box, "", addSpace=False, orientation="vertical", width=350)

        self.view_type_combo = gui.comboBox(view_box_1, self, "view_type", label="View Results",
                                            labelWidth=220,
                                            items=["No", "Yes"],
                                            callback=self.set_ViewType, sendSelectedValue=False, orientation="horizontal")

        self.tab = []
        self.tabs = gui.tabWidget(plot_tab)

        self.initializeTabs()

        self.xoppy_output = QtGui.QTextEdit()
        self.xoppy_output.setReadOnly(True)

        out_box = gui.widgetBox(out_tab, "System Output", addSpace=True, orientation="horizontal")
        out_box.layout().addWidget(self.xoppy_output)

        self.xoppy_output.setFixedHeight(600)
        self.xoppy_output.setFixedWidth(600)

        gui.rubber(self.mainArea)
Beispiel #57
0
 def viewport_rect(self):
     """
     Return the bounding rect of the document's viewport on the scene.
     """
     view = self.document.view()
     vsize = view.viewport().size()
     viewportrect = QRect(0, 0, vsize.width(), vsize.height())
     return view.mapToScene(viewportrect).boundingRect()
 def newAppCreation(self):
     self.usertabel.setHidden(True)
     self.groupstabel.setHidden(True)
     self.noPermissionAccessLabel = QtGui.QLabel(self.tabs[4])
     self.noPermissionAccessLabel.setGeometry(QRect(50, 50, 420, 100))
     self.noPermissionAccessLabel.setText(
         'You have to save and upload the new application once\nfirst, then you can edit it\'s permissions'
     )
 def noPermissionAccess(self):
     self.usertabel.setHidden(True)
     self.groupstabel.setHidden(True)
     self.noPermissionAccessLabel = QtGui.QLabel(self.tabs[4])
     self.noPermissionAccessLabel.setGeometry(QRect(50, 50, 420, 50))
     self.noPermissionAccessLabel.setText(
         'Could not access application permissions. User permission is not high enough'
     )
Beispiel #60
0
 def mousePressEvent(self, event):
     if not self.doc:
         return
     self.dragPosition = event.pos()
     if not self.rubberBand:
         self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
     self.rubberBand.setGeometry(QRect(self.dragPosition, QSize()))
     self.rubberBand.show()