Esempio n. 1
0
    def __init__(self):

        self._draw_count = 0
        interactive = matplotlib.is_interactive()
        matplotlib.interactive(False)
        self.roi_callback = None

        self.fig = Figure(facecolor=settings.BACKGROUND_COLOR)

        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self,
                                   QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)

        FigureCanvas.updateGeometry(self)
        self.manager = FigureManager(self, 0)
        matplotlib.interactive(interactive)

        self._resize_timer = QtCore.QTimer()
        self._resize_timer.setInterval(250)
        self._resize_timer.setSingleShot(True)
        self._resize_timer.timeout.connect(self._on_timeout)

        self.renderer = None
    def on_activate(self):
        """ Initialisation performed during activation of the module.
        """
        self._process = self.process()
        self._control = self.control()

        self.previousdelta = 0
        self.cv = self._control.get_control_value()

        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        self.timer.setInterval(self.timestep)

        self.timer.timeout.connect(self._calcNextStep,
                                   QtCore.Qt.QueuedConnection)
        self.sigNewValue.connect(self._control.set_control_value)

        self.history = np.zeros([3, 5])
        self.savingState = False
        self.enable = False
        self.integrated = 0
        self.countdown = 2

        self.timer.start(self.timestep)
Esempio n. 3
0
    def get(cls, title, text, parent, default=None, icon=None):
        dlg = cls(title, text, parent, icon=icon)
        if default:
            dlg.set_text(default)

        dlg.show()
        dlg.raise_()

        def show_popup():
            x = dlg.lineedit.x()
            y = dlg.lineedit.y() + dlg.lineedit.height()
            point = QtCore.QPoint(x, y)
            mapped = dlg.mapToGlobal(point)
            dlg.lineedit.popup().move(mapped.x(), mapped.y())
            dlg.lineedit.popup().show()
            dlg.lineedit.refresh()
            dlg.lineedit.setFocus(True)

        QtCore.QTimer().singleShot(100, show_popup)

        if dlg.exec_() == cls.Accepted:
            return dlg.text()
        else:
            return None
Esempio n. 4
0
    def _initUI(self):
        self.setFixedSize(QSize(259, 270))
        self.setGeometry(1600, 50, 259, 270)
        self.setWindowFlags(Qt.FramelessWindowHint
                            | QtCore.Qt.WindowStaysOnTopHint | Qt.Tool)

        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明

        self.label = QtWidgets.QLabel(self)
        self.label.setGeometry(QtCore.QRect(0, 0, 259, 111))
        self.label.setMinimumSize(QtCore.QSize(259, 111))
        self.label.setBaseSize(QtCore.QSize(259, 111))
        self.label.setStyleSheet(
            'font: 75 20pt "Adobe Arabic";color:rgb(255,0,0)')
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        # self.label.setText(self.getPos())

        self.timer = QtCore.QTimer(self)
        self.timer.start(1)
        self.timer.timeout.connect(self.start)

        self.setCursor(QCursor(Qt.PointingHandCursor))
        self.show()
Esempio n. 5
0
    def __init__(self, widget, dioptas_model):
        """
        :param widget: Reference to IntegrationWidget
        :param dioptas_model: Reference to DioptasModel object

        :type widget: IntegrationWidget
        :type dioptas_model: DioptasModel
        """

        self.widget = widget
        self.model = dioptas_model

        self.move_widget = widget.move_widget

        # Create timer
        self.epics_update_timer = QtCore.QTimer(self.widget)

        # read epics_config
        self.hor_motor_name = epics_config['sample_position_x']
        self.ver_motor_name = epics_config['sample_position_y']
        self.focus_motor_name = epics_config['sample_position_z']
        self.omega_motor_name = epics_config['sample_position_omega']

        self.connect_signals()
Esempio n. 6
0
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self._shutting_down = False

        # Setup widget
        self.jupyter_widget = _make_jupyter_widget_with_kernel('python3')
        self.jupyter_widget.syntax_style = 'monokai'
        self.jupyter_widget.set_default_style(colors='Linux')
        self.jupyter_widget.kernel_manager.kernel_restarted.connect(
            self._handle_kernel_restart
        )

        # Setup kernel readiness checks
        self._ready_lock = threading.Lock()
        self._kernel_is_ready = False
        self._pending_devices = []
        self._pending_commands = []

        self._device_history = set()

        self._check_readiness_timer = QtCore.QTimer()
        self._check_readiness_timer.setInterval(100)
        self._check_readiness_timer.timeout.connect(self._wait_for_readiness)
        self._check_readiness_timer.start()
        self.kernel_ready.connect(self._add_pending_devices)

        # Set the layout
        self.setLayout(QtWidgets.QHBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self.jupyter_widget)

        # Ensure we shutdown the kernel
        app = QtWidgets.QApplication.instance()
        app.aboutToQuit.connect(lambda: self.shutdown(block=True))

        self.device_added.connect(self._add_device_history)
 def __init__(self,
              xs,
              ys,
              xr,
              x,
              fx,
              app=None,
              parent=None,
              width=5,
              height=4,
              dpi=100):
     PlotFigure.__init__(self, parent, width, height, dpi)
     self.animateTimer = QtCore.QTimer(self)
     self.animateTimer.timeout.connect(self.update_figure)
     self.xs = xs
     self.ys = ys
     self.xr = xr
     self.x = x
     self.fx = fx
     self.generator = self.points_generator()
     self.parent = parent
     self.app = app
     self.axes.plot(self.xs, self.ys, label='function', color='r', lw=2)
     self.axes.legend()
Esempio n. 8
0
    def display_log(self, record):
        self.show_log.emit([record])


EL = ExceptionLauncher()
# Exceptions raised by the event loop should be displayed in the MainWindow status_bar.
# see http://stackoverflow.com/questions/40608610/exceptions-in-pyqt-event-loop-and-ipython
# when running in ipython, we have to monkeypatch sys.excepthook in the qevent loop.


def patch_excepthook():
    EL.old_except_hook = sys.excepthook
    sys.excepthook = EL.display_exception


TIMER = QtCore.QTimer()
TIMER.setSingleShot(True)
TIMER.setInterval(0)
TIMER.timeout.connect(patch_excepthook)
TIMER.start()


class LogHandler(QtCore.QObject, logging.Handler):
    """
    A handler class which sends log strings to a wx object
    """
    show_log = QtCore.Signal(list)

    def __init__(self):
        """
        Initialize the handler
    def on_activate(self, e=None):
        """ Activation method called on change to active state.

        @param object e: Fysom.event object from Fysom class.
                         An object created by the state machine module Fysom,
                         which is connected to a specific event (have a look
                         in the Base Class). This object contains the passed
                         event, the state before the event happened and the
                         destination of the state which should be reached
                         after the event had happened.

        This method creates the Manager main window.
        """
        if _has_pyqtgraph:
            # set background of pyqtgraph
            testwidget = QWidget()
            testwidget.ensurePolished()
            bgcolor = testwidget.palette().color(QPalette.Normal,
                                                 testwidget.backgroundRole())
            # set manually the background color in hex code according to our
            # color scheme:
            pg.setConfigOption('background', bgcolor)

            # opengl usage
            if 'useOpenGL' in self._manager.tree['global']:
                pg.setConfigOption('useOpenGL',
                                   self._manager.tree['global']['useOpenGL'])
        self._mw = ManagerMainWindow()
        self.restoreWindowPos(self._mw)
        self.errorDialog = ErrorDialog(self)
        self._about = AboutDialog()
        version = self.getSoftwareVersion()
        configFile = self._manager.configFile
        self._about.label.setText(
            '<a href=\"https://github.com/Ulm-IQO/qudi/commit/{0}\"'
            ' style=\"color: cyan;\"> {0} </a>, on branch {1}.'.format(
                version[0], version[1]))
        self.versionLabel = QtWidgets.QLabel()
        self.versionLabel.setText(
            '<a href=\"https://github.com/Ulm-IQO/qudi/commit/{0}\"'
            ' style=\"color: cyan;\"> {0} </a>,'
            ' on branch {1}, configured from {2}'.format(
                version[0], version[1], configFile))
        self.versionLabel.setOpenExternalLinks(True)
        self._mw.statusBar().addWidget(self.versionLabel)
        # Connect up the buttons.
        self._mw.actionQuit.triggered.connect(self._manager.quit)
        self._mw.actionLoad_configuration.triggered.connect(self.getLoadFile)
        self._mw.actionReload_current_configuration.triggered.connect(self.reloadConfig)
        self._mw.actionSave_configuration.triggered.connect(self.getSaveFile)
        self._mw.action_Load_all_modules.triggered.connect(self._manager.startAllConfiguredModules)
        self._mw.actionAbout_Qt.triggered.connect(QtWidgets.QApplication.aboutQt)
        self._mw.actionAbout_Qudi.triggered.connect(self.showAboutQudi)
        self._mw.actionReset_to_default_layout.triggered.connect(self.resetToDefaultLayout)

        self._manager.sigShowManager.connect(self.show)
        self._manager.sigConfigChanged.connect(self.updateConfigWidgets)
        self._manager.sigModulesChanged.connect(self.updateConfigWidgets)
        # Log widget
        self._mw.logwidget.setManager(self._manager)
        for loghandler in logging.getLogger().handlers:
            if isinstance(loghandler, core.logger.QtLogHandler):
                loghandler.sigLoggedMessage.connect(self.handleLogEntry)
        # Module widgets
        self.sigStartModule.connect(self._manager.startModule)
        self.sigReloadModule.connect(self._manager.restartModuleSimple)
        self.sigCleanupStatus.connect(self._manager.removeStatusFile)
        self.sigStopModule.connect(self._manager.deactivateModule)
        self.sigLoadConfig.connect(self._manager.loadConfig)
        self.sigSaveConfig.connect(self._manager.saveConfig)
        # Module state display
        self.checkTimer = QtCore.QTimer()
        self.checkTimer.start(1000)
        self.updateGUIModuleList()
        # IPython console widget
        self.startIPython()
        self.updateIPythonModuleList()
        self.startIPythonWidget()
        # thread widget
        self._mw.threadWidget.threadListView.setModel(self._manager.tm)
        # remote widget
        self._mw.remoteWidget.hostLabel.setText('URL:')
        self._mw.remoteWidget.portLabel.setText(
            'rpyc://{0}:{1}/'.format(self._manager.rm.host,
                                     self._manager.rm.server.port))
        self._mw.remoteWidget.remoteModuleListView.setModel(
            self._manager.rm.remoteModules)
        self._mw.remoteWidget.sharedModuleListView.setModel(
            self._manager.rm.sharedModules)

        self._mw.configDisplayDockWidget.hide()
        self._mw.remoteDockWidget.hide()
        self._mw.threadDockWidget.hide()
        self._mw.show()
Esempio n. 10
0
 def onStart(self):
     self.timer = QtCore.QTimer()
     self.timer.timeout.connect(self.flushFileStatus)
     self.timer.setInterval(100)
     self.timer.setSingleShot(True)
Esempio n. 11
0
 def started(self):
     self.trigger_timer = QtCore.QTimer()
     self.trigger_timer.timeout.connect(self._check_timeout)
     self.trigger_timer.start(1000)
Esempio n. 12
0
 def start(self):
     if self._timer is None:
         self._timer = QtCore.QTimer()
         self._timer.timeout.connect(self.poll)
     self._timer.start(round(self.time_to_dead * 1000))
Esempio n. 13
0
    def __init__(self,
                 nplots,
                 ncurves=1,
                 title='Multi trace plot',
                 station=None):
        """ Plot window for multiple 1D traces """
        self.title = title
        self.verbose = 1
        self.station = station
        plotwin = pg.GraphicsWindow(title=title)
        self.plotwin = plotwin

        win = QtWidgets.QWidget()
        win.show()
        win.setWindowTitle(self.title)
        win.resize(800, 600)
        self.win = win
        topLayout = QtWidgets.QHBoxLayout()
        win.start_button = QtWidgets.QPushButton('Start')
        win.stop_button = QtWidgets.QPushButton('Stop')
        win.ppt_button = QtWidgets.QPushButton('PPT')
        for b in [win.start_button, win.stop_button, win.ppt_button]:
            b.setMaximumHeight(24)

        self.diff = False
        self._moving_average = True
        self.alpha = 0.3  # for moving average
        self.ydata = None

        win.averaging_box = QtWidgets.QCheckBox('Averaging')
        win.averaging_box.setChecked(self._moving_average)

        topLayout.addWidget(win.start_button)
        topLayout.addWidget(win.stop_button)
        topLayout.addWidget(win.ppt_button)
        topLayout.addWidget(win.averaging_box)

        vertLayout = QtWidgets.QVBoxLayout()

        vertLayout.addLayout(topLayout)
        vertLayout.addWidget(plotwin)

        win.setLayout(vertLayout)

        self.nx = int(np.ceil(np.sqrt(nplots)))
        self.ny = int(np.ceil((nplots / self.nx)))

        # Enable antialiasing for prettier plots
        # pg.setConfigOptions(antialias=True)

        self.plots = []
        self.ncurves = ncurves
        self.curves = []
        pens = [(255, 0, 0), (0, 0, 255), (0, 255, 0), (255, 255, 0)] * 3

        for ii in range(self.ny):
            for ix in range(self.nx):
                p = plotwin.addPlot()
                self.plots.append(p)
                cc = []
                for ii in range(ncurves):
                    c = p.plot(pen=pens[ii])
                    cc += [c]
                self.curves.append(cc)
            plotwin.nextRow()

        self.fps = qtt.pgeometry.fps_t()

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self._updatefunction)

        def connect_slot(target):
            """ Create a slot by dropping signal arguments """
            def signal_drop_arguments(*args, **kwargs):
                target()

            return signal_drop_arguments

        win.start_button.clicked.connect(connect_slot(self.startreadout))
        win.stop_button.clicked.connect(connect_slot(self.stopreadout))
        win.ppt_button.clicked.connect(connect_slot(self.add_ppt))
        win.averaging_box.clicked.connect(
            connect_slot(self.enable_averaging_slot))

        self.setGeometry = self.win.setGeometry
Esempio n. 14
0
    def __init__(self,
                 parent=None,
                 width: int = 600,
                 resultHeight: int = 36,
                 titleHeight: int = 36,
                 primaryTextWidth: int = 320,
                 secondaryTextWidth: int = 200,
                 maxVisibleItemCount: int = 8):
        super().__init__(parent)
        self.alignment = QC.Qt.AlignCenter
        self.resultHeight = resultHeight
        self.titleHeight = titleHeight
        self.primaryTextWidth = primaryTextWidth
        self.locator = None
        self.secondaryTextWidth = secondaryTextWidth
        self.maxVisibleItemCount = maxVisibleItemCount
        self.reservedItemCounts = []
        self.visibleResultItemCounts = []
        self.currentJobIds = []
        self.titleItems = []
        self.resultItems = []
        self.escapeShortcuts = []
        self.selectedLayoutItemIndex = 0
        self.defaultStylingEnabled = True
        self.context = None
        self.lastQuery = str()
        self.setVisible(False)
        self.setLayout(QW.QVBoxLayout())
        self.searchEdit = QW.QLineEdit()
        self.resultList = QW.QScrollArea()
        self.resultLayout = QW.QVBoxLayout()
        self.resultList.setWidget(QW.QWidget())
        self.resultList.widget().setLayout(self.resultLayout)
        self.resultList.setWidgetResizable(True)
        self.resultLayout.setSizeConstraint(QW.QLayout.SetMinAndMaxSize)
        self.layout().addWidget(self.searchEdit)
        self.layout().addWidget(self.resultList)
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setSpacing(0)
        self.resultLayout.setContentsMargins(0, 0, 0, 0)
        self.resultLayout.setSpacing(0)
        self.setFixedWidth(width)
        self.setWindowFlags(QC.Qt.FramelessWindowHint
                            | QC.Qt.WindowStaysOnTopHint
                            | QC.Qt.CustomizeWindowHint | QC.Qt.Popup)
        self.resultList.setSizeAdjustPolicy(
            QW.QAbstractScrollArea.AdjustToContents)
        self.setSizePolicy(QW.QSizePolicy.Fixed, QW.QSizePolicy.Maximum)
        self.setEscapeShortcuts([QC.Qt.Key_Escape])
        self.editorDownShortcut = QW.QShortcut(QG.QKeySequence(QC.Qt.Key_Down),
                                               self.searchEdit)
        self.editorDownShortcut.setContext(QC.Qt.WidgetShortcut)
        self.editorDownShortcut.activated.connect(self.handleEditorDown)

        def handleTextEdited():
            for i in range(len(self.resultItems)):
                for it in self.resultItems[i]:
                    self.setResultVisible(it, False)
                self.setResultVisible(self.titleItems[i], False)
            self.selectedLayoutItemIndex = 0
            self.updateResultListHeight()

        self.searchEdit.textEdited.connect(handleTextEdited)

        def handleSearchFocused():
            if self.selectedLayoutItemIndex < self.resultLayout.count():
                widget = self.resultLayout.itemAt(
                    self.selectedLayoutItemIndex).widget()
                if widget:
                    if isinstance(widget, QLocatorResultWidget):
                        widget.setSelected(False)
                        self.selectedLayoutItemIndex = 0

        filter = FocusEventFilter()
        self.searchEdit.installEventFilter(filter)
        filter.focused.connect(handleSearchFocused)

        self.queryTimer = QC.QTimer(self)
        self.queryTimer.setInterval(0)
        self.queryTimer.setSingleShot(True)

        def handleQueryTimeout():
            if not self.locator: return
            self.currentJobIds = self.locator.query(self.lastQuery,
                                                    self.context)

        self.queryTimer.timeout.connect(handleQueryTimeout)
        self.searchEdit.textEdited.connect(self.queryLocator)

        self.updateResultListHeight()
Esempio n. 15
0
 def setup_backup_timer(self):
     self.backup_timer = QtCore.QTimer(self.widget)
     self.backup_timer.timeout.connect(self.save_default_settings)
     self.backup_timer.setInterval(600000)  # every 10 minutes
     self.backup_timer.start()
Esempio n. 16
0
    def __init__(self, name='Measurement Control',
                 rda_variable='qtt_abort_running_measurement', text_vars=[],
                 **kwargs):
        """ Simple control for running measurements

        Args:
            name (str): used as window title
            rda_variable (str):
            text_vars (list):

        """
        super().__init__(**kwargs)
        w = self
        w.setWindowTitle(name)
        vbox = QtWidgets.QVBoxLayout()
        self.verbose = 0
        self.name = name
        self.rda_variable = rda_variable
        self.rda = rda_t()
        self.text_vars = text_vars
        if len(text_vars) > 0:
            self.vLabels = {}
            self.vEdits = {}
            self.vButtons = {}
            self.vActions = []
            for tv in text_vars:
                self.vLabels[tv] = QtWidgets.QLabel()
                self.vLabels[tv].setText('%s:' % tv)
                self.vEdits[tv] = (QtWidgets.QTextEdit())
                try:
                    self.vEdits[tv].setText(
                        self.rda.get(tv, b'').decode('utf-8'))
                except Exception as Ex:
                    print('could not retrieve value %s: %s' % (tv, str(Ex)))
                self.vButtons[tv] = QtWidgets.QPushButton()
                self.vButtons[tv].setText('Send')
                self.vButtons[tv].setStyleSheet(
                    "background-color: rgb(255,150,100);")
                self.vButtons[tv].clicked.connect(partial(self.sendVal, tv))
                vbox.addWidget(self.vLabels[tv])
                vbox.addWidget(self.vEdits[tv])
                vbox.addWidget(self.vButtons[tv])
        self.text = QtWidgets.QLabel()
        self.updateStatus()
        vbox.addWidget(self.text)
        self.abortbutton = QtWidgets.QPushButton()
        self.abortbutton.setText('Abort measurement')
        self.abortbutton.setStyleSheet("background-color: rgb(255,150,100);")
        self.abortbutton.clicked.connect(self.abort_measurements)
        vbox.addWidget(self.abortbutton)
        self.enable_button = QtWidgets.QPushButton()
        self.enable_button.setText('Enable measurements')
        self.enable_button.setStyleSheet("background-color: rgb(255,150,100);")
        self.enable_button.clicked.connect(self.enable_measurements)
        vbox.addWidget(self.enable_button)
        widget = QtWidgets.QWidget()
        widget.setLayout(vbox)
        self.setCentralWidget(widget)

        menuBar = self.menuBar()

        menuDict = {
            '&Edit': {'&Get all Values': self.getAllValues},
            '&Help': {'&Info': self.showHelpBox}
        }
        for (k, menu) in menuDict.items():
            mb = menuBar.addMenu(k)
            for (kk, action) in menu.items():

                act = QtWidgets.QAction(kk, self)
                mb.addAction(act)
                act.triggered.connect(action)
        w.resize(300, 300)
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateStatus)  # this also works
        self.timer.start(1000)
        self.show()
Esempio n. 17
0
    def __init__(
            self,
            datafunction=None,
            sweepInstrument=None,
            sweepparams=None,
            sweepranges=None,
            alpha=.3,
            verbose=1,
            show_controls=True,
            window_title='live view',
            plot_dimension=None,
            plot_title=None,
            is1dscan=None, **kwargs):
        """Return a new livePlot object."""
        super().__init__(**kwargs)

        self.window_title = window_title
        win = QtWidgets.QWidget()
        win.resize(800, 600)
        win.setWindowTitle(self.window_title)
        vertLayout = QtWidgets.QVBoxLayout()

        self._averaging_enabled = 2
        if show_controls:
            topLayout = QtWidgets.QHBoxLayout()
            win.start_button = QtWidgets.QPushButton('Start')
            win.stop_button = QtWidgets.QPushButton('Stop')
            win.averaging_box = QtWidgets.QCheckBox('Averaging')
            win.averaging_box.setChecked(self._averaging_enabled)
            for b in [win.start_button, win.stop_button]:
                b.setMaximumHeight(24)
            topLayout.addWidget(win.start_button)
            topLayout.addWidget(win.stop_button)
            topLayout.addWidget(win.averaging_box)
            vertLayout.addLayout(topLayout)
        plotwin = pg.GraphicsWindow(title="Live view")
        vertLayout.addWidget(plotwin)
        win.setLayout(vertLayout)
        self.setGeometry = win.setGeometry
        self.win = win
        self.plotwin = plotwin
        self.verbose = verbose
        self.idx = 0
        self.maxidx = 1e9
        self.data = None
        self.data_avg = None
        self.sweepInstrument = sweepInstrument
        self.sweepparams = sweepparams
        self.sweepranges = sweepranges
        self.fps = pgeometry.fps_t(nn=6)
        self.datafunction = datafunction
        self.datafunction_result = None
        self.plot_dimension=plot_dimension
        self.alpha = alpha
        if is1dscan is None:
            is1dscan = (
                isinstance(
                    self.sweepparams, str) or (
                    isinstance(
                        self.sweepparams, (list, dict)) and len(
                        self.sweepparams) == 1))
            if isinstance(self.sweepparams, dict):
                if 'gates_horz' not in self.sweepparams:
                    is1dscan = True
        if verbose:
            print('live_plotting: is1dscan %s' % is1dscan)
        if self.sweepparams is None:
            p1 = plotwin.addPlot(title=plot_title)
            p1.setLabel('left', 'param2')
            p1.setLabel('bottom', 'param1')
            if plot_dimension == 1:
                dd = np.zeros((0,))
                plot = p1.plot(dd, pen='b')
                self.plot = plot
            else:
                self.plot = pg.ImageItem()
                p1.addItem(self.plot)
            self._crosshair = []
        elif is1dscan:
            p1 = plotwin.addPlot(title=plot_title)
            p1.setLabel('left', 'Value')
            p1.setLabel('bottom', self.sweepparams, units='mV')
            dd = np.zeros((0,))
            plot = p1.plot(dd, pen='b')
            self.plot = plot
            vpen = pg.QtGui.QPen(pg.QtGui.QColor(
                130, 130, 175, 60), 0, pg.QtCore.Qt.SolidLine)
            gv = pg.InfiniteLine([0, 0], angle=90, pen=vpen)
            gv.setZValue(0)
            p1.addItem(gv)
            self._crosshair = [gv]
            self.crosshair(show=False)
        elif isinstance(self.sweepparams, (list, dict)):
            # 2D scan
            p1 = plotwin.addPlot(title=plot_title)
            if type(self.sweepparams) is dict:
                [xlabel, ylabel] = ['sweepparam_v', 'stepparam_v']
            else:
                [xlabel, ylabel] = self.sweepparams
            p1.setLabel('bottom', xlabel, units='mV')
            p1.setLabel('left', ylabel, units='mV')
            self.plot = pg.ImageItem()
            p1.addItem(self.plot)
            vpen = pg.QtGui.QPen(pg.QtGui.QColor(
                0, 130, 235, 60), 0, pg.QtCore.Qt.SolidLine)
            gh = pg.InfiniteLine([0, 0], angle=90, pen=vpen)
            gv = pg.InfiniteLine([0, 0], angle=0, pen=vpen)
            gh.setZValue(0)
            gv.setZValue(0)
            p1.addItem(gh)
            p1.addItem(gv)
            self._crosshair = [gh, gv]
            self.crosshair(show=False)
        else:
            raise Exception(
                'The number of sweep parameters should be either None, 1 or 2.')
        self.plothandle = p1
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updatebg)
        self.win.show()

        def connect_slot(target):
            """ Create a slot by dropping signal arguments """
            def signal_drop_arguments(*args, **kwargs):
                target()
            return signal_drop_arguments

        if show_controls:
            win.start_button.clicked.connect(connect_slot(self.startreadout))
            win.stop_button.clicked.connect(connect_slot(self.stopreadout))
            win.averaging_box.clicked.connect(
                connect_slot(self.enable_averaging_slot))

        self.datafunction_result = None

        self.plotwin.scene().sigMouseClicked.connect(self._onClick)
Esempio n. 18
0
    def __init__(self, *args):
        super(main_GUI, self).__init__(*args)
        self.setWindowTitle("MOSAICpy :: Modular image processing tool")
        self.LLSItemThreads = []
        self.compressionThreads = []
        self.argQueue = [
        ]  # holds all argument lists that will be sent to threads
        self.aborted = False  # current abort status
        self.spimwins = []
        self._eta = 0

        # delete and reintroduce custom folderqueue.LLSDragDropTable and imp window
        self.listbox.setParent(None)
        self.listbox = folderqueue.LLSDragDropTable(self)
        self.listbox.status_update.connect(self.statusBar.showMessage)
        self.listbox.item_starting.connect(self.initProgress)
        self.listbox.step_finished.connect(self.incrementProgress)
        self.listbox.work_finished.connect(self.onProcessFinished)
        self.listbox.eta_update.connect(self.set_eta)
        self.processSplitter.insertWidget(0, self.listbox)
        self.impListWidget.setParent(None)
        self.impContainer = implist.ImpListContainer(parent=self)
        self.impListWidget = self.impContainer.list
        self.processSplitter.addWidget(self.impContainer)
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateClock)
        self.actionAbort.triggered.connect(self.listbox.abort_workers)

        handler = qtlogger.NotificationHandler()
        handler.emitSignal.connect(self.log.append)
        logger.addHandler(handler)

        self.camcorDialog = camcalibgui.CamCalibDialog()
        self.genFlashParams.clicked.connect(self.camcorDialog.show)
        self.actionCamera_Calibration.triggered.connect(self.camcorDialog.show)

        # connect buttons
        self.processButton.clicked.connect(self.onProcess)
        # self.errorOptOutCheckBox.stateChanged.connect(self.toggleOptOut)

        # def toggleActiveGPU(val):
        #     gpunum = int(self.sender().objectName().strip('useGPU_'))
        #     app = QtCore.QCoreApplication.instance()
        #     if not hasattr(app, 'gpuset'):
        #         app.gpuset = set()
        #     if val:
        #         app.gpuset.add(gpunum)
        #         logger.debug("GPU {} added to gpuset.".format(gpunum))
        #     else:
        #         if gpunum in app.gpuset:
        #             app.gpuset.remove(gpunum)
        #             logger.debug("GPU {} removed from gpuset.".format(gpunum))
        #     logger.debug("GPUset now: {}".format(app.gpuset))

        # add GPU checkboxes and add
        # try:
        #     app = QtCore.QCoreApplication.instance()
        #     if not hasattr(app, 'gpuset'):
        #         app.gpuset = set()
        #     gpulist = mosaicpy.cudabinwrapper.gpulist()
        #     if len(gpulist):
        #         for i, gpu in enumerate(gpulist):
        #             box = QtWidgets.QCheckBox(self.tab_config)
        #             box.setChecked(True)
        #             box.setObjectName('useGPU_{}'.format(i))
        #             box.setText(gpu.strip('GeForce'))
        #             box.stateChanged.connect(toggleActiveGPU)
        #             app.gpuset.add(i)
        #             self.gpuGroupBoxLayout.addWidget(box)
        #     else:
        #         label = QtWidgets.QLabel(self.tab_config)
        #         label.setText('No CUDA-capabled GPUs detected')
        #         self.gpuGroupBoxLayout.addWidget(label)

        # except mosaicpy.cudabinwrapper.CUDAbinException as e:
        #     logger.warn(e)
        #     pass

        # connect actions

        # set validators for cRange and tRange fields
        ctrangeRX = QtCore.QRegExp(r"(\d[\d-]*,?)*")  # could be better
        ctrangeValidator = QtGui.QRegExpValidator(ctrangeRX)
        self.processCRangeLineEdit.setValidator(ctrangeValidator)
        self.processTRangeLineEdit.setValidator(ctrangeValidator)
        self.previewCRangeLineEdit.setValidator(ctrangeValidator)
        self.previewTRangeLineEdit.setValidator(ctrangeValidator)

        self.preview_threads = None
        self.previewAborted = False
        self.previewButton.clicked.connect(self.onPreview)
        if not preview._spimagine:
            self.prevBackendMatplotlibRadio.setChecked(True)
            self.prevBackendSpimagineRadio.setDisabled(True)
            self.prevBackendSpimagineRadio.setText("spimagine [unavailable]")

        self.disableSpimagineCheckBox.clicked.connect(
            lambda: QtWidgets.QMessageBox.information(
                self,
                "Restart Required",
                "Please quit and restart MOSAICpy for changes to take effect",
                QtWidgets.QMessageBox.Ok,
            ))

        # connect worker signals and slots

        self.RegCalib_channelRefModeCombo.clear()
        self.RegCalib_channelRefCombo.clear()

        # Restore settings from previous session and show ready status
        settings.guirestore(self, SETTINGS, SETTINGS)

        self.RegCalibPathLineEdit.setText("")
        self.RegFilePath.setText("")

        self.clock.display("00:00:00")
        self.statusBar.showMessage("Ready")

        self.show()
        self.raise_()
Esempio n. 19
0
    def update(self):
        super(MyGUI, self).update()
        if self.ser.is_open:
            in_str = self.ser.readline().decode('utf-8').strip()
            if in_str:
                in_value = float(in_str)
                display_string = "{0:.3f}".format(
                    in_value + self.doubleSpinBox_offset.value())
                self.lcdNumber.display(display_string)

                cbsdk_conn = CbSdkConnection()
                if cbsdk_conn.is_connected and (display_string !=
                                                self.display_string):
                    cbsdk_conn.set_comments("DTT:" + display_string)
                    self.display_string = display_string
                else:
                    self.pushButton_send.setText("Send")


if __name__ == '__main__':
    qapp = QtWidgets.QApplication(sys.argv)
    window = MyGUI()
    window.show()
    timer = QtCore.QTimer()
    timer.timeout.connect(window.update)
    timer.start(100)

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtWidgets.QApplication.instance().exec_()
Esempio n. 20
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle(_('Training'))
        self.set_default_window_flags(self)
        self.setWindowModality(Qt.ApplicationModal)

        self.batch_size = 0
        self.training_has_started = False

        layout = QtWidgets.QVBoxLayout()
        self.setLayout(layout)

        sep_label_text = _('of')

        epoch_label = QtWidgets.QLabel(_('Epoch'))
        self.epoch_value = QtWidgets.QLabel('-')
        epoch_sep = QtWidgets.QLabel(sep_label_text)
        self.epoch_max_value = QtWidgets.QLabel('-')

        batch_label = QtWidgets.QLabel(_('Batch'))
        self.batch_value = QtWidgets.QLabel('-')
        batch_sep = QtWidgets.QLabel(sep_label_text)
        self.batch_max_value = QtWidgets.QLabel('-')

        self.average_speed = 0
        self.speed_count = 0
        speed_label = QtWidgets.QLabel(_('Speed'))
        self.speed_value = QtWidgets.QLabel('-')

        time_label = QtWidgets.QLabel(_('Duration'))
        self.time_value = QtWidgets.QLabel('00:00:00')

        finished_label = QtWidgets.QLabel(_('Time left'))
        self.finished_value = QtWidgets.QLabel('-')

        self.start_time = False
        self.time_timer = QtCore.QTimer()
        self.time_timer.timeout.connect(self.timer_tick)
        self.time_timer.start(500)

        details_group = QtWidgets.QGroupBox()
        details_group.setTitle(_('Details'))
        details_group_layout = QtWidgets.QGridLayout()
        details_group.setLayout(details_group_layout)
        details_group_layout.addWidget(epoch_label, 0, 0, 1, 2)
        details_group_layout.addWidget(self.epoch_value, 0, 2)
        details_group_layout.addWidget(epoch_sep, 0, 3)
        details_group_layout.addWidget(self.epoch_max_value, 0, 4)
        details_group_layout.addWidget(batch_label, 1, 0, 1, 2)
        details_group_layout.addWidget(self.batch_value, 1, 2)
        details_group_layout.addWidget(batch_sep, 1, 3)
        details_group_layout.addWidget(self.batch_max_value, 1, 4)
        details_group_layout.addWidget(speed_label, 2, 0, 1, 2)
        details_group_layout.addWidget(self.speed_value, 2, 2, 1, 3)
        details_group_layout.addWidget(time_label, 3, 0, 1, 2)
        details_group_layout.addWidget(self.time_value, 3, 2, 1, 3)
        details_group_layout.addWidget(finished_label, 4, 0, 1, 2)
        details_group_layout.addWidget(self.finished_value, 4, 2, 1, 3)
        layout.addWidget(details_group)

        self.metric_labels = []
        self.metric_values = []
        self.metric_group = QtWidgets.QGroupBox()
        self.metric_group.setTitle(_('Metric'))
        self.metric_group_layout = QtWidgets.QGridLayout()
        self.metric_group.setLayout(self.metric_group_layout)
        layout.addWidget(self.metric_group)

        large_font = QtGui.QFont('Arial', 13, QtGui.QFont.Normal)

        self.validation_labels = []
        self.validation_values = []
        self.validation_group = QtWidgets.QGroupBox()
        self.validation_group.setTitle(_('Validation'))
        self.validation_group.setFont(large_font)
        self.validation_group.setStyleSheet('background-color:#f6f6f6;')
        self.validation_group_layout = QtWidgets.QGridLayout()
        self.validation_group.setLayout(self.validation_group_layout)
        layout.addWidget(self.validation_group)

        # # Colors
        # self.setAutoFillBackground(True)
        # color = QtGui.QColor('#f0f0f0')
        # p = self.palette()
        # p.setColor(self.backgroundRole(), color)
        # self.setPalette(p)

        # self.validation_group.setAutoFillBackground(True)
        # color = QtGui.QColor('#fafafa')
        # p = self.validation_group.palette()
        # p.setColor(self.validation_group.backgroundRole(), color)
        # self.validation_group.setPalette(p)

        self.image_label = QtWidgets.QLabel()
        layout.addWidget(self.image_label)

        self.progress_bar = QtWidgets.QProgressBar()
        layout.addWidget(self.progress_bar)

        layout.addStretch()

        button_box = QtWidgets.QDialogButtonBox()
        cancel_btn = button_box.addButton(
            _('Cancel'), QtWidgets.QDialogButtonBox.RejectRole)
        cancel_btn.clicked.connect(self.cancel_btn_clicked)
        layout.addWidget(button_box)

        self.resize(300, 300)
Esempio n. 21
0
def run_demo(close_after=None, auto_test=False):
    '''
    Args:
    close_after: either None or integer. Number of seconds
    after which the demo will close
    auto_test: boolean. If true then randomly select a style at intervals.

    This function provides a demonstration in changing the application style sheet.
    1) The first option is to set the style sheet once with
       app.setStyleSheet(StylePicker("default").get_sheet())
    2) The second option is to include a style picker widget (QComboBox) that'll
       change the application style sheet when a new style is selected
       grid.addWidget(StylePickerWidget(), 2, 0)
    '''

    app = QtWidgets.QApplication.instance()
    if not app:
        app = QtWidgets.QApplication([])

    win = QtWidgets.QMainWindow()
    win.setWindowTitle("Style Sheets")

    frame = QtWidgets.QFrame()
    win.setCentralWidget(frame)

    grid = QtWidgets.QGridLayout(frame)
    grid.setHorizontalSpacing(5)
    grid.setVerticalSpacing(5)
    grid.addWidget(QtWidgets.QLabel("Username"), 0, 0)
    grid.addWidget(QtWidgets.QLabel("Password"), 1, 0)
    user_input = QtWidgets.QLineEdit()
    pass_input = QtWidgets.QLineEdit()
    grid.addWidget(user_input, 0, 1)
    grid.addWidget(pass_input, 1, 1)

    picker_widget = StylePickerWidget()
    grid.addWidget(picker_widget, 2, 0)
    grid.addWidget(QtWidgets.QPushButton("Submit"), 2, 1)
    win.show()

    def choose_random_style():
        ''' select a random style from the picker_widget '''
        style_list = StylePicker().available_styles
        chosen_style = random.choice(style_list)
        picker_widget.setCurrentIndex(picker_widget.findText(chosen_style))

    def close_demo():
        ''' close the demo once 'close_after' seconds have elapsed '''
        win.close()

    if auto_test:
        timer = QtCore.QTimer()
        timer.timeout.connect(choose_random_style)
        timer.start(1000)

    if isinstance(close_after, int):
        close_timer = QtCore.QTimer()
        close_timer.singleShot(close_after * 1000, close_demo) # seconds * 1000 = milliseconds

    app.setStyleSheet(StylePicker("default").get_sheet())
    app.exec_()
    def on_activate(self):
        """ Activation method called on change to active state.

        This method creates the Manager main window.
        """
        if _has_pyqtgraph:
            # set background of pyqtgraph
            testwidget = QWidget()
            testwidget.ensurePolished()
            bgcolor = testwidget.palette().color(QPalette.Normal,
                                                 testwidget.backgroundRole())
            # set manually the background color in hex code according to our
            # color scheme:
            pg.setConfigOption('background', bgcolor)

            # opengl usage
            if 'useOpenGL' in self._manager.tree['global']:
                pg.setConfigOption('useOpenGL',
                                   self._manager.tree['global']['useOpenGL'])
        self._mw = ManagerMainWindow()
        self.restoreWindowPos(self._mw)
        self.errorDialog = ErrorDialog(self)
        self._about = AboutDialog()
        version = self.getSoftwareVersion()
        configFile = self._manager.configFile
        self._about.label.setText(
            '<a href=\"https://github.com/Ulm-IQO/qudi/commit/{0}\"'
            ' style=\"color: cyan;\"> {0} </a>, on branch {1}.'.format(
                version[0], version[1]))
        self.versionLabel = QtWidgets.QLabel()
        self.versionLabel.setText(
            '<a href=\"https://github.com/Ulm-IQO/qudi/commit/{0}\"'
            ' style=\"color: cyan;\"> {0} </a>,'
            ' on branch {1}, configured from {2}'.format(
                version[0], version[1], configFile))
        self.versionLabel.setOpenExternalLinks(True)
        self._mw.statusBar().addWidget(self.versionLabel)
        # Connect up the buttons.
        self._mw.actionQuit.triggered.connect(self._manager.quit)
        self._mw.actionLoad_configuration.triggered.connect(self.getLoadFile)
        self._mw.actionReload_current_configuration.triggered.connect(
            self.reloadConfig)
        self._mw.actionSave_configuration.triggered.connect(self.getSaveFile)
        self._mw.action_Load_all_modules.triggered.connect(
            self._manager.startAllConfiguredModules)
        self._mw.actionAbout_Qt.triggered.connect(
            QtWidgets.QApplication.aboutQt)
        self._mw.actionAbout_Qudi.triggered.connect(self.showAboutQudi)
        self._mw.actionReset_to_default_layout.triggered.connect(
            self.resetToDefaultLayout)

        self._manager.sigShowManager.connect(self.show)
        self._manager.sigConfigChanged.connect(self.updateConfigWidgets)
        self._manager.sigModulesChanged.connect(self.updateConfigWidgets)
        self._manager.sigShutdownAcknowledge.connect(self.promptForShutdown)
        # Log widget
        self._mw.logwidget.setManager(self._manager)
        for loghandler in logging.getLogger().handlers:
            if isinstance(loghandler, core.logger.QtLogHandler):
                loghandler.sigLoggedMessage.connect(self.handleLogEntry)
        # Module widgets
        self.sigStartModule.connect(self._manager.startModule)
        self.sigReloadModule.connect(self._manager.restartModuleRecursive)
        self.sigCleanupStatus.connect(self._manager.removeStatusFile)
        self.sigStopModule.connect(self._manager.deactivateModule)
        self.sigLoadConfig.connect(self._manager.loadConfig)
        self.sigSaveConfig.connect(self._manager.saveConfig)
        self.sigRealQuit.connect(self._manager.realQuit)
        # Module state display
        self.checkTimer = QtCore.QTimer()
        self.checkTimer.start(1000)
        self.updateGUIModuleList()
        # IPython console widget
        self.startIPython()
        self.updateIPythonModuleList()
        self.startIPythonWidget()
        # thread widget
        self._mw.threadWidget.threadListView.setModel(self._manager.tm)
        # remote widget
        # hide remote menu item if rpyc is not available
        self._mw.actionRemoteView.setVisible(self._manager.rm is not None)
        if self._manager.rm is not None:
            self._mw.remoteWidget.remoteModuleListView.setModel(
                self._manager.rm.remoteModules)
            if self._manager.remote_server:
                self._mw.remoteWidget.hostLabel.setText('Server URL:')
                self._mw.remoteWidget.portLabel.setText(
                    'rpyc://{0}:{1}/'.format(self._manager.rm.server.host,
                                             self._manager.rm.server.port))
                self._mw.remoteWidget.sharedModuleListView.setModel(
                    self._manager.rm.sharedModules)
            else:
                self._mw.remoteWidget.hostLabel.setVisible(False)
                self._mw.remoteWidget.portLabel.setVisible(False)
                self._mw.remoteWidget.sharedModuleListView.setVisible(False)

        self._mw.configDisplayDockWidget.hide()
        self._mw.remoteDockWidget.hide()
        self._mw.threadDockWidget.hide()
        self._mw.show()
Esempio n. 23
0
 def configureTimers(self):
     self.timerPlot = QtCore.QTimer()
     self.timerPlot.timeout.connect(self.updateData)
Esempio n. 24
0
 def initTimers(self):
     self.timer = QtCore.QTimer(self)
     self.timer.timeout.connect(self.updateFigure)
     #self.cam.captured.connect(self.onCapture)
     self.timer.start(50)
Esempio n. 25
0
    def __init__(self):
        super(IconBrowser, self).__init__()
        self.setMinimumSize(400, 300)
        self.setWindowTitle('QtAwesome Icon Browser')

        qtawesome._instance()
        fontMaps = qtawesome._resource['iconic'].charmap

        iconNames = []
        for fontCollection, fontData in fontMaps.items():
            for iconName in fontData:
                iconNames.append('%s.%s' % (fontCollection, iconName))

        self._filterTimer = QtCore.QTimer(self)
        self._filterTimer.setSingleShot(True)
        self._filterTimer.setInterval(AUTO_SEARCH_TIMEOUT)
        self._filterTimer.timeout.connect(self._updateFilter)

        model = IconModel(self.palette().color(QtGui.QPalette.Text))
        model.setStringList(sorted(iconNames))

        self._proxyModel = QtCore.QSortFilterProxyModel()
        self._proxyModel.setSourceModel(model)
        self._proxyModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)

        self._listView = IconListView(self)
        self._listView.setUniformItemSizes(True)
        self._listView.setViewMode(QtWidgets.QListView.IconMode)
        self._listView.setModel(self._proxyModel)
        self._listView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self._listView.doubleClicked.connect(self._copyIconText)

        self._lineEdit = QtWidgets.QLineEdit(self)
        self._lineEdit.setAlignment(QtCore.Qt.AlignCenter)
        self._lineEdit.textChanged.connect(self._triggerDelayedUpdate)
        self._lineEdit.returnPressed.connect(self._triggerImmediateUpdate)

        self._comboBox = QtWidgets.QComboBox(self)
        self._comboBox.setMinimumWidth(75)
        self._comboBox.currentIndexChanged.connect(
            self._triggerImmediateUpdate)
        self._comboBox.addItems([ALL_COLLECTIONS] + sorted(fontMaps.keys()))

        lyt = QtWidgets.QHBoxLayout()
        lyt.setContentsMargins(0, 0, 0, 0)
        lyt.addWidget(self._comboBox)
        lyt.addWidget(self._lineEdit)

        searchBarFrame = QtWidgets.QFrame(self)
        searchBarFrame.setLayout(lyt)

        self._copyButton = QtWidgets.QPushButton('Copy Name', self)
        self._copyButton.clicked.connect(self._copyIconText)

        lyt = QtWidgets.QVBoxLayout()
        lyt.addWidget(searchBarFrame)
        lyt.addWidget(self._listView)
        lyt.addWidget(self._copyButton)

        frame = QtWidgets.QFrame(self)
        frame.setLayout(lyt)

        self.setCentralWidget(frame)

        QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_Return),
            self,
            self._copyIconText,
        )

        self._lineEdit.setFocus()

        geo = self.geometry()
        desktop = QtWidgets.QApplication.desktop()
        screen = desktop.screenNumber(desktop.cursor().pos())
        centerPoint = desktop.screenGeometry(screen).center()
        geo.moveCenter(centerPoint)
        self.setGeometry(geo)
Esempio n. 26
0
    def __init__(self, parent=None, wflags=QtCore.Qt.WindowFlags(), **kw):
        # the current button
        self._ActiveButton = QtCore.Qt.NoButton

        # private attributes
        self.__oldFocus = None
        self.__saveX = 0
        self.__saveY = 0
        self.__saveModifiers = QtCore.Qt.NoModifier
        self.__saveButtons = QtCore.Qt.NoButton

        # do special handling of some keywords:
        # stereo, rw

        stereo = 0

        #if kw.has_key('stereo'):
        if stereo in kw:
            if kw['stereo']:
                stereo = 1

        rw = None

        #if kw.has_key('rw'):
        if 'rw' in kw:
            rw = kw['rw']

        # create qt-level widget
        QtWidgets.QWidget.__init__(self, parent,
                                   wflags | QtCore.Qt.MSWindowsOwnDC)

        if rw:  # user-supplied render window
            self._RenderWindow = rw
        else:
            self._RenderWindow = vtk.vtkRenderWindow()

        self._RenderWindow.SetWindowInfo(str(int(self.winId())))

        if stereo:  # stereo mode
            self._RenderWindow.StereoCapableWindowOn()
            self._RenderWindow.SetStereoTypeToCrystalEyes()

        self._Iren = vtk.vtkGenericRenderWindowInteractor()
        self._Iren.SetRenderWindow(self._RenderWindow)

        # do all the necessary qt setup
        self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent)
        self.setAttribute(QtCore.Qt.WA_PaintOnScreen)
        self.setMouseTracking(True)  # get all mouse events
        self.setFocusPolicy(QtCore.Qt.WheelFocus)
        self.setSizePolicy(
            QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                  QtWidgets.QSizePolicy.Expanding))

        self._Timer = QtCore.QTimer(self)
        # self.connect(self._Timer, QtCore.SIGNAL('timeout()'), self.TimerEvent)

        self._Iren.AddObserver('CreateTimerEvent', self.CreateTimer)
        self._Iren.AddObserver('DestroyTimerEvent', self.DestroyTimer)
        self._Iren.GetRenderWindow().AddObserver('CursorChangedEvent',
                                                 self.CursorChangedEvent)
Esempio n. 27
0
    def __init__(self,
                 parent=None,
                 dialog=False,
                 title='QtAwesome Icon Browser',
                 btnOkName='OK',
                 btnCopyName='Copy Name',
                 color="gray"):
        super().__init__(parent)

        self.dialog = dialog
        self.selected = ""
        self.color = color

        self.setMinimumSize(400, 600)
        self.setWindowTitle(title)
        if dialog:
            self.setWindowModality(QtCore.Qt.WindowModal)

        qtawesome._instance()
        fontMaps = qtawesome._resource['iconic'].charmap

        iconNames = []
        for fontCollection, fontData in fontMaps.items():
            for iconName in fontData:
                iconNames.append('%s.%s' % (fontCollection, iconName))

        self._filterTimer = QtCore.QTimer(self)
        self._filterTimer.setSingleShot(True)
        self._filterTimer.setInterval(AUTO_SEARCH_TIMEOUT)
        self._filterTimer.timeout.connect(self._updateFilter)

        model = IconModel(self.color)
        model.setStringList(sorted(iconNames))

        self._proxyModel = QtCore.QSortFilterProxyModel()
        self._proxyModel.setSourceModel(model)
        self._proxyModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)

        self._listView = IconListView(self)
        self._listView.setUniformItemSizes(True)
        self._listView.setViewMode(QtWidgets.QListView.IconMode)
        self._listView.setModel(self._proxyModel)
        self._listView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        if dialog:
            self._listView.doubleClicked.connect(self._selectIconText)
        else:
            self._listView.doubleClicked.connect(self._copyIconText)
        self._listView.selectionModel().selectionChanged.connect(
            self._updateNameField)

        self._lineEdit = QtWidgets.QLineEdit(self)
        self._lineEdit.setAlignment(QtCore.Qt.AlignCenter)
        self._lineEdit.textChanged.connect(self._triggerDelayedUpdate)
        self._lineEdit.returnPressed.connect(self._triggerImmediateUpdate)

        self._comboBox = QtWidgets.QComboBox(self)
        self._comboBox.setMinimumWidth(75)
        self._comboBox.currentIndexChanged.connect(
            self._triggerImmediateUpdate)
        self._comboBox.addItems([ALL_COLLECTIONS] + sorted(fontMaps.keys()))

        lyt = QtWidgets.QHBoxLayout()
        lyt.setContentsMargins(0, 0, 0, 0)
        lyt.addWidget(self._comboBox)
        lyt.addWidget(self._lineEdit)
        self._combo_style = QtWidgets.QComboBox(self)
        self._combo_style.addItems([
            qtawesome.styles.DEFAULT_DARK_PALETTE,
            qtawesome.styles.DEFAULT_LIGHT_PALETTE
        ])
        self._combo_style.currentTextChanged.connect(self._updateStyle)
        lyt.addWidget(self._combo_style)

        searchBarFrame = QtWidgets.QFrame(self)
        searchBarFrame.setLayout(lyt)

        self._nameField = QtWidgets.QLineEdit(self)
        self._nameField.setAlignment(QtCore.Qt.AlignCenter)
        self._nameField.setReadOnly(True)

        if self.dialog:
            self._copyButton = QtWidgets.QPushButton(btnOkName, self)
            self._copyButton.clicked.connect(self._selectIconText)
        else:
            self._copyButton = QtWidgets.QPushButton(btnCopyName, self)
            self._copyButton.clicked.connect(self._copyIconText)

        lyt = QtWidgets.QVBoxLayout()
        lyt.addWidget(searchBarFrame)
        lyt.addWidget(self._listView)
        lyt.addWidget(self._nameField)
        lyt.addWidget(self._copyButton)

        self.setLayout(lyt)

        self.setTabOrder(self._comboBox, self._lineEdit)
        self.setTabOrder(self._lineEdit, self._combo_style)
        self.setTabOrder(self._combo_style, self._listView)
        self.setTabOrder(self._listView, self._nameField)
        self.setTabOrder(self._nameField, self._copyButton)
        self.setTabOrder(self._copyButton, self._comboBox)

        QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_Return),
            self,
            self._copyIconText,
        )
        QtWidgets.QShortcut(
            QtGui.QKeySequence("Ctrl+F"),
            self,
            self._lineEdit.setFocus,
        )

        self._lineEdit.setFocus()

        geo = self.geometry()

        # QApplication.desktop() has been removed in Qt 6.
        # Instead, QGuiApplication.screenAt(QPoint) is supported
        # in Qt 5.10 or later.
        try:
            screen = QtGui.QGuiApplication.screenAt(QtGui.QCursor.pos())
            centerPoint = screen.geometry().center()
        except AttributeError:
            desktop = QtWidgets.QApplication.desktop()
            screen = desktop.screenNumber(desktop.cursor().pos())
            centerPoint = desktop.screenGeometry(screen).center()

        geo.moveCenter(centerPoint)
        self.setGeometry(geo)
Esempio n. 28
0
    def __init__(self, keithley):
        super(self.__class__, self).__init__()
        # load user interface layout from .ui file
        uic.loadUi(
            os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         'main.ui'), self)
        self.keithley = keithley

        # create figure area
        self._set_up_fig()

        # create LED indicator
        self.led = LedIndicator(self)
        self.led.setDisabled(True)  # Make the led non clickable
        self.statusBar.addPermanentWidget(self.led)
        self.led.setChecked(False)

        # change color of status bar
        self.statusBar.setStyleSheet('QStatusBar{background:transparent;}')

        # set validators for lineEdit fields
        self.lineEditVgStart.setValidator(QtGui.QDoubleValidator())
        self.lineEditVgStop.setValidator(QtGui.QDoubleValidator())
        self.lineEditVgStep.setValidator(QtGui.QDoubleValidator())
        self.lineEditVdStart.setValidator(QtGui.QDoubleValidator())
        self.lineEditVdStop.setValidator(QtGui.QDoubleValidator())
        self.lineEditVdStep.setValidator(QtGui.QDoubleValidator())
        self.lineEditInt.setValidator(QtGui.QDoubleValidator())
        self.lineEditSettling.setValidator(QtGui.QDoubleValidator())

        ## load default settings into GUI
        self._on_load_default()

        # connect to call-backs
        self.pushButtonTransfer.clicked.connect(self._on_transfer_clicked)
        self.pushButtonOutput.clicked.connect(self._on_output_clicked)
        self.pushButtonAbort.clicked.connect(self._on_abort_clicked)

        self.comboBoxGateSMU.currentIndexChanged.connect(
            self._on_smu_gate_changed)
        self.comboBoxDrainSMU.currentIndexChanged.connect(
            self._on_smu_drain_changed)

        self.actionSettings.triggered.connect(self._on_settings_clicked)
        self.actionConnect.triggered.connect(self._on_connect_clicked)
        self.actionDisconnect.triggered.connect(self._on_disconnect_clicked)
        self.action_Exit.triggered.connect(self._on_exit_clicked)
        self.actionSaveSweepData.triggered.connect(self._on_save_clicked)
        self.actionLoad_data_from_file.triggered.connect(self._on_load_clicked)
        self.actionSaveDefaults.triggered.connect(self._on_save_default)
        self.actionLoadDefaults.triggered.connect(self._on_load_default)

        self.actionSaveSweepData.setEnabled(False)

        # update when keithley is connected
        self._update_Gui_connection()

        # create address dialog
        self.addressDialog = KeithleyAddressDialog(self.keithley)

        # connection update timer: check periodically if keithley is connected
        # and busy, act accordingly
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update_connection_status)
        self.timer.start(10000)  # Call every 10 seconds
Esempio n. 29
0
 def __init__(self, interval, callback):
     from qtpy import QtCore
     self._timer = QtCore.QTimer()
     self._timer.setInterval(interval)
     self._timer.timeout.connect(callback)
Esempio n. 30
0
    def __init__(self,
                 my_config: dotdict,
                 app: QApplication,
                 parent: QtWidgets.QWidget = None) -> None:
        global config, storage_path
        config = my_config

        self.app = app
        super(QtWidgets.QWidget, self).__init__(parent)
        self.setWindowIcon(
            QtGui.QIcon(
                QtGui.QIcon(
                    os.path.join(os.environ["CLICKPOINTS_ICON"],
                                 "ClickPoints.ico"))))

        self.setMinimumWidth(650)
        self.setMinimumHeight(400)
        self.setWindowTitle("ClickPoints")

        self.scale_factor = app.desktop().logicalDpiX() / 96

        self.setAcceptDrops(True)

        # center window
        screen_geometry = QtWidgets.QApplication.desktop().screenGeometry()
        x = (screen_geometry.width() - self.width()) / 2
        y = (screen_geometry.height() - self.height()) / 2
        self.move(x, y * 0.5)

        # add layout
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.setLayout(self.layout)

        # setup mono space font
        QtGui.QFontDatabase.addApplicationFont(
            os.path.join(os.environ["CLICKPOINTS_ICON"],
                         "FantasqueSansMono-Regular.ttf"))
        self.mono_font = QtGui.QFont("Fantasque Sans Mono")

        self.layoutButtons = QtWidgets.QHBoxLayout()
        self.layoutButtons.setSpacing(5)
        self.layoutButtons.setContentsMargins(0, 0, 0, 5)
        self.button_play = QtWidgets.QPushButton()
        self.button_play.clicked.connect(lambda x: self.SaveDatabase())
        self.button_play.setIcon(qta.icon("fa.save"))
        self.button_play.setToolTip("save current project")
        self.layoutButtons.addWidget(self.button_play)

        self.button_play = QtWidgets.QPushButton()
        self.button_play.clicked.connect(self.Folder)
        self.button_play.setIcon(qta.icon("fa.folder-open"))
        self.button_play.setToolTip(
            "add/remove folder from the current project")
        self.layoutButtons.addWidget(self.button_play)

        self.layout.addLayout(self.layoutButtons)

        # view/scene setup
        self.view = QExtendedGraphicsView(dropTarget=self)
        self.layout.addWidget(self.view)
        self.view.zoomEvent = self.zoomEvent
        self.view.panEvent = self.panEvent
        self.local_scene = self.view.scene
        self.origin = self.view.origin

        # init image display
        self.ImageDisplay = BigImageDisplay(self.origin, self)

        # init media handler
        self.load_thread = None
        self.load_timer = QtCore.QTimer()
        self.load_timer.setInterval(0.1)
        self.load_timer.timeout.connect(self.LoadTimer)
        self.loading_time = time.time()

        # init the modules
        self.modules = [self.ImageDisplay]
        arg_dict = {
            "window": self,
            "layout": self.layout,
            "parent": self.view.origin,
            "parent_hud": self.view.hud,
            "view": self.view,
            "image_display": self.ImageDisplay,
            "modules": self.modules,
            "file": __file__
        }
        for mod, hud in zip(used_modules, used_huds):
            allowed = True
            if "can_create_module" in dir(mod):
                allowed = mod.can_create_module(config)
            if allowed:
                # Get a list of the arguments the function takes
                arg_name_list = GetModuleInitArgs(mod)
                # Set the proper hud argument
                if "parent_hud" in arg_name_list:
                    arg_dict["parent_hud"] = eval("self.view." + hud)
                # Filter out only the arguments the function wants
                arg_dict2 = {
                    k: v
                    for k, v in arg_dict.items() if k in arg_name_list
                }
                # Initialize the module
                self.modules.append(mod(**arg_dict2))

        SetBroadCastModules(self.modules)

        self.changeTracker = self.GetModule("ChangeTracker")

        #self.layoutButtons.addStretch()

        # find next module, which can be activated
        for module in self.modules:
            if "setActiveModule" in dir(module) and module.setActiveModule(
                    True, True):
                break

        # initialize some variables
        self.im = None
        self.layer_index = 1
        self.current_layer = None

        # select the first frame
        self.target_frame = 0

        # set focus policy for buttons
        for i in range(self.layoutButtons.count()):
            if self.layoutButtons.itemAt(i).widget():
                self.layoutButtons.itemAt(i).widget().setFocusPolicy(
                    Qt.NoFocus)

        self.signal_jump.connect(self.JumpFrames)
        self.signal_jumpTo.connect(self.JumpToFrame)
        self.signal_broadcast.connect(
            lambda s, a: BroadCastEvent(self.modules, s, *a))

        self.setFocus()

        self.start_timer = QtCore.QTimer.singleShot(
            1, lambda: self.loadUrl(config.srcpath))

        self.app.processEvents()