Exemple #1
0
def showInformation(message):
    """
    shows a information dialog with given message
    """

    app = guidata.qapplication()
    QMessageBox.information(None, "Information", message)
def showInformation(message, title="Information"):
    """
    shows a information dialog with given message
    """

    app = guidata.qapplication()
    QMessageBox.information(None, title, message)
def showWarning(message, title="Warning"):
    """
    shows a warning dialog with given message
    """

    app = guidata.qapplication()
    QMessageBox.warning(None, title, message)
Exemple #4
0
def showInformation(message):
    """
    shows a information dialog with given message
    """

    guidata.qapplication().beep()
    QMessageBox.information(None, "Information", message)
Exemple #5
0
def exec_image_save_dialog(parent, data, template=None,
                           basedir='', app_name=None):
    """
    Executes an image save dialog box (QFileDialog.getSaveFileName)
        * parent: parent widget (None means no parent)
        * data: image pixel array data
        * template: image template (pydicom dataset) for DICOM files
        * basedir: base directory ('' means current directory)
        * app_name (opt.): application name (used as a title for an eventual 
          error message box in case something goes wrong when saving image)
    
    Returns filename if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filename, _filter = getsavefilename(parent, _("Save as"), basedir,
        io.iohandler.get_filters('save', dtype=data.dtype, template=template))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    if filename:
        filename = to_text_string(filename)
        kwargs = {}
        if osp.splitext(filename)[1].lower() == '.dcm':
            kwargs['template'] = template
        try:
            io.imwrite(filename, data, **kwargs)
            return filename
        except Exception as msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(parent,
                 _('Error') if app_name is None else app_name,
                 (_("%s could not be written:") % osp.basename(filename))+\
                 "\n"+str(msg))
            return
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<p>%s Matt Nottingham
           <br>Copyright &copy; 2015 Matt Nottingham
           <p>Python %s, Qt %s, PyQt %s %s %s""" % \
           (APP_NAME, VERS, _("Developped by"), platform.python_version(),
            QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system()) )
Exemple #7
0
    def start_compute(self,
                      name,
                      func,
                      param=None,
                      suffix=None,
                      interactive=True):
        self.QProxy.emit(SIGNAL("computing"))
        if interactive and param is not None:
            if interactive == 'text' and not param.text_edit():
                return
            elif not param.edit():
                return
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            processing = name
            if suffix is not None:
                processing += " | " + suffix(param)

            result = Measurement()
            result.copy_param(self.measurement)
            result.set_rawdata(self.apply_func(func, param))
            result['processing'] += processing + "\n"
        except Exception, msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(
                None, APP_NAME,
                _(u"An error occured:") + "\n%s" % unicode(msg))
            raise ComputationError, msg
Exemple #8
0
def exec_image_open_dialog(parent,
                           basedir='',
                           app_name=None,
                           to_grayscale=True,
                           dtype=None):
    """
    Executes an image open dialog box (QFileDialog.getOpenFileName)
        * parent: parent widget (None means no parent)
        * basedir: base directory ('' means current directory)
        * app_name (opt.): application name (used as a title for an eventual 
          error message box in case something goes wrong when saving image)
        * to_grayscale (default=True): convert image to grayscale
    
    Returns (filename, data) tuple if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filename, _filter = getopenfilename(
        parent, _("Open"), basedir,
        io.iohandler.get_filters('load', dtype=dtype))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    filename = to_text_string(filename)
    try:
        data = io.imread(filename, to_grayscale=to_grayscale)
    except Exception as msg:
        import traceback
        traceback.print_exc()
        QMessageBox.critical(parent,
             _('Error') if app_name is None else app_name,
             (_("%s could not be opened:") % osp.basename(filename))+\
             "\n"+str(msg))
        return
    return filename, data
Exemple #9
0
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<p>%s Pierre Raybaut
           <br>Copyright &copy; 2009-2010 CEA
           <p>Python %s, Qt %s, PyQt %s %s %s""" % \
           (APP_NAME, VERSION, _("Developped by"), platform.python_version(),
            QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system()) )
Exemple #10
0
def exec_image_open_dialog(parent, basedir='', app_name=None,
                           to_grayscale=True, dtype=None):
    """
    Executes an image open dialog box (QFileDialog.getOpenFileName)
        * parent: parent widget (None means no parent)
        * basedir: base directory ('' means current directory)
        * app_name (opt.): application name (used as a title for an eventual 
          error message box in case something goes wrong when saving image)
        * to_grayscale (default=True): convert image to grayscale
    
    Returns (filename, data) tuple if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filename, _filter = getopenfilename(parent, _("Open"), basedir,
                                io.iohandler.get_filters('load', dtype=dtype))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    filename = to_text_string(filename)
    try:
        data = io.imread(filename, to_grayscale=to_grayscale)
    except Exception as msg:
        import traceback
        traceback.print_exc()
        QMessageBox.critical(parent,
             _('Error') if app_name is None else app_name,
             (_("%s could not be opened:") % osp.basename(filename))+\
             "\n"+str(msg))
        return
    return filename, data
Exemple #11
0
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<p>%s Pierre Raybaut
           <br>Copyright &copy; 2009-2010 CEA
           <p>Python %s, Qt %s, PyQt %s %s %s""" % \
           (APP_NAME, VERSION, _("Developped by"), platform.python_version(),
            QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system()) )
Exemple #12
0
 def about( self ):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<p>%s Darko Petrovic
           <br>(Lisence goes here)
           <p>Python %s, Qt %s, PyQt %s %s %s""" % \
           (APP_NAME, VERSION, _("Developped by"), platform.python_version(),
            QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system()) )
Exemple #13
0
def showWarning(message):
    """
    shows a warning dialog with given message
    """

    app = guidata.qapplication()
    QMessageBox.warning(None, "Warning", message)
Exemple #14
0
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
                       """<b>%s</b><br>
                       v%s<p>
                       Copyright &copy; 2014 IRA-INAF<br><br>
                       %s
                       """ % \
                       (APP_DESCRIPTION, dwdata.dw_version(), LICENSE))
Exemple #15
0
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<br>%s<p>
           <br>Copyright © François Bianco, University of Geneva
           <br>[email protected]
           <br>Distributed under the GNU GPL License v.3
           """ % \
           (APP_NAME, VERSION, APP_DESC))
Exemple #16
0
def showWarning(message):
    """
    shows a warning dialog with given message
    """


    guidata.qapplication().beep()
    QMessageBox.warning(None, "Warning", message)
Exemple #17
0
 def inner(ds, it, value, parent, target=target):
     invalidFields = ds.check()
     if len(invalidFields):
         msg = "The following fields are invalid: \n"
         msg += "\n".join(invalidFields)
         QMessageBox.warning(parent, "Error", msg)
         return
     target()
 def inner(ds, it, value, parent, target=target):
     invalidFields = ds.check()
     if len(invalidFields):
         msg = "The following fields are invalid: \n"
         msg += "\n".join(invalidFields)
         QMessageBox.warning(parent, "Error", msg)
         return
     target()
Exemple #19
0
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<br>%s<p>
           <br>Copyright © François Bianco, University of Geneva
           <br>[email protected]
           <br>Distributed under the GNU GPL License v.3
           """ % \
           (APP_NAME, VERSION, APP_DESC))
Exemple #20
0
 def wrapped(ds, it, value, parent):
     # check inputs before callback is executed
     invalidFields = ds.check()
     if len(invalidFields):
         msg = "The following fields are invalid: \n"
         msg += "\n".join(invalidFields)
         QMessageBox.warning(parent, "Error", msg)
         return
     callback(ds)
 def wrapped(ds, it, value, parent):
     # check inputs before callback is executed
     invalidFields = ds.check()
     if len(invalidFields):
         msg = "The following fields are invalid: \n"
         msg += "\n".join(invalidFields)
         QMessageBox.warning(parent, "Error", msg)
         return
     callback(ds)
Exemple #22
0
 def on_actionAbout_triggered(self):
     QMessageBox.about(self, "About Zupport GUI",
                       """<b>Zupport GUI</b> v %s
                         <p>Copyright &copy; 2011 Joona Lehtomaki 
                         <*****@*****.**>.
                         All rights reserved.
                         <p>Support zools for Zonation related pre- and post-processing operations.</p>
                         <p>Python %s - Qt %s - PySide %s on %s</p>""" % (
                         __version__, platform.python_version(),
                         QT_VERSION,
                         PYQT_VERSION, platform.system()))
Exemple #23
0
 def check(self):
     is_ok = True
     for edl in self.edit_layout:
         if not edl.check_all_values():
             is_ok = False
     if not is_ok:
         QMessageBox.warning(self, self.instance.get_title(),
                     _("Some required entries are incorrect")+"\n"+\
                     _("Please check highlighted fields."))
         return False
     return True
Exemple #24
0
 def check(self):
     is_ok = True
     for edl in self.edit_layout:
         if not edl.check_all_values():
             is_ok = False
     if not is_ok:
         QMessageBox.warning(self, self.instance.get_title(),
                             _("Some required entries are incorrect")+".\n",
                             _("Please check highlighted fields."))
         return False
     return True
Exemple #25
0
 def on_actionAbout_triggered(self):
     QMessageBox.about(self, "About Zupport GUI",
                       """<b>Zupport GUI</b> v %s
                         <p>Copyright &copy; 2011 Joona Lehtomaki 
                         <*****@*****.**>.
                         All rights reserved.
                         <p>Support zools for Zonation related pre- and post-processing operations.</p>
                         <p>Python %s - Qt %s - PySide %s on %s</p>""" % (
                         __version__, platform.python_version(),
                         QT_VERSION,
                         PYQT_VERSION, platform.system()))
Exemple #26
0
 def on_actionOpen_log_triggered(self):
     logfile = os.path.join(USER_DATA_DIR, 'zupport.log')
     if os.path.exists(logfile):
         import webbrowser
         webbrowser.open(logfile)
         self.logger.debug('Opened log file %s' % logfile)
     else:
         msg = "Zupport log file cannot be found in default location %s" % os.path.dirname(logfile)
         self.logger.debug(msg)
         QMessageBox.warning(self, "File not found", 
                             msg, 
                             buttons=QMessageBox.Ok, 
                             defaultButton=QMessageBox.NoButton)
Exemple #27
0
 def on_actionOpen_log_triggered(self):
     logfile = os.path.join(USER_DATA_DIR, 'zupport.log')
     if os.path.exists(logfile):
         import webbrowser
         webbrowser.open(logfile)
         self.logger.debug('Opened log file %s' % logfile)
     else:
         msg = "Zupport log file cannot be found in default location %s" % os.path.dirname(logfile)
         self.logger.debug(msg)
         QMessageBox.warning(self, "File not found", 
                             msg, 
                             buttons=QMessageBox.Ok, 
                             defaultButton=QMessageBox.NoButton)
Exemple #28
0
 def initStage(self):
     # TODO put this in thread and show egg clock
     if self.stage is not None:
         ## Create and display the splash screen
         #splash_pix = QPixmap('icons/piController.png')
         #splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
         #splash.setMask(splash_pix.mask())
         #splash.show()
         # TODO: give choice to select stage
         pitools.startup(self.stage, stages='M-112.1DG-NEW', refmode='FNL')
         #splash.close()
         # TODO: show dialog for waiting
         self.velocityLabel.setText('Velocity: {:f}mm/s'.format(
             self.stage.qVEL()['1']))
         self.velocity.setValue(int(1000 * self.stage.qVEL()['1']))
         self.stageConnected.emit()
         self._xAxeChanged()
         self.currentPos.setText('{:.7f}'.format(self.stage.qPOS()['1']))
         self.__startCurrPosThr()
         self.stageRange = (self.stage.qTMN()['1'], self.stage.qTMX()['1'])
         self.scanStep.validator().setBottom(0)
         self.initStageBtn.setEnabled(False)
     else:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Critical)
         msg.setText('No stage connected')
         msg.exec_()
Exemple #29
0
 def edit(self):
     import guidata
     from guidata.qt.QtGui import QMessageBox
     app = guidata.qapplication()
     while True:
         aborted = self.parameters.edit(size=(600, 800)) == 0
         if not aborted:
             ok, msg = self.check_fields()
             if not ok:
                 QMessageBox.warning(None, "Error", msg)
                 continue
             global global_config
             global_config = self
         break
     return aborted
Exemple #30
0
 def edit(self):
     import guidata
     from guidata.qt.QtGui import QMessageBox
     app = guidata.qapplication()
     while True:
         aborted = self.parameters.edit(size=(600, 800)) == 0
         if not aborted:
             ok, msg = self.check_fields()
             if not ok:
                 QMessageBox.warning(None, "Error", msg)
                 continue
             global global_config
             global_config = self
         break
     return aborted
Exemple #31
0
    def saveDataHDF5(self):
        import datetime
        import h5py

        now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S_FTIR')
        with h5py.File('data/{:s}.h5'.format(now)) as f:
            f.attrs['comments'] = self.fileUi.comment.text()
            f.attrs['stage'] = ''
            f.attrs['stage_settings'] = ''
            f.attrs['detector'] = ''
            f.attrs['detector_settings'] = ''

            # save time domain
            foo = self.tdWidget.calcFun.functions
            texts = [
                self.tdWidget.calcFun.itemText(i) for i in range(len(foo))
            ]
            dt = []
            for i in texts:
                dt.append(('x_{:s}'.format(i), np.float))
                dt.append(('y_{:s}'.format(i), np.float))
            dt = np.dtype(dt)
            dataTd = np.zeros(self.tdSignal.getData(foo[0][0])[0].shape[0],
                              dtype=dt)
            for i, fun in enumerate(foo):
                x, y = self.tdSignal.getData(
                    fun[0])  # [0]: fun, [1]: inverse fun
                dataTd['x_{:s}'.format(texts[i])] = x
                dataTd['y_{:s}'.format(texts[i])] = y
            dset = f.create_dataset('timeDomain', data=dataTd)
            self.tdSignal.plot.save_widget('data/{:s}_TD.png'.format(now))

            # save frequency domain
            foo = self.tdWidget.calcFun.functions
            texts = [
                self.tdWidget.calcFun.itemText(i) for i in range(len(foo))
            ]
            dt = []
            for i in texts:
                dt.append(('x_{:s}'.format(i), np.float))
                dt.append(('y_{:s}'.format(i), np.float))
            dt = np.dtype(dt)
            dataFd = np.zeros(self.fdSignal.getData(foo[0][0])[0].shape[0],
                              dtype=dt)
            for i, fun in enumerate(foo):
                x, y = self.fdSignal.getData(fun[0])
                dataFd['x_{:s}'.format(texts[i])] = x
                dataFd['y_{:s}'.format(texts[i])] = y
            #np.savetxt('data/{:s}_FD.txt'.format(now), dataFd, header=header)
            dset = f.create_dataset('frequencyDomain', data=dataFd)
            self.fdSignal.plot.save_widget('data/{:s}_FD.png'.format(now))

        # TODO: maybe put this in status bar
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText('Data saved')
        msg.exec_()
Exemple #32
0
 def stop_button( self ):
     sel = 0
     if self.sessiontype == 'timed':
         sel = QMessageBox.warning( self, "Timed Session",
                                    "A Timed Session is currently active!\nIf you stop the session "
                                    "the session will be stored as a free session.", "OK", "Cancel")
     if sel == 0:
         self.session_stop()
Exemple #33
0
 def open(self):
     try:
         self._open()
     except:
         msgBox = QMessageBox()
         msgBox.setText("Wrong type of directory!")
         msgBox.exec_()
         return -1
Exemple #34
0
def exec_image_save_dialog(parent,
                           data,
                           template=None,
                           basedir='',
                           app_name=None):
    """
    Executes an image save dialog box (QFileDialog.getSaveFileName)
        * parent: parent widget (None means no parent)
        * data: image pixel array data
        * template: image template (pydicom dataset) for DICOM files
        * basedir: base directory ('' means current directory)
        * app_name (opt.): application name (used as a title for an eventual 
          error message box in case something goes wrong when saving image)
    
    Returns filename if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filename, _filter = getsavefilename(
        parent, _("Save as"), basedir,
        io.iohandler.get_filters('save', dtype=data.dtype, template=template))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    if filename:
        filename = to_text_string(filename)
        kwargs = {}
        if osp.splitext(filename)[1].lower() == '.dcm':
            kwargs['template'] = template
        try:
            io.imwrite(filename, data, **kwargs)
            return filename
        except Exception as msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(parent,
                 _('Error') if app_name is None else app_name,
                 (_("%s could not be written:") % osp.basename(filename))+\
                 "\n"+str(msg))
            return
Exemple #35
0
def askYesNo(message, allow_cancel=False, title="Question"):
    """shows message and asks for "yes" or "no" (or "cancel" if allow_cancel is True).
       returns True, False (or None).
    """

    app = guidata.qapplication()
    flags = QMessageBox.Yes | QMessageBox.No
    if allow_cancel:
        flags |= QMessageBox.Cancel

    reply = QMessageBox.question(None, title, message, flags)

    if reply == QMessageBox.Cancel:
        return None
    else:
        return reply == QMessageBox.Yes
def askYesNo(message, allow_cancel=False, title="Question"):
    """shows message and asks for "yes" or "no" (or "cancel" if allow_cancel is True).
       returns True, False (or None).
    """

    app = guidata.qapplication()
    flags = QMessageBox.Yes | QMessageBox.No
    if allow_cancel:
        flags |= QMessageBox.Cancel

    reply = QMessageBox.question(None, title, message, flags)

    if reply == QMessageBox.Cancel:
        return None
    else:
        return reply == QMessageBox.Yes
Exemple #37
0
    def __openCam(self):
        self.camera = greatEyes()
        if not self.camera.connected:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText('Sorry, could not connect to camera :(\n' + 
                    self.camera.status)
            msg.exec_()
            return
        self.openCamBtn.setText('Connected')
        self.message.emit('Camera connected')
        self.openCamBtn.setStyleSheet('QPushButton {color: green;}')

        self.readoutSpeedCombo.setEnabled(True)
        self.exposureTimeSpin.setEnabled(True)
        self.binningXCombo.setEnabled(False)
        self.binningYCombo.setEnabled(False)
        self.temperatureSpin.setEnabled(True)
        self.updateInterSpin.setEnabled(True)

        self.openCamBtn.setEnabled(False)
        self.startAquBtn.setEnabled(True) 
Exemple #38
0
 def properties_changed(self):
     row = self.imagelist.currentRow()
     image = self.images[row]
     try:
         image.x
     except:
         pass
     else:
         if ((self.properties.dataset.franges != 0
              and self.properties.dataset.franges < len(image.x)
              and self.properties.dataset.frangei <
              self.properties.dataset.franges)
                 or (self.properties.dataset.franges == 0
                     and self.properties.dataset.frangei < len(image.x))):
             pass
         else:
             msgBox = QMessageBox()
             msgBox.setText(
                 "Fit range void or out of bound! Range max 0:%s" %
                 (len(image.x) - 1))
             msgBox.exec_()
             return -1
     update_dataset(image, self.properties.dataset)
     #self.dssel.section = self.data_ref.list2choices(self.data_ref.sections[int(self.ds.dataset.feed)])
     csections.set(
         self.data_ref.list2choices(self.data_ref.sections[int(
             self.ds.dataset.feed)]))
     update_dataset(self.dssel, self.ds.dataset)
     self.update_info()
     if self.flagname:
         self.data_ref.flag = self.data_ref.get_flag_curve(
             self.flagname, self.dssel.section)
     #for i in self.images:
     #    i.otype = image.otype
     if image.rall == True:
         for i in self.images:
             i.rangei = image.rangei
             i.ranges = image.ranges
     if image.eall == True:
         for i in self.images:
             i.excluded = image.excluded
     for i in self.images:
         i.frangei = image.frangei
         i.franges = image.franges
     try:
         self.show_data(image.x, image.y, self.data_ref.flag)
     except:
         pass
Exemple #39
0
    def saveData(self):
        import datetime
        now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')

        # save time domain
        foo = self.tdWidget.calcFun.functions
        texts = [self.tdWidget.calcFun.itemText(i) for i in range(len(foo))]
        tmp = ['td_x_{:s},td_y_{:s}'.format(i, i) for i in texts] 
        header = ','.join(tmp)
        dataTd = np.zeros((self.tdSignal.getData(foo[0][0])[0].shape[0],
                          2*len(foo)))
        for i, fun in enumerate(foo):
            x, y =  self.tdSignal.getData(fun[0])# [0]: fun, [1]: inverse fun
            dataTd[:,2*i] = x
            dataTd[:,2*i+1] = y
        np.savetxt('data/{:s}_TD.txt'.format(now), dataTd, header=header)
        self.tdSignal.plot.save_widget('data/{:s}_TD.png'.format(now))
        
        # save frequency domain
        foo = self.fdWidget.calcFun.functions
        texts = [self.fdWidget.calcFun.itemText(i) for i in range(len(foo))]
        tmp = ['fd_x_{:s},fd_y_{:s}'.format(i, i) for i in texts] 
        header += ','.join(tmp)
        dataFd = np.zeros((self.fdSignal.getData(foo[0][0])[0].shape[0],
                          2*len(foo)))
        for fun in foo:
            x, y = self.fdSignal.getData(fun[0])
            dataFd[:,2*i] = x
            dataFd[:,2*i+1] = y
        np.savetxt('data/{:s}_FD.txt'.format(now), dataFd, header=header)
        self.fdSignal.plot.save_widget('data/{:s}_FD.png'.format(now))

        # TODO: maybe put this in status bar
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText('Data saved')
        msg.exec_()
Exemple #40
0
def info_popup(message, parent=None):
    QMessageBox.information(parent, 'Message', message, QMessageBox.Ok)
Exemple #41
0
def warning_popup(message, parent=None):
    QMessageBox.warning(parent, 'Message', message, QMessageBox.Ok)
Exemple #42
0
def info_popup(message, parent=None):
    QMessageBox.information(parent, 'Message', message, QMessageBox.Ok)
Exemple #43
0
def warning_popup(message, parent=None):
    QMessageBox.warning(parent, 'Message', message, QMessageBox.Ok)
def ErrorMessage(message):
    QMessageBox.warning(None, 'Error', message)
Exemple #45
0
    def apply_fit(self):
        msgBox = QMessageBox()
        msgBox.setText("Apply corrections?")
        msgBox.setInformativeText(
            "Select to which files will be applied the correction.")
        CancelButton = msgBox.addButton("Cancel", msgBox.RejectRole)
        SelectButton = msgBox.addButton("Select", msgBox.NoRole)
        AllButton = msgBox.addButton("All", msgBox.YesRole)
        #msgBox.setDefaultButton(QMessageBox.Cancel)
        msgBox.exec_()
        if msgBox.clickedButton() == CancelButton:
            return -1
        elif msgBox.clickedButton() == AllButton:
            filelist = None
        elif msgBox.clickedButton() == SelectButton:
            flret = getopenfilenames(self, _("Select file list"),
                                     self.data_ref.dir_name)[0]
            filelist = []
            for f in flret:
                filelist.append((basename(str(f)), dirname(str(f))))
            msgBox = QMessageBox()
            msgBox.setText("Select the correction file")
            msgBox.addButton(QMessageBox.Ok)
            msgBox.exec_()

        filename = getopenfilename(
            self, _("Correction file"),
            self.data_ref.dir_name + "/" + basename(
                normpath(self.data_ref.dir_name) + "_fit." +
                self.data_ref.files_type))
        try:
            self.data_ref.applycorr(str(filename[0]), filelist)
        except:
            msgBox = QMessageBox()
            msgBox.setText("Not a correction file!")
            msgBox.exec_()
            return -1
Exemple #46
0
    def openDev(self):
        # search for devices
        libtiepie.device_list.update()
        # try to open an oscilloscope with block measurement support
        for item in libtiepie.device_list:
            if item.can_open(libtiepie.DEVICETYPE_OSCILLOSCOPE):
                self.scp = item.open_oscilloscope()
                if self.scp.measure_modes & libtiepie.MM_BLOCK:
                    break
                else:
                    self.scp = None
        # init UI
        #print(self.scp.name, 'found')
        if self.scp is not None:
            # Set measure mode:
            self.scp.measure_mode = libtiepie.MM_BLOCK

            # Set sample frequency:
            self.scp.sample_frequency = 1e6  # 1 MHz

            # Set record length:
            self.scp.record_length = 10000  # 10000 samples

            # Set pre sample ratio:
            self.scp.pre_sample_ratio = 0  # 0 %

            # Set trigger timeout:
            self.scp.trigger_time_out = 100e-3  # 100 ms

            # Enable channel 1 for measurement
            # http://api.tiepie.com/libtiepie/0.5/group__scp__ch__enabled.html
            self.scp.channels[
                0].enabled = True  # by default all channels are enabled
            self.scp.range = 0.2
            self.scp.coupling = libtiepie.CK_DCV  # DC Volt

            # Disable all channel trigger sources
            for ch in self.scp.channels:
                ch.trigger.enabled = False
            # Setup channel trigger on 1
            ch = self.scp.channels[0]
            ch.trigger.enabled = True
            ch.trigger.kind = libtiepie.TK_RISINGEDGE
            ch.trigger.levels[0] = 0.5  # 50%
            ch.trigger.hystereses[0] = 0.05  # 5%

            # update UI
            # channel
            self.measCh.addItems(
                ['Ch{:d}'.format(i) for i in range(self.scp.channels.count)])
            self.chSens.addItems(
                ['{:.1f} V'.format(i) for i in self.scp.channels[0].ranges])
            self.frequency.setValidator(
                QIntValidator(1, 1e-3 * self.scp.sample_frequency_max))
            self.frequency.setText('{:d}'.format(
                int(self.scp.sample_frequency * 1e-3)))
            self.recordLen.setValidator(
                QIntValidator(1, self.scp.record_length_max))
            self.recordLen.setText('{:d}'.format(self.scp.record_length))
            # trigger
            self.triggCh.addItems(
                ['Ch{:d}'.format(i) for i in range(self.scp.channels.count)])
            # TODO: doen't work in module anymore!!
            #self.triggLevel.setText(str(ch.trigger.levels[0]))
            #self.hystereses.setText(str(ch.trigger.hystereses[0]))
            self.triggKind.addItems([
                '{:s}'.format(i) for i in libtiepie.trigger_kind_str(
                    ch.trigger.kinds).split(', ')
            ])

            self.openDevBtn.setEnabled(False)

            # tell the world that the scope is connected
            self.xAxeChanged.emit(
                0, 1 / int(self.frequency.text()) * 1e-3 *
                int(self.recordLen.text()))
            self.yAxeChanged.emit(-1 * self.scp.range, self.scp.range)
            self.triggLevelChanged.emit(ch.trigger.levels[0] * 2 *
                                        self.scp.range - self.scp.range)
            self.scpConnected.emit()

        else:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText('No supported device found')
            msg.exec_()