Пример #1
0
class LabelCompartilharImagemRemoto(QLabel):
    def __init__(self, ip, parent=None):
        super().__init__(parent)
        
        self.setAcceptDrops(True)
        self.setText("Arraste e solte uma imagem aqui")

        self._pixmap = None
        
        self._servicoCompartilhar = CompartilharImagemRemoto()
        self._servicoCompartilhar.setPara(ip)
        self._servicoCompartilhar.imagemRecebida.connect(self._mostrarImagem)
        
    def _mostrarImagem(self, imagem):
        self.setPixmap(imagem)
        
    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            url = event.mimeData().urls()[0].toString().strip("file:///")
            
            self._pixmap = QPixmap()
            self._pixmap.load(url)
            if not self._pixmap.isNull():
                event.acceptProposedAction()
    
    def dropEvent(self, event):
        #self.setPixmap(self._pixmap)
        self._servicoCompartilhar.enviarImagem(self._pixmap)
Пример #2
0
class WeatherWidget(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        http = QNetworkAccessManager()
        self.weatherText = self.trUtf8("正在查询天气情况...")
        self.pixmap = QPixmap()
        self.setContextMenuPolicy(Qt.ActionsContextMenu)
#        self.actionConfigure=QAction(QIcon(":/images/configure.png"), self.trUtf8("配置(&C)..."), None)
#        self.actionConfigure.triggered.connect(self.configure)
#        self.addAction(self.actionConfigure)
        self.provider = LiqweiProvider(http)
        self.provider.gotResult.connect(self.setResult)

    def paintEvent(self, event):
        QWidget.paintEvent(self, event)
        painter = QPainter(self)
        painter.drawText(self.rect(), Qt.AlignLeft | Qt.AlignVCenter, self.weatherText)
        if not self.pixmap.isNull():
            r = self.pixmap.rect()
            r.moveTop(5)
            r.moveRight(self.width() - 5)
            painter.drawPixmap(r, self.pixmap)

    def setResult(self, text, pixmapPath):
        self.weatherText = text
        self.pixmap = QPixmap(pixmapPath)
        self.update()
Пример #3
0
class WeatherWidget(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        http = QNetworkAccessManager()
        self.weatherText = self.trUtf8("正在查询天气情况...")
        self.pixmap = QPixmap()
        self.setContextMenuPolicy(Qt.ActionsContextMenu)
        #        self.actionConfigure=QAction(QIcon(":/images/configure.png"), self.trUtf8("配置(&C)..."), None)
        #        self.actionConfigure.triggered.connect(self.configure)
        #        self.addAction(self.actionConfigure)
        self.provider = LiqweiProvider(http)
        self.provider.gotResult.connect(self.setResult)

    def paintEvent(self, event):
        QWidget.paintEvent(self, event)
        painter = QPainter(self)
        painter.drawText(self.rect(), Qt.AlignLeft | Qt.AlignVCenter,
                         self.weatherText)
        if not self.pixmap.isNull():
            r = self.pixmap.rect()
            r.moveTop(5)
            r.moveRight(self.width() - 5)
            painter.drawPixmap(r, self.pixmap)

    def setResult(self, text, pixmapPath):
        self.weatherText = text
        self.pixmap = QPixmap(pixmapPath)
        self.update()
Пример #4
0
    def getPixmap(self, key):
        """
        Public method to retrieve a pixmap.

        @param key name of the wanted pixmap (string)
        @return the requested pixmap (QPixmap)
        """
        print(key)
        if key:
            try:
                return self.pixmapCache[key]
            except KeyError:

                if not os.path.isabs(key):
                    print(self.searchPath)
                    for path in self.searchPath:
                        fileName = path + "/" + key
                        print("%s, %s",path, fileName)
                        pm = QPixmap(fileName)
                        if not pm.isNull():
                            break
                    else:
                        pm = QPixmap()
                else:
                    pm = QPixmap(key)
                self.pixmapCache[key] = pm
                return self.pixmapCache[key]
        return QPixmap()
Пример #5
0
    def dump(self):
        super(FilenameImageWidget, self).dump()
        filename = self.get_actual_filename()
#        if filename and
        img = QPixmap(filename)
        if img.isNull():
            img = QPixmap(":/icons/does-not-exist.png")
        self._viewer.setPixmap(img)
Пример #6
0
class GraphicsPixmapWidget(QGraphicsWidget):
    """
    A QGraphicsWidget displaying a QPixmap
    """
    def __init__(self, pixmap=None, parent=None):
        super().__init__(parent)
        self.setCacheMode(QGraphicsItem.ItemCoordinateCache)
        self._pixmap = QPixmap(pixmap) if pixmap is not None else QPixmap()
        self._keepAspect = True
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    def setPixmap(self, pixmap):
        self._pixmap = QPixmap(pixmap)
        self.updateGeometry()
        self.update()

    def pixmap(self):
        return QPixmap(self._pixmap)

    def setKeepAspectRatio(self, keep):
        if self._keepAspect != keep:
            self._keepAspect = bool(keep)
            self.update()

    def keepAspectRatio(self):
        return self._keepAspect

    def setGeometry(self, rect):
        self.prepareGeometryChange()
        super().setGeometry(rect)

    def sizeHint(self, which, constraint=QSizeF()):
        if which == Qt.PreferredSize:
            return QSizeF(self._pixmap.size())
        else:
            return QGraphicsWidget.sizeHint(self, which, constraint)

    def paint(self, painter, option, widget=0):
        if self._pixmap.isNull():
            return

        rect = self.contentsRect()
        pixsize = QSizeF(self._pixmap.size())
        aspectmode = (Qt.KeepAspectRatio if self._keepAspect
                      else Qt.IgnoreAspectRatio)
        pixsize.scale(rect.size(), aspectmode)
        pixrect = QRectF(QPointF(0, 0), pixsize)
        pixrect.moveCenter(rect.center())

        painter.save()
        painter.setPen(QPen(QColor(0, 0, 0, 50), 3))
        painter.drawRoundedRect(pixrect, 2, 2)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)
        source = QRectF(QPointF(0, 0), QSizeF(self._pixmap.size()))
        painter.drawPixmap(pixrect, self._pixmap, source)
        painter.restore()
Пример #7
0
    def resetPhoto(self):
        QgsMessageLog.logMessage("In formCamera::resetPhoto ... ",
                                 tag="TOMs panel")

        pixmap = QPixmap(self.currFileName)
        if pixmap.isNull():
            pass
        else:
            self.FIELD.setPixmap(pixmap)
            self.FIELD.setScaledContents(True)
Пример #8
0
 def setLogo( self, logo ):
     """
     Sets the logo image for this dialog
     
     :param      logo | <QPixmap> || <str>
     """
     if ( isinstance(logo, basestring) ):
         logo = QPixmap(logo)
     
     self.uiLogoLBL.setHidden(logo.isNull())
     self.uiLogoLBL.setPixmap(logo)
Пример #9
0
    def setLogo(self, logo):
        """
        Sets the logo image for this dialog
        
        :param      logo | <QPixmap> || <str>
        """
        if (isinstance(logo, basestring)):
            logo = QPixmap(logo)

        self.uiLogoLBL.setHidden(logo.isNull())
        self.uiLogoLBL.setPixmap(logo)
Пример #10
0
 def get_icon(character):
     if character["altname"]:
         char = character["altname"]
     else:
         char = character["name"]
     char = char.replace(" ", "_")
     pixmap = QPixmap("://icons/%s.png" % char)
     if not pixmap.isNull():
         return QIcon(pixmap)
     else:
         return None
Пример #11
0
 def get_icon(character):
     if character["altname"]:
         char = character["altname"]
     else:
         char = character["name"]
     char = char.replace(" ", "_")
     pixmap = QPixmap("://icons/%s.png" % char)
     if not pixmap.isNull():
         return QIcon(pixmap)
     else:
         return None
Пример #12
0
 def _themeIcon(fileName):
   pix = QPixmap(qgis.core.QgsApplication.defaultThemePath()+"/"+fileName)
   if not pix.isNull():
       return QIcon(pix)
   # mapping from QGIS 2.0 icon file names to QGIS 1.x
   alternatives = { "/mActionOptions.svg" : "/mActionOptions.png",
     "/mActionFileSaveAs.svg" : "/mActionFileSaveAs.png", "/mActionFileOpen.svg" : "/mActionFileOpen.png",
     "/mActionSignPlus.png" : "/symbologyAdd.png", "/mActionSignMinus.png" : "/symbologyRemove.png" }
   if fileName in alternatives:
     return QIcon(qgis.core.QgsApplication.defaultThemePath()+"/"+alternatives[fileName])
   else:
     return QIcon()
Пример #13
0
    def loadImage(self, inputFile):
        self._setStatusLabel('load', ProcessStatus.Running)
        if (not inputFile.exists()):
            self._showStatus('ERROR: Input file not found! File path was ' +
                             inputFile.absoluteFilePath())
            self._setStatusLabel('load', ProcessStatus.Failure)
            return False

        self._inputFile = inputFile
        pixmap = QPixmap(self._inputFile.absoluteFilePath())
        if pixmap.isNull():
            self._signalError('Loading of raw image failed.')
            return

        pixmap = QPixmap(self._inputFile.absoluteFilePath())
        w = pixmap.width()
        h = pixmap.height()

        self._scene.addPixmap(pixmap)
        self._scene.setSceneRect(QRectF(0, 0, w, h))

        self.planView.setSceneView(self._scene, QRectF(0, 0, w, h))
        self.headerView.setSceneView(self._scene, QRectF(0, 0, w, 200))
        self.footerView.setSceneView(self._scene,
                                     QRectF(100, h - 600, w - 200, 500))

        self.gcpWidget1.setScene(self._scene, 250, 100, 2)
        self.gcpWidget2.setScene(self._scene, 250, 3050, 2)
        self.gcpWidget3.setScene(self._scene, 3200, 3050, 2)
        self.gcpWidget4.setScene(self._scene, 3200, 100, 2)

        self.inputFileNameLabel.setText(self._inputFile.baseName())
        drawing = Drawing(self._inputFile)
        if drawing.isValid():
            self.siteEdit.setText(drawing.item().siteCode())
            self.typeCombo.setCurrentIndex(
                self.typeCombo.findData(drawing.item().classCode()))
            self.numberSpin.setValue(int(drawing.item().itemId()) or 0)
            self.eastSpin.setValue(drawing.easting() or 0)
            self.northSpin.setValue(drawing.northing() or 0)
            self.suffixEdit.setText(drawing.suffix())
            self._updateFileNames(drawing)
            self._updateGeoPoints()
            pointFile = self.pointFileInfo()
            if pointFile.exists():
                self._loadGcp(pointFile.absoluteFilePath())
            self._setStatusLabel('load', ProcessStatus.Success)
            QCoreApplication.processEvents()
            return True

        return False
Пример #14
0
class GraphicsPixmapWidget(QGraphicsWidget):

    def __init__(self, pixmap, parent=None):
        QGraphicsWidget.__init__(self, parent)
        self.setCacheMode(QGraphicsItem.ItemCoordinateCache)
        self._pixmap = pixmap
        self._pixmapSize = QSizeF()
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    def setPixmap(self, pixmap):
        if self._pixmap != pixmap:
            self._pixmap = QPixmap(pixmap)
            self.updateGeometry()

    def pixmap(self):
        return QPixmap(self._pixmap)

    def setPixmapSize(self, size):
        if self._pixmapSize != size:
            self._pixmapSize = QSizeF(size)
            self.updateGeometry()

    def pixmapSize(self):
        if self._pixmapSize.isValid():
            return QSizeF(self._pixmapSize)
        else:
            return QSizeF(self._pixmap.size())

    def sizeHint(self, which, constraint=QSizeF()):
        if which == Qt.PreferredSize:
            return self.pixmapSize()
        else:
            return QGraphicsWidget.sizeHint(self, which, constraint)

    def paint(self, painter, option, widget=0):
        if self._pixmap.isNull():
            return

        rect = self.contentsRect()

        pixsize = self.pixmapSize()
        pixrect = QRectF(QPointF(0, 0), pixsize)
        pixrect.moveCenter(rect.center())

        painter.save()
        painter.setPen(QPen(QColor(0, 0, 0, 50), 3))
        painter.drawRoundedRect(pixrect, 2, 2)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)
        source = QRectF(QPointF(0, 0), QSizeF(self._pixmap.size()))
        painter.drawPixmap(pixrect, self._pixmap, source)
        painter.restore()
Пример #15
0
class GraphicsPixmapWidget(QGraphicsWidget):
    def __init__(self, pixmap, parent=None):
        QGraphicsWidget.__init__(self, parent)
        self.setCacheMode(QGraphicsItem.ItemCoordinateCache)
        self._pixmap = pixmap
        self._pixmapSize = QSizeF()
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    def setPixmap(self, pixmap):
        if self._pixmap != pixmap:
            self._pixmap = QPixmap(pixmap)
            self.updateGeometry()

    def pixmap(self):
        return QPixmap(self._pixmap)

    def setPixmapSize(self, size):
        if self._pixmapSize != size:
            self._pixmapSize = QSizeF(size)
            self.updateGeometry()

    def pixmapSize(self):
        if self._pixmapSize.isValid():
            return QSizeF(self._pixmapSize)
        else:
            return QSizeF(self._pixmap.size())

    def sizeHint(self, which, constraint=QSizeF()):
        if which == Qt.PreferredSize:
            return self.pixmapSize()
        else:
            return QGraphicsWidget.sizeHint(self, which, constraint)

    def paint(self, painter, option, widget=0):
        if self._pixmap.isNull():
            return

        rect = self.contentsRect()

        pixsize = self.pixmapSize()
        pixrect = QRectF(QPointF(0, 0), pixsize)
        pixrect.moveCenter(rect.center())

        painter.save()
        painter.setPen(QPen(QColor(0, 0, 0, 50), 3))
        painter.drawRoundedRect(pixrect, 2, 2)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)
        source = QRectF(QPointF(0, 0), QSizeF(self._pixmap.size()))
        painter.drawPixmap(pixrect, self._pixmap, source)
        painter.restore()
Пример #16
0
    def loadImage(self, inputFile):
        self._setStatusLabel('load', ProcessStatus.Running)
        if (not inputFile.exists()):
            self._showStatus('ERROR: Input file not found! File path was ' + inputFile.absoluteFilePath())
            self._setStatusLabel('load', ProcessStatus.Failure)
            return False

        self._inputFile = inputFile
        pixmap = QPixmap(self._inputFile.absoluteFilePath())
        if pixmap.isNull():
            self._signalError('Loading of raw image failed.')
            return

        pixmap = QPixmap(self._inputFile.absoluteFilePath())
        w = pixmap.width()
        h = pixmap.height()

        self._scene.addPixmap(pixmap)
        self._scene.setSceneRect(QRectF(0, 0, w, h))

        self.planView.setSceneView(self._scene, QRectF(0, 0, w, h))
        self.headerView.setSceneView(self._scene, QRectF(0, 0, w, 200))
        self.footerView.setSceneView(self._scene, QRectF(100, h - 600, w - 200, 500))

        self.gcpWidget1.setScene(self._scene, 250, 100, 2)
        self.gcpWidget2.setScene(self._scene, 250, 3050, 2)
        self.gcpWidget3.setScene(self._scene, 3200, 3050, 2)
        self.gcpWidget4.setScene(self._scene, 3200, 100, 2)

        self.inputFileNameLabel.setText(self._inputFile.baseName())
        drawing = Drawing(self._inputFile)
        if drawing.isValid():
            self.siteEdit.setText(drawing.item().siteCode())
            self.typeCombo.setCurrentIndex(self.typeCombo.findData(drawing.item().classCode()))
            self.numberSpin.setValue(int(drawing.item().itemId()) or 0)
            self.eastSpin.setValue(drawing.easting() or 0)
            self.northSpin.setValue(drawing.northing() or 0)
            self.suffixEdit.setText(drawing.suffix())
            self._updateFileNames(drawing)
            self._updateGeoPoints()
            pointFile = self.pointFileInfo()
            if pointFile.exists():
                self._loadGcp(pointFile.absoluteFilePath())
            self._setStatusLabel('load', ProcessStatus.Success)
            QCoreApplication.processEvents()
            return True

        return False
Пример #17
0
                    def set_pixmap(thumb=thumbnail, future=future):
                        if future.cancelled():
                            return
                        if future.exception():
                            # Should be some generic error image.
                            pixmap = QPixmap()
                            thumb.setToolTip(thumb.toolTip() + "\n" +
                                             str(future.exception()))
                        else:
                            pixmap = QPixmap.fromImage(future.result())

                        thumb.setPixmap(pixmap)
                        if not pixmap.isNull():
                            thumb.setThumbnailSize(self.pixmapSize(pixmap))

                        self._updateStatus(future)
Пример #18
0
                    def set_pixmap(thumb=thumbnail, future=future):
                        if future.cancelled():
                            return
                        if future.exception():
                            # Should be some generic error image.
                            pixmap = QPixmap()
                            thumb.setToolTip(thumb.toolTip() + "\n" +
                                             str(future.exception()))
                        else:
                            pixmap = QPixmap.fromImage(future.result())

                        thumb.setPixmap(pixmap)
                        if not pixmap.isNull():
                            thumb.setThumbnailSize(self.pixmapSize(pixmap))

                        self._updateStatus(future)
Пример #19
0
    def _showCurrentPicture(self, selRow):
        '''Show current selected item's picture'''
        selRow = selRow()
        model = self.ui.listData.model()
        picPath = model.data(model.createIndex(selRow, model.getPicRowIndex())).toString()
        #self.ui.pictureShow.setText(u'选择了第%d列, 地址为:%s'%(selRow, picData))
        #TODO: using QPixelMap to load and show the image for correct scale

        picShow = self.ui.pictureShow
        pixmap = QPixmap(picPath)
        if pixmap.isNull():
            picShow.setText(u'第%d行数据对应的图片\n[%s]\n\n无法加载显示!'%(selRow, picPath))
        else:
            rect = picShow.frameRect()
            pixmap.scaled(rect.width(), rect.height(), Qt.KeepAspectRatioByExpanding)
            self.ui.pictureShow.setPixmap(pixmap)
Пример #20
0
def mapCanvas_saveAsImage(iface, request):
    """
    Return the currently visible content of the map canvas as an image.

    HTTP query arguments:
        format (optional): any image format string supported by QGIS' (default: 'png', other options e.g. 'jpeg')

    Returns:
        An image the same size as the currently visible map canvas. The content-type of the response is set to 'image/' + format.
    """
    ext = request.args.get('format', 'png')
    tmpfile, tmpfilename = mkstemp('.' + ext)
    os.close(tmpfile)

    # if either is unspecified or otherwise invalid, QGIS display size is used
    pixmap = QPixmap(int(request.args.get('width', 0)), int(request.args.get('height', 0)))
    if pixmap.isNull():
        pixmap = None

    # if the canvas has been modified very recently, it might not be done
    # re-rendering yet... current fix (from QGIS 3 we could simply use:
    # iface.mapCanvas().waitWhileRendering()
    loop = QEventLoop()
    iface.mapCanvas().mapCanvasRefreshed.connect(loop.quit)
    # trigger repaint
    iface.mapCanvas().refresh() # could use refreshAllLayers() to empty cache too
    # wait
    loop.exec_()
    # all good
    iface.mapCanvas().mapCanvasRefreshed.disconnect(loop.quit)

    # doesn't provide status information about success of writing, have to
    # check file size below
    iface.mapCanvas().saveAsImage(tmpfilename, pixmap, ext)

    with open(tmpfilename, 'r') as content_file:
        imagedata = content_file.read()
    os.remove(tmpfilename)
    # TODO QGIS also writes a 'world file' (same filename + 'w' at the end)?

    if len(imagedata) == 0:
        raise IOError('Failed to write canvas contents in format ' + ext)

    # FIXME format = 'jpg' generates image correctly but has incorrect MIMEtype
    return NetworkAPIResult(imagedata, content_type='image/' + ext.lower())
Пример #21
0
def crop_pixmaps(path, mask, pretend=False):
    """ crop all pixmaps in a dir according to a masks.  This function
    does nothing in regards to validating modules. If the pixmaps
    exist and an entry exists in masks, the pixmaps get chopped.
    """
    from PyQt4.QtGui import QPixmap
    for fname in os.listdir(path):
        if extension(fname) == 'png':
            fpath = os.path.join(path, fname)
            pixmap = QPixmap(fpath)
            x, y, w, h = mask[0], mask[1], mask[2], mask[3]
            if pixmap.isNull() is False and \
               pixmap.width() > w and \
               pixmap.height() > h:
                pixmap = pixmap.copy(x, y, w, h)
                if pretend:
                    print 'PRETEND:',
                else:
                    pixmap.save(fpath, 'PNG')
                print 'wrote %s x=%i y=%i w=%i h=%i' % (fpath, x, y, w, h)
Пример #22
0
 def _runCropStep(self):
     if self._debug:
         debug('Crop')
     self._step = Georeferencer.Crop
     self._args = []
     self._command = ''
     pixmap = QPixmap(self._rawFile.absoluteFilePath())
     if pixmap.isNull():
         self._signalError('Loading of raw image failed.')
         return
     pixmap = pixmap.copy(0, 0, pixmap.width(), int(pixmap.height() * 0.84))
     image = pixmap.toImage()
     if image.isNull():
         self._signalError('Cropping of raw image failed.')
         return
     if not image.save(self._cropFile.absoluteFilePath(), 'PNG', 100):
         self._signalError('Saving of cropped image failed.')
         return
     self._signalStatus()
     self._runTranslateStep()
Пример #23
0
    def paint(self, painter, option, index):
        filePath = self.model.filePath(index)
        fileName = self.model.fileName(index)
        r = option.rect

        img = QPixmap(filePath)
        if img.isNull():
            # If not image file, try to load icon with QFileIconProvider
            # according to file type (extension name).
            # Currently not work as intended.
            fileInfo = self.model.fileInfo(index)
            icon = QFileIconProvider().icon(fileInfo)
            img = icon.pixmap(QSize(32, 32))

        # Scale to height, align center horizontally, align bottom vertically.
        if img.height() > self.thumbHeight:
            img = img.scaledToHeight(self.thumbHeight, Qt.SmoothTransformation)
        if img.width() > self.thumbHeight:
            img = img.scaledToWidth(self.thumbHeight, 
                    Qt.SmoothTransformation)
        imgLeft = (self.width - img.width()) / 2
        imgTop = self.thumbHeight - img.height()
        painter.drawPixmap(r.left()+imgLeft, r.top()+imgTop, img)

        rect = QRect(r.left(), r.top()+self.thumbHeight,
                     self.width, self.nameHeight)
        flag = Qt.AlignHCenter | Qt.TextWrapAnywhere
        # get the bounding rectangle of the fileName
        bdRect = painter.boundingRect(rect, flag, fileName)
        if bdRect.height() < rect.height():
            rect = bdRect

        if option.state & QStyle.State_Selected:
            painter.setBrush(self.parent().palette().highlight())
            painter.drawRoundedRect(rect, 5, 5)
            pen = QPen(self.parent().palette().highlightedText(), 1, Qt.SolidLine)
        else:
            pen = QPen(self.parent().palette().text(), 1, Qt.SolidLine)

        painter.setPen(pen)
        painter.drawText(rect, flag, fileName)
Пример #24
0
    def paint(self, painter, option, index):
        filePath = self.model.filePath(index)
        fileName = self.model.fileName(index)
        r = option.rect

        img = QPixmap(filePath)
        if img.isNull():
            # If not image file, try to load icon with QFileIconProvider
            # according to file type (extension name).
            # Currently not work as intended.
            fileInfo = self.model.fileInfo(index)
            icon = QFileIconProvider().icon(fileInfo)
            img = icon.pixmap(QSize(32, 32))

        # Scale to height, align center horizontally, align bottom vertically.
        if img.height() > self.thumbHeight:
            img = img.scaledToHeight(self.thumbHeight, Qt.SmoothTransformation)
        if img.width() > self.thumbHeight:
            img = img.scaledToWidth(self.thumbHeight, Qt.SmoothTransformation)
        imgLeft = (self.width - img.width()) / 2
        imgTop = self.thumbHeight - img.height()
        painter.drawPixmap(r.left() + imgLeft, r.top() + imgTop, img)

        rect = QRect(r.left(),
                     r.top() + self.thumbHeight, self.width, self.nameHeight)
        flag = Qt.AlignHCenter | Qt.TextWrapAnywhere
        # get the bounding rectangle of the fileName
        bdRect = painter.boundingRect(rect, flag, fileName)
        if bdRect.height() < rect.height():
            rect = bdRect

        if option.state & QStyle.State_Selected:
            painter.setBrush(self.parent().palette().highlight())
            painter.drawRoundedRect(rect, 5, 5)
            pen = QPen(self.parent().palette().highlightedText(), 1,
                       Qt.SolidLine)
        else:
            pen = QPen(self.parent().palette().text(), 1, Qt.SolidLine)

        painter.setPen(pen)
        painter.drawText(rect, flag, fileName)
Пример #25
0
    def setIcon(self, icon):
        """
        Set the message icon.

        :type icon: QIcon | QPixmap | QString | QStyle.StandardPixmap
        """
        if isinstance(icon, QStyle.StandardPixmap):
            icon = self.style().standardIcon(icon)
        else:
            icon = QIcon(icon)

        if self.__icon != icon:
            self.__icon = QIcon(icon)
            if not self.__icon.isNull():
                size = self.style().pixelMetric(
                    QStyle.PM_SmallIconSize, None, self)
                pm = self.__icon.pixmap(QSize(size, size))
            else:
                pm = QPixmap()

            self.__iconlabel.setPixmap(pm)
            self.__iconlabel.setVisible(not pm.isNull())
Пример #26
0
    def findIconHelper(self, size=int, themeName=str, iconName=str):
        pixmap = QPixmap()

        if iconName == '' or self.themeName == '':
            return pixmap

        if themeName == '':
            themeName = self.themeName

        if themeName == self.themeName:
            index = self.themeIndex
        else:
            index = self.readThemeIndex(themeName)

        subDirs = filter(lambda x: x[0] == size, index.dirList)
        for iconDir in self.iconDirs:
            if path.exists(path.join(iconDir, themeName)):
                for theme in subDirs:
                    fileName = path.join(iconDir, themeName, theme[1],
                                         '%s.png' % str(iconName))
                    logging.debug('Looking for : %s' % fileName)
                    if path.exists(fileName):
                        pixmap.load(fileName)
                        logging.debug('Icon: %s found in theme %s' % \
                                (iconName, themeName))
                        return pixmap

        for iconDir in self.extraIcons:
            fileName = path.join(iconDir, '%s.png' % str(iconName))
            if path.exists(fileName):
                pixmap.load(fileName)
                logging.debug('Icon: %s found in %s' % (iconName, iconDir))
                return pixmap

        if len(self._themes) > 0:
            self._themes.pop(0)
            if not len(self._themes) == 0 and pixmap.isNull():
                pixmap = self.findIconHelper(size, self._themes[0], iconName)
        return pixmap
Пример #27
0
    def findIconHelper(self, size = int, themeName = str, iconName = str):
        pixmap = QPixmap()

        if iconName == '' or self.themeName == '':
            return pixmap

        if themeName == '':
            themeName = self.themeName

        if themeName == self.themeName:
            index = self.themeIndex
        else:
            index = self.readThemeIndex(themeName)

        subDirs = filter(lambda x:x[0] == size, index.dirList)
        for iconDir in self.iconDirs:
            if path.exists(path.join(iconDir, themeName)):
                for theme in subDirs:
                    fileName = path.join(iconDir, themeName, theme[1],
                            '%s.png' % str(iconName))
                    logging.debug('Looking for : %s' % fileName)
                    if path.exists(fileName):
                        pixmap.load(fileName)
                        logging.debug('Icon: %s found in theme %s' % \
                                (iconName, themeName))
                        return pixmap

        for iconDir in self.extraIcons:
            fileName = path.join(iconDir, '%s.png' % str(iconName))
            if path.exists(fileName):
                pixmap.load(fileName)
                logging.debug('Icon: %s found in %s' % (iconName, iconDir))
                return pixmap

        if len(self._themes) > 0:
            self._themes.pop(0)
            if not len(self._themes) == 0 and pixmap.isNull():
                pixmap = self.findIconHelper(size, self._themes[0], iconName)
        return pixmap
Пример #28
0
 def viewurl(self, url):
     """
     Open a URL in Roam
     :param url:
     :return:
     """
     key = url.toString().lstrip('file://')
     try:
         # Hack. Eww fix me.
         data, imagetype = roam.htmlviewer.images[os.path.basename(key)]
         pix = QPixmap()
         if imagetype == 'base64':
             pix.loadFromData(data)
         else:
             pix.load(data)
         self.openimage(pix)
     except KeyError:
         pix = QPixmap()
         pix.load(key)
         if pix.isNull():
             QDesktopServices.openUrl(url)
             return
         self.openimage(pix)
Пример #29
0
 def viewurl(self, url):
     """
     Open a URL in Roam
     :param url:
     :return:
     """
     key = url.toString().lstrip('file://')
     try:
         # Hack. Eww fix me.
         data, imagetype = roam.htmlviewer.images[os.path.basename(key)]
         pix = QPixmap()
         if imagetype == 'base64':
             pix.loadFromData(data)
         else:
             pix.load(data)
         self.openimage(pix)
     except KeyError:
         pix = QPixmap()
         pix.load(key)
         if pix.isNull():
             QDesktopServices.openUrl(url)
             return
         self.openimage(pix)
Пример #30
0
class MainUI(QtGui.QMainWindow):
    BUTTON_IMAGE = 'im.png'

    def __init__(self, *args):
        QtGui.QMainWindow.__init__(self)
        self.pix=None
	self.flag=0
        self.resize(350, 140)
        self.initButton(self)
        self.connect(self.ImageButton, QtCore.SIGNAL('clicked()'), self.buttonClicked)
        #self.connect(self.pushButton, QtCore.SIGNAL('clicked()'), self.proceed)

    def initButton(self,MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(550, 600)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Kinnari"))
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setWordWrap(False)
        self.label.setMargin(1)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.widget = QtGui.QWidget(self.centralwidget)
        self.widget.setEnabled(True)
        self.widget.setMinimumSize(QtCore.QSize(800,450))
        self.widget.setSizeIncrement(QtCore.QSize(0, 0))
        self.widget.setObjectName(_fromUtf8("widget"))
        self.gridLayout = QtGui.QGridLayout(self.widget)
        self.gridLayout.setMargin(0)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        #self.label_3 = ExtendedQLabel(self.widget)
        self.ImageButton = ExtendedQLabel(self.widget)
        #self.ImageButton.move(0, 0)
        self.ImageButton.setPixmap(QtGui.QPixmap(self.BUTTON_IMAGE))
        #self.ImageButton.setGeometry(QtCore.QRect(0, 0, 1000, 1000))
        self.ImageButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.ImageButton.setText(_fromUtf8(""))
        self.ImageButton.setObjectName(_fromUtf8("ImageButton"))
        self.ImageButton.setScaledContents(True)

        self.verticalLayout.addWidget(self.widget)
        self.gridLayout.addWidget(self.ImageButton, 0, 0, 1, 1)
        self.pushButton = QtGui.QCommandLinkButton(self.centralwidget)
        self.pushButton.setMaximumSize(QtCore.QSize(100, 16777215))
        self.pushButton.setObjectName(_fromUtf8("commandLinkButton"))
        self.pushButton.setLayoutDirection(QtCore.Qt.RightToLeft)
        self.verticalLayout.addWidget(self.pushButton, QtCore.Qt.AlignRight)
        self.pushButton.clicked.connect(self.proceed)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def buttonClicked(self):
        self.file_name = QtGui.QFileDialog.getOpenFileName(self, "Pick a folder")
        self.pix = QPixmap(self.file_name)
        if not self.pix.isNull():
            self.ImageButton.setPixmap(self.pix)
            self.flag=1

        else:
             self.ImageButton.setPixmap(QtGui.QPixmap(self.BUTTON_IMAGE))
             mBox=QMessageBox()
             mBox.setText("Not a Valid Image or Image Not Selected!")
             mBox.setWindowTitle("ERROR")
             mBox.setStandardButtons(QMessageBox.Ok)
             mBox.exec_()


    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.label.setText(_translate("MainWindow", "IMAGE BASED SEARCH", None))
        self.pushButton.setText(_translate("MainWindow", "Proceed", None))

    def proceed(self):
      if self.flag==1 and not self.pix.isNull() :
        self.list = []
        mpath="/home/aparna/4thsem/pop/ooad/pics_sift"
        print time.ctime()
        for f in os.listdir(mpath):
            print f
            res=sift.compare(str(os.path.join(mpath,f)),str(self.file_name),0)
            print time.ctime()
            if res >=8:
                self.list.append((str(os.path.join(mpath,f)),res))
            
        self.list=sorted(self.list,key=lambda x:x[1],reverse=True)
        for i in self.list:
          print i
        if len(self.list)!=0 :
          p1 = Ui_MainWindow(self.pix, self.list,self.file_name)
          p1.run(self.pix,self.list,self.file_name)
          #self.close()
        """app1 = QtGui.QApplication(sys.argv)
        print "Hi ..."
        form1 = Ui_MainWindow.setupUi()
        #form1.show()
        print "Hity ..."
        #sys.exit(app1.exec_())"""
      else :
            mBox=QMessageBox()
            mBox.setText("Please select an image !")
            mBox.setWindowTitle("ERROR")
            mBox.setStandardButtons(QMessageBox.Ok)
            mBox.exec_()
Пример #31
0
class Dialog(QDialog):
    """A Dialog with basic layout features:
    
    a main widget,
    an icon or pixmap,
    a separator,
    buttons (provided by a QDialogButtonBox)
    
    """
    def __init__(self,
                 parent = None,
                 message = "",
                 title = "",
                 icon = None,
                 iconSize = QSize(64, 64),
                 pixmap = None,
                 separator = True,
                 buttonOrientation = Qt.Horizontal,
                 buttons = ('ok', 'cancel'),
                 help = None,
                 **kwargs):
        """Initializes the dialog.
        
        parent = a parent widget or None.
        
        The following keyword arguments are recognized:
        - message: the text to display in the message label
        - title: the window title
        - icon or pixmap: shown in the left area
        - iconSize: size of the icon in the left (QSize, default: 64x64)
        - separator: draw a separator line or not (default: True)
        - buttonOrientation: Qt.Horizontal (default) or Qt.Vertical
        - buttons: which buttons to use (default: Ok, Cancel)
        - help: function to call when a help button is clicked.
        
        Other keyword arguments are passed to QDialog.
        
        """
        super(Dialog, self).__init__(parent, **kwargs)
        self._icon = QIcon()
        self._separatorWidget = Separator()
        self._mainWidget = QWidget()
        self._pixmap = QPixmap()
        self._pixmapLabel = QLabel(self)
        self._messageLabel = QLabel(self)
        self._buttonBox = b = QDialogButtonBox(self)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        layout = QGridLayout()
        layout.setSpacing(10)
        self.setLayout(layout)
        
        # handle keyword args
        self._buttonOrientation = buttonOrientation
        self._iconSize = iconSize
        self._separator = separator
        if title:
            self.setWindowTitle(title)
        self.setMessage(message)
        if icon:
            self.setIcon(icon)
        elif pixmap:
            self.setPixmap(pixmap)
        b.helpRequested.connect(help or self.helpRequest)
        self.setStandardButtons(buttons)
        self.reLayout()
        
    def helpRequest(self):
        """Called when a help button is clicked."""
        pass
    
    def setButtonOrientation(self, orientation):
        """Sets the button orientation.
        
        Qt.Horizontal (default) puts the buttons at the bottom of the dialog
        in a horizontal row, Qt.Vertical puts the buttons at the right in a
        vertical column.
        
        """
        if orientation != self._buttonOrientation:
            self._buttonOrientation = orientation
            self._buttonBox.setOrientation(orientation)
            self.reLayout()
    
    def buttonOrientation(self):
        """Returns the button orientation."""
        return self._buttonOrientation
        
    def setIcon(self, icon):
        """Sets the icon to display in the left area.
        
        May be:
        - None or QIcon()
        - one of 'info', 'warning', 'critical', 'question'
        - a QStyle.StandardPixmap
        - a QIcon.
        
        """
        if icon in standardicons:
            icon = standardicons[icon]
        if isinstance(icon, QStyle.StandardPixmap):
            icon = self.style().standardIcon(icon)
        if icon is None:
            icon = QIcon()
        self._icon = icon
        self.setPixmap(icon.pixmap(self._iconSize))
    
    def icon(self):
        """Returns the currently set icon as a QIcon."""
        return self._icon
        
    def setIconSize(self, size):
        """Sets the icon size (QSize or int)."""
        if isinstance(size, int):
            size = QSize(size, size)
        changed = size != self._iconSize
        self._iconSize = size
        if changed and not self._icon.isNull():
            self.setPixmap(self._icon.pixmap(size))
    
    def iconSize(self):
        """Returns the icon size (QSize)."""
        return self._iconSize
        
    def setPixmap(self, pixmap):
        """Sets the pixmap to display in the left area."""
        changed = self._pixmap.isNull() != pixmap.isNull()
        self._pixmap = pixmap
        self._pixmapLabel.setPixmap(pixmap)
        if not pixmap.isNull():
            self._pixmapLabel.setFixedSize(pixmap.size())
        if changed:
            self.reLayout()
        
    def pixmap(self):
        """Returns the currently set pixmap."""
        return self._pixmap
    
    def setMessage(self, text):
        """Sets the main text in the dialog."""
        self._messageLabel.setText(text)
    
    def message(self):
        """Returns the main text."""
        return self._messageLabel.text()
    
    def messageLabel(self):
        """Returns the QLabel displaying the message text."""
        return self._messageLabel
        
    def buttonBox(self):
        """Returns our QDialogButtonBox instance."""
        return self._buttonBox
    
    def setStandardButtons(self, buttons):
        """Convenience method to set standard buttons in the button box.
        
        Accepts a sequence of string names from the standardbuttons constant,
        or a QDialogButtonBox.StandardButtons value.
        
        """
        if isinstance(buttons, (set, tuple, list)):
            buttons = functools.reduce(operator.or_,
                map(standardbuttons.get, buttons),
                QDialogButtonBox.StandardButtons())
        self._buttonBox.setStandardButtons(buttons)
    
    def button(self, button):
        """Returns the given button.
        
        May be a QDialogButtonBox.StandardButton or a key from standardbuttons.
        
        """
        if button in standardbuttons:
            button = standardbuttons[button]
        return self._buttonBox.button(button)
    
    def setSeparator(self, enabled):
        """Sets whether to show a line between contents and buttons."""
        changed = self._separator != enabled
        self._separator = enabled
        if changed:
            self.reLayout()
    
    def hasSeparator(self):
        """Returns whether a separator line is shown."""
        return self._separator
        
    def setMainWidget(self, widget):
        """Sets the specified widget as our main widget."""
        old = self._mainWidget
        if old:
            old.setParent(None)
        self._mainWidget = widget
        self.reLayout()
    
    def mainWidget(self):
        """Returns the current main widget (an empty QWidget by default)."""
        return self._mainWidget
    
    def reLayout(self):
        """(Internal) Lays out all items in this dialog."""
        layout = self.layout()
        while layout.takeAt(0):
            pass
        
        if not self._pixmap.isNull():
            col = 1
            layout.addWidget(self._pixmapLabel, 0, 0, 2, 1)
        else:
            layout.setColumnStretch(1, 0)
            col = 0
        layout.setColumnStretch(col, 1)
        self._pixmapLabel.setVisible(not self._pixmap.isNull())    
        layout.addWidget(self._messageLabel, 0, col)
        layout.addWidget(self._mainWidget, 1, col)
        if self._buttonOrientation == Qt.Horizontal:
            if self._separator:
                layout.addWidget(self._separatorWidget, 2, 0, 1, col+1)
            layout.addWidget(self._buttonBox, 3, 0, 1, col+1)
        else:
            if self._separator:
                layout.addWidget(self._separatorWidget, 0, col+1, 2, 1)
            layout.addWidget(self._buttonBox, 0, col+2, 2, 1)
        self._separatorWidget.setVisible(self._separator)
Пример #32
0
 def __init__(self):
     MaskEditor.__init__(self)
     pixmap = QPixmap(PNG)
     assert pixmap.isNull() == False
     self.setPixmap(pixmap)
     self.resize(200, 200)
Пример #33
0
class Dialog(QDialog):
    """A Dialog with basic layout features:
    
    a main widget,
    an icon or pixmap,
    a separator,
    buttons (provided by a QDialogButtonBox)
    
    """
    def __init__(self,
                 parent=None,
                 message="",
                 title="",
                 icon=None,
                 iconSize=QSize(64, 64),
                 pixmap=None,
                 separator=True,
                 buttonOrientation=Qt.Horizontal,
                 buttons=('ok', 'cancel'),
                 help=None,
                 **kwargs):
        """Initializes the dialog.
        
        parent = a parent widget or None.
        
        The following keyword arguments are recognized:
        - message: the text to display in the message label
        - title: the window title
        - icon or pixmap: shown in the left area
        - iconSize: size of the icon in the left (QSize, default: 64x64)
        - separator: draw a separator line or not (default: True)
        - buttonOrientation: Qt.Horizontal (default) or Qt.Vertical
        - buttons: which buttons to use (default: Ok, Cancel)
        - help: function to call when a help button is clicked.
        
        Other keyword arguments are passed to QDialog.
        
        """
        super(Dialog, self).__init__(parent, **kwargs)
        self._icon = QIcon()
        self._separatorWidget = Separator()
        self._mainWidget = QWidget()
        self._pixmap = QPixmap()
        self._pixmapLabel = QLabel(self)
        self._messageLabel = QLabel(self)
        self._buttonBox = b = QDialogButtonBox(self)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        layout = QGridLayout()
        layout.setSpacing(10)
        self.setLayout(layout)

        # handle keyword args
        self._buttonOrientation = buttonOrientation
        self._iconSize = iconSize
        self._separator = separator
        if title:
            self.setWindowTitle(title)
        self.setMessage(message)
        if icon:
            self.setIcon(icon)
        elif pixmap:
            self.setPixmap(pixmap)
        b.helpRequested.connect(help or self.helpRequest)
        self.setStandardButtons(buttons)
        self.reLayout()

    def helpRequest(self):
        """Called when a help button is clicked."""
        pass

    def setButtonOrientation(self, orientation):
        """Sets the button orientation.
        
        Qt.Horizontal (default) puts the buttons at the bottom of the dialog
        in a horizonzal row, Qt.Vertical puts the buttons at the right in a
        vertical column.
        
        """
        if orientation != self._buttonOrientation:
            self._buttonOrientation = orientation
            self._buttonBox.setOrientation(orientation)
            self.reLayout()

    def buttonOrientation(self):
        """Returns the button orientation."""
        return self._buttonOrientation

    def setIcon(self, icon):
        """Sets the icon to display in the left area.
        
        May be:
        - None or QIcon()
        - one of 'info', 'warning', 'critical', 'question'
        - a QStyle.StandardPixmap
        - a QIcon.
        
        """
        if icon in standardicons:
            icon = standardicons[icon]
        if isinstance(icon, QStyle.StandardPixmap):
            icon = self.style().standardIcon(icon)
        if icon is None:
            icon = QIcon()
        self._icon = icon
        self.setPixmap(icon.pixmap(self._iconSize))

    def icon(self):
        """Returns the currently set icon as a QIcon."""
        return self._icon

    def setIconSize(self, size):
        """Sets the icon size (QSize or int)."""
        if isinstance(size, int):
            size = QSize(size, size)
        changed = size != self._iconSize
        self._iconSize = size
        if changed and not self._icon.isNull():
            self.setPixmap(self._icon.pixmap(size))

    def iconSize(self):
        """Returns the icon size (QSize)."""
        return self._iconSize

    def setPixmap(self, pixmap):
        """Sets the pixmap to display in the left area."""
        changed = self._pixmap.isNull() != pixmap.isNull()
        self._pixmap = pixmap
        self._pixmapLabel.setPixmap(pixmap)
        if not pixmap.isNull():
            self._pixmapLabel.setFixedSize(pixmap.size())
        if changed:
            self.reLayout()

    def pixmap(self):
        """Returns the currently set pixmap."""
        return self._pixmap

    def setMessage(self, text):
        """Sets the main text in the dialog."""
        self._messageLabel.setText(text)

    def message(self):
        """Returns the main text."""
        return self._messageLabel.text()

    def messageLabel(self):
        """Returns the QLabel displaying the message text."""
        return self._messageLabel

    def buttonBox(self):
        """Returns our QDialogButtonBox instance."""
        return self._buttonBox

    def setStandardButtons(self, buttons):
        """Convenience method to set standard buttons in the button box.
        
        Accepts a sequence of string names from the standardbuttons constant,
        or a QDialogButtonBox.StandardButtons value.
        
        """
        if isinstance(buttons, (set, tuple, list)):
            buttons = functools.reduce(operator.or_,
                                       map(standardbuttons.get, buttons),
                                       QDialogButtonBox.StandardButtons())
        self._buttonBox.setStandardButtons(buttons)

    def button(self, button):
        """Returns the given button.
        
        May be a QDialogButtonBox.StandardButton or a key from standardbuttons.
        
        """
        if button in standardbuttons:
            button = standardbuttons[button]
        return self._buttonBox.button(button)

    def setSeparator(self, enabled):
        """Sets whether to show a line between contents and buttons."""
        changed = self._separator != enabled
        self._separator = enabled
        if changed:
            self.reLayout()

    def hasSeparator(self):
        """Returns whether a separator line is shown."""
        return self._separator

    def setMainWidget(self, widget):
        """Sets the specified widget as our main widget."""
        old = self._mainWidget
        if old:
            old.setParent(None)
        self._mainWidget = widget
        self.reLayout()

    def mainWidget(self):
        """Returns the current main widget (an empty QWidget by default)."""
        return self._mainWidget

    def reLayout(self):
        """(Internal) Lays out all items in this dialog."""
        layout = self.layout()
        while layout.takeAt(0):
            pass

        if not self._pixmap.isNull():
            col = 1
            layout.addWidget(self._pixmapLabel, 0, 0, 2, 1)
        else:
            layout.setColumnStretch(1, 0)
            col = 0
        layout.setColumnStretch(col, 1)
        self._pixmapLabel.setVisible(not self._pixmap.isNull())
        layout.addWidget(self._messageLabel, 0, col)
        layout.addWidget(self._mainWidget, 1, col)
        if self._buttonOrientation == Qt.Horizontal:
            if self._separator:
                layout.addWidget(self._separatorWidget, 2, 0, 1, col + 1)
            layout.addWidget(self._buttonBox, 3, 0, 1, col + 1)
        else:
            if self._separator:
                layout.addWidget(self._separatorWidget, 0, col + 1, 2, 1)
            layout.addWidget(self._buttonBox, 0, col + 2, 2, 1)
        self._separatorWidget.setVisible(self._separator)
Пример #34
0
class Preview(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__pixmap = QPixmap()
        # Flag indicating if the widget was resized as a result of user
        # initiated window resize. When false the widget will automatically
        # resize/re-position based on pixmap size.
        self.__hasExplicitSize = False
        self.__inUpdateWindowGeometry = False

    def setPixmap(self, pixmap):
        if self.__pixmap != pixmap:
            self.__pixmap = QPixmap(pixmap)
            self.__updateWindowGeometry()
            self.update()
            self.updateGeometry()

    def pixmap(self):
        return QPixmap(self.__pixmap)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        if self.isVisible() and self.isWindow() and \
                not self.__inUpdateWindowGeometry:
            # mark that we have an explicit user provided size
            self.__hasExplicitSize = True

    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

    def sizeHint(self):
        return self.__pixmap.size()

    def paintEvent(self, event):
        if self.__pixmap.isNull():
            return

        sourcerect = QRect(QPoint(0, 0), self.__pixmap.size())
        pixsize = QSizeF(self.__pixmap.size())
        rect = self.contentsRect()
        pixsize.scale(QSizeF(rect.size()), Qt.KeepAspectRatio)
        targetrect = QRectF(QPointF(0, 0), pixsize)
        targetrect.moveCenter(QPointF(rect.center()))
        painter = QPainter(self)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)
        painter.drawPixmap(targetrect, self.__pixmap, QRectF(sourcerect))
        painter.end()
Пример #35
0
	def __init__(self, parent=None):
		'''
		Initializes all components in the dialog.
		Whoever uses this view, and its controller,
		must letter bind the controller and the view
		using view.setController(c)
		
		The controller then will be able to access
		all the view elements with the getters
		defined in this dummy view class.
		
		The controller can also connect to events
		triggered by this dialog.
		'''
		QDialog.__init__(self)
		View.__init__(self)
		#self.createMenubar()
		#set up the fields
		
		self.setWindowTitle(i18n.LABEL_WINDOW_LOGIN_TITLE)
		imagePath = os.path.join("i18n","images","us_en") 
		self.setWindowIcon(QIcon(os.path.join(imagePath,"bloop.png")))		
		
		#Blooploader Logo
		pixmap = QPixmap(os.path.join('i18n','images','us_en','login_logo.png'))
		assert(not pixmap.isNull())
		self._logoLabel_ = QLabel()
		self._logoLabel_.setPixmap(pixmap)
		
		#login row
		self._usernameLabel_ = QLabel(i18n.LABEL_USERNAME)
		self._usernameLineEdit_ = QLineEdit()
		self._usernameWidget_ = PairedWidget(self._usernameLabel_, self._usernameLineEdit_)

		#password row
		self._passwordLabel_ = QLabel(i18n.LABEL_PASSWORD)
		self._passwordLineEdit_ = QLineEdit()
		self._passwordLineEdit_.setEchoMode(QLineEdit.Password)
		self._passWidget_ = PairedWidget(self._passwordLabel_, self._passwordLineEdit_)
		
		#remember me row
		self._rememberCheckbox_ = QCheckBox(i18n.LABEL_REMEMBER_ME)
		self._rememberWidget_= QWidget() 
		rememberLayout = QHBoxLayout()
		rememberLayout.addStretch()
		rememberLayout.addWidget(self._rememberCheckbox_)
		self._rememberWidget_.setLayout(rememberLayout)
		
		#buttons
		self._loginButton_ = QPushButton(i18n.LABEL_LOGIN)
		self._buttonsWidget_ = QHBoxLayout()
		self._buttonsWidget_.addStretch()
		self._buttonsWidget_.addWidget(self._loginButton_)

		#MyBloop.com Link at the end
		self._myBloopSiteLink_ = QLabel('<a href="http://www.mybloop.com">www.mybloop.com</a>')
		myBloopSiteLinkLayout = QHBoxLayout()
		myBloopSiteLinkLayout.addStretch()
		myBloopSiteLinkLayout.addWidget(self._myBloopSiteLink_)
		myBloopSiteLinkLayout.addStretch()
		
		#Stack em up vertically
		self._mainLayout_ = QVBoxLayout()
		self._mainLayout_.addStretch()
		self._mainLayout_.addWidget(self._logoLabel_,0,Qt.AlignCenter)
		self._mainLayout_.addWidget(self._usernameWidget_)
		self._mainLayout_.addWidget(self._passWidget_)
		self._mainLayout_.addWidget(self._rememberWidget_)
		self._mainLayout_.addLayout(self._buttonsWidget_)
		self._mainLayout_.addLayout(myBloopSiteLinkLayout)
		self._mainLayout_.addStretch()
		
		#Add another layout to show while we wait
		#put all this on a QStackedLayout
		self._passwordLineEdit_.setStyleSheet("border-style: outset; border-width: 1px; border-radius: 3px; border-color: gray; padding: 3px;")
		self._usernameLineEdit_.setStyleSheet("border-style: outset; border-width: 1px; border-radius: 3px; border-color: gray; padding: 3px;")
		self._waitLayout_ = QVBoxLayout()
		self._waitLayout_.setAlignment(Qt.AlignHCenter)

		self._waitLabel_ = QLabel()
		pixmap = QPixmap(os.path.join('i18n','images','us_en','loading.png'))
		self._waitLabel_.setPixmap(pixmap)
		self._waitLayout_.addWidget(self._waitLabel_)
		self._waitLayout_.addStretch()

		self._stackedLayout_ = QStackedLayout()

		waitWidget = QWidget()
		waitWidget.setLayout(self._waitLayout_)

		mainWidget = QWidget()
		mainWidget.setLayout(self._mainLayout_)

		self._stackedLayout_.addWidget(mainWidget)
		self._stackedLayout_.addWidget(waitWidget)

		self._stackedLayout_.setCurrentIndex(0) #main layout

		self.fillBackground()
		loginLayout = QVBoxLayout()
		loginLayout.addLayout(self._stackedLayout_)
		self.setLayout(loginLayout)
Пример #36
0
class pngDisplay(QWidget):
    def __init__(self, parent=None):
        super(pngDisplay, self).__init__(parent)
        #self.profiler = cProfile.Profile()
        # create the label that displays the image - cribbing from the Image
        # Viewer example in the Qt docs.
        self.imLabel = QLabel()
        self.imLabel.setBackgroundRole(QPalette.Base)
        self.imLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.imLabel.setScaledContents(True)
        # Create a gray field to use when no png is available
        self.defaultPM = QPixmap(700,900)
        self.defaultPM.fill(QColor("gray"))
        # Create a scroll area within which to display our imLabel, this
        # enables the creation of horizontal and vertical scroll bars, when
        # the imLabel exceeds the size of the scroll area.
        self.scarea = QScrollArea()
        # The following two lines make sure that page up/dn gets through
        # the scrollarea widget and up to us.
        self.setFocusPolicy(Qt.ClickFocus)
        self.scarea.setFocusProxy(self)
        self.scarea.setBackgroundRole(QPalette.Dark)
        #self.scarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        #self.scarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scarea.setWidget(self.imLabel)
        # create the text label that will have the page number in it
        self.txLabel = QLabel(u"No image")
        self.txLabel.setAlignment(Qt.AlignBottom | Qt.AlignHCenter)
        self.txLabel.setFrameStyle(QFrame.Sunken | QFrame.StyledPanel)
        # Create a spinbox to set the zoom from 15 to 200 with a label:
        # (originally a slider, hence the name)
        self.minZoom = 0.15
        self.maxZoom = 2.00
        self.zlider = QSpinBox()
        self.zlider.setRange(int(100*self.minZoom),int(100*self.maxZoom))
        # connect the value change signal to a slot to handle it
        self.connect(self.zlider, SIGNAL("valueChanged(int)"), self.newZoomFactor)
        # create the to-width and to-height zoom buttons
        zoomWidthButton = QPushButton(u'to Width')
        self.connect(zoomWidthButton, SIGNAL("clicked()"), self.zoomToWidth)
        zoomHeightButton = QPushButton(u'to Height')
        self.connect(zoomHeightButton, SIGNAL("clicked()"), self.zoomToHeight)
        # Make an hbox to contain the spinbox and two pushbuttons, with
        # stretch on left and right to center the group.
        zlabel = QLabel(
            u'&Zoom ' + str(self.zlider.minimum())
            + '-' + str(self.zlider.maximum()) + '%')
        zlabel.setBuddy(self.zlider)
        zhbox = QHBoxLayout()
        zhbox.addStretch(1)
        zhbox.addWidget(zlabel,0,Qt.AlignLeft)
        zhbox.addWidget(self.zlider,0)
        zhbox.addStretch(1)
        zhbox.addWidget(zoomWidthButton)
        zhbox.addWidget(zoomHeightButton)
        zhbox.addStretch(1)
        # With all the pieces in hand, create our layout basically a
        # vertical stack: scroll area, label, slider box.
        vbox = QVBoxLayout()
        # the image gets a high stretch and default alignment, the text
        # label hugs the bottom and doesn't stretch at all.
        vbox.addWidget(self.txLabel,0,Qt.AlignBottom)
        vbox.addWidget(self.scarea,10)
        vbox.addLayout(zhbox,0)
        self.setLayout(vbox)
        # Initialize assuming no book is open.
        self.ready = False # nothing to display
        # Recover the last-set zoom factor from the settings object, default 1.0
        qv = IMC.settings.value("pngs/zoomFactor",QVariant(1.0))
        self.zoomFactor = qv.toFloat()[0]
        # The following causes entry into newZoomFactor, below, which tests
        # self.ready, hence the latter has to be assigned-to first.
        self.zlider.setValue(int(self.zoomFactor*100))
        self.clear()

    # local subroutine to initialize our contents for an empty edit.
    # called from _init_ and from newPosition when we discover the file
    # has been cleared on us. Don't reset the zoomFactor, leave it as
    # the user last set it.
    def clear(self):
        # Clear the page name, used by pqNotes
        IMC.currentImageNumber = None # will be name of last png file e.g. "002"
        # Clear the page filename, used in our caption label
        self.lastPage = QString() # last file name e.g. "002.png"
        # Clear the path to the pngs folder, used to fetch image files
        self.pngPath = QString()
        # Clear the index of the last-shown page in the page table
        # -1 means no page is being displayed.
        self.lastIndex = -1
        # Clear the index of the next page to display, normally same as last
        self.nextIndex = -1
        # Set not-ready to indicate no pngs directory available.
        self.ready = False
        # Clear out & release storage of our QImage and QPixmaps
        self.pixmap = QPixmap() # null pixmap
        self.image = QImage()
        self.noImage() # show gray image

    # Display a blank gray frame and "No Image" below.
    # Called from clear() above and from showPage when no valid image.
    def noImage(self) :
        self.imLabel.setPixmap(self.defaultPM)
        self.txLabel.setText(u"No image")
        self.lastIndex = -1 # didn't see a prior page
        self.nextIndex = -1

    # This slot gets the main window's signal shuttingDown.
    # We save our current zoom factor into IMC.settings.
    def shuttingDown(self):
        IMC.settings.setValue("pngs/zoomFactor",QVariant(self.zoomFactor))

    # This slot gets pqMain's signal docHasChanged(QString), telling
    # us that a different document has been loaded. This could be for
    # a successful File>Open, or a failed File>Open or File>New.
    # The bookPath is a null QString for File>New, or the full bookPath.
    # If the latter, we convert that into the path to the pngs folder,
    # and see if bookPath/pngs is a directory. If so, we set self.ready
    # to true, indicating it is worthwhile to try opening image files.
    # At this point the gray image is displayed and previously would remain displayed
    # until the user moved the cursor in some way, generating cursorPositionChanged.
    # That's a minor annoyance, to avoid it we will fake that signal now.
    def newFile(self, bookPath):
        if not bookPath.isNull(): # this was successful File>Open
            finf = QFileInfo(bookPath)
            self.pngPath = finf.absolutePath().append(u"/pngs/")
            finf = QFileInfo(self.pngPath)
            if finf.exists() and finf.isDir(): # looking good
                self.ready = True
                self.newPosition()
            else:
                # We could inform the user we couldn't find a pngs folder,
                # but you know -- the user is probably already aware of that.
                self.clear() # just put up the gray default image
        else: # It was a File>New
            self.clear()

    # This function is the slot that is connected to the editor's
    # cursorPositionChanged signal. Its input is cursor position and
    # the page table. Its output is to set self.nextIndex to the
    # desired next image table row, and to call showPage.
    def newPosition(self):
        if self.ready :
            # We have a book and some pngs. Find the position of the higher end
            # of the current selection.
            pos = IMC.editWidget.textCursor().selectionEnd()
            # Get the page table index that matches this position, or -1
            # if that is above the first psep, or there is no page data
            self.nextIndex = IMC.pageTable.getIndex(pos)
        else :# No file loaded or no pngs folder found.
            self.nextIndex = -1
        if self.nextIndex != self.lastIndex :
            self.showPage()

    # Display the page indexed by self.nextIndex. This is called when the cursor
    # moves to a new page (newPosition, above), or when the PageUp/Dn keys are used,
    # (keyPressEvent, below) or when the zoom factor changes in any of several ways.
    def showPage(self):
        # If self.lastIndex is different from self.nextIndex, the page has
        # changed, and we need to load a new image.
        if self.lastIndex != self.nextIndex :
            self.lastIndex = self.nextIndex # don't come here again until it changes.
            if self.lastIndex > -1 :
                # Form the image filename as a Qstring, e.g. "025" and save that for
                # use by pqNotes:
                IMC.currentImageNumber = IMC.pageTable.getScan(self.lastIndex)
                # dbg = unicode(IMC.currentImageNumber)
                # Form the complete filename by appending ".png" and save as
                # self.lastPage for use in forming our caption label.
                self.lastPage = QString(IMC.currentImageNumber).append(QString(u".png"))
                # dbg = unicode(self.lastPage)
                # Form the full path to the image. Try to load it as a QImage.
                pngName = QString(self.pngPath).append(self.lastPage)
                self.image = QImage(pngName,'PNG')
                # dbg = unicode(self.image)
                # dbg = self.image.isNull()
                # If that successfully loaded an image, make sure it is one byte/pixel.
                if not self.image.isNull() \
                   and self.image.format() != QImage.Format_Indexed8 :
                    # It might be Format_Mono (1 bit/pixel) or even Format_RGB32.
                    self.image = self.image.convertToFormat(QImage.Format_Indexed8,Qt.ColorOnly)
                # Convert the image to a pixmap. If it's null, so is the pixmap.
                self.pixmap = QPixmap.fromImage(self.image,Qt.ColorOnly)
            else :
                IMC.currentImageNumber = QString(u"n.a.")
                self.lastPage = QString()
                self.image = QImage()
                self.pixmap = QPixmap()
        if not self.pixmap.isNull():
            # We successfully found and loaded an image and converted it to pixmap.
            # Load it in our label for display, set the zoom factor, and the caption.
            # We do this every time through (even if lastIndex equalled nextIndex)
            # because the zoomfactor might have changed.
            self.imLabel.setPixmap(self.pixmap)
            self.imLabel.resize( self.zoomFactor * self.pixmap.size() )
            folio = IMC.pageTable.getDisplay(self.lastIndex)
            self.txLabel.setText(u"image {0} (folio {1})".format(self.lastPage,folio))
        else: # no file was loaded. It's ok if pages are missing
            self.noImage() # display the gray image.

    # Catch the signal from the Zoom spinbox with a new value.
    # Store the new value as a float, and if we have a page, repaint it.
    def newZoomFactor(self,new_value):
        self.zoomFactor = new_value / 100
        if self.ready :
            self.showPage()

    # Catch the click on zoom-to-width and zoom-to height. The job is basically
    # the same for both. 1: Using the QImage that should be in self.image,
    # scan the pixels to find the width (height) of the nonwhite area.
    # 2. Get the ratio of that to our image label's viewport width (height).
    # 4. Set that ratio as the zoom factor and redraw the image. And finally
    # 5. Set the scroll position(s) of our scroll area to left-justify the text.
    #
    # We get access to the pixels using QImage:bits() which gives us a PyQt4
    # "voidptr" that we can index to get byte values.
    #
    def zoomToWidth(self):
        if (not self.ready) or (self.image.isNull()) :
            return # nothing to do here
        #self.profiler.enable() #dbg
        # Query the Color look-up table and build a list of the Green values
        # corresponding to each possible pixel value. Probably there are just
        # two colors so colortab is [0,255] but there could be more, depending
        # on how the PNG was defined, 16 or 32 or even 255 grayscale.
        colortab = [ int((self.image.color(c) >> 4) & 255)
                     for c in range(self.image.colorCount()) ]
        ncols = self.image.width() # number of logical pixels across
        stride = (ncols + 3) & (-4) # number of bytes per scanline
        nrows = self.image.height() # number of pixels high
        vptr = self.image.bits() # uchar * bunch-o-pixel-bytes
        vptr.setsize(stride * nrows) # make the pointer indexable

        # Scan in from left and right to find the outermost dark spots.
        # Looking for single pixels yeilds too many false positives, so we
        # look for three adjacent pixels that sum to less than 32.
        # Most pages start with many lines of white pixels so in hopes of
        # establishing the outer edge early, we start at the middle, go to
        # the end, then do the top half.
        left_side = int(ncols/2) # leftmost dark spot seen so far
        # scan from the middle down
        for r in xrange(int(nrows/2)*stride, (nrows-1)*stride, stride) :
            pa, pb = 255, 255 # virtual white outside border
            for c in xrange(left_side):
                pc = colortab[ ord(vptr[c + r]) ]
                if (pa + pb + pc) < 32 : # black or dark gray pair
                    left_side = c # new, further-left, left margin
                    break # no need to look further on this line
                pa = pb
                pb = pc
        # scan from the top to the middle, hopefully left_side is small now
        for r in xrange(0, int(nrows/2)*stride, stride) :
            pa, pb = 255, 255 # virtual white outside border
            for c in xrange(left_side):
                pc = colortab[ ord(vptr[c + r]) ]
                if (pa + pb + pc) < 32 : # black or dark gray pair
                    left_side = c # new, further-left, left margin
                    break # no need to look further on this line
                pa = pb
                pb = pc
        # Now do the same for the right margin.
        right_side = int(ncols/2) # rightmost dark spot seen so far
        for r in xrange(int(nrows/2)*stride, (nrows-1)*stride, stride) :
            pa, pb = 255, 255 # virtual white outside border
            for c in xrange(ncols-1,right_side,-1) :
                pc = colortab[ ord(vptr[c + r]) ]
                if (pa + pb + pc) < 32 : # black or dark gray pair
                    right_side = c # new, further-right, right margin
                    break
                pa = pb
                pb = pc
        for r in xrange(0, int(nrows/2)*stride, stride)  :
            pa, pb = 255, 255 # virtual white outside border
            for c in xrange(ncols-1,right_side,-1) :
                pc = colortab[ ord(vptr[c + r]) ]
                if (pa + pb + pc) < 32 : # black or dark gray pair
                    right_side = c # new, further-right, right margin
                    break
                pa = pb
                pb = pc
        # The area with color runs from left_side to right_side. How does
        # that compare to the size of our viewport? Scale to that and redraw.
        #print('ls {0} rs {1} vp {2}'.format(left_side,right_side,self.scarea.viewport().width()))
        text_size = right_side - left_side + 2
        port_width = self.scarea.viewport().width()
        self.zoomFactor = max( self.minZoom, min( self.maxZoom, port_width / text_size ) )
        # the next line signals newZoomFactor, which calls showPage.
        self.zlider.setValue(int(100*self.zoomFactor))
        # Set the scrollbar to show the page from its left margin.
        self.scarea.horizontalScrollBar().setValue(int( left_side * self.zoomFactor) )
        #self.profiler.disable() #dbg
        #pstats.Stats(self.profiler).print_stats() # dbg


    def zoomToHeight(self):
        if (not self.ready) or (self.image.isNull()) :
            return # nothing to do here
        # Query the Color look-up table and build a list of the Green values
        # corresponding to each possible pixel value. Probably there are just
        # two colors so colortab is [0,255] but there could be more, depending
        # on how the PNG was defined, 16 or 32 or even 255 grayscale.
        colortab = [ int((self.image.color(c) >> 4) & 255)
                     for c in range(self.image.colorCount()) ]
        ncols = self.image.width() # number of logical pixels across
        stride = (ncols + 3) & (-4) # number of bytes per scanline
        nrows = self.image.height() # number of pixels high
        vptr = self.image.bits() # uchar * bunch-o-pixel-bytes
        vptr.setsize(stride * nrows) # make the pointer indexable
        # Scan in from top and bottom to find the outermost rows with
        # significant pixels.
        top_side = -1 # The uppermost row with a significant spot of black
        offset = 0 # vptr index to the first/next pixel row
        for r in range(nrows) :
            pa, pb = 255, 255 # virtual white outside border
            for c in range(ncols) :
                pc = colortab[ ord(vptr[offset + c]) ]
                if (pa + pb + pc) < 32 : # black or dark gray triplet
                    top_side = r # that's the row,
                    break # ..so stop scanning
                pa, pb = pb, pc
            if top_side >= 0 : # we hit
                break # ..so don't scan down any further
            offset += stride # continue to next row
        # top_side indexes the first row with a significant blot
        if top_side == -1 : # never found one: an all-white page. bug out.
            return
        bottom_side = nrows # The lowest row with a significant blot
        offset = stride * nrows # vptr index to last/next row of pixels
        for r in range(nrows,top_side,-1) :
            offset -= stride
            pa, pb = 255, 255 # virtual white outside border
            for c in range(ncols) :
                pc = colortab[ ord(vptr[offset + c]) ]
                if (pa + pb + pc) < 32 : # black or dark gray triplet
                    bottom_side = r
                    break
                pa, pb = pb, pc
            if bottom_side < nrows : # we hit
                break
        # bottom_side is the lowest row with significant pixels. It must be
        # < nrows, there is at least one row (top_side) with a dot in it.
        # However if the page is mostly white, don't zoom to that extent.
        if bottom_side < (top_side+100) :
            return # seems to be a mostly-white page, give up
        # The text area runs from scanline top_side to bottom_side.
        text_height = bottom_side - top_side + 1
        port_height = self.scarea.viewport().height()
        self.zoomFactor = max( self.minZoom, min( self.maxZoom, port_height / text_height ) )
        self.zlider.setValue(int(100*self.zoomFactor)) # signals newZoomFactor->showPage
        # Set the scrollbar to show the page from its top margin.
        self.scarea.verticalScrollBar().setValue(int( top_side * self.zoomFactor) )

    # Re-implement the parent's keyPressEvent in order to provide zoom:
    # ctrl-plus increases the image size by 1.25
    # ctrl-minus decreases the image size by 0.8
    # Also trap pageup/dn and use to walk through images.
    # At this point we do not reposition the editor to match the page viewed.
    # we page up/dn but as soon as focus returns to the editor and the cursor
    # moves, this display will snap back to the edited page. As a user that
    # seems best, come over to Pngs and page ahead to see what's coming, then
    # back to the editor to read or type.
    def keyPressEvent(self, event):
        # assume we will not handle this key and clear its accepted flag
        event.ignore()
        # If we are initialized and have displayed some page, look at the key
        if self.ready:
            kkey = int( int(event.modifiers()) & IMC.keypadDeModifier) | int(event.key())
            if kkey in IMC.zoomKeys :
                # ctl/cmd + or -, do the zoom
                event.accept()
                fac = (0.8) if (kkey == IMC.ctl_minus) else (1.25)
                fac *= self.zoomFactor # target zoom factor
                if (fac >= self.minZoom) and (fac <= self.maxZoom): # keep in bounds
                    self.zoomFactor = fac
                    self.zlider.setValue(int(100*fac))
                    self.showPage()
            elif (event.key() == Qt.Key_PageUp) or (event.key() == Qt.Key_PageDown) :
                event.accept() # real pgUp or pgDn, we do it
                fac = 1 if (event.key() == Qt.Key_PageDown) else -1
                fac += self.lastIndex
                if (fac >= 0) and (fac < IMC.pageTable.size()) :
                    # not off either end of the book, so,
                    self.nextIndex = fac
                    self.showPage()
        if not event.isAccepted() : # we don't do those, pass them on
            super(pngDisplay, self).keyPressEvent(event)
Пример #37
0
    def photoDetails(self):

        # Function to deal with photo fields

        QgsMessageLog.logMessage("In photoDetails", tag="TOMs panel")

        FIELD1 = self.demandDialog.findChild(QLabel, "Photo_Widget_01")
        FIELD2 = self.demandDialog.findChild(QLabel, "Photo_Widget_02")
        FIELD3 = self.demandDialog.findChild(QLabel, "Photo_Widget_03")

        photoPath = QgsExpressionContextUtils.projectScope().variable(
            'PhotoPath')
        projectFolder = QgsExpressionContextUtils.projectScope().variable(
            'project_folder')
        path_absolute = os.path.join(projectFolder, photoPath)

        if path_absolute == None:
            reply = QMessageBox.information(None, "Information",
                                            "Please set value for PhotoPath.",
                                            QMessageBox.Ok)
            return

        # Check path exists ...
        if os.path.isdir(path_absolute) == False:
            reply = QMessageBox.information(
                None, "Information", "PhotoPath folder " + str(path_absolute) +
                " does not exist. Please check value.", QMessageBox.Ok)
            return

        layerName = self.currDemandLayer.name()

        # Generate the full path to the file

        # fileName1 = "Photos"
        fileName1 = "Photos_01"
        fileName2 = "Photos_02"
        fileName3 = "Photos_03"

        idx1 = self.currDemandLayer.fieldNameIndex(fileName1)
        idx2 = self.currDemandLayer.fieldNameIndex(fileName2)
        idx3 = self.currDemandLayer.fieldNameIndex(fileName3)

        QgsMessageLog.logMessage("In photoDetails. idx1: " + str(idx1) + "; " +
                                 str(idx2) + "; " + str(idx3),
                                 tag="TOMs panel")
        # if currFeatureFeature[idx1]:
        # QgsMessageLog.logMessage("In photoDetails. photo1: " + str(currFeatureFeature[idx1]), tag="TOMs panel")
        # QgsMessageLog.logMessage("In photoDetails. photo2: " + str(currFeatureFeature.attribute(idx2)), tag="TOMs panel")
        # QgsMessageLog.logMessage("In photoDetails. photo3: " + str(currFeatureFeature.attribute(idx3)), tag="TOMs panel")

        if FIELD1:
            QgsMessageLog.logMessage("In photoDetails. FIELD 1 exisits",
                                     tag="TOMs panel")
            if self.currFeature[idx1]:
                newPhotoFileName1 = os.path.join(path_absolute,
                                                 self.currFeature[idx1])
            else:
                newPhotoFileName1 = None

            # QgsMessageLog.logMessage("In photoDetails. Photo1: " + str(newPhotoFileName1), tag="TOMs panel")
            pixmap1 = QPixmap(newPhotoFileName1)
            if pixmap1.isNull():
                pass
                # FIELD1.setText('Picture could not be opened ({path})'.format(path=newPhotoFileName1))
            else:
                FIELD1.setPixmap(pixmap1)
                FIELD1.setScaledContents(True)
                QgsMessageLog.logMessage("In photoDetails. Photo1: " +
                                         str(newPhotoFileName1),
                                         tag="TOMs panel")

            if cv2_available == True:
                START_CAMERA_1 = self.demandDialog.findChild(
                    QPushButton, "startCamera1")
                TAKE_PHOTO_1 = self.demandDialog.findChild(
                    QPushButton, "getPhoto1")
                TAKE_PHOTO_1.setEnabled(False)

                self.camera1 = formCamera(path_absolute, newPhotoFileName1)
                START_CAMERA_1.clicked.connect(
                    functools.partial(self.camera1.useCamera, START_CAMERA_1,
                                      TAKE_PHOTO_1, FIELD1))
                self.camera1.notifyPhotoTaken.connect(
                    functools.partial(self.savePhotoTaken, idx1))

        if FIELD2:
            QgsMessageLog.logMessage("In photoDetails. FIELD 2 exisits",
                                     tag="TOMs panel")
            if self.currFeature[idx2]:
                newPhotoFileName2 = os.path.join(path_absolute,
                                                 self.currFeature[idx2])
            else:
                newPhotoFileName2 = None

            # newPhotoFileName2 = os.path.join(path_absolute, str(self.currFeature[idx2]))
            # newPhotoFileName2 = os.path.join(path_absolute, str(self.currFeature.attribute(fileName2)))
            # QgsMessageLog.logMessage("In photoDetails. Photo2: " + str(newPhotoFileName2), tag="TOMs panel")
            pixmap2 = QPixmap(newPhotoFileName2)
            if pixmap2.isNull():
                pass
                # FIELD1.setText('Picture could not be opened ({path})'.format(path=newPhotoFileName1))
            else:
                FIELD2.setPixmap(pixmap2)
                FIELD2.setScaledContents(True)
                QgsMessageLog.logMessage("In photoDetails. Photo2: " +
                                         str(newPhotoFileName2),
                                         tag="TOMs panel")

            if cv2_available == True:
                START_CAMERA_2 = self.demandDialog.findChild(
                    QPushButton, "startCamera2")
                TAKE_PHOTO_2 = self.demandDialog.findChild(
                    QPushButton, "getPhoto2")
                TAKE_PHOTO_2.setEnabled(False)

                self.camera2 = formCamera(path_absolute, newPhotoFileName2)
                START_CAMERA_2.clicked.connect(
                    functools.partial(self.camera2.useCamera, START_CAMERA_2,
                                      TAKE_PHOTO_2, FIELD2))
                self.camera2.notifyPhotoTaken.connect(
                    functools.partial(self.savePhotoTaken, idx2))

        if FIELD3:
            QgsMessageLog.logMessage("In photoDetails. FIELD 3 exisits",
                                     tag="TOMs panel")

            if self.currFeature[idx3]:
                newPhotoFileName3 = os.path.join(path_absolute,
                                                 self.currFeature[idx3])
            else:
                newPhotoFileName3 = None

            # newPhotoFileName3 = os.path.join(path_absolute, str(self.currFeature[idx3]))
            # newPhotoFileName3 = os.path.join(path_absolute,
            #                                 str(self.currFeature.attribute(fileName3)))
            # newPhotoFileName3 = os.path.join(path_absolute, str(layerName + "_Photos_03"))

            # QgsMessageLog.logMessage("In photoDetails. Photo3: " + str(newPhotoFileName3), tag="TOMs panel")
            pixmap3 = QPixmap(newPhotoFileName3)
            if pixmap3.isNull():
                pass
                # FIELD1.setText('Picture could not be opened ({path})'.format(path=newPhotoFileName1))
            else:
                FIELD3.setPixmap(pixmap3)
                FIELD3.setScaledContents(True)
                QgsMessageLog.logMessage("In photoDetails. Photo3: " +
                                         str(newPhotoFileName3),
                                         tag="TOMs panel")

            if cv2_available == True:
                START_CAMERA_3 = self.demandDialog.findChild(
                    QPushButton, "startCamera3")
                TAKE_PHOTO_3 = self.demandDialog.findChild(
                    QPushButton, "getPhoto3")
                TAKE_PHOTO_3.setEnabled(False)

                self.camera3 = formCamera(path_absolute, newPhotoFileName3)
                START_CAMERA_3.clicked.connect(
                    functools.partial(self.camera3.useCamera, START_CAMERA_3,
                                      TAKE_PHOTO_3, FIELD3))
                self.camera3.notifyPhotoTaken.connect(
                    functools.partial(self.savePhotoTaken, idx3))

        pass
 def __init__(self):
     WidgetEditor.__init__(self)
     pixmap = QPixmap('data/pk_button.png')
     assert pixmap.isNull() == False
     self.maskEditor.setPixmap(pixmap)