예제 #1
0
    def printPlot(self):
        """Open the print dialog and print the plot.

        Use :meth:`Plot.saveGraph` to print the plot.

        :return: True if successful
        """
        # Init printer and start printer dialog
        dialog = qt.QPrintDialog(self.getPrinter(), self.plot)
        dialog.setWindowTitle('Print Plot')
        if not dialog.exec_():
            return False

        # Save Plot as PNG and make a pixmap from it with default dpi
        pngData = _plotAsPNG(self.plot)

        pixmap = qt.QPixmap()
        pixmap.loadFromData(pngData, 'png')

        xScale = self.getPrinter().pageRect().width() / pixmap.width()
        yScale = self.getPrinter().pageRect().height() / pixmap.height()
        scale = min(xScale, yScale)

        # Draw pixmap with painter
        painter = qt.QPainter()
        if not painter.begin(self.getPrinter()):
            return False

        painter.drawPixmap(0, 0,
                           pixmap.width() * scale,
                           pixmap.height() * scale,
                           pixmap)
        painter.end()

        return True
예제 #2
0
    def __createCompoundIcon(self, backgroundIcon, foregroundIcon):
        icon = qt.QIcon()

        sizes = backgroundIcon.availableSizes()
        sizes = sorted(sizes, key=lambda s: s.height())
        sizes = filter(lambda s: s.height() < 100, sizes)
        sizes = list(sizes)
        if len(sizes) > 0:
            baseSize = sizes[-1]
        else:
            baseSize = qt.QSize(32, 32)

        modes = [qt.QIcon.Normal, qt.QIcon.Disabled]
        for mode in modes:
            pixmap = qt.QPixmap(baseSize)
            pixmap.fill(qt.Qt.transparent)
            painter = qt.QPainter(pixmap)
            painter.drawPixmap(0, 0, backgroundIcon.pixmap(baseSize,
                                                           mode=mode))
            painter.drawPixmap(0, 0, foregroundIcon.pixmap(baseSize,
                                                           mode=mode))
            painter.end()
            icon.addPixmap(pixmap, mode=mode)

        return icon
예제 #3
0
    def setProfile(self, x, y, colormap):
        """

        :param profile: a 1D numpy array
        :param colormap: an XsocsPlot2DColormap instance
        :param nColors: number of colors
        :return:
        """
        assert x.ndim == 1
        assert y.ndim == 1

        self.__colormap = colormap
        self.__pixmap = pixmap = Qt.QPixmap(Qt.QSize(x.size,
                                                     self._pimapHeight))
        pixmap.fill()

        xMin = x.min()
        xMax = x.max()

        colors = _applyColormap(colormap, x)
        profileValues = (y * (1.0 * self._pimapHeight / y.max()))
        points = [Qt.QPointF(0, 0)]
        points.extend(
            [Qt.QPointF(idx, val) for idx, val in enumerate(profileValues)])
        points.extend([Qt.QPointF(colormap.nColors - 1, 0)])
        poly = Qt.QPolygonF(points)

        if colormap.minVal is not None:
            lineMin = ((colormap.minVal - xMin) * (pixmap.width() - 1) /
                       (xMax - xMin))
        else:
            lineMin = None

        if colormap.maxVal is not None:
            lineMax = ((colormap.maxVal - xMin) * (pixmap.width() - 1) /
                       (xMax - xMin))
        else:
            lineMax = None

        self.__lineMin = lineMin
        self.__lineMax = lineMax

        gradient = Qt.QLinearGradient(Qt.QPoint(0, 0),
                                      Qt.QPoint(colormap.nColors - 1, 0))
        for idx, color in enumerate(colors):
            qColor = Qt.QColor.fromRgbF(*color)
            gradient.setColorAt(idx / (1.0 * (colormap.nColors - 1)), qColor)

        painter = Qt.QPainter(pixmap)
        painter.save()
        painter.scale(1, -1.)
        painter.translate(Qt.QPointF(0., -1.0 * self._pimapHeight))
        brush = Qt.QBrush(gradient)
        painter.setBrush(brush)
        painter.setPen(Qt.QPen(Qt.Qt.NoPen))
        painter.drawPolygon(poly)
        painter.restore()
        painter.end()
        self.update()
예제 #4
0
def getQPixmap(name):
    """Create a QPixmap from its name.

    :param str name: Name of the icon, in one of the defined icons
                     in this module.
    :return: Corresponding QPixmap
    :raises: ValueError when name is not known
    """
    qfile = getQFile(name)
    return qt.QPixmap(qfile.fileName())
예제 #5
0
    def __init__(self, plot, parent=None):

        qt.QToolButton.__init__(self, parent)
        self.setIcon(qt.QIcon(qt.QPixmap(IconDict["plugin"])))
        self.setToolTip("Call/Load 1D Plugins")

        # fill attr pluginList and pluginInstanceDict with existing plugins
        PluginLoader.__init__(self, method='getPlugin1DInstance')

        # plugins expect a legacy API, not the silx Plot API
        self.plot = weakref.proxy(plot, self._ooPlotDestroyed)

        self.clicked.connect(self._pluginClicked)
예제 #6
0
    def __init__(self, *args, **kwargs):
        super(QColorEditor, self).__init__(*args, **kwargs)
        layout = qt.QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        button = qt.QToolButton()
        icon = qt.QIcon(qt.QPixmap(32, 32))
        button.setIcon(icon)
        layout.addWidget(button)
        button.clicked.connect(self.__showColorDialog)
        layout.addStretch(1)

        self.__color = None
        self.__previousColor = None
예제 #7
0
파일: fileDialogs.py 프로젝트: kklmn/ParSeq
 def updatePreview(self, path):
     if path.endswith('.pspj'):
         fname = path.replace('.pspj', '')
     else:
         return
     self.previewPanel.pms = []
     self.previewPanel.pmNames = []
     for i, (name, node) in enumerate(csi.nodes.items()):
         pngName = fname + '-{0}-{1}.png'.format(i + 1, name)
         pmName = u'{0} \u2013 {1}'.format(i + 1, name)
         if os.path.exists(pngName):
             self.previewPanel.pms.append(qt.QPixmap(pngName))
             self.previewPanel.pmNames.append(pmName)
     self.previewPanel.updatePreview()
예제 #8
0
 def icon(self):
     pixmap = qt.QPixmap(2, 2)
     painter = qt.QPainter(pixmap)
     painter.setPen(qt.QColor(255, 0, 0))
     painter.drawPoint(qt.QPoint(0, 0))
     painter.setPen(qt.QColor(255, 255, 0))
     painter.drawPoint(qt.QPoint(1, 0))
     painter.setPen(qt.QColor(0, 255, 0))
     painter.drawPoint(qt.QPoint(0, 1))
     painter.setPen(qt.QColor(0, 255, 255))
     painter.drawPoint(qt.QPoint(1, 1))
     painter.end()
     pixmap = pixmap.scaled(32, 32, qt.Qt.IgnoreAspectRatio, qt.Qt.FastTransformation)
     return qt.QIcon(pixmap)
예제 #9
0
 def data(self, index=qt.QModelIndex(), role=qt.Qt.DisplayRole):
     peakModel = self.__peakSelectionModel[index.row()]
     column = index.column()
     if role == qt.Qt.DecorationRole:
         if column == 0:
             color = peakModel.color()
             pixmap = qt.QPixmap(16, 16)
             pixmap.fill(color)
             icon = qt.QIcon(pixmap)
             return icon
         else:
             return None
     if role == qt.Qt.DisplayRole or role == qt.Qt.EditRole:
         if column == 0:
             return peakModel.name()
         if column == 1:
             return len(peakModel.coords())
         if column == 2:
             return peakModel.ringNumber()
     return None
예제 #10
0
파일: fileDialogs.py 프로젝트: kklmn/ParSeq
 def updatePreview(self):
     self.previewSlider.setVisible(len(self.pms) > 1)
     if not self.pms:
         self.previewContent.setPixmap(qt.QPixmap())
         self.previewLabel.setText('Preview')
         return
     if self.pmIndex > len(self.pms) - 1:
         self.pmIndex = len(self.pms) - 1
     elif self.pmIndex < 0:
         self.pmIndex = 0
     if self.pms[self.pmIndex].isNull():
         return
     self.previewSlider.setRange(0, len(self.pms) - 1)
     self.previewSlider.setValue(self.pmIndex)
     size = self.size()
     self.previewContent.setMinimumSize(1, 1)
     self.previewContent.setPixmap(self.pms[self.pmIndex].scaled(
         size.width(),
         size.height(),
         aspectRatioMode=qt.Qt.KeepAspectRatio,
         transformMode=qt.Qt.SmoothTransformation))
     self.previewLabel.setText('Preview: ' + self.pmNames[self.pmIndex])
예제 #11
0
    def _pluginClicked(self):
        actionNames = []
        menu = qt.QMenu(self)
        menu.addAction("Reload Plugins")
        actionNames.append("Reload Plugins")
        menu.addAction("Set User Plugin Directory")
        actionNames.append("Set User Plugin Directory")

        if _logger.getEffectiveLevel() == logging.DEBUG:
            text = "Toggle DEBUG mode OFF"
        else:
            text = "Toggle DEBUG mode ON"

        menu.addAction(text)
        menu.addSeparator()
        actionNames.append(text)
        callableKeys = ["Dummy0", "Dummy1", "Dummy2"]
        pluginInstances = self.pluginInstanceDict
        for pluginName in self.pluginList:
            if pluginName in ["PyMcaPlugins.Plugin1DBase", "Plugin1DBase"]:
                continue
            module = sys.modules[pluginName]
            if hasattr(module, 'MENU_TEXT'):
                text = module.MENU_TEXT
            else:
                text = os.path.basename(module.__file__)
                if text.endswith('.pyc'):
                    text = text[:-4]
                elif text.endswith('.py'):
                    text = text[:-3]

            methods = pluginInstances[pluginName].getMethods(
                plottype=self.plot._plotType)
            if not len(methods):
                continue
            elif len(methods) == 1:
                pixmap = pluginInstances[pluginName].getMethodPixmap(
                    methods[0])
                tip = pluginInstances[pluginName].getMethodToolTip(methods[0])
                if pixmap is not None:
                    action = qt.QAction(qt.QIcon(qt.QPixmap(pixmap)), text,
                                        self)
                else:
                    action = qt.QAction(text, self)
                if tip is not None:
                    action.setToolTip(tip)
                menu.addAction(action)
            else:
                menu.addAction(text)
            actionNames.append(text)
            callableKeys.append(pluginName)
        menu.hovered.connect(self._actionHovered)
        a = menu.exec_(qt.QCursor.pos())
        if a is None:
            return None

        idx = actionNames.index(a.text())
        if a.text() == "Reload Plugins":
            n, message = self.getPlugins(exceptions=True)
            if n < 1:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Information)
                msg.setWindowTitle("No plugins")
                msg.setInformativeText(" Problem loading plugins ")
                msg.setDetailedText(message)
                msg.exec_()
            return
        if a.text() == "Set User Plugin Directory":
            dirName = qt.QFileDialog.getExistingDirectory(
                self, "Enter user plugins directory", os.getcwd())
            if len(dirName):
                pluginsDir = self.getPluginDirectoryList()
                pluginsDirList = [pluginsDir[0], dirName]
                self.setPluginDirectoryList(pluginsDirList)
            return
        if "Toggle DEBUG mode" in a.text():
            _toggleLogger()
        key = callableKeys[idx]

        methods = pluginInstances[key].getMethods(plottype=self.plot._plotType)
        if len(methods) == 1:
            idx = 0
        else:
            actionNames = []
            # allow the plugin designer to specify the order
            #methods.sort()
            menu = qt.QMenu(self)
            for method in methods:
                text = method
                pixmap = pluginInstances[key].getMethodPixmap(method)
                tip = pluginInstances[key].getMethodToolTip(method)
                if pixmap is not None:
                    action = qt.QAction(qt.QIcon(qt.QPixmap(pixmap)), text,
                                        self)
                else:
                    action = qt.QAction(text, self)
                if tip is not None:
                    action.setToolTip(tip)
                menu.addAction(action)
                actionNames.append((text, pixmap, tip, action))
            #qt.QObject.connect(menu, qt.SIGNAL("hovered(QAction *)"), self._actionHovered)
            menu.hovered.connect(self._actionHovered)
            a = menu.exec_(qt.QCursor.pos())
            if a is None:
                return None
            idx = -1
            for action in actionNames:
                if a.text() == action[0]:
                    idx = actionNames.index(action)
        try:
            pluginInstances[key].applyMethod(methods[idx])
        except:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setWindowTitle("Plugin error")
            msg.setText("An error has occured while executing the plugin:")
            msg.setInformativeText(str(sys.exc_info()[1]))
            msg.setDetailedText(traceback.format_exc())
            msg.exec_()
예제 #12
0
 def _setColor(self, qColor):
     button = self.findChild(qt.QToolButton)
     pixmap = qt.QPixmap(32, 32)
     pixmap.fill(qColor)
     button.setIcon(qt.QIcon(pixmap))
     self.__color = qColor