Exemplo n.º 1
0
    def requestPixmap(self, path, rsize, size):
        """@reimp @public
    @param[in]  providerId  unicode  unused
    @param[out]  rsize  QSize
    @param[in]  size  QSize
    @return  QPixmap not None

    virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
    """

        ret = QPixmap(QUrl(path).toLocalFile())
        if ret.isNull():
            derror("failed to load image: '%s'" % path)
        elif size != ret.size() and not size.isEmpty() and not ret.size(
        ).isEmpty():
            if ret.width() * size.height() > ret.height() * size.width():
                ret = ret.scaledToHeight(min(800, size.height()),
                                         Qt.SmoothTransformation)
            else:
                w = 1000 if ret.width() > ret.height() else 600
                ret = ret.scaledToWidth(min(w, size.width()),
                                        Qt.SmoothTransformation)
        #elif size != ret.size():
        #  ret = (ret.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if not size.isEmpty() else
        #         ret.scaledToWidth(size.width(), Qt.SmoothTransformation) if size.width() > 0 else
        #         ret.scaledToHeight(size.height(), Qt.SmoothTransformation) if size.height() > 0 else
        #         ret)
        rsize.setWidth(ret.width())
        rsize.setHeight(ret.height())
        return ret
Exemplo n.º 2
0
class CheckIconWidget(QWidget):
  """An icon widget that operates as a checkbox"""
  NORMAL_OPACITY = .5
  HOVER_OPACITY = .85
  FIRST_ICON = 1000
  SECOND_ICON = 2000
  
  checked = Signal(bool)
  
  def __init__(self, firstIcon, secondIcon, parent=None):
    super(CheckIconWidget, self).__init__(parent)
    self.setMouseTracking(True)
    self._mouse_over = False
    self._checked = False
    self._first_icon = QPixmap(firstIcon)
    self._second_icon = QPixmap(secondIcon)
    w1, w2 = self._first_icon.width(), self._second_icon.width()
    h1, h2 = self._first_icon.height(), self._second_icon.height()
    max_w = w1 if w1 > w2 else w2
    max_h = h1 if h1 > h2 else h2
    # set the size to contain both images, but they should have the same size
    self.setFixedSize(max_w, max_h)
    
  def mousePressEvent(self, mpe):
    self._checked = not self._checked
    self.checked.emit(self._checked)
    self.repaint()
    
  def mouseMoveEvent(self, mme):
    self._mouse_over = True
    self.setCursor(Qt.CursorShape.PointingHandCursor)
    self.repaint()
    
  def leaveEvent(self, le):
    self._mouse_over = False
    self.repaint()
    
  def paintEvent(self, pe):
    painter = QPainter(self)
    if self._checked:
      pixmap = self._second_icon
    else:
      pixmap = self._first_icon
      
    if self._mouse_over:
      painter.setOpacity(self.HOVER_OPACITY)
    else:
      painter.setOpacity(self.NORMAL_OPACITY)  
    painter.drawPixmap(0, 0, pixmap)
Exemplo n.º 3
0
    def paint(self, painter, option, index):
        rect = option.rect
        movie = index.data(Qt.UserRole)

        painter.setOpacity(0.7)
        if option.state & QStyle.State_Selected:
            painter.drawRect(rect)

        # draw poster background
        painter.setPen(self.outline)
        painter.setBrush(self.backgoundBrush)
        painter.drawRect(rect)

        # draw poster
        pixmap = QPixmap(movie.poster).scaled(rect.width() - 25,
                                              rect.height() - 50,
                                              Qt.KeepAspectRatio,
                                              Qt.SmoothTransformation)

        posterRect = QRect(rect.x() + 15,
                           rect.y() + 15, pixmap.width(), pixmap.height())
        painter.drawPixmap(posterRect, pixmap)

        # draw movie title
        titleRect = QRect(rect.x(),
                          rect.bottom() - 30, rect.width(), rect.height())

        releaseText = "({})".format(
            movie.releaseDate.split("-")[0]) if movie.releaseDate else ""
        painter.drawText(titleRect, Qt.AlignHCenter,
                         u"{0} {1}".format(movie.name, releaseText))
Exemplo n.º 4
0
class Ant():
    def __init__(self, name):
        self.picture = QPixmap()
        self.motion = AntMotion()
        self.name = name
        self.zombie = False

    def width(self):
        return self.picture.width()

    def height(self):
        return self.picture.height()
Exemplo n.º 5
0
	def paintEvent(self, event):
		painter = QPainter(self)

		painter.setBrush(Qt.white)
		painter.drawRect(self.rect())

		painter.translate(self.width()/2, self.height()/2)

		if self.pixReady:
			grammarPix = QPixmap("/tmp/grammar.png")
			pw = grammarPix.width()
			ph = grammarPix.height()
			painter.drawPixmap(-pw/2, -ph/2, grammarPix)
Exemplo n.º 6
0
    def setInfo( *args ):
        filePath = cmds.textField( Window_global.txf_imagePath, q=1, tx=1 )
        pixmap = QPixmap(filePath)
        
        Window_global.imgWidth = pixmap.width()
        Window_global.imgHeight = pixmap.height()
        cmds.intField( Window_global.intf_imageWidth, e=1, v=Window_global.imgWidth )
        cmds.intField( Window_global.intf_imageHeight, e=1, v=Window_global.imgHeight )
        
        planeWidth = cmds.floatField( Window_global.floatf_planeWidth, q=1, v=1 )
        planeHeight = planeWidth * float(Window_global.imgWidth) / float(Window_global.imgHeight)

        cmds.floatField( Window_global.floatf_planeHeight, e=1, v= planeHeight )
Exemplo n.º 7
0
class AntObject():
    def __init__(self, point=QPoint(0, 0)):
        self.picture = QPixmap()
        self.point = point
        self.enabled = True

    def width(self):
        return self.picture.width()

    def height(self):
        return self.picture.height()

    def __eq__(self, other):
        return self.point == other.point and self.width() == other.width() and self.height() == other.height()
Exemplo n.º 8
0
 def setLogo(self):
     """Sets the company logo in the same place in all views"""
     
     logoPixmap = QPixmap(':/resources/logo.png')
     self.iconLabel = QLabel(self)
     self.iconLabel.setPixmap(logoPixmap)
     self.iconLabel.setGeometry(20, 20, logoPixmap.width(), logoPixmap.height())
     
     self.linkLabel = QLabel(self)
     self.linkLabel.setText(
             """<font size="1"><a href="http://www.iqstorage.com/fromiqbox.php">
             Developed at IQ Storage FTP Hosing Services</a></font>""")
     self.linkLabel.setOpenExternalLinks(True)
     # Defines a visual line separator to be placed under the `logoPixmap` `QLabel`
     self.line = QFrame()
     self.line.setFrameShape(QFrame.HLine);
     self.line.setFrameShadow(QFrame.Sunken);
Exemplo n.º 9
0
    def setLogo(self):
        """Sets the company logo in the same place in all views"""

        logoPixmap = QPixmap(':/resources/logo.png')
        self.iconLabel = QLabel(self)
        self.iconLabel.setPixmap(logoPixmap)
        self.iconLabel.setGeometry(20, 20, logoPixmap.width(),
                                   logoPixmap.height())

        self.linkLabel = QLabel(self)
        self.linkLabel.setText(
            """<font size="1"><a href="http://www.iqstorage.com/fromiqbox.php">
                Developed at IQ Storage FTP Hosing Services</a></font>""")
        self.linkLabel.setOpenExternalLinks(True)
        # Defines a visual line separator to be placed under the `logoPixmap` `QLabel`
        self.line = QFrame()
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
Exemplo n.º 10
0
    def setInfo(*args):
        filePath = cmds.textField(Window_global.txf_imagePath, q=1, tx=1)
        pixmap = QPixmap(filePath)

        Window_global.imgWidth = pixmap.width()
        Window_global.imgHeight = pixmap.height()
        cmds.intField(Window_global.intf_imageWidth,
                      e=1,
                      v=Window_global.imgWidth)
        cmds.intField(Window_global.intf_imageHeight,
                      e=1,
                      v=Window_global.imgHeight)

        planeWidth = cmds.floatField(Window_global.floatf_planeWidth, q=1, v=1)
        planeHeight = planeWidth * float(Window_global.imgWidth) / float(
            Window_global.imgHeight)

        cmds.floatField(Window_global.floatf_planeHeight, e=1, v=planeHeight)
Exemplo n.º 11
0
class IconWidget(QWidget):
  """A widget that is clickable, has a fixed size and draws
     an icon which changes opacity on hover. Setting a tooltip is recommended"""
  clicked = Signal()
  def __init__(self, iconPath, hoverOpacity=1, normalOpacity=0.25, parent=None):
    super(IconWidget, self).__init__(parent)
    self.setMouseTracking(True)
    self._icon = QPixmap(iconPath)
    self.setFixedSize(QSize(self._icon.width(), self._icon.height()))
    self._hover_opacity = hoverOpacity
    self._normal_opacity = normalOpacity
    self._mouse_over = False # this is correct because when an icon appears after another, it appears where the mouse is
    self._enabled = True
    
  def paintEvent(self, pe):
    painter = QPainter(self)
    icon = QPixmap(self._icon)
    icon = icon.scaled(self.size(), Qt.IgnoreAspectRatio)
    if not self._mouse_over or not self._enabled:
      painter.setOpacity(self._normal_opacity)
    else:
      painter.setOpacity(self._hover_opacity)
    painter.drawPixmap(0, 0, icon)
    
  def mouseMoveEvent(self, mme):
    if self._mouse_over: return
    self._mouse_over = True
    self.setCursor(Qt.CursorShape.PointingHandCursor)
    self.repaint()
    
  def leaveEvent(self, le):
    self._mouse_over = False
    self.repaint()
    
  def mousePressEvent(self, mpe):
    self.clicked.emit()
    
  def makeEnabled(self):
    self._enabled = True
    self.show()
    
  def makeDisabled(self):
    self._enabled = False
    self.hide()
Exemplo n.º 12
0
def tag_image(source, dest, tag, font, fontsize, x, y, width, height, aspectx, aspecty, red, green, blue, bold=False, italic=False):
    """docstring for tag_image"""

    app = QApplication.instance()
    
    pixmap = QPixmap(source)

    color = QColor(red,green,blue)
    font = QFont(font)
    font.setPixelSize(int(fontsize*pixmap.height()))
    font.setItalic(italic)
    font.setBold(bold)

    painter = QPainter(pixmap)
    painter.setPen(color)
    painter.setFont(font);
    painter.drawText(x*pixmap.width(),y*pixmap.height(), tag)
    painter.end()

    # Resize and save
    return pixmap.toImage().scaled(width*aspectx, height*aspecty, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation).scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation).save(dest)
Exemplo n.º 13
0
    def requestPixmap(self, name, rsize, size):
        """@reimp @public
    @param[in]  providerId  unicode  unused
    @param[out]  rsize  QSize
    @param[in]  size  QSize
    @return  QPixmap not None

    virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
    """
        ret = QPixmap(rc.image_path(name))
        if ret.isNull():
            derror("failed to load image: '%s'" % name)
        elif ret.size() != size:
            ret = (
                ret.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                if not size.isEmpty() else ret.scaledToWidth(
                    size.width(), Qt.SmoothTransformation) if size.width() > 0
                else ret.scaledToHeight(size.height(), Qt.SmoothTransformation)
                if size.height() > 0 else ret)
        rsize.setWidth(ret.width())
        rsize.setHeight(ret.height())
        return ret
Exemplo n.º 14
0
    def requestPixmap(self, path, rsize, size):
        """@reimp @public
    @param[in]  providerId  unicode  unused
    @param[out]  rsize  QSize
    @param[in]  size  QSize
    @return  QPixmap not None

    virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
    """

        icon = rc.file_icon(path)
        if icon.isNull():
            derror("failed to load image: '%s'" % path)
            ret = QPixmap()
        elif not size.isEmpty():
            ret = icon.pixmap(size)
        else:
            #sizes = icon.availableSizes(QIcon.Selected, QIcon.Off) # crash for executable
            ret = icon.pixmap(*FileImageProvider.ICON_SIZE)

        rsize.setWidth(ret.width())
        rsize.setHeight(ret.height())
        return ret
Exemplo n.º 15
0
 def paintEvent(self, event):
     painter = QStylePainter(self)
     painter.setPen(self.palette().color(QPalette.Text))
     # Draw the combobox frame, focus rect, selected etc.
     opt = QStyleOptionComboBox()
     self.initStyleOption(opt)
     opt.currentText = ""  # Don't draw the raw HTML
     painter.drawComplexControl(QStyle.CC_ComboBox, opt)
     # Draw the icon and text
     painter.drawControl(QStyle.CE_ComboBoxLabel, opt)
     # Draw the HTML
     self.label.setText(self.currentText())
     self.label.adjustSize()
     pixmap = QPixmap(self.label.width(), self.label.height())
     pixmap.fill(Qt.transparent)
     self.label.render(pixmap, renderFlags=QWidget.RenderFlags(0))
     rect = QRect(opt.rect)
     y = (rect.height() - self.label.height()) / 2
     rect.setX(self.fontMetrics().width("n"))
     rect.setY(y)
     rect.setHeight(pixmap.height())
     rect.setWidth(pixmap.width())
     painter.drawPixmap(rect, pixmap, pixmap.rect())
Exemplo n.º 16
0
class MdiArea(QMdiArea):  # MdiArea::MdiArea(MainWindow* mw, QWidget *parent) : QMdiArea(parent), mainWin(mw)
    """
    Subclass of `QMdiArea`_

    TOWRITE
    """

    def __init__(self, mw, parent=None):
        """
        Default class constructor.

        :param `mw`: Pointer to a application main window instance.
        :type `mw`: `MainWindow`_
        :param `parent`: Pointer to a parent widget instance.
        :type `parent`: `QWidget`_
        """
        super(MdiArea, self).__init__(parent)

        self.mainWin = mw
        self.gSpiralsImgPath = mw.gImgDir + os.sep + 'texture-spirals.png'
        self.gLogoSpiralsImgPath = mw.gImgDir + os.sep + 'logo-spirals.png'

        try:  #if QT_VERSION >= 0x040800
            self.setTabsClosable(True)
        except AttributeError:
            pass

        self.useLogo = False
        self.useTexture = False
        self.useColor = False

        self.bgLogo = QPixmap()
        self.bgTexture = QPixmap(self.gSpiralsImgPath)
        self.bgColor = QColor()

        self.bgLogo = QPixmap(self.gLogoSpiralsImgPath)

        # Brushes
        self.colorBrush = QBrush(QColor(EMBROIDERBLUE1))
        self.backgroundBrush = QBrush(QPixmap(self.gSpiralsImgPath))
        linearGrad = QLinearGradient(QPointF(0, 0), QPointF(400, 400))
        linearGrad.setColorAt(0, QColor(EMBROIDERBLUE1))
        linearGrad.setColorAt(1, QColor(EMBROIDERBLUE2))
        self.gradientBrush = QBrush(linearGrad)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setActivationOrder(QMdiArea.ActivationHistoryOrder)

        self.setFocusPolicy(Qt.WheelFocus)
        self.setFocus()

        self.setAcceptDrops(True)
        self.doSetDocumentMode(True)

    def __del__(self):
        """Class destructor."""
        qDebug("MdiArea Destructor")

    def useBackgroundLogo(self, use):
        """
        TOWRITE

        :param `use`: TOWRITE
        :type `use`: bool
        """
        self.useLogo = use
        self.forceRepaint()

    def useBackgroundTexture(self, use):
        """
        TOWRITE

        :param `use`: TOWRITE
        :type `use`: bool
        """
        self.useTexture = use
        self.forceRepaint()

    def useBackgroundColor(self, use):
        """
        TOWRITE

        :param `use`: TOWRITE
        :type `use`: bool
        """
        self.useColor = use
        self.forceRepaint()

    def setBackgroundLogo(self, fileName):
        """
        TOWRITE

        :param `fileName`: TOWRITE
        :type `fileName`: QString
        """
        self.bgLogo.load(fileName)
        self.forceRepaint()

    def setBackgroundTexture(self, fileName):
        """
        TOWRITE

        :param `fileName`: TOWRITE
        :type `fileName`: QString
        """
        self.bgTexture.load(fileName)
        self.forceRepaint()

    def setBackgroundColor(self, color):
        """
        TOWRITE

        :param `color`: TOWRITE
        :type `color`: `QColor`_
        """
        if not color:  # .isValid()
            self.bgColor = self.background().color()
        else:
            self.bgColor = color

        self.forceRepaint()

    def mouseDoubleClickEvent(self, event):
        """
        Handles the ``mouseDoubleClickEvent`` event for :class:`MdiArea`.

        :param `event`: A `QMouseEvent`_ to be processed.
        """
        qDebug('%s' % event.button())
        evtBtn = event.button()
        if evtBtn == Qt.LeftButton: # return 1
            self.mainWin.openFile()
        elif evtBtn == Qt.RightButton: # return 2
            qDebug('DoubleRightClick')
        elif evtBtn == Qt.MiddleButton: # return 4
            qDebug('DoubleMiddleClick')
        elif evtBtn == Qt.XButton1: # Aux1 return 8
            qDebug('DoubleAux1Click')
        elif evtBtn == Qt.XButton2: # Aux2 return 16
            qDebug('DoubleAux2Click')

    ## def paintEvent(self, event):
    ##     """
    ##     Handles the ``paintEvent`` event for :class:`MdiArea`.
    ##
    ##     :param `event`: A `QPaintEvent`_ to be processed.
    ##     """
    ##     vport = self.viewport()  # QWidget*
    ##     rect = vport.rect()  # QRect
    ##
    ##     painter = QPainter(vport)
    ##     painter.setRenderHint(QPainter.SmoothPixmapTransform)
    ##
    ##     # Always fill with a solid color first.
    ##     if self.useColor:
    ##         painter.fillRect(rect, self.bgColor)
    ##     else:
    ##         painter.fillRect(rect, self.background())
    ##
    ##     # Then overlay the texture.
    ##     if self.useTexture:
    ##         bgBrush = QBrush(self.bgTexture)
    ##         painter.fillRect(rect, bgBrush)
    ##
    ##     # Overlay the logo last.
    ##     if self.useLogo:
    ##         bgLogo = self.bgLogo
    ##         # Center the pixmap.
    ##         dx = (rect.width() - bgLogo.width()) / 2     # int
    ##         dy = (rect.height() - bgLogo.height()) / 2   # int
    ##         painter.drawPixmap(dx, dy, bgLogo.width(), bgLogo.height(), bgLogo)

    def paintEvent(self, event):
        """
        Handles the ``paintEvent`` event for :class:`MdiArea`.

        :param `event`: A `QPaintEvent`_ to be processed.
        """
        vport = self.viewport()
        rect = vport.rect()

        painter = QPainter(vport)
        painter.setRenderHint(painter.SmoothPixmapTransform)

        # Always fill with a solid color first
        if self.useColor:
            # painter.fillRect(rect, self.colorBrush)
            painter.fillRect(rect, self.bgColor)
        else:
            painter.fillRect(rect, self.background())

        # Then overlay the texture
        if self.useTexture:
            # painter.fillRect(rect, self.backgroundBrush)
            bgBrush = QBrush(self.bgTexture)
            painter.fillRect(rect, bgBrush)
            

        # Overlay the logo last
        if self.useLogo:
            if not len(self.subWindowList()):  # Nothing is open.
                cSizeW, cSizeH = rect.width(), rect.height()
                bgLogoW, bgLogoH = self.bgLogo.width(), self.bgLogo.height()
                if bgLogoW > cSizeW:
                    # Proportional Scaling an Image.
                    newHeight = bgLogoH * cSizeW // bgLogoW
                    scaledLogo = self.bgLogo.scaled(cSizeW, newHeight)
                    painter.drawPixmap(0,
                                       cSizeH // 2 - scaledLogo.height() // 2,
                                       scaledLogo)
                else:
                    painter.drawPixmap((cSizeW - bgLogoW) // 2,
                                       (cSizeH - bgLogoH) // 2,
                                       self.bgLogo)
            else:
                # Center the pixmap
                dx = (rect.width() - self.bgLogo.width()) / 2
                dy = (rect.height() - self.bgLogo.height()) / 2
                painter.drawPixmap(dx, dy,
                                   self.bgLogo.width(), self.bgLogo.height(),
                                   self.bgLogo)

    def zoomExtentsAllSubWindows(self):
        """
        TOWRITE
        """
        for window in self.subWindowList():  # foreach(QMdiSubWindow* window, subWindowList())
            mdiWin = window  # MdiWindow* mdiWin = qobject_cast<MdiWindow*>(window);
            if mdiWin:
                v = mdiWin.getView()  # View*
                if v:
                    v.recalculateLimits()
                    v.zoomExtents()

    def forceRepaint(self):
        """
        TOWRITE
        """
        # HACK: Take that QMdiArea!
        hack = self.size()  # QSize
        self.resize(hack + QSize(1, 1))
        self.resize(hack)

    def moveEvent(self, event):
        """
        Handles the ``moveEvent`` event for :class:`MDIArea`.

        :param `event`: A `QMoveEvent`_ to be processed.
        """
        # Dragging while MouseButton is down.
        qDebug("QMdiArea moveEvent")

    def contextMenuEvent(self, event):
        """
        Handles the ``contextMenuEvent`` event for :class:`MDIArea`.

        :param `event`: A `QContextMenuEvent`_ to be processed.
        """
        mainWin = self.mainWin
        if not len(self.subWindowList()): # Nothing is open.
            # Build a menu suitable for the startup screen.
            menu = QMenu(self)
            menu.addAction(mainWin.actionHash["ACTION_new"])
            menu.addAction(mainWin.actionHash["ACTION_open"])
            menu.addAction(mainWin.actionHash["ACTION_settingsdialog"])
            menu.addAction(mainWin.actionHash["ACTION_help"])
            menu.addAction(mainWin.actionHash["ACTION_about"])
            menu.addAction(mainWin.actionHash["ACTION_exit"])
            menu.popup(self.mapToGlobal(event.pos()))
            # menu.exec_(self.mapToGlobal(event.pos()))
        else:
            # Build a menu suitable for when the mdi workspace is open.
            mainWin.fileMenu.popup(self.mapToGlobal(event.pos()))

        event.accept()
        qDebug("QMdiArea contextMenuEvent")

    def doSetDocumentMode(self, enabled=False):
        """
        Set the document mode for :class:`MDIArea`.

        :param `enabled`: Whether the tab bar is set to document mode in tabbed view mode.
         Document mode is disabled by default.
        :type `enabled`: bool
        """
        self.setDocumentMode(enabled)

    # Slots ------------------------------------------------------------------

    @Slot()
    def cascade(self):
        """
        TOWRITE
        """
        self.cascadeSubWindows()
        self.zoomExtentsAllSubWindows()

    @Slot()
    def tile(self):
        """
        TOWRITE
        """
        self.tileSubWindows()
        self.zoomExtentsAllSubWindows()
Exemplo n.º 17
0
class ImagePreset(RawPreset):
    def setup(self):
        self.add_parameter(FloatParameter('speed-rotation', 0.1))
        self.add_parameter(FloatParameter('speed-hue', 0.0))
        self.add_parameter(FloatParameter('center-orbit-distance', 0.0))
        self.add_parameter(FloatParameter('center-orbit-speed', 0.1))
        self.add_parameter(StringParameter('image-file', ""))
        self.add_parameter(StringParameter('edge-mode',
                                           "clamp"))  # mirror, tile, clamp
        self.add_parameter(FloatParameter('center-x', 0.0))
        self.add_parameter(FloatParameter('center-y', 0.0))
        self.add_parameter(FloatParameter('scale', 1.0))
        self.add_parameter(FloatParameter('ghost', 0.0))
        self.add_parameter(FloatParameter('beat-lum-boost', 0.1))
        self.add_parameter(FloatParameter('beat-lum-time', 0.05))

        self.pixel_locations = self.scene().get_all_pixel_locations()
        self.hue_inner = random.random() + 100
        self._center_rotation = random.random()
        self.angle = 0
        self.lum_boost = 0
        self.hue_offset = 0
        self.imagename = None
        self.image = None
        self._buffer = None

        self.parameter_changed(None)

    def parameter_changed(self, parameter):
        if self.imagename != self.parameter('image-file').get():
            self.pixmap = QPixmap(self.parameter('image-file').get())
            self.imagename = self.parameter('image-file').get()
            image = self.pixmap.toImage()
            if image:
                #image = image.convertToFormat(QImage.Format_ARGB32)
                self.image = np.frombuffer(image.bits(), dtype=np.uint8)
                self.image = self.image.reshape(self.pixmap.height(),
                                                self.pixmap.width(), 4).T

                self.image = np.asarray(
                    (self.image[2], self.image[1], self.image[0])).T

                self.image = rgb_to_hls(self.image)
                #print self.image

                print "image", self.parameter(
                    'image-file').get(), "loaded:", self.image.shape

        self.lastFrame = None

    def reset(self):
        pass

    def draw(self, dt):
        if self.pixmap:
            lum_boost = self.parameter('beat-lum-boost').get()
            if self._mixer.is_onset():
                self.lum_boost += lum_boost

            self.hue_offset += dt * self.parameter('speed-hue').get()
            self._center_rotation += dt * self.parameter(
                'center-orbit-speed').get()
            self.angle += dt * self.parameter('speed-rotation').get()
            orbitx = math.cos(self._center_rotation) * self.parameter(
                'center-orbit-distance').get()
            orbity = math.sin(self._center_rotation) * self.parameter(
                'center-orbit-distance').get()

            locations = np.copy(self.pixel_locations.T)
            cx, cy = self.scene().center_point()
            locations[0] -= cx + orbitx
            locations[1] -= cy + orbity
            rotMatrix = np.array([
                (math.cos(self.angle), -math.sin(self.angle)),
                (math.sin(self.angle), math.cos(self.angle))
            ])
            x, y = rotMatrix.T.dot(locations)
            x /= self.parameter('scale').get()
            y /= self.parameter('scale').get()
            x += self.pixmap.width() / 2 + self.parameter('center-x').get()
            y += self.pixmap.height() / 2 + self.parameter('center-y').get()
            x = np.int_(x)
            y = np.int_(y)

            edge_mode = self.parameter('edge-mode').get()
            if edge_mode == "clamp":
                np.clip(x, 0, self.pixmap.width() - 1, x)
                np.clip(y, 0, self.pixmap.height() - 1, y)
            elif edge_mode == "tile":
                np.mod(np.abs(x), self.pixmap.width(), x)
                np.mod(np.abs(y), self.pixmap.height(), y)
            elif edge_mode == "mirror":
                np.mod(np.abs(x), self.pixmap.width() * 2 - 1, x)
                np.mod(np.abs(y), self.pixmap.height() * 2 - 1, y)
                np.abs(x - (self.pixmap.width() - 1), x)
                np.abs(y - (self.pixmap.height() - 1), y)
            else:
                print "Unknown image preset edge mode (clamp, tile, or mirror)."

            locations = np.asarray([x, y]).T

            colors = self.image[locations.T[1], locations.T[0]]

            colors.T[0] += self.hue_offset
            colors.T[1] += self.lum_boost

            ghost = self.parameter('ghost').get()
            if abs(ghost) > 0:
                if self.lastFrame != None:
                    if self._buffer is None:
                        self._buffer = np.empty_like(self.lastFrame)
                    colors = hls_blend(colors, self.lastFrame, self._buffer,
                                       ghost, "add", 1.0, 0.1)
                self.lastFrame = colors

            lum_time = self.parameter('beat-lum-time').get()
            if lum_time and self.lum_boost:
                if self.lum_boost > 0:
                    self.lum_boost = max(
                        0, self.lum_boost - lum_boost * dt / lum_time)
                else:
                    self.lum_boost = min(
                        0, self.lum_boost - lum_boost * dt / lum_time)

            self._pixel_buffer = colors
Exemplo n.º 18
0
class ImagePattern(Pattern):
    def setup(self):
        self.add_parameter(FloatParameter('speed-rotation', 0.1))
        self.add_parameter(FloatParameter('speed-hue', 0.0))
        self.add_parameter(FloatParameter('center-orbit-distance', 0.0))
        self.add_parameter(FloatParameter('center-orbit-speed', 0.1))
        self.add_parameter(StringParameter('image-file', ""))
        self.add_parameter(StringParameter('edge-mode', "clamp")) # mirror, tile, clamp
        self.add_parameter(FloatParameter('center-x', 0.0))
        self.add_parameter(FloatParameter('center-y', 0.0))
        self.add_parameter(FloatParameter('scale', 1.0))
        self.add_parameter(FloatParameter('ghost', 0.0))
        self.add_parameter(FloatParameter('beat-lum-boost', 0.1))
        self.add_parameter(FloatParameter('beat-lum-time', 0.05))

        self.pixel_locations = self.scene().get_all_pixel_locations()
        self.hue_inner = random.random() + 100
        self._center_rotation = random.random()
        self.angle = 0
        self.lum_boost = 0
        self.hue_offset = 0
        self.imagename = None
        self.image = None
        self._buffer = None

    def parameter_changed(self, parameter):
        if self.imagename != self.parameter('image-file').get():
            self.pixmap = QPixmap(self.parameter('image-file').get())
            self.imagename = self.parameter('image-file').get()
            image = self.pixmap.toImage()
            if image:
                #image = image.convertToFormat(QImage.Format_ARGB32)
                self.image = np.frombuffer(image.bits(), dtype=np.uint8)
                self.image = self.image.reshape(self.pixmap.height(), self.pixmap.width(), 4).T

                self.image = np.asarray((self.image[2],self.image[1],self.image[0])).T

                self.image = rgb_to_hls(self.image)
                print self.image

                #print "image", self.parameter('image-file').get(), "loaded:", self.image.shape
            else:
                print "No image!"

        self.lastFrame = None

    def reset(self):
        pass

    def draw(self, dt):
        if self.pixmap:
            lum_boost = self.parameter('beat-lum-boost').get()
            if self._app.mixer.is_onset():
                self.lum_boost += lum_boost

            self.hue_offset += dt * self.parameter('speed-hue').get()
            self._center_rotation += dt * self.parameter('center-orbit-speed').get()
            self.angle += dt * self.parameter('speed-rotation').get()
            orbitx = math.cos(self._center_rotation) * self.parameter('center-orbit-distance').get()
            orbity = math.sin(self._center_rotation) * self.parameter('center-orbit-distance').get()

            locations = np.copy(self.pixel_locations.T)
            cx, cy = self.scene().center_point()
            locations[0] -= cx + orbitx
            locations[1] -= cy + orbity
            rotMatrix = np.array([(math.cos(self.angle), -math.sin(self.angle)), (math.sin(self.angle),  math.cos(self.angle))])
            x,y = rotMatrix.T.dot(locations)
            x /= self.parameter('scale').get()
            y /= self.parameter('scale').get()
            x += self.pixmap.width() / 2 + self.parameter('center-x').get()
            y += self.pixmap.height() / 2 + self.parameter('center-y').get()
            x = np.int_(x)
            y = np.int_(y)

            edge_mode = self.parameter('edge-mode').get()
            if edge_mode == "clamp":
                np.clip(x, 0, self.pixmap.width() - 1, x)
                np.clip(y, 0, self.pixmap.height() - 1, y)
            elif edge_mode == "tile":
                np.mod(np.abs(x), self.pixmap.width(), x)
                np.mod(np.abs(y), self.pixmap.height(), y)
            elif edge_mode == "mirror":
                np.mod(np.abs(x), self.pixmap.width() * 2 - 1, x)
                np.mod(np.abs(y), self.pixmap.height() * 2 - 1, y)
                np.abs(x - (self.pixmap.width() - 1), x)
                np.abs(y - (self.pixmap.height() - 1), y)
            else:
                print "Unknown image preset edge mode (clamp, tile, or mirror)."

            locations = np.asarray([x,y]).T

            colors = self.image[locations.T[1], locations.T[0]]

            colors.T[0] += self.hue_offset
            colors.T[1] += self.lum_boost

            ghost = self.parameter('ghost').get()
            if abs(ghost) > 0:
                if self.lastFrame != None:
                    if self._buffer is None:
                        self._buffer = np.empty_like(self.lastFrame)
                    colors = hls_blend(colors, self.lastFrame, self._buffer, ghost, "add", 1.0, 0.1)
                self.lastFrame = colors

            lum_time = self.parameter('beat-lum-time').get()
            if lum_time and self.lum_boost:
                if self.lum_boost > 0:
                    self.lum_boost = max(0, self.lum_boost - lum_boost * dt / lum_time)
                else:
                    self.lum_boost = min(0, self.lum_boost - lum_boost * dt / lum_time)

            self._pixel_buffer = colors
Exemplo n.º 19
0
    def paint(self, painter, option, index):
        """ Overrideoljuk a saját igényeinkre"""

        rect = option.rect

        movieObj = index.data(Qt.UserRole)

        # BACKGROUND rect
        painter.setPen(Qt.NoPen)

        if option.state & QStyle.State_Selected:
            painter.setBrush(self.selectedColor)
        else:
            painter.setBrush(self.bgColor)

        painter.drawRect(rect)

        # POSTER rect
        painter.setBrush(self.posterBrush)
        painter.setPen(self.posterOutline)

        # Posert image rect
        pixmap = QPixmap(movieObj.poster)
        pixmapRect = QRect(rect.x() + 5,
                           rect.y() + 5, pixmap.width(), pixmap.height())
        painter.drawPixmap(pixmapRect, pixmap)

        # TITLE rect
        painter.setFont(self.font)
        titleRect = QRect(pixmapRect.left(), pixmapRect.bottom(),
                          pixmapRect.width(), 40)
        painter.drawText(titleRect, Qt.AlignVCenter | Qt.AlignHCenter,
                         movieObj.name)

        if option.state & QStyle.State_Selected:
            painter.setPen(Qt.NoPen)
            painter.setBrush(self.transparentBG)
            painter.drawRect(rect)

        if movieObj.getMovieWatchedStatus() == 1:

            watchedRect = QRect(rect.x() + 2, rect.y() + 2, 25, 25)
            watchedIcon = QPixmap(fileUtils.get_icon("watchedfiltericon"))
            painter.setBrush(self.watchedBG)
            painter.drawPixmap(watchedRect, watchedIcon)
            painter.setBrush(self.watchedBG)
            painter.setPen(Qt.NoPen)
            painter.drawRect(
                QRect(rect.x() - 2,
                      rect.y() - 2,
                      rect.width() + 4,
                      rect.height() + 4))

        elif movieObj.getMovieWatchedStatus() == 0:
            painter.setBrush(self.unWatchedBG)
            painter.setPen(Qt.NoPen)
            painter.drawRect(
                QRect(rect.x() - 2,
                      rect.y() - 2,
                      rect.width() + 4,
                      rect.height() + 4))
Exemplo n.º 20
0
 def testQPixmapConstructor(self):
     label = QLabel()
     pixmap1 = QPixmap(xpm)
     self.assertFalse(pixmap1.isNull())
     self.assertEqual(pixmap1.width(), 27)
     self.assertEqual(pixmap1.height(), 22)
Exemplo n.º 21
0
class MdiArea(
        QMdiArea
):  # MdiArea::MdiArea(MainWindow* mw, QWidget *parent) : QMdiArea(parent), mainWin(mw)
    """
    Subclass of `QMdiArea`_

    TOWRITE
    """
    def __init__(self, mw, parent=None):
        """
        Default class constructor.

        :param `mw`: Pointer to a application main window instance.
        :type `mw`: `MainWindow`_
        :param `parent`: Pointer to a parent widget instance.
        :type `parent`: `QWidget`_
        """
        super(MdiArea, self).__init__(parent)

        self.mainWin = mw
        self.gSpiralsImgPath = mw.gImgDir + os.sep + 'texture-spirals.png'
        self.gLogoSpiralsImgPath = mw.gImgDir + os.sep + 'logo-spirals.png'

        try:  #if QT_VERSION >= 0x040800
            self.setTabsClosable(True)
        except AttributeError:
            pass

        self.useLogo = False
        self.useTexture = False
        self.useColor = False

        self.bgLogo = QPixmap()
        self.bgTexture = QPixmap(self.gSpiralsImgPath)
        self.bgColor = QColor()

        self.bgLogo = QPixmap(self.gLogoSpiralsImgPath)

        # Brushes
        self.colorBrush = QBrush(QColor(EMBROIDERBLUE1))
        self.backgroundBrush = QBrush(QPixmap(self.gSpiralsImgPath))
        linearGrad = QLinearGradient(QPointF(0, 0), QPointF(400, 400))
        linearGrad.setColorAt(0, QColor(EMBROIDERBLUE1))
        linearGrad.setColorAt(1, QColor(EMBROIDERBLUE2))
        self.gradientBrush = QBrush(linearGrad)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setActivationOrder(QMdiArea.ActivationHistoryOrder)

        self.setFocusPolicy(Qt.WheelFocus)
        self.setFocus()

        self.setAcceptDrops(True)
        self.doSetDocumentMode(True)

    def __del__(self):
        """Class destructor."""
        qDebug("MdiArea Destructor")

    def useBackgroundLogo(self, use):
        """
        TOWRITE

        :param `use`: TOWRITE
        :type `use`: bool
        """
        self.useLogo = use
        self.forceRepaint()

    def useBackgroundTexture(self, use):
        """
        TOWRITE

        :param `use`: TOWRITE
        :type `use`: bool
        """
        self.useTexture = use
        self.forceRepaint()

    def useBackgroundColor(self, use):
        """
        TOWRITE

        :param `use`: TOWRITE
        :type `use`: bool
        """
        self.useColor = use
        self.forceRepaint()

    def setBackgroundLogo(self, fileName):
        """
        TOWRITE

        :param `fileName`: TOWRITE
        :type `fileName`: QString
        """
        self.bgLogo.load(fileName)
        self.forceRepaint()

    def setBackgroundTexture(self, fileName):
        """
        TOWRITE

        :param `fileName`: TOWRITE
        :type `fileName`: QString
        """
        self.bgTexture.load(fileName)
        self.forceRepaint()

    def setBackgroundColor(self, color):
        """
        TOWRITE

        :param `color`: TOWRITE
        :type `color`: `QColor`_
        """
        if not color:  # .isValid()
            self.bgColor = self.background().color()
        else:
            self.bgColor = color

        self.forceRepaint()

    def mouseDoubleClickEvent(self, event):
        """
        Handles the ``mouseDoubleClickEvent`` event for :class:`MdiArea`.

        :param `event`: A `QMouseEvent`_ to be processed.
        """
        qDebug('%s' % event.button())
        evtBtn = event.button()
        if evtBtn == Qt.LeftButton:  # return 1
            self.mainWin.openFile()
        elif evtBtn == Qt.RightButton:  # return 2
            qDebug('DoubleRightClick')
        elif evtBtn == Qt.MiddleButton:  # return 4
            qDebug('DoubleMiddleClick')
        elif evtBtn == Qt.XButton1:  # Aux1 return 8
            qDebug('DoubleAux1Click')
        elif evtBtn == Qt.XButton2:  # Aux2 return 16
            qDebug('DoubleAux2Click')

    ## def paintEvent(self, event):
    ##     """
    ##     Handles the ``paintEvent`` event for :class:`MdiArea`.
    ##
    ##     :param `event`: A `QPaintEvent`_ to be processed.
    ##     """
    ##     vport = self.viewport()  # QWidget*
    ##     rect = vport.rect()  # QRect
    ##
    ##     painter = QPainter(vport)
    ##     painter.setRenderHint(QPainter.SmoothPixmapTransform)
    ##
    ##     # Always fill with a solid color first.
    ##     if self.useColor:
    ##         painter.fillRect(rect, self.bgColor)
    ##     else:
    ##         painter.fillRect(rect, self.background())
    ##
    ##     # Then overlay the texture.
    ##     if self.useTexture:
    ##         bgBrush = QBrush(self.bgTexture)
    ##         painter.fillRect(rect, bgBrush)
    ##
    ##     # Overlay the logo last.
    ##     if self.useLogo:
    ##         bgLogo = self.bgLogo
    ##         # Center the pixmap.
    ##         dx = (rect.width() - bgLogo.width()) / 2     # int
    ##         dy = (rect.height() - bgLogo.height()) / 2   # int
    ##         painter.drawPixmap(dx, dy, bgLogo.width(), bgLogo.height(), bgLogo)

    def paintEvent(self, event):
        """
        Handles the ``paintEvent`` event for :class:`MdiArea`.

        :param `event`: A `QPaintEvent`_ to be processed.
        """
        vport = self.viewport()
        rect = vport.rect()

        painter = QPainter(vport)
        painter.setRenderHint(painter.SmoothPixmapTransform)

        # Always fill with a solid color first
        if self.useColor:
            # painter.fillRect(rect, self.colorBrush)
            painter.fillRect(rect, self.bgColor)
        else:
            painter.fillRect(rect, self.background())

        # Then overlay the texture
        if self.useTexture:
            # painter.fillRect(rect, self.backgroundBrush)
            bgBrush = QBrush(self.bgTexture)
            painter.fillRect(rect, bgBrush)

        # Overlay the logo last
        if self.useLogo:
            if not len(self.subWindowList()):  # Nothing is open.
                cSizeW, cSizeH = rect.width(), rect.height()
                bgLogoW, bgLogoH = self.bgLogo.width(), self.bgLogo.height()
                if bgLogoW > cSizeW:
                    # Proportional Scaling an Image.
                    newHeight = bgLogoH * cSizeW // bgLogoW
                    scaledLogo = self.bgLogo.scaled(cSizeW, newHeight)
                    painter.drawPixmap(0,
                                       cSizeH // 2 - scaledLogo.height() // 2,
                                       scaledLogo)
                else:
                    painter.drawPixmap((cSizeW - bgLogoW) // 2,
                                       (cSizeH - bgLogoH) // 2, self.bgLogo)
            else:
                # Center the pixmap
                dx = (rect.width() - self.bgLogo.width()) / 2
                dy = (rect.height() - self.bgLogo.height()) / 2
                painter.drawPixmap(dx, dy, self.bgLogo.width(),
                                   self.bgLogo.height(), self.bgLogo)

    def zoomExtentsAllSubWindows(self):
        """
        TOWRITE
        """
        for window in self.subWindowList(
        ):  # foreach(QMdiSubWindow* window, subWindowList())
            mdiWin = window  # MdiWindow* mdiWin = qobject_cast<MdiWindow*>(window);
            if mdiWin:
                v = mdiWin.getView()  # View*
                if v:
                    v.recalculateLimits()
                    v.zoomExtents()

    def forceRepaint(self):
        """
        TOWRITE
        """
        # HACK: Take that QMdiArea!
        hack = self.size()  # QSize
        self.resize(hack + QSize(1, 1))
        self.resize(hack)

    def moveEvent(self, event):
        """
        Handles the ``moveEvent`` event for :class:`MDIArea`.

        :param `event`: A `QMoveEvent`_ to be processed.
        """
        # Dragging while MouseButton is down.
        qDebug("QMdiArea moveEvent")

    def contextMenuEvent(self, event):
        """
        Handles the ``contextMenuEvent`` event for :class:`MDIArea`.

        :param `event`: A `QContextMenuEvent`_ to be processed.
        """
        mainWin = self.mainWin
        if not len(self.subWindowList()):  # Nothing is open.
            # Build a menu suitable for the startup screen.
            menu = QMenu(self)
            menu.addAction(mainWin.actionHash["ACTION_new"])
            menu.addAction(mainWin.actionHash["ACTION_open"])
            menu.addAction(mainWin.actionHash["ACTION_settingsdialog"])
            menu.addAction(mainWin.actionHash["ACTION_help"])
            menu.addAction(mainWin.actionHash["ACTION_about"])
            menu.addAction(mainWin.actionHash["ACTION_exit"])
            menu.popup(self.mapToGlobal(event.pos()))
            # menu.exec_(self.mapToGlobal(event.pos()))
        else:
            # Build a menu suitable for when the mdi workspace is open.
            mainWin.fileMenu.popup(self.mapToGlobal(event.pos()))

        event.accept()
        qDebug("QMdiArea contextMenuEvent")

    def doSetDocumentMode(self, enabled=False):
        """
        Set the document mode for :class:`MDIArea`.

        :param `enabled`: Whether the tab bar is set to document mode in tabbed view mode.
         Document mode is disabled by default.
        :type `enabled`: bool
        """
        self.setDocumentMode(enabled)

    # Slots ------------------------------------------------------------------

    @Slot()
    def cascade(self):
        """
        TOWRITE
        """
        self.cascadeSubWindows()
        self.zoomExtentsAllSubWindows()

    @Slot()
    def tile(self):
        """
        TOWRITE
        """
        self.tileSubWindows()
        self.zoomExtentsAllSubWindows()