Пример #1
0
    def __init__(self, parent=None, toolbar=None):
        super().__init__(parent)

        layout = QHBoxLayout()
        self.setLayout(layout)
        self.graphic_widget = LiveDataPanel(parent, parent.client, {})
        self.graphic_widget.hide()
        self.log_widget = ConsolePanel(parent, parent.client, {})
        self.log_widget.hide()

        self.widgets = QStackedWidget(parent)
        self.widgets.addWidget(self.graphic_widget)
        self.widgets.addWidget(self.log_widget)

        layout.addWidget(self.widgets)

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

        if toolbar:
            self.resize(parent.size() - toolbar.size())
        else:
            self.resize(parent.size())

        # make the window frameless
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        self.fillColor = QColor(30, 30, 30, 120)
        self.penColor = QColor("#333333")

        self.SIGNALS = TranslucentWidgetSignals()
        self.raise_()
Пример #2
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self._arrays = None
        self._plotcount = 1
        # self._axesrange = (1, 1)  # y, x (rows, cols)
        self._axesrange = {'x': (0, 1, 2), 'y': (0, 1, 2)}
        self._fixedsize = False
        self._axesratio = 1.0
        self._logscale = False
        self._rois = {}
        self._saveName = None

        layout = QHBoxLayout()
        self.gr = GRWidget(self)
        layout.addWidget(self.gr)
        self.setLayout(layout)

        self.plot = Plot(self, viewport=(0.1, 0.95, 0.1, 0.95))
        self.axes = Axes(self,
                         viewport=self.plot.viewport,
                         xdual=True,
                         ydual=True)
        self.plot.addAxes(self.axes)
        self.gr.addPlot(self.plot)
Пример #3
0
 def __init__(self, parent, designMode=False, **kwds):
     self._inner = None
     QWidget.__init__(self, parent, **kwds)
     NicosWidget.__init__(self)
     self._layout = QHBoxLayout()
     self._layout.setContentsMargins(0, 0, 0, 0)
     self.setLayout(self._layout)
     if designMode:
         self._layout.insertWidget(0, QLabel('(Value Editor)', self))
Пример #4
0
    def __init__(self, parent=None, toolbar=None):
        super(TranslucentWidget, self).__init__(parent)

        # loadUi(self, 'overlay.ui', '%s/windows'%uipath)
        layout = QHBoxLayout()
        self.setLayout(layout)
        self.graphic_widget = LiveDataPanel(parent, parent.client, {})
        self.graphic_widget.hide()
        self.log_widget = ConsolePanel(parent, parent.client, {})
        self.log_widget.hide()

        self.widgets = QStackedWidget(parent)
        self.widgets.addWidget(self.graphic_widget)
        self.widgets.addWidget(self.log_widget)

        #
        #
        # for panel in parent.panels:
        #     try:
        #         print('%s - %s'%(panel.panelName, panel.__class__.__name__))
        #     except:
        #         pass
        #
        #     if not self.graphic_widget and panel.__class__.__name__ == \
        #             'LiveDataPanel':
        #         print(panel.panelName)
        #         self.graphic_widget = panel
        #         self.widgets.addWidget(self.graphic_widget)
        #     if not self.log_widget and panel.__class__.__name__ == \
        #             'ConsolePanel':
        #         print(panel.panelName)
        #         self.log_widget = panel
        #         self.widgets.addWidget(self.log_widget)

        layout.addWidget(self.widgets)

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

        if toolbar:
            self.resize(parent.size() - toolbar.size())
        else:
            self.resize(parent.size())

        # make the window frameless
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        self.fillColor = QColor(30, 30, 30, 120)
        self.penColor = QColor("#333333")

        # self.popup_fillColor = QColor(240, 240, 240, 255)
        # self.popup_penColor = QColor(200, 200, 200, 255)

        self.SIGNALS = TranslucentWidgetSignals()
        self.raise_()
Пример #5
0
 def createWidget(self, parent, client):
     if self.value is None:
         self.value = 30 * 60
     self._widget = QWidget(parent)
     layout = QHBoxLayout()
     self._widget.number = QSpinBox(self._widget)
     self._widget.number.setValue(30)
     self._widget.number.setMinimum(1)
     self._widget.number.setMaximum(10000)
     self._widget.unit = QComboBox(self._widget)
     self._widget.unit.addItems(['sec', 'min', 'hr'])
     self._widget.unit.setCurrentIndex(1)
     layout.addWidget(self._widget.number)
     layout.addWidget(self._widget.unit)
     layout.setContentsMargins(0, 0, 0, 0)
     self._widget.setLayout(layout)
     self._widget.number.valueChanged.connect(self._updateValue)
     self._widget.unit.currentIndexChanged.connect(self._updateValue)
     self._widget.setMinimumWidth(120)
     if self.value is not None:
         if self.value % 3600 == 0:
             self._widget.number.setValue(self.value // 3600)
             self._widget.unit.setCurrentIndex(2)
         elif self.value % 60 == 0:
             self._widget.number.setValue(self.value // 60)
             self._widget.unit.setCurrentIndex(1)
         else:
             self._widget.number.setValue(self.value)
             self._widget.unit.setCurrentIndex(0)
     return self._widget
Пример #6
0
    def __init__(self, parent, client, options):
        Panel.__init__(self, parent, client, options)

        if not simpleapi or not mpy:
            raise RuntimeError('Mantid modules could not be imported. '
                               'Ensure Mantid is installed and PYTHONPATH is '
                               'set to contain the Mantid /bin directory.')

        hbox = QHBoxLayout(self)
        hbox.setContentsMargins(0, 0, 0, 0)
        self.setLayout(hbox)

        self._watcher = MantidDeviceWatcher(self)
        self._widget = None
        self._workspace = None
        self._current_idf = None
Пример #7
0
 def __init__(self, parent, client, uifile):
     QWidget.__init__(self, parent)
     new_layout = QHBoxLayout()
     self.subwidget = QWidget(self)
     if uifile:
         uic.loadUi(uifile, self.subwidget)
     self.button = QToolButton(self)
     self.setButton('+')
     self.button.clicked.connect(self.on_button_click)
     new_layout.addWidget(self.subwidget)
     new_layout.addSpacerItem(QSpacerItem(15, 1, QSizePolicy.Fixed))
     new_layout.addWidget(self.button)
     new_layout.setContentsMargins(0, 0, 0, 0)
     self.setLayout(new_layout)
     for ch in self.subwidget.findChildren(NicosWidget):
         ch.setClient(client)
Пример #8
0
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        DlgUtils.__init__(self, 'Live data')
        self.panel = parent
        layout1 = QVBoxLayout()
        self.plot = QwtPlot(self)
        layout1.addWidget(self.plot)
        self.curve = QwtPlotCurve()
        self.curve.setRenderHint(QwtPlotCurve.RenderAntialiased)
        self.curve.attach(self.plot)
        self.marker = QwtPlotMarker()
        self.marker.attach(self.plot)
        self.markerpen = QPen(Qt.red)
        self.marker.setSymbol(
            QwtSymbol(QwtSymbol.Ellipse, QBrush(), self.markerpen, QSize(7,
                                                                         7)))
        self.zoomer = QwtPlotZoomer(self.plot.canvas())
        self.zoomer.setMousePattern(QwtPlotZoomer.MouseSelect3, Qt.NoButton)
        self.picker = QwtPlotPicker(self.plot.canvas())
        self.picker.setSelectionFlags(QwtPlotPicker.PointSelection
                                      | QwtPlotPicker.ClickSelection)
        self.picker.setMousePattern(QwtPlotPicker.MouseSelect1, Qt.MidButton)
        self.picker.selected.connect(self.pickerSelected)
        layout2 = QHBoxLayout()
        layout2.addWidget(QLabel('Scale:', self))
        self.scale = QComboBox(self)
        self.scale.addItems([
            'Single detectors, sorted by angle',
            'Scattering angle 2theta (deg)', 'Q value (A-1)'
        ])
        self.scale.currentIndexChanged[int].connect(self.scaleChanged)
        layout2.addWidget(self.scale)
        layout2.addStretch()
        self.scaleframe = QFrame(self)
        self.scaleframe.setLayout(layout2)
        self.scaleframe.setVisible(False)
        layout1.addWidget(self.scaleframe)
        mainframe = QFrame(self)
        mainframe.setLayout(layout1)
        self.setCentralWidget(mainframe)
        self.setContentsMargins(6, 6, 6, 6)
        plotfont = scaledFont(self.font(), 0.7)
        self.plot.setAxisFont(QwtPlot.xBottom, plotfont)
        self.plot.setAxisFont(QwtPlot.yLeft, plotfont)
        self.plot.setCanvasBackground(Qt.white)
        self.resize(800, 200)

        self._detinfo = None
        self._anglemap = None
        self._infowindow = None
        self._infolabel = None
        self._xs = self._ys = None
        self._type = None
Пример #9
0
 def __init__(self, parent, inner, annotation):
     QWidget.__init__(self, parent)
     layout = self._layout = QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     self._inner = inner
     self._inner.valueModified.connect(self.valueModified)
     self._inner.valueChosen.connect(self.valueChosen)
     layout.addWidget(inner)
     layout.addWidget(QLabel(annotation, parent))
     self.setLayout(layout)
Пример #10
0
    def initUi(self):
        # axes setup
        self.widget = InteractiveGRWidget(self)
        self.plot = Plot(viewport=(.1, .95, .25, .95))
        self.axes = NicosTimePlotAxes(self.plot._viewport)
        self.axes.setWindow(0, 1, 0, 1)
        self.plot.addAxes(self.axes)
        self.plot.setLegend(True)
        self.plot.setLegendWidth(0.07)
        self.plot.offsetXLabel = -.2
        self.axes.setXtickCallback(self.xtickCallBack)
        self.widget.addPlot(self.plot)
        layout = QHBoxLayout(self)
        layout.addWidget(self.widget)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        self.curves = []

        # event support
        self.widget.cbm.addHandler(LegendEvent.ROI_CLICKED,
                                   self.on_legendItemClicked, LegendEvent)
        self.widget.cbm.addHandler(MouseEvent.MOUSE_MOVE, self.on_mouseMove)

        self.timeSeriesUpdate.connect(self.on_timeSeriesUpdate)
Пример #11
0
    def __init__(self, parent, client, **settings):
        QMainWindow.__init__(self, parent)
        self.client = client
        self.setWindowTitle(' ')  # window title is unnecessary
        flags = self.windowFlags()
        flags |= Qt.WindowStaysOnTopHint
        flags ^= Qt.WindowMinimizeButtonHint
        self.setWindowFlags(flags)

        self.sgroup = SettingGroup('EstopTool')
        with self.sgroup as settings:
            self.restoreGeometry(settings.value('geometry', '', QByteArray))

        icon = QIcon(':/estop')
        icon.addFile(':/estopdown', mode=QIcon.Active)
        self.btn = PicButton(icon, self)

        widget = QWidget(self)
        layout = QHBoxLayout()
        layout.addWidget(self.btn)
        layout.setContentsMargins(3, 3, 3, 3)
        widget.setLayout(layout)
        self.setCentralWidget(widget)
        self.btn.clicked.connect(self.dostop)
        self.setFixedSize(self.minimumSize())
        self.show()
Пример #12
0
 def setPanelToolbar(self):
     bar = QToolBar('History viewer')
     bar.addAction(self.actionNew)
     bar.addAction(self.actionEditView)
     bar.addSeparator()
     bar.addAction(self.actionSavePlot)
     bar.addAction(self.actionPrint)
     bar.addAction(self.actionSaveData)
     bar.addSeparator()
     bar.addAction(self.actionUnzoom)
     bar.addAction(self.actionLogScale)
     bar.addSeparator()
     bar.addAction(self.actionAutoScale)
     bar.addAction(self.actionScaleX)
     bar.addAction(self.actionScaleY)
     bar.addSeparator()
     bar.addAction(self.actionResetView)
     bar.addAction(self.actionDeleteView)
     bar.addSeparator()
     bar.addAction(self.actionFitPeak)
     wa = QWidgetAction(bar)
     self.fitPickCheckbox = QCheckBox(bar)
     self.fitPickCheckbox.setText('Pick')
     self.fitPickCheckbox.setChecked(True)
     self.actionPickInitial.setChecked(True)
     self.fitPickCheckbox.toggled.connect(self.actionPickInitial.setChecked)
     self.actionPickInitial.toggled.connect(self.fitPickCheckbox.setChecked)
     layout = QHBoxLayout()
     layout.setContentsMargins(10, 0, 10, 0)
     layout.addWidget(self.fitPickCheckbox)
     frame = QFrame(bar)
     frame.setLayout(layout)
     wa.setDefaultWidget(frame)
     bar.addAction(wa)
     ag = QActionGroup(bar)
     ag.addAction(self.actionFitPeakGaussian)
     ag.addAction(self.actionFitPeakLorentzian)
     ag.addAction(self.actionFitPeakPV)
     ag.addAction(self.actionFitPeakPVII)
     ag.addAction(self.actionFitTc)
     ag.addAction(self.actionFitCosine)
     ag.addAction(self.actionFitSigmoid)
     ag.addAction(self.actionFitLinear)
     ag.addAction(self.actionFitExponential)
     wa = QWidgetAction(bar)
     self.fitComboBox = QComboBox(bar)
     for a in ag.actions():
         itemtext = a.text().replace('&', '')
         self.fitComboBox.addItem(itemtext)
         self.fitfuncmap[itemtext] = a
     self.fitComboBox.currentIndexChanged.connect(
         self.on__fitComboBox_currentIndexChanged)
     wa.setDefaultWidget(self.fitComboBox)
     bar.addAction(wa)
     bar.addSeparator()
     bar.addAction(self.actionFitArby)
     self.bar = bar
     self.actionFitLinear.trigger()
     return bar
Пример #13
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self._array = None
        self._axesrange = (1, 1)  # y, x (rows, cols)
        self._fixedsize = False
        self._axesratio = 1.0
        self._logscale = False
        self._rois = {}

        layout = QHBoxLayout()
        self.gr = GRWidget(self)
        layout.addWidget(self.gr)
        self.setLayout(layout)

        self.plot = Plot(self, viewport=(.1, .95, .1, .95))
        self.axes = Axes(self,
                         viewport=self.plot.viewport,
                         xdual=True,
                         ydual=True)
        self.plot.addAxes(self.axes)
        self.gr.addPlot(self.plot)
Пример #14
0
 def __init__(self, parent, name, selections, preselect):
     QFrame.__init__(self, parent)
     self.name = name
     self.selections = selections
     layout = QHBoxLayout()
     layout.addWidget(QLabel(name, self))
     self.combo = QComboBox(self)
     self.combo.addItems(selections)
     if preselect in selections:
         self.combo.setCurrentIndex(selections.index(preselect))
     else:
         self.combo.setCurrentIndex(0)
     layout.addWidget(self.combo)
     layout.setContentsMargins(0, 0, 0, 0)
     self.setLayout(layout)
Пример #15
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.setLayout(QHBoxLayout())
     self.layout().setContentsMargins(0.1, 0.1, 0.1, 0.1)
     self.layout().setSpacing(1)
     self.val = QLineEdit()
     self.val.setValidator(QDoubleValidator(0, 1000000, 2))
     self.layout().addWidget(self.val)
     self.unit = QComboBox()
     self.unit.insertItems(0, self.units)
     self.layout().addWidget(self.unit)
     self.setValue(1)
     self.val.returnPressed.connect(self.on_returnPressed)
     self.val.editingFinished.connect(self.on_returnPressed)
     self.unit.currentIndexChanged.connect(self.recalcValue)
Пример #16
0
 def __init__(self, parent, inner, curvalue, client):
     QWidget.__init__(self, parent)
     layout = self._layout = QHBoxLayout()
     self.checkbox = QCheckBox(self)
     if curvalue is not None:
         self.checkbox.setCheckState(Qt.Checked)
     if curvalue is None:
         curvalue = inner()  # generate a dummy value
     self.inner_widget = create(self, inner, curvalue, client=client)
     self.inner_widget.setEnabled(self.checkbox.isChecked())
     self.inner_widget.valueModified.connect(self.valueModified)
     layout.addWidget(self.checkbox)
     layout.addWidget(self.inner_widget)
     layout.setContentsMargins(0, 0, 0, 0)
     self.checkbox.stateChanged.connect(self.on_checkbox_stateChanged)
     self.setLayout(layout)
Пример #17
0
 def __init__(self, parent, values):
     QWidget.__init__(self, parent)
     layout = QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     self._values = {}
     for value in values:
         btn = QPushButton(str(value), self)
         self._values[btn] = value
         btn.clicked.connect(self.on_button_pressed)
         layout.addWidget(btn)
     self.setLayout(layout)
Пример #18
0
    def __init__(self, controller, parent=None, state=None):
        QWidget.__init__(self, parent)

        # update Request for parameter gets sent to controller
        self.controller = controller

        # contains widgets that are currently displayed
        self.widgets = []
        self.state = state if state is not None else self.standard_value
        self.doubleclick = None

        # setting up layout:
        layout = QHBoxLayout()
        layout.setContentsMargins(0.1, 0.1, 0.1, 0.1)
        layout.setSpacing(1)
        self.setLayout(layout)
Пример #19
0
    def __init__(self, parent=None):
        """Create a new QRangeSlider instance.

            :param parent: QWidget parent
            :return: New QRangeSlider instance.

        """
        super(QRangeSlider, self).__init__(parent)
        self.setupUi(self)
        self.setMouseTracking(False)

        #self._splitter.setChildrenCollapsible(False)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)

        # head layout
        self._head_layout = QHBoxLayout()
        self._head_layout.setSpacing(0)
        self._head_layout.setContentsMargins(0, 0, 0, 0)
        self._head.setLayout(self._head_layout)
        self.head = Head(self._head, main=self)
        self._head_layout.addWidget(self.head)

        # handle layout
        self._handle_layout = QHBoxLayout()
        self._handle_layout.setSpacing(0)
        self._handle_layout.setContentsMargins(0, 0, 0, 0)
        self._handle.setLayout(self._handle_layout)
        self.handle = Handle(self._handle, main=self)
        self.handle.setTextColor((150, 255, 150))
        self._handle_layout.addWidget(self.handle)

        # tail layout
        self._tail_layout = QHBoxLayout()
        self._tail_layout.setSpacing(0)
        self._tail_layout.setContentsMargins(0, 0, 0, 0)
        self._tail.setLayout(self._tail_layout)
        self.tail = Tail(self._tail, main=self)
        self._tail_layout.addWidget(self.tail)

        # defaults
        self.setMin(0)
        self.setMax(99)
        self.setStart(0)
        self.setEnd(99)
        self.setDrawValues(True)
Пример #20
0
 def __init__(self, parent, client, panelcfg, title, **options):
     from nicos.clients.gui.panels.utils import createWindowItem
     QDialog.__init__(self, parent)
     self.panels = []
     self.mainwindow = parent.mainwindow
     self.log = NicosLogger('PanelDialog')
     self.log.parent = self.mainwindow.log
     self.client = client
     self.user_color = self.palette().color(QPalette.Base)
     self.user_font = self.font()
     if isinstance(panelcfg, type) and issubclass(panelcfg, Panel):
         panelcfg = panel('%s.%s' % (panelcfg.__module__,
                                     panelcfg.__name__), **options)
     elif isinstance(panelcfg, str):
         panelcfg = panel(panelcfg, **options)
     hbox = QHBoxLayout()
     hbox.setContentsMargins(0, 0, 0, 0)
     pnl = createWindowItem(panelcfg, self, self, self.mainwindow, self.log)
     if pnl:
         hbox.addWidget(pnl)
     self.setLayout(hbox)
     self.setWindowTitle(title)
     SetupDepWindowMixin.__init__(self, self.client)
     self.setProperty('type', 'PanelDialog')
Пример #21
0
    def getToolbars(self):
        if not self.bars:
            bar = QToolBar('Scans')
            bar.addAction(self.actionSavePlot)
            bar.addAction(self.actionPrint)
            bar.addSeparator()
            bar.addAction(self.actionXAxis)
            bar.addAction(self.actionYAxis)
            bar.addAction(self.actionNormalized)
            bar.addSeparator()
            bar.addAction(self.actionLogXScale)
            bar.addAction(self.actionLogScale)
            bar.addAction(self.actionUnzoom)
            bar.addSeparator()
            bar.addAction(self.actionAutoScale)
            bar.addAction(self.actionScaleX)
            bar.addAction(self.actionScaleY)
            bar.addAction(self.actionLegend)
            bar.addAction(self.actionErrors)
            bar.addAction(self.actionResetPlot)
            bar.addAction(self.actionDeletePlot)
            bar.addSeparator()
            bar.addAction(self.actionAutoDisplay)
            bar.addAction(self.actionCombine)

            fitbar = QToolBar('Scan fitting')
            fitbar.addAction(self.actionFitPeak)
            wa = QWidgetAction(fitbar)
            self.fitPickCheckbox = QCheckBox(fitbar)
            self.fitPickCheckbox.setText('Pick')
            self.fitPickCheckbox.setChecked(True)
            self.actionPickInitial.setChecked(True)
            self.fitPickCheckbox.toggled.connect(self.actionPickInitial.setChecked)
            self.actionPickInitial.toggled.connect(self.fitPickCheckbox.setChecked)
            layout = QHBoxLayout()
            layout.setContentsMargins(10, 0, 10, 0)
            layout.addWidget(self.fitPickCheckbox)
            frame = QFrame(fitbar)
            frame.setLayout(layout)
            wa.setDefaultWidget(frame)
            fitbar.addAction(wa)
            ag = QActionGroup(fitbar)
            ag.addAction(self.actionFitPeakGaussian)
            ag.addAction(self.actionFitPeakLorentzian)
            ag.addAction(self.actionFitPeakPV)
            ag.addAction(self.actionFitPeakPVII)
            ag.addAction(self.actionFitTc)
            ag.addAction(self.actionFitCosine)
            ag.addAction(self.actionFitSigmoid)
            ag.addAction(self.actionFitLinear)
            ag.addAction(self.actionFitExponential)
            wa = QWidgetAction(fitbar)
            self.fitComboBox = QComboBox(fitbar)
            for a in ag.actions():
                itemtext = a.text().replace('&', '')
                self.fitComboBox.addItem(itemtext)
                self.fitfuncmap[itemtext] = a
            self.fitComboBox.currentIndexChanged.connect(
                self.on_fitComboBox_currentIndexChanged)
            wa.setDefaultWidget(self.fitComboBox)
            fitbar.addAction(wa)
            fitbar.addSeparator()
            fitbar.addAction(self.actionFitArby)

            self.bars = [bar, fitbar]

        return self.bars
Пример #22
0
    def __init__(self, parent=None, statusbar=None):
        super(StatusBarOverlay, self).__init__(parent)

        self.statusbar = statusbar

        print(parent.__class__.__name__)

        layout = QVBoxLayout()

        line = QHBoxLayout()
        self.graphicsButton = QPushButton('Graphics')
        self.logButton = QPushButton('Log')
        self.toggleButton = QPushButton('Show')
        self.graphicsButton.setCheckable(True)
        self.logButton.setCheckable(True)
        self.toggleButton.setCheckable(True)

        self.buttonsBox = QButtonGroup()
        self.buttonsBox.addButton(self.graphicsButton)
        self.buttonsBox.addButton(self.logButton)
        # self.buttonsBox.addButton(self.toggleButton)

        line.addStretch()
        line.addWidget(self.graphicsButton)
        line.addWidget(self.logButton)
        line.addWidget(self.toggleButton)
        line.addStretch()

        line.setObjectName('ButtonsLayout')
        layout.addLayout(line)

        del line
        line = QHBoxLayout()

        layout.addLayout(line)
        self.setLayout(layout)
        self.toggleButton.clicked.connect(self.on_toggle)

        self.set_hidden()
Пример #23
0
    def initGui(self):
        def log_unhandled(*exc_info):
            traceback.print_exception(*exc_info)
            self.log.exception('unhandled exception in QT callback',
                               exc_info=exc_info)
        sys.excepthook = log_unhandled

        self._qtapp = QApplication(['qtapp'], organizationName='nicos',
                                   applicationName='gui')
        self._master = master = MonitorWindow()

        if self._geometry == 'fullscreen':
            master.showFullScreen()
            master._wantFullScreen = True
            # In some Qt5 versions, showFullScreen is buggy and doesn't
            # actually resize the window (but hides decoration etc).
            # So, explicitly set the geometry of the first screen.
            master.setGeometry(QApplication.screens()[0].geometry())
            QCursor.setPos(master.geometry().bottomRight())
        elif isinstance(self._geometry, tuple):
            w, h, x, y = self._geometry
            master.setGeometry(x, y, w, h)

        # colors used for the display of watchdog warnings, not for the
        # individual value displays
        self._bgcolor = QColor('gray')
        self._black = QColor('black')
        self._red = QColor('red')
        self._gray = QColor('gray')

        master.setWindowTitle(self.title)
        self._bgcolor = master.palette().color(QPalette.Window)

        timefont  = QFont(self.font, self._timefontsize)
        blockfont = QFont(self.font, self._fontsizebig)
        warnfont  = QFont(self.font, self._fontsizebig)
        warnfont.setBold(True)
        labelfont = QFont(self.font, self._fontsize)
        stbarfont = QFont(self.font, int(self._fontsize * 0.8))
        valuefont = QFont(self.valuefont or self.font, self._fontsize)

        blheight = QFontMetrics(blockfont).height()
        tiheight = QFontMetrics(timefont).height()

        # split window into to panels/frames below each other:
        # one displays time, the other is divided further to display blocks.
        # first the timeframe:
        masterframe = QFrame(master)
        masterlayout = QVBoxLayout()
        if self.title:
            self._titlelabel = QLabel(
                '', master, font=timefont, autoFillBackground=True,
                alignment=Qt.AlignHCenter)
            pal = self._titlelabel.palette()
            pal.setColor(QPalette.WindowText, self._gray)
            self._titlelabel.setPalette(pal)
            self._titlelabel.setSizePolicy(QSizePolicy.Preferred,
                                           QSizePolicy.Fixed)
            self._master.updateTitle.connect(self._titlelabel.setText)
            masterlayout.addWidget(self._titlelabel)
            masterlayout.addSpacing(0.2 * tiheight)
        else:
            self._titlelabel = None

        self._warnpanel = QFrame(master)
        self._warnpanel.setVisible(False)

        warningslayout = QVBoxLayout()
        lbl = QLabel('Warnings', self._warnpanel, font=warnfont)
        lbl.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        warningslayout.addWidget(lbl)
        self._warnlabel = SqueezedLabel('', self._warnpanel, font=blockfont)
        warningslayout.addWidget(self._warnlabel)
        self._warnpanel.setLayout(warningslayout)
        masterlayout.addWidget(self._warnpanel)
        master.switchWarnPanel.connect(self._switch_warnpanel)

        displayframe = QFrame(master)
        self._plots = {}

        colorScheme = lightColorScheme if self.colors == 'light' else None
        fontCache = {1.0: valuefont}

        def _create_field(groupframe, field):

            def _setup(widget):
                fontscale = field.get('fontscale', 1.0)
                if fontscale not in fontCache:
                    fontCache[fontscale] = scaledFont(valuefont, fontscale)
                widget.valueFont = fontCache[fontscale]
                widget.setFont(labelfont)
                for key in field:
                    if key in widget.properties:
                        setattr(widget, key, field[key])
                widget.setSource(self)
                if hasattr(widget, 'widgetInfo'):
                    widget.widgetInfo.connect(self.newWidgetInfo)
                return widget

            if isinstance(field, str):
                field = {'dev': field}
            if 'min' in field:
                field['min'] = repr(field['min'])
            if 'max' in field:
                field['max'] = repr(field['max'])
            setups = field.get('setups', None)

            if 'gui' in field:
                resource = findResource(field.pop('gui'))
                try:
                    instance = uic.loadUi(resource)
                except Exception as err:
                    self.log.exception('could not load .ui file %r, ignoring',
                                       resource)
                    instance = QLabel('%r could not be loaded:\n%s' %
                                      (resource, err))
                else:
                    for child in instance.findChildren(NicosWidget):
                        _setup(child)
                instance.setups = setups
                return instance
            elif 'widget' in field:
                widget_class = self._class_import(field.pop('widget'))
                widget = widget_class(groupframe)
                if isinstance(widget, NicosWidget):
                    _setup(widget)
                for child in widget.findChildren(NicosWidget):
                    _setup(child)
                widget.setups = setups
                return widget
            elif 'plot' in field and plot_available:
                # XXX make this more standard
                plotwidget = self._plots.get(field['plot'])
                if plotwidget:
                    plotwidget.devices += [field.get('dev', field.get('key', ''))]
                    plotwidget.names += [field.get('name', field.get('dev', field.get('key', '')))]
                    return None
                plotwidget = TrendPlot(groupframe)
                _setup(plotwidget)
                plotwidget.legend = field.get('legend', True)
                plotwidget.plotwindow = field.get('plotwindow', 3600)
                plotwidget.plotinterval = field.get('plotinterval', 2)
                self._plots[field['plot']] = plotwidget
                plotwidget.devices = [field.get('dev', field.get('key', ''))]
                plotwidget.names = [field.get('name', field.get('dev', field.get('key', '')))]
                plotwidget.setups = setups
                return plotwidget
            elif 'picture' in field:
                picwidget = PictureDisplay(groupframe)
                picwidget.filepath = field['picture']
                picwidget.setups = setups
                return _setup(picwidget)
            else:
                display = ValueDisplay(groupframe, colorScheme=colorScheme,
                                       showExpiration=self.noexpired)
                display.setups = setups
                return _setup(display)

        # now iterate through the layout and create the widgets to display it
        displaylayout = QVBoxLayout(spacing=20)
        for superrow in self.layout:
            boxlayout = QHBoxLayout(spacing=20)
            boxlayout.setContentsMargins(10, 10, 10, 10)
            for column in superrow:
                columnlayout = QVBoxLayout(spacing=0.8*blheight)
                for block in column:
                    block = self._resolve_block(block)
                    blocklayout_outer = QHBoxLayout()
                    blocklayout_outer.addStretch()
                    blocklayout = QVBoxLayout()
                    blocklayout.addSpacing(0.5 * blheight)
                    blockbox = BlockBox(displayframe, block._title, blockfont,
                                        block._options)
                    for row in block:
                        if row in (None, '---'):
                            blocklayout.addSpacing(12)
                        else:
                            rowlayout = QHBoxLayout()
                            rowlayout.addStretch()
                            rowlayout.addSpacing(self._padding)
                            for field in row:
                                fieldwidget = _create_field(blockbox, field)
                                if fieldwidget:
                                    rowlayout.addWidget(fieldwidget)
                                    rowlayout.addSpacing(self._padding)
                                    if fieldwidget.setups:
                                        if blockbox.setups:
                                            blockbox._onlyfields.append(fieldwidget)
                                        else:
                                            self._onlyfields.append(fieldwidget)
                                            # start hidden
                                            fieldwidget.setHidden(True)
                            rowlayout.addStretch()
                            blocklayout.addLayout(rowlayout)
                    if blockbox.setups:
                        self._onlyblocks.append((blocklayout_outer, blockbox))
                        blockbox.setHidden(True)  # start hidden
                    blocklayout.addSpacing(0.3 * blheight)
                    blockbox.setLayout(blocklayout)
                    blocklayout_outer.addWidget(blockbox)
                    blocklayout_outer.addStretch()
                    columnlayout.addLayout(blocklayout_outer)
                columnlayout.addStretch()
                boxlayout.addLayout(columnlayout)
            displaylayout.addLayout(boxlayout)
        displayframe.setLayout(displaylayout)

        for plot in self._plots.values():
            plot.setSource(self)

        masterlayout.addWidget(displayframe)

        masterframe.setLayout(masterlayout)
        master.setCentralWidget(masterframe)

        # initialize status bar
        self._statuslabel = QLabel(font=stbarfont)
        master.statusBar().addWidget(self._statuslabel)
        self._statustimer = None
        master.show()
Пример #24
0
    def __init__(self, model, name, addr):
        super(BaseDev, self).__init__()
        self.name = name
        self.model = model
        self.addr = addr

        self._namelabel = QLabel(name)
        self._namelabel.setMinimumWidth(120)
        self._namelabel.setMaximumWidth(120)
        # self._groupbox = QGroupBox(name)
        self._groupbox = QFrame()
        # self._groupbox.setFlat(False)
        # self._groupbox.setCheckable(False)
        self._hlayout = QHBoxLayout()
        self._hlayout.addWidget(self._namelabel)
        self._hlayout.addWidget(self._groupbox)
        self._hlayout.setSpacing(0)

        # inside of the groupbox there is a vbox with 1 or 2 hboxes
        self._inner_vbox = QVBoxLayout()
        self._groupbox.setLayout(self._inner_vbox)

        # upper inner hbox
        self._inner_hbox1 = QHBoxLayout()
        self._inner_vbox.addLayout(self._inner_hbox1)

        # fill upper hbox
        self.valueWidget = QLineEdit('0b123456789abcdef0')
        self.valueWidget.setMaximumWidth(120)
        self._inner_hbox1.addWidget(self.valueWidget)

        if self.has_target:
            self.targetWidget = QLineEdit()
            self.targetWidget.setPlaceholderText('')
            self.targetWidget.setMaximumWidth(120)
            self.targetWidget.returnPressed.connect(self._go_clicked)
            self._inner_hbox1.addWidget(self.targetWidget)
            self.goButton = QPushButton('Go')
            self.goButton.clicked.connect(self._go_clicked)
            self._inner_hbox1.addWidget(self.goButton)
            self.stopButton = QPushButton('Stop')
            self.stopButton.clicked.connect(self._stop_clicked)
            self._inner_hbox1.addWidget(self.stopButton)

        # now (conditionally) the second hbox
        if self.has_status:
            self._inner_hbox2 = QHBoxLayout()
            self._inner_vbox.addLayout(self._inner_hbox2)

            self.statvalueWidget = QLineEdit('statval')
            self.statvalueWidget.setMaximumWidth(120)
            self._inner_hbox2.addWidget(self.statvalueWidget)
            self.statusWidget = QLineEdit('Statusstring if available')
            self.statusWidget.setMaximumWidth(10000)
            self._inner_hbox2.addWidget(self.statusWidget)
            self.resetButton = QPushButton('Reset')
            self.resetButton.clicked.connect(self._reset_clicked)
            self._inner_hbox1.addWidget(self.resetButton)
            # self._inner_hbox2.addStretch(0.1)

        # allow space for resizing
        self._inner_hbox1.addStretch(1)

        self._inner_vbox.setSpacing(0)
        self._inner_vbox.setContentsMargins(0, 0, 0, 0)

        self._hlayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self._hlayout)
        self.show()
Пример #25
0
    def __init__(self, parent, client, options):
        Panel.__init__(self, parent, client, options)
        loadUi(self, 'panels/editor.ui')

        self.window = parent
        self.custom_font = None
        self.custom_back = None

        self.mainwindow.codeGenerated.connect(self.on_codeGenerated)

        if not has_scintilla:
            self.actionComment.setEnabled(False)

        self.menus = None
        self.bar = None
        self.current_status = None
        self.recentf_actions = []
        self.searchdlg = None
        self.menuRecent = QMenu('Recent files')

        self.menuToolsActions = []

        for fn in self.recentf:
            action = QAction(fn.replace('&', '&&'), self)
            action.setData(fn)
            action.triggered.connect(self.openRecentFile)
            self.recentf_actions.append(action)
            self.menuRecent.addAction(action)

        self.tabber = QTabWidget(self, tabsClosable=True, documentMode=True)
        self.tabber.currentChanged.connect(self.on_tabber_currentChanged)
        self.tabber.tabCloseRequested.connect(self.on_tabber_tabCloseRequested)

        self.toolconfig = options.get('tools')
        self.sim_window = options.get('sim_window', 'inline')
        if self.sim_window not in ('single', 'multi', 'inline'):
            self.log.warning('invalid sim_window option %r, using inline',
                             self.sim_window)
            self.sim_window = 'inline'

        hlayout = QHBoxLayout()
        hlayout.setContentsMargins(0, 0, 0, 0)
        hlayout.addWidget(self.tabber)
        self.mainFrame.setLayout(hlayout)

        self.editors = []    # tab index -> editor
        self.filenames = {}  # editor -> filename
        self.watchers = {}   # editor -> QFileSystemWatcher
        self.currentEditor = None

        self.saving = False  # True while saving
        self.warnWidget.hide()

        self.simFrame = SimResultFrame(self, None, self.client)
        self.simPaneFrame.layout().addWidget(self.simFrame)
        self.simPane.hide()
        self.simWindows = []

        self.splitter.restoreState(self.splitterstate)
        self.treeModel = QFileSystemModel()
        idx = self.treeModel.setRootPath('/')
        self.treeModel.setNameFilters(['*.py', '*.txt'])
        self.treeModel.setNameFilterDisables(False)  # hide them
        self.fileTree.setModel(self.treeModel)
        self.fileTree.header().hideSection(1)
        self.fileTree.header().hideSection(2)
        self.fileTree.header().hideSection(3)
        self.fileTree.header().hide()
        self.fileTree.setRootIndex(idx)
        if not options.get('show_browser', True):
            self.scriptsPane.hide()
        self.actionShowScripts = self.scriptsPane.toggleViewAction()
        self.actionShowScripts.setText('Show Script Browser')

        self.activeGroup = QActionGroup(self)
        self.activeGroup.addAction(self.actionRun)
        self.activeGroup.addAction(self.actionSimulate)
        self.activeGroup.addAction(self.actionUpdate)

        client.simresult.connect(self.on_client_simresult)
        if self.client.connected:
            self.on_client_connected()
        else:
            self.on_client_disconnected()
        client.connected.connect(self.on_client_connected)
        client.disconnected.connect(self.on_client_disconnected)
        client.setup.connect(self.on_client_connected)
        client.cache.connect(self.on_client_cache)
        client.experiment.connect(self.on_client_experiment)

        if self.openfiles:
            for fn in self.openfiles:
                self.openFile(fn, quiet=True)
        else:
            self.newFile()
Пример #26
0
 def reinitLayout(self):
     # reinitialize UI after switching horizontal/vertical layout
     if self.props['horizontal']:
         new_layout = QHBoxLayout()
         new_layout.addWidget(self.namelabel)
         new_layout.addStretch()
         new_layout.addWidget(self.valuelabel)
         self.namelabel.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
     else:
         new_layout = QVBoxLayout()
         new_layout.addWidget(self.namelabel)
         tmplayout = QHBoxLayout()
         if self.width >= 0:
             tmplayout.addStretch()
         tmplayout.addWidget(self.valuelabel)
         if self.width >= 0:
             tmplayout.addStretch()
         new_layout.addLayout(tmplayout)
         self.namelabel.setAlignment(Qt.AlignHCenter)
     if self.layout():
         sip.delete(self.layout())
     new_layout.setContentsMargins(1, 1, 1, 1)  # save space
     self.setLayout(new_layout)
Пример #27
0
    def __init__(self,
                 model,
                 name,
                 index,
                 addr,
                 has_status=False,
                 target=None,
                 value_offset=1):
        QWidget.__init__(self)
        self.index = index
        self.name = name
        self.model = model

        self.offset = value_offset
        self.has_status = has_status
        self.has_target = target is not None
        self.base_address = addr

        self._namelabel = QLabel(name)
        self._namelabel.setMinimumWidth(120)
        self._namelabel.setMaximumWidth(120)
        # self._groupbox = QGroupBox(name)
        self._groupbox = QFrame()
        # self._groupbox.setFlat(False)
        # self._groupbox.setCheckable(False)
        self._hlayout = QHBoxLayout()
        self._hlayout.addWidget(self._namelabel)
        self._hlayout.addWidget(self._groupbox)
        self._hlayout.setSpacing(0)

        # inside of the groupbox there is a vbox with 1 or 2 hboxes
        self._inner_vbox = QVBoxLayout()
        self._groupbox.setLayout(self._inner_vbox)

        # upper inner hbox
        self._inner_hbox1 = QHBoxLayout()
        self._inner_vbox.addLayout(self._inner_hbox1)

        # fill upper hbox
        self.valueWidget = QLineEdit('0b123456789abcdef0')
        self.valueWidget.setMaximumWidth(120)
        self._inner_hbox1.addWidget(self.valueWidget)

        if self.has_target:
            self.targetWidget = QLineEdit()
            self.targetWidget.setPlaceholderText(target)
            self.targetWidget.setMaximumWidth(120)
            self.targetWidget.returnPressed.connect(lambda *a: model.targeter(
                index,
                (self.targetWidget.text(), self.targetWidget.setText(''))[0]))
            self._inner_hbox1.addWidget(self.targetWidget)
            self.goButton = QPushButton('Go')
            self.goButton.clicked.connect(lambda *a: model.targeter(
                index,
                (self.targetWidget.text(), self.targetWidget.setText(''))[0]))
            self._inner_hbox1.addWidget(self.goButton)
            self.stopButton = QPushButton('Stop')
            self.stopButton.clicked.connect(lambda *a: model.stopper(index))
            self._inner_hbox1.addWidget(self.stopButton)

        # now (conditionally) the second hbox
        if has_status:
            self._inner_hbox2 = QHBoxLayout()
            self._inner_vbox.addLayout(self._inner_hbox2)

            self.statvalueWidget = QLineEdit('statval')
            self.statvalueWidget.setMaximumWidth(120)
            self._inner_hbox2.addWidget(self.statvalueWidget)
            self.statusWidget = QLineEdit('Statusstring if available')
            self.statusWidget.setMaximumWidth(10000)
            self._inner_hbox2.addWidget(self.statusWidget)
            self.resetButton = QPushButton('Reset')
            self.resetButton.clicked.connect(lambda *a: model.resetter(index))
            self._inner_hbox1.addWidget(self.resetButton)
            # self._inner_hbox2.addStretch(0.1)

        # allow space for resizing
        self._inner_hbox1.addStretch(1)

        self._inner_vbox.setSpacing(0)
        self._inner_vbox.setContentsMargins(0, 0, 0, 0)

        self._hlayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self._hlayout)
        self.show()
Пример #28
0
 def insertItem(self, *widgets):
     item = QWidget(self.frame)
     item._widgets = widgets
     layout = QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     for widget in widgets:
         layout.addWidget(widget)
     if self.allow_reorder:
         btn = QPushButton(QIcon(':/up'), '', item)
         btn._item = item
         btn.clicked.connect(self.on_upBtn_clicked)
         layout.addWidget(btn)
         btn = QPushButton(QIcon(':/down'), '', item)
         btn._item = item
         btn.clicked.connect(self.on_downBtn_clicked)
         layout.addWidget(btn)
     btn = QPushButton(QIcon(':/remove'), '', item)
     btn._item = item
     btn.clicked.connect(self.on_removeBtn_clicked)
     layout.addWidget(btn)
     item.setLayout(layout)
     self.layout.insertWidget(self.layout.count() - 2, item)
     self.items.append(item)
Пример #29
0
class QRangeSlider(QWidget, Ui_Form):
    """
    The QRangeSlider class implements a horizontal range slider widget.

    Inherits QWidget.

    Methods

        * __init__ (self, QWidget parent = None)
        * bool drawValues (self)
        * int end (self)
        * (int, int) getRange (self)
        * int max (self)
        * int min (self)
        * int start (self)
        * setBackgroundStyle (self, QString styleSheet)
        * setDrawValues (self, bool draw)
        * setEnd (self, int end)
        * setStart (self, int start)
        * setRange (self, int start, int end)
        * setSpanStyle (self, QString styleSheet)

    Signals

        * endValueChanged (int)
        * maxValueChanged (int)
        * minValueChanged (int)
        * startValueChanged (int)

    Customizing QRangeSlider

    You can style the range slider as below:
    ::
        QRangeSlider * {
            border: 0px;
            padding: 0px;
        }
        QRangeSlider #Head {
            background: #222;
        }
        QRangeSlider #Span {
            background: #393;
        }
        QRangeSlider #Span:active {
            background: #282;
        }
        QRangeSlider #Tail {
            background: #222;
        }

    Styling the range slider handles follows QSplitter options:
    ::
        QRangeSlider > QSplitter::handle {
            background: #393;
        }
        QRangeSlider > QSplitter::handle:vertical {
            height: 4px;
        }
        QRangeSlider > QSplitter::handle:pressed {
            background: #ca5;
        }

    """
    endValueChanged = pyqtSignal(int)
    maxValueChanged = pyqtSignal(int)
    minValueChanged = pyqtSignal(int)
    startValueChanged = pyqtSignal(int)

    # define splitter indices
    _SPLIT_START = 1
    _SPLIT_END = 2

    # signals
    minValueChanged = pyqtSignal(int)
    maxValueChanged = pyqtSignal(int)
    startValueChanged = pyqtSignal(int)
    endValueChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        """Create a new QRangeSlider instance.

            :param parent: QWidget parent
            :return: New QRangeSlider instance.

        """
        super(QRangeSlider, self).__init__(parent)
        self.setupUi(self)
        self.setMouseTracking(False)

        #self._splitter.setChildrenCollapsible(False)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)

        # head layout
        self._head_layout = QHBoxLayout()
        self._head_layout.setSpacing(0)
        self._head_layout.setContentsMargins(0, 0, 0, 0)
        self._head.setLayout(self._head_layout)
        self.head = Head(self._head, main=self)
        self._head_layout.addWidget(self.head)

        # handle layout
        self._handle_layout = QHBoxLayout()
        self._handle_layout.setSpacing(0)
        self._handle_layout.setContentsMargins(0, 0, 0, 0)
        self._handle.setLayout(self._handle_layout)
        self.handle = Handle(self._handle, main=self)
        self.handle.setTextColor((150, 255, 150))
        self._handle_layout.addWidget(self.handle)

        # tail layout
        self._tail_layout = QHBoxLayout()
        self._tail_layout.setSpacing(0)
        self._tail_layout.setContentsMargins(0, 0, 0, 0)
        self._tail.setLayout(self._tail_layout)
        self.tail = Tail(self._tail, main=self)
        self._tail_layout.addWidget(self.tail)

        # defaults
        self.setMin(0)
        self.setMax(99)
        self.setStart(0)
        self.setEnd(99)
        self.setDrawValues(True)

    def min(self):
        """:return: minimum value"""
        return getattr(self, '__min', None)

    def max(self):
        """:return: maximum value"""
        return getattr(self, '__max', None)

    def setMin(self, value):
        """sets minimum value"""
        assert isinstance(value, int)
        setattr(self, '__min', value)
        self.minValueChanged.emit(value)

    def setMax(self, value):
        """sets maximum value"""
        assert isinstance(value, int)
        setattr(self, '__max', value)
        self.maxValueChanged.emit(value)

    def start(self):
        """:return: range slider start value"""
        return getattr(self, '__start', None)

    def end(self):
        """:return: range slider end value"""
        return getattr(self, '__end', None)

    def _setStart(self, value):
        """stores the start value only"""
        setattr(self, '__start', value)
        self.startValueChanged.emit(value)

    def setStart(self, value):
        """sets the range slider start value"""
        assert isinstance(value, int)
        v = self._valueToPos(value, self._SPLIT_START)
        self._splitter.splitterMoved.disconnect()
        self._splitter.moveSplitter(v, self._SPLIT_START)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)
        self._setStart(value)

    def _setEnd(self, value):
        """stores the end value only"""
        setattr(self, '__end', value)
        self.endValueChanged.emit(value)

    def setEnd(self, value):
        """set the range slider end value"""
        assert isinstance(value, int)
        v = self._valueToPos(value, self._SPLIT_END)
        self._splitter.splitterMoved.disconnect()
        self._splitter.moveSplitter(v, self._SPLIT_END)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)
        self._setEnd(value)

    def drawValues(self):
        """:return: True if slider values will be drawn"""
        return getattr(self, '__drawValues', None)

    def setDrawValues(self, draw):
        """sets draw values boolean to draw slider values"""
        assert isinstance(draw, bool)
        setattr(self, '__drawValues', draw)

    def getRange(self):
        """:return: the start and end values as a tuple"""
        return (self.start(), self.end())

    def setRange(self, start, end):
        """set the start and end values"""
        self.setStart(start)
        self.setEnd(end)

    def keyPressEvent(self, event):
        """overrides key press event to move range left and right"""
        key = event.key()
        if key == Qt.Key_Left:
            s = self.start() - 1
            e = self.end() - 1
        elif key == Qt.Key_Right:
            s = self.start() + 1
            e = self.end() + 1
        else:
            event.ignore()
            return
        event.accept()
        if s >= self.min() and e <= self.max():
            self.setRange(s, e)

    def setBackgroundStyle(self, style):
        """sets background style"""
        self._tail.setStyleSheet(style)
        self._head.setStyleSheet(style)

    def setSpanStyle(self, style):
        """sets range span handle style"""
        self._handle.setStyleSheet(style)

    def _valueToPos(self, value, index):
        """converts slider value to local pixel x coord"""
        left, right = self._splitter.getRange(index)
        return scale(value, (self.min(), self.max()), (left, right))

    def _posToValue(self, xpos, index):
        """converts local pixel x coord to slider value"""
        left, right = self._splitter.getRange(index)
        return scale(xpos, (left, right), (self.min(), self.max()))

    def _handleMoveSplitter(self, xpos, index):
        """private method for handling moving splitter handles"""
        def _lockWidth(widget):
            width = widget.size().width()
            widget.setMinimumWidth(width)
            widget.setMaximumWidth(width)

        def _unlockWidth(widget):
            widget.setMinimumWidth(0)
            widget.setMaximumWidth(16777215)

        v = self._posToValue(xpos, index)

        if index == self._SPLIT_START:
            _lockWidth(self._tail)
            if v >= self.end():
                return
            self._setStart(v)

        elif index == self._SPLIT_END:
            _lockWidth(self._head)
            if v <= self.start():
                return
            self._setEnd(v)

        _unlockWidth(self._tail)
        _unlockWidth(self._head)
        _unlockWidth(self._handle)
Пример #30
0
class DeviceValueEdit(NicosWidget, QWidget):

    designer_description = 'Editor for a device value with the right kind ' \
        'of widget'

    valueModified = pyqtSignal()
    valueChosen = pyqtSignal(object)

    dev = PropDef('dev', str, '', 'Device name')
    useButtons = PropDef('useButtons', bool, False,
                         'Use buttons for values with few choices?')
    allowEnter = PropDef('allowEnter', bool, True,
                         'Emit valueChosen signal on pressing Enter?')
    updateValue = PropDef('updateValue', bool, False,
                          'Update the editor when the device value changes?')
    showUnit = PropDef('showUnit', bool, True,
                       'Show the unit next to the input')

    def __init__(self, parent, designMode=False, **kwds):
        self._inner = None
        QWidget.__init__(self, parent, **kwds)
        NicosWidget.__init__(self)
        self._layout = QHBoxLayout()
        self._layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self._layout)
        if designMode:
            self._layout.insertWidget(0, QLabel('(Value Editor)', self))

    def setFocus(self):
        if self._inner is not None:
            self._inner.setFocus()
        else:
            QWidget.setFocus(self)

    def propertyUpdated(self, pname, value):
        if pname == 'dev':
            self._reinit()
        NicosWidget.propertyUpdated(self, pname, value)

    def setClient(self, client):
        NicosWidget.setClient(self, client)
        self._reinit()

    def on_client_connected(self):
        self._reinit()

    def registerKeys(self):
        if self.props['updateValue']:
            self.registerDevice(self.props['dev'])

    def on_devValueChange(self, dev, value, strvalue, unitvalue, expired):
        self._reinit(value)

    def on_devMetaChange(self, dev, fmtstr, unit, fixed):
        self._reinit()

    def _reinit(self, curvalue=None):
        if not self._client or not self._client.isconnected:
            return
        devname = str(self.props['dev'])
        if devname:
            params = self._client.getDeviceParams(devname)
            valuetype = self._client.getDeviceValuetype(devname)
            valueinfo = self._client.eval(
                'session.getDevice(%r).valueInfo()' % devname, None)
            unit = params.get('unit', '') if self.props['showUnit'] else ''
            fmtstr = params.get('fmtstr', '%s')
            if curvalue is None:
                curvalue = params.get('target')
            if curvalue is None and valuetype is not None:
                curvalue = valuetype()
        else:
            valuetype = str
            curvalue = ''
            fmtstr = '%s'
            unit = ''
            valueinfo = None

        self._inner = create(self,
                             valuetype,
                             curvalue,
                             fmtstr,
                             unit,
                             allow_buttons=self.props['useButtons'],
                             allow_enter=self.props['allowEnter'],
                             client=self._client,
                             valinfo=valueinfo)
        last = self._layout.takeAt(0)
        if last:
            last.widget().deleteLater()
        self._layout.insertWidget(0, self._inner)
        self._inner.valueModified.connect(self.valueModified)
        self._inner.valueChosen.connect(self.valueChosen)

    def getValue(self):
        if self._inner:
            return self._inner.getValue()

    def setValue(self, value):
        self._reinit(value)