예제 #1
0
    def __init__(self, parent, symbol, Z, name):
        qt.QPushButton.__init__(self, parent)

        self.symbol = symbol
        self.Z = Z
        self.name = name

        self.setText(symbol)
        self.setFlat(1)
        self.setCheckable(0)

        self.setSizePolicy(
            qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding))

        self.selected = 0
        self.current = 0
        self.colors = [
            qt.QColor(qt.Qt.yellow),
            qt.QColor(qt.Qt.darkYellow),
            qt.QColor(qt.Qt.gray)
        ]

        self.brush = qt.QBrush()

        self.clicked.connect(self.clickedSlot)
예제 #2
0
파일: PyMcaMdi.py 프로젝트: sjmvm/pymca
def main(args):
    app = qt.QApplication(args)
    #if sys.platform == 'win32':
    if 1:
        winpalette = qt.QPalette(qt.QColor(230, 240, 249),
                                 qt.QColor(238, 234, 238))
        app.setPalette(winpalette)

    options = ''
    longoptions = ['spec=', 'shm=']
    try:
        opts, args = getopt.getopt(sys.argv[1:], options, longoptions)
    except getopt.error:
        _logger.error(sys.exc_info()[1])
        sys.exit(1)
    # --- waiting widget
    kw = {}
    for opt, arg in opts:
        if opt in ('--spec'):
            kw['spec'] = arg
        elif opt in ('--shm'):
            kw['shm'] = arg
    #demo = McaWindow.McaWidget(**kw)
    demo = PyMcaMdi()
    app.lastWindowClosed.connect(app.quit)
    demo.show()
    app.exec_()
예제 #3
0
    def updatePrinter(self):
        if DEBUG:
            print("UPDATE PRINTER")
        printer = self.printer
        if self.scene is None:
            self.scene = qt.QGraphicsScene()
            self.scene.setBackgroundBrush(qt.QColor(qt.Qt.lightGray))
            self.scene.setSceneRect(
                qt.QRectF(0, 0, printer.width(), printer.height()))

        if self.page is None:
            self.page = qt.QGraphicsRectItem(0, 0, printer.width(),
                                             printer.height())
            self.page.setBrush(qt.QColor(qt.Qt.white))
            self.scene.addItem(self.page)

        self.scene.setSceneRect(
            qt.QRectF(0, 0, self.printer.width(), self.printer.height()))
        self.page.setPos(qt.QPointF(0.0, 0.0))
        self.page.setRect(
            qt.QRectF(0, 0, self.printer.width(), self.printer.height()))

        if self.view is None:
            self.view = qt.QGraphicsView(self.scene)
            self.mainLayout.addWidget(self.view)
            self._buildStatusBar()
        self.view.fitInView(self.page.rect(), qt.Qt.KeepAspectRatio)
        self._viewScale = 1.00
        #self.view.scale(1./self._viewScale, 1./self._viewScale)
        #self.view.fitInView(self.page.rect(), qt.Qt.KeepAspectRatio)
        #self._viewScale = 1.00
        self.__updateTargetLabel()
예제 #4
0
def main():
    app = qt.QApplication([])
    winpalette = qt.QPalette(qt.QColor(230, 240, 249),
                             qt.QColor(238, 234, 238))
    app.setPalette(winpalette)
    w = ElementsInfo()
    w.show()
    app.exec_()
예제 #5
0
파일: ElementsInfo.py 프로젝트: sjmvm/pymca
def main():
    logging.basicConfig(level=logging.INFO)
    app = qt.QApplication([])
    winpalette = qt.QPalette(qt.QColor(230, 240, 249),
                             qt.QColor(238, 234, 238))
    app.setPalette(winpalette)
    w = ElementsInfo()
    w.show()
    app.exec_()
예제 #6
0
파일: HDF5Widget.py 프로젝트: gbzan/pymca
    def __init__(self, ffile, node, parent=None, path=None):
        self.__sorting = False
        self.__sorting_list = None
        self.__sorting_order = qt.Qt.AscendingOrder
        if 1:  #with ffile.plock:
            self._file = ffile
            self._parent = parent
            if hasattr(node, '_posixPath'):
                self._name = node._posixPath
            else:
                self._name = node.name
            """
            if hasattr(node, "_sourceName"):
                self._name = node._sourceName
            else:
                self._name = posixpath.basename(node.name)
            """
            self._type = type(node).__name__

            self._hasChildren = is_group(node)
            #self._attrs = []
            self._color = qt.QColor(qt.Qt.black)
            if hasattr(node, 'attrs'):
                attrs = list(node.attrs)
                for cname in ['class', 'NX_class']:
                    if cname in attrs:
                        nodeattr = node.attrs[cname]
                        if sys.version < '3.0':
                            _type = "%s" % nodeattr
                        elif hasattr(nodeattr, "decode"):
                            _type = nodeattr.decode('utf=8')
                        else:
                            _type = "%s" % nodeattr
                        self._type = _type
                        if _type in ["NXdata"]:
                            self._color = qt.QColor(qt.Qt.blue)
                        elif ("default" in attrs):
                            self._color = qt.QColor(qt.Qt.blue)
                        #self._attrs = attrs
                        break
                        #self._type = _type[2].upper() + _type[3:]
            self._children = []
            if hasattr(node, 'dtype'):
                self._dtype = safe_str(node.dtype)
            else:
                self._dtype = ""
            if hasattr(node, 'shape'):
                if 0:
                    self._shape = safe_str(node.shape)
                else:
                    self._shape = node.shape
            else:
                self._shape = ""
예제 #7
0
 def __init__(self, parent=None, scene=None, keepratio=True):
     if QTVERSION < '5.0':
         qt.QGraphicsRectItem.__init__(self, parent, scene)
     else:
         qt.QGraphicsRectItem.__init__(self, parent)
     #rect = parent.sceneBoundingRect()
     rect = parent.boundingRect()
     x = rect.x()
     y = rect.y()
     w = rect.width()
     h = rect.height()
     self._newRect = None
     self.keepRatio = keepratio
     self.setRect(qt.QRectF(x + w - 40, y + h - 40, 40, 40))
     self.setAcceptHoverEvents(True)
     if DEBUG:
         self.setBrush(qt.QBrush(qt.Qt.white, qt.Qt.SolidPattern))
     else:
         pen = qt.QPen()
         color = qt.QColor(qt.Qt.white)
         color.setAlpha(0)
         pen.setColor(color)
         pen.setStyle(qt.Qt.NoPen)
         self.setPen(pen)
         self.setBrush(color)
     self.setFlag(self.ItemIsMovable, True)
     self.show()
예제 #8
0
    def setData(self, modelIndex, value, role):
        if modelIndex.isValid:
            idx = modelIndex.row()
        else:
            return None
        if idx >= len(self.legendList):
            #raise IndexError('list index out of range')
            print('setData -- List index out of range, idx: %d' % idx)
            return None

        item = self.legendList[idx]
        try:
            if role == qt.Qt.DisplayRole:
                # Set legend
                item[0] = str(value)
            elif role == self.iconColorRole:
                item[1]['color'] = qt.QColor(value)
            elif role == self.iconLineWidthRole:
                item[1]['linewidth'] = int(value)
            elif role == self.iconSymbolRole:
                item[1]['symbol'] = str(value)
            elif role == qt.Qt.CheckStateRole:
                item[2] = value
            elif role == self.showLineRole:
                item[3] = value
            elif role == self.showSymbolRole:
                item[4] = value
        except ValueError:
            if DEBUG == 1:
                print('Conversion failed:' + '\n\tvalue:', value + '\n\trole:',
                      role)
        # Can that be right? Read docs again..
        self.dataChanged.emit(modelIndex, modelIndex)
        return True
예제 #9
0
def main():
    app = qt.QApplication(sys.argv)
    winpalette = qt.QPalette(qt.QColor(230, 240, 249),
                             qt.QColor(238, 234, 238))
    app.setPalette(winpalette)
    if len(sys.argv) > 1:
        ene = float(sys.argv[1])
    else:
        ene = 5.9
    mw = qt.QWidget()
    l = qt.QVBoxLayout(mw)
    l.setSpacing(0)
    w = PeakIdentifier(mw, energy=ene, useviewer=1)
    l.addWidget(w)
    mw.setWindowTitle("Peak Identifier")
    mw.show()
    app.exec_()
예제 #10
0
 def hoverLeaveEvent(self, event):
     self.setCursor(qt.QCursor(qt.Qt.ArrowCursor))
     pen = qt.QPen()
     color = qt.QColor(qt.Qt.white)
     color.setAlpha(0)
     pen.setColor(color)
     pen.setStyle(qt.Qt.NoPen)
     self.setPen(pen)
     self.setBrush(color)
     return qt.QGraphicsRectItem.hoverLeaveEvent(self, event)
예제 #11
0
def main():
    import sys
    import getopt
    app = qt.QApplication(sys.argv)
    winpalette = qt.QPalette(qt.QColor(230, 240, 249),
                             qt.QColor(238, 234, 238))
    app.setPalette(winpalette)
    options = ''
    longoptions = []
    opts, args = getopt.getopt(sys.argv[1:], options, longoptions)
    for opt, arg in opts:
        pass
    filelist = args
    app.lastWindowClosed.connect(app.quit)
    w = EdfFileSimpleViewer()
    if len(filelist):
        w.setFileList(filelist)
    w.show()
    app.exec_()
예제 #12
0
def main():
    import sys
    import getopt
    from PyMca5.PyMcaCore.LoggingLevel import getLoggingLevel
    app = qt.QApplication(sys.argv)
    winpalette = qt.QPalette(qt.QColor(230, 240, 249),
                             qt.QColor(238, 234, 238))
    app.setPalette(winpalette)
    options = ''
    longoptions = ['logging=', 'debug=']
    opts, args = getopt.getopt(sys.argv[1:], options, longoptions)

    logging.basicConfig(level=getLoggingLevel(opts))
    filelist = args
    app.lastWindowClosed.connect(app.quit)
    w = EdfFileSimpleViewer()
    if len(filelist):
        w.setFileList(filelist)
    w.show()
    app.exec_()
예제 #13
0
    def data(self, modelIndex, role):
        if modelIndex.isValid:
            idx = modelIndex.row()
        else:
            return None
        if idx >= len(self.legendList):
            raise IndexError('list index out of range')

        item = self.legendList[idx]
        if role == qt.Qt.DisplayRole:
            # Data to be rendered in the form of text
            legend = QString(item[0])
            #return QVariant(legend)
            return legend
        elif role == qt.Qt.SizeHintRole:
            #size = qt.QSize(200,50)
            print('LegendModel -- size hint role not implemented')
            return qt.QSize()
        elif role == qt.Qt.TextAlignmentRole:
            alignment = qt.Qt.AlignVCenter | qt.Qt.AlignLeft
            return alignment
        elif role == qt.Qt.BackgroundRole:
            # Background color, must be QBrush
            if idx % 2:
                brush = qt.QBrush(qt.QColor(240, 240, 240))
            else:
                brush = qt.QBrush(qt.Qt.white)
            return brush
        elif role == qt.Qt.ForegroundRole:
            # ForegroundRole color, must be QBrush
            brush = qt.QBrush(qt.Qt.blue)
            return brush
        elif role == qt.Qt.CheckStateRole:
            return item[2] == True
        elif role == qt.Qt.ToolTipRole or role == qt.Qt.StatusTipRole:
            return ''
        elif role == self.iconColorRole:
            return item[1]['color']
        elif role == self.iconLineWidthRole:
            return item[1]['linewidth']
        elif role == self.iconSymbolRole:
            return item[1]['symbol']
        elif role == self.showLineRole:
            return item[3]
        elif role == self.showSymbolRole:
            return item[4]
        elif role == self.legendTypeRole:
            return 0  # item[4] ..curveType..
        #elif role == qt.Qt.EditRole:
        #    return qt.QString('What now?')
        else:
            print('Unkown role requested: %s', str(role))
            return None
예제 #14
0
 def data(self, index, role):
     if role == qt.Qt.DisplayRole:
         item = self.getProxyFromIndex(index)
         column = index.column()
         if column == 0:
             if isinstance(item, H5FileProxy):
                 return MyQVariant(os.path.basename(item.file.filename))
             else:
                 if hasattr(item, "name"):
                     return MyQVariant(posixpath.basename(item.name))
                 else:
                     # this can only happen with the root
                     return MyQVariant("/")
         if column == 1:
             showtitle = True
             if showtitle:
                 if hasattr(item, 'type'):
                     if item.type in ["Entry", "NXentry"]:
                         children = item.children
                         names = [
                             posixpath.basename(o.name) for o in children
                         ]
                         if "title" in names:
                             idx = names.index("title")
                             if len(children[idx].getNode().shape):
                                 #stored as an array of strings!!!
                                 #return just the first item
                                 return MyQVariant(
                                     "%s" %
                                     children[idx].getNode().value[0])
                             else:
                                 #stored as a string
                                 return MyQVariant(
                                     "%s" % children[idx].getNode().value)
             return MyQVariant(item.type)
         if column == 2:
             return MyQVariant(item.shape)
         if column == 3:
             return MyQVariant(item.dtype)
     elif role == qt.Qt.ForegroundRole:
         item = self.getProxyFromIndex(index)
         column = index.column()
         if column == 0:
             if hasattr(item, "color"):
                 return MyQVariant(qt.QColor(item.color))
     elif role == qt.Qt.ToolTipRole:
         item = self.getProxyFromIndex(index)
         if hasattr(item, "color"):
             if item.color == qt.Qt.blue:
                 return MyQVariant(
                     "Item has a double click NXdata associated action")
     return MyQVariant()
예제 #15
0
def main():
    import sys
    import getopt
    import glob
    from PyMca5.PyMcaCore.LoggingLevel import getLoggingLevel
    app = qt.QApplication(sys.argv)
    winpalette = qt.QPalette(qt.QColor(230, 240, 249),
                             qt.QColor(238, 234, 238))
    app.setPalette(winpalette)
    options = ''
    longoptions = ['logging=', 'debug=']
    opts, args = getopt.getopt(sys.argv[1:], options, longoptions)
    logging.basicConfig(level=getLoggingLevel(opts))
    _logger.setLevel(getLoggingLevel(opts))
    filelist = args
    if len(filelist) == 1:
        if sys.platform.startswith("win") and '*' in filelist[0]:
            filelist = glob.glob(filelist[0])
    app.lastWindowClosed.connect(app.quit)
    w = EdfFileSimpleViewer()
    if len(filelist):
        w.setFileList(filelist)
    w.show()
    app.exec()
예제 #16
0
    def __init__(self, parent, peak):
        qt.QPushButton.__init__(self, parent)
        #, peak)
        self.peak = peak

        font = self.font()
        font.setBold(1)
        self.setText(peak)
        self.setFlat(1)
        if QTVERSION < '4.0.0':
            self.setToggleButton(0)
        self.setSizePolicy(
            qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding))

        self.selected = 0
        self.brush = qt.QBrush(qt.QColor(qt.Qt.yellow))

        self.clicked.connect(self.clickedSlot)
예제 #17
0
파일: ElementsInfo.py 프로젝트: sjmvm/pymca
 def _energySlot(self):
     string = str(self.energy.text())
     if len(string):
         try:
             value = float(string)
         except:
             msg = qt.QMessageBox(self.energy)
             msg.setIcon(qt.QMessageBox.Critical)
             msg.setText("Invalid Float")
             msg.exec_()
             self.energy.setFocus()
             return
         if self.energyValue is not None:
             if value != self.energyValue:
                 self.energyValue = value
                 Elements.updateDict(energy=value)
         else:
             self.energyValue = value
             Elements.updateDict(energy=value)
         self.energy.setPaletteBackgroundColor(qt.QColor('white'))
         self.infoWidget.setFocus()
     else:
         self.energyValue = None
         self.energy.setText("")
예제 #18
0
 def focusOutEvent(self,event):
     self.setPaletteBackgroundColor(qt.QColor('white'))
     self.returnPressed[()].emit()
예제 #19
0
 def focusInEvent(self,event):
     self.setPaletteBackgroundColor(qt.QColor('yellow'))
예제 #20
0
 def focusOutEvent(self, event):
     self.setPaletteBackgroundColor(qt.QColor('white'))
     self.__mySlot()
예제 #21
0
    def fillFromResult(self, result):
        if 'mmolar' in result:
            mmolarflag = True
        else:
            mmolarflag = False
        groupsList = result['groups']
        nrows = len(groupsList)
        if nrows != self.rowCount():
            self.setRowCount(nrows)
        if mmolarflag:
            self.labels = [
                'Element', 'Group', 'Fit Area', 'Sigma Area',
                'mM concentration'
            ]
        else:
            self.labels = [
                'Element', 'Group', 'Fit Area', 'Sigma Area', 'Mass fraction'
            ]
        if 'layerlist' in result:
            for label in result['layerlist']:
                self.labels += [label]
        self.setColumnCount(len(self.labels))
        for i in range(len(self.labels)):
            item = self.horizontalHeaderItem(i)
            if item is None:
                item = qt.QTableWidgetItem(self.labels[i],
                                           qt.QTableWidgetItem.Type)
            item.setText(self.labels[i])
            self.setHorizontalHeaderItem(i, item)

        line = 0
        for group in groupsList:
            element, group0 = group.split()
            # transitions = group0 + " xrays"
            fitarea = QString("%.6e" % (result['fitarea'][group]))
            sigmaarea = QString("%.2e" % (result['sigmaarea'][group]))
            area = QString("%.6e" % (result['area'][group]))
            if result['mass fraction'][group] < 0.0:
                fraction = QString("Unknown")
            else:
                if mmolarflag:
                    fraction = QString("%.4g" % (result['mmolar'][group]))
                else:
                    fraction = QString("%.4g" %
                                       (result['mass fraction'][group]))
            if line % 2:
                color = qt.QColor(255, 250, 205)
            else:
                color = qt.QColor('white')
            if 'Expected Area' in self.labels:
                fields = [element, group0, fitarea, sigmaarea, area, fraction]
            else:
                fields = [element, group0, fitarea, sigmaarea, fraction]
            if 'layerlist' in result:
                for layer in result['layerlist']:
                    if result[layer]['mass fraction'][group] < 0.0:
                        fraction = QString("Unknown")
                    else:
                        if mmolarflag:
                            fraction = QString(
                                "%.4g" % (result[layer]['mmolar'][group]))
                        else:
                            fraction = QString(
                                "%.4g" %
                                (result[layer]['mass fraction'][group]))
                    fields += [fraction]
            col = 0
            for field in fields:
                item = self.item(line, col)
                if item is None:
                    item = qt.QTableWidgetItem(field, qt.QTableWidgetItem.Type)
                    self.setItem(line, col, item)
                else:
                    item.setText(field)
                if hasattr(item, "setBackground"):
                    # Qt5
                    item.setBackground(color)
                else:
                    # Qt4
                    item.setBackgroundColor(color)
                item.setFlags(qt.Qt.ItemIsSelectable | qt.Qt.ItemIsEnabled)
                col += 1
            line += 1

        for i in range(self.columnCount()):
            if (i > 1) and (i < 5):
                self.resizeColumnToContents(i)
예제 #22
0
 def setSymbolColor(self, color):
     '''
     :param color: determines the symbol color
     :type style: qt.QColor
     '''
     self.symbolColor = qt.QColor(color)
예제 #23
0
 def setLineColor(self, color):
     self.lineColor = qt.QColor(color)
예제 #24
0
파일: HDF5Widget.py 프로젝트: gbzan/pymca
 def data(self, index, role):
     if role == qt.Qt.DisplayRole:
         item = self.getProxyFromIndex(index)
         column = index.column()
         if column == 0:
             if isinstance(item, H5FileProxy):
                 return MyQVariant(os.path.basename(item.file.filename))
             else:
                 if hasattr(item, "name"):
                     return MyQVariant(posixpath.basename(item.name))
                 else:
                     # this can only happen with the root
                     return MyQVariant("/")
         if column == 1:
             showtitle = True
             if showtitle:
                 if hasattr(item, 'type'):
                     if item.type in ["Entry", "NXentry"]:
                         if hasattr(item, "children"):
                             children = item.children
                             names = [
                                 posixpath.basename(o.name)
                                 for o in children
                             ]
                             if "title" in names:
                                 idx = names.index("title")
                                 node = children[idx].getNode()
                                 if hasattr(node, "shape") and len(
                                         node.shape):
                                     #stored as an array of strings???
                                     #return just the first item
                                     if hasattr(node, "asstr"):
                                         try:
                                             return MyQVariant(
                                                 "%s" % node.asstr()[()][0])
                                         except:
                                             return MyQVariant("%s" %
                                                               node[()][0])
                                 else:
                                     #stored as a string
                                     try:
                                         try:
                                             return MyQVariant(
                                                 "%s" % node.asstr()[()])
                                         except:
                                             return MyQVariant("%s" %
                                                               node[()])
                                     except:
                                         # issue #745
                                         return MyQVariant("Unknown %s" %
                                                           node)
                         else:
                             _logger.critical("Entry %s has no children" %
                                              item.name)
             return MyQVariant(item.type)
         if column == 2:
             return MyQVariant(item.shape)
         if column == 3:
             return MyQVariant(item.dtype)
     elif role == qt.Qt.ForegroundRole:
         item = self.getProxyFromIndex(index)
         column = index.column()
         if column == 0:
             if hasattr(item, "color"):
                 return MyQVariant(qt.QColor(item.color))
     elif role == qt.Qt.ToolTipRole:
         item = self.getProxyFromIndex(index)
         if hasattr(item, "color"):
             if item.color == qt.Qt.blue:
                 return MyQVariant(
                     "Item has a double click NXdata associated action")
     return MyQVariant()
예제 #25
0
 colors = [
     qt.Qt.darkRed, qt.Qt.green, qt.Qt.yellow, qt.Qt.darkCyan, qt.Qt.blue,
     qt.Qt.darkBlue, qt.Qt.red, qt.Qt.darkYellow
 ]
 #symbols = ['circle', 'triangle', 'utriangle', 'diamond', 'square', 'cross']
 symbols = ['o', 't', '+', 'x', 's', 'd', '.', ',']
 app = qt.QApplication([])
 win = LegendListView()
 #win = LegendListContextMenu()
 #win = qt.QWidget()
 #layout = qt.QVBoxLayout()
 #layout.setContentsMargins(0,0,0,0)
 llist = []
 for idx, (l, c, s) in enumerate(zip(legends, colors, symbols)):
     ddict = {
         'color': qt.QColor(c),
         'linewidth': 4,
         'symbol': s,
     }
     legend = l
     llist.append((legend, ddict))
     #item = qt.QListWidgetItem(win)
     #legendWidget = LegendListItemWidget(l)
     #legendWidget.icon.setSymbol(s)
     #legendWidget.icon.setColor(qt.QColor(c))
     #layout.addWidget(legendWidget)
     #win.setItemWidget(item, legendWidget)
 #win = LegendListItemWidget('Some Legend 1')
 #print(llist)
 model = LegendModel(legendList=llist)
 win.setModel(model)
예제 #26
0
파일: Mca2Edf.py 프로젝트: aicampbell/pymca
def main():
    import logging
    from PyMca5.PyMcaCore.LoggingLevel import getLoggingLevel
    import getopt
    options = 'f'
    longoptions = ['outdir=', 'listfile=', 'mcastep=', 'logging=', 'debug=']
    filelist = None
    outdir = None
    listfile = None
    mcastep = 1
    opts, args = getopt.getopt(sys.argv[1:], options, longoptions)
    for opt, arg in opts:
        if opt in ('--outdir'):
            outdir = arg
        elif opt in ('--listfile'):
            listfile = arg
        elif opt in ('--mcastep'):
            mcastep = int(arg)

    logging.basicConfig(level=getLoggingLevel(opts))
    if listfile is None:
        filelist = []
        for item in args:
            filelist.append(item)
    else:
        fd = open(listfile)
        filelist = fd.readlines()
        fd.close()
        for i in range(len(filelist)):
            filelist[i] = filelist[i].replace('\n', '')
    app = qt.QApplication(sys.argv)
    winpalette = qt.QPalette(qt.QColor(230, 240, 249),
                             qt.QColor(238, 234, 238))
    app.setPalette(winpalette)
    app.lastWindowClosed.connect(app.quit)
    if len(filelist) == 0:
        w = Mca2EdfGUI(actions=1)
        w.show()
        sys.exit(app.exec_())
    else:
        text = "Batch from %s to %s" % (os.path.basename(filelist[0]), \
                                        os.path.basename(filelist[-1]))
        window = Mca2EdfWindow(name=text, actions=1)
        b = Mca2EdfBatch(window, filelist, outdir, mcastep)

        def cleanup():
            b.pleasePause = 0
            b.pleaseBreak = 1
            b.wait()
            qApp = qt.QApplication.instance()
            qApp.processEvents()

        def pause():
            if b.pleasePause:
                b.pleasePause = 0
                window.pauseButton.setText("Pause")
            else:
                b.pleasePause = 1
                window.pauseButton.setText("Continue")

        window.pauseButton.clicked.connect(pause)
        window.abortButton.clicked.connect(window.close)
        app.aboutToQuit.connect(cleanup)
        window.show()
        b.start()
        sys.exit(app.exec_())
예제 #27
0
 def fillfrommca(self, result, diag=1):
     line = 0
     #calculate the number of rows
     nrows = 0
     for group in result['groups']:
         nrows += 1
         for peak in result[group]['peaks']:
             nrows += 1
         for peak0 in result[group]['escapepeaks']:
             peak = peak0 + "esc"
             if result[group][peak]['ratio'] > 0.0:
                 nrows += 1
     self.setRowCount(nrows)
     for group in result['groups']:
         ele, group0 = group.split()
         fitarea = QString("%.4e" % (result[group]['fitarea']))
         sigmaarea = QString("%.2e" % (result[group]['sigmaarea']))
         fields = [ele, group0, fitarea, sigmaarea]
         col = 0
         color = qt.QColor('white')
         nlines = self.rowCount()
         if (line + 1) > nlines:
             self.setRowCount(line + 1)
         for i in range(len(self.labels)):
             if i < len(fields):
                 item = self.item(line, col)
                 text = fields[i]
                 if item is None:
                     item = qt.QTableWidgetItem(text,
                                                qt.QTableWidgetItem.Type)
                     self.setItem(line, col, item)
                 else:
                     item.setText(text)
                     if hasattr(item, "setBackground"):
                         item.setBackground(color)
                     else:
                         item.setBackgroundColor(color)
                     item.setFlags(qt.Qt.ItemIsSelectable
                                   | qt.Qt.ItemIsEnabled)
             else:
                 item = self.item(line, col)
                 if item is not None:
                     item.setText("")
                 #self.setItem(line, col, item)
             col = col + 1
         line += 1
         #Lemon Chiffon = (255,250,205)
         color = qt.QColor(255, 250, 205)
         for peak in result[group]['peaks']:
             name = peak
             energy = QString("%.3f" % (result[group][peak]['energy']))
             ratio = QString("%.5f" % (result[group][peak]['ratio']))
             area = QString("%.4e" % (result[group][peak]['fitarea']))
             sigma = QString("%.2e" % (result[group][peak]['sigmaarea']))
             fwhm = QString("%.3f" % (result[group][peak]['fwhm']))
             chisq = QString("%.2f" % (result[group][peak]['chisq']))
             if (line + 1) > nlines:
                 self.setRowCount(line + 1)
             fields = [name, area, sigma, energy, ratio, fwhm, chisq]
             col = 1
             for field in fields:
                 item = self.item(line, col)
                 text = field
                 if item is None:
                     item = qt.QTableWidgetItem(text,
                                                qt.QTableWidgetItem.Type)
                     self.setItem(line, col, item)
                 else:
                     item.setText(text)
                 if hasattr(item, "setBackground"):
                     item.setBackground(color)
                 else:
                     item.setBackgroundColor(color)
                 item.setFlags(qt.Qt.ItemIsSelectable | qt.Qt.ItemIsEnabled)
                 col = col + 1
             line += 1
         for peak0 in result[group]['escapepeaks']:
             peak = peak0 + "esc"
             if result[group][peak]['ratio'] > 0.0:
                 energy = QString("%.3f" % (result[group][peak]['energy']))
                 ratio = QString("%.5f" % (result[group][peak]['ratio']))
                 area = QString("%.4e" % (result[group][peak]['fitarea']))
                 sigma = QString("%.2e" %
                                 (result[group][peak]['sigmaarea']))
                 fwhm = QString("%.3f" % (result[group][peak]['fwhm']))
                 chisq = QString("%.2f" % (result[group][peak]['chisq']))
                 if (line + 1) > nlines:
                     self.setRowCount(line + 1)
                 fields = [peak, area, sigma, energy, ratio, fwhm, chisq]
                 col = 1
                 for field in fields:
                     item = self.item(line, col)
                     if item is None:
                         item = qt.QTableWidgetItem(
                             field, qt.QTableWidgetItem.Type)
                         self.setItem(line, col, item)
                     else:
                         item.setText(field)
                     if hasattr(item, "setBackground"):
                         item.setBackground(color)
                     else:
                         item.setBackgroundColor(color)
                     item.setFlags(qt.Qt.ItemIsSelectable
                                   | qt.Qt.ItemIsEnabled)
                     col = col + 1
                 line += 1
     for i in range(self.columnCount()):
         if i > -1:
             self.resizeColumnToContents(i)
예제 #28
0
 def focusInEvent(self, event):
     self.setPaletteBackgroundColor(qt.QColor('yellow'))
     # TODO not like focusOutEvent ?
     '''
예제 #29
0
 def focusOutEvent(self, event):
     self.setPaletteBackgroundColor(qt.QColor('white'))
     qt.QLineEdit.focusOutEvent(self, event)
예제 #30
0
    def addPixmap(self,
                  pixmap,
                  title=None,
                  comment=None,
                  commentPosition=None):
        """
        add a pixmap to the print preview scene
        """
        if self._toBeCleared:
            self.__clearAll()
        if self.printer is None:
            self.setup()
        if title is None:
            title = '                                            '
            title += '                                            '
        if comment is None:
            comment = '                                            '
            comment += '                                            '
        if commentPosition is None:
            commentPosition = "CENTER"
        if self.badNews:
            return
        if QTVERSION < "5.0":
            rectItem = qt.QGraphicsRectItem(self.page, self.scene)
        else:
            rectItem = qt.QGraphicsRectItem(self.page)
        scale = 1.0  # float(0.5 * self.scene.width()/pixmap.width())
        rectItem.setRect(qt.QRectF(1, 1, pixmap.width(), pixmap.height()))

        pen = rectItem.pen()
        color = qt.QColor(qt.Qt.red)
        color.setAlpha(1)
        pen.setColor(color)
        rectItem.setPen(pen)
        rectItem.setZValue(1)
        rectItem.setFlag(qt.QGraphicsItem.ItemIsSelectable, True)
        rectItem.setFlag(qt.QGraphicsItem.ItemIsMovable, True)
        rectItem.setFlag(qt.QGraphicsItem.ItemIsFocusable, False)

        #I add the resize tool
        rectItemResizeRect = GraphicsResizeRectItem(rectItem, self.scene)
        rectItemResizeRect.setZValue(2)

        #I add a pixmap item
        if QTVERSION < "5.0":
            pixmapItem = qt.QGraphicsPixmapItem(rectItem, self.scene)
        else:
            pixmapItem = qt.QGraphicsPixmapItem(rectItem)
        pixmapItem.setPixmap(pixmap)
        #pixmapItem.moveBy(0, 0)
        pixmapItem.setZValue(0)

        #I add the title
        if QTVERSION < "5.0":
            textItem = qt.QGraphicsTextItem(title, rectItem, self.scene)
        else:
            textItem = qt.QGraphicsTextItem(title, rectItem)
        textItem.setTextInteractionFlags(qt.Qt.TextEditorInteraction)
        offset = 0.5 * textItem.boundingRect().width()
        textItem.moveBy(0.5 * pixmap.width() - offset, -20)
        textItem.setZValue(2)

        #I add the comment
        if QTVERSION < "5.0":
            commentItem = qt.QGraphicsTextItem(comment, rectItem, self.scene)
        else:
            commentItem = qt.QGraphicsTextItem(comment, rectItem)
        commentItem.setTextInteractionFlags(qt.Qt.TextEditorInteraction)
        offset = 0.5 * commentItem.boundingRect().width()
        if commentPosition.upper() == "LEFT":
            x = 1
        else:
            x = 0.5 * pixmap.width() - offset
        commentItem.moveBy(x, pixmap.height() + 20)
        commentItem.setZValue(2)

        #I should adjust text size here
        #textItem.scale(2,2)
        #commentItem.scale(2,2)
        if QTVERSION < "5.0":
            rectItem.scale(scale, scale)
        else:
            # the correct equivalent would be:
            # rectItem.setTransform(qt.QTransform.fromScale(scalex, scaley))
            rectItem.setScale(scale)
        rectItem.moveBy(20, 40)