Ejemplo n.º 1
0
    def setupui(self):
        """."""
        vbl = QVBoxLayout(self)
        if self.orbtype.startswith('sum'):
            img_propty = 'MTurnSum-Mon'
            orb_propty = 'MTurnIdxSum-Mon'
            unit = 'count'
            color = 'black'
        elif self.orbtype.startswith('x'):
            img_propty = 'MTurnOrbX-Mon'
            orb_propty = 'MTurnIdxOrbX-Mon'
            unit = 'm'
            color = 'blue'
        else:
            img_propty = 'MTurnOrbY-Mon'
            orb_propty = 'MTurnIdxOrbY-Mon'
            unit = 'm'
            color = 'red'
        lbl_text = img_propty.split('-')[0]

        self.spect = Spectrogram(
            parent=self,
            device=self.device,
            prefix=self.prefix,
            image_channel=self.devpref.substitute(propty=img_propty),
            xaxis_channel=self.devpref.substitute(propty='BPMPosS-Mon'),
            yaxis_channel=self.devpref.substitute(propty='MTurnTime-Mon'))
        self.spect.new_data_sig.connect(self.update_graph)
        self.spect.normalizeData = True
        self.spect.yaxis.setLabel('Time', units='s')
        self.spect.xaxis.setLabel('BPM Position', units='m')
        self.spect.colorbar.label_format = '{:<8.1f}'
        lab = QLabel(lbl_text + ' Orbit', self, alignment=Qt.AlignCenter)
        lab.setStyleSheet("font-weight: bold;")
        vbl.addWidget(lab)
        vbl.addWidget(self.spect)

        vbl.addStretch()
        lab = QLabel('Average ' + lbl_text + ' vs Time',
                     self,
                     alignment=Qt.AlignCenter)
        lab.setStyleSheet("font-weight: bold;")
        hbl = QHBoxLayout()
        hbl.addStretch()
        hbl.addWidget(lab)
        hbl.addStretch()
        if self.orbtype.startswith('sum'):
            hbl.addWidget(QLabel('  Eff [%] =', self))
            ratio_avg = QLabel('000.0', self, alignment=Qt.AlignRight)
            ratio_std = QLabel('000.0', self, alignment=Qt.AlignLeft)
            hbl.addWidget(ratio_avg, alignment=Qt.AlignRight)
            hbl.addWidget(
                QLabel('<html><head/><body><p>&#177;</p></body></html>', self))
            hbl.addWidget(ratio_std, alignment=Qt.AlignLeft)
            hbl.addStretch()
            self.ratio_sum_avg.connect(ratio_avg.setText)
            self.ratio_sum_std.connect(ratio_std.setText)
        vbl.addLayout(hbl)

        graph = Graph(self)
        graph.setLabel('bottom', text='Time', units='s')
        graph.setLabel('left', text='Avg ' + lbl_text, units=unit)
        opts = dict(y_channel='A',
                    x_channel=self.devpref.substitute(propty='MTurnTime-Mon'),
                    name='',
                    color=color,
                    redraw_mode=2,
                    lineStyle=1,
                    lineWidth=3,
                    symbol='o',
                    symbolSize=10)
        graph.addChannel(**opts)
        graph.setShowLegend(False)
        graph.plotItem.scene().sigMouseMoved.connect(self._show_tooltip_time)
        self.curve = graph.curveAtIndex(0)
        self.graph_time = graph
        vbl.addWidget(graph)

        if not self.orbtype.startswith('sum'):
            return

        vbl.addStretch()
        wid = QWidget(self)
        lab = QLabel(lbl_text + ' orbit at index:',
                     wid,
                     alignment=Qt.AlignRight | Qt.AlignVCenter)
        lab.setStyleSheet("font-weight: bold;")
        pdmlab = SiriusLabel(wid,
                             self.devpref.substitute(propty='MTurnIdx-RB'))
        pdmlab.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        pdmlab.setStyleSheet('min-width:4em;')
        wid.setLayout(QHBoxLayout())
        wid.layout().addStretch()
        wid.layout().addWidget(lab)
        wid.layout().addWidget(pdmlab)
        wid.layout().addStretch()
        vbl.addWidget(wid)
        graph = Graph(self)
        vbl.addWidget(graph)
        graph.setLabel('bottom', text='BPM Position', units='m')
        graph.setLabel('left', text='Sum', units='count')
        opts = dict(y_channel=self.devpref.substitute(propty=orb_propty),
                    x_channel=self.devpref.substitute(propty='BPMPosS-Mon'),
                    name='',
                    color=color,
                    redraw_mode=2,
                    lineStyle=1,
                    lineWidth=3,
                    symbol='o',
                    symbolSize=10)
        graph.addChannel(**opts)
        graph.setShowLegend(False)
        graph.plotItem.scene().sigMouseMoved.connect(self._show_tooltip)
        self.graph = graph
Ejemplo n.º 2
0
    def setupUi(self):
        # create title bar, content
        self.vboxWindow = QVBoxLayout(self)
        self.vboxWindow.setContentsMargins(0, 0, 0, 0)

        self.windowFrame = QWidget(self)
        self.windowFrame.setObjectName('windowFrame')

        self.vboxFrame = QVBoxLayout(self.windowFrame)
        self.vboxFrame.setContentsMargins(0, 0, 0, 0)

        self.titleBar = WindowDragger(self, self.windowFrame)
        self.titleBar.setObjectName('titleBar')
        self.titleBar.setSizePolicy(
            QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed))

        self.hboxTitle = QHBoxLayout(self.titleBar)
        self.hboxTitle.setContentsMargins(0, 0, 0, 0)
        self.hboxTitle.setSpacing(0)

        self.lblTitle = QLabel('Title')
        self.lblTitle.setObjectName('lblTitle')
        self.lblTitle.setAlignment(Qt.AlignCenter)

        spButtons = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.btnMinimize = QToolButton(self.titleBar)
        self.btnMinimize.setObjectName('btnMinimize')
        self.btnMinimize.setSizePolicy(spButtons)

        self.btnRestore = QToolButton(self.titleBar)
        self.btnRestore.setObjectName('btnRestore')
        self.btnRestore.setSizePolicy(spButtons)
        self.btnRestore.setVisible(False)

        self.btnMaximize = QToolButton(self.titleBar)
        self.btnMaximize.setObjectName('btnMaximize')
        self.btnMaximize.setSizePolicy(spButtons)

        self.btnClose = QToolButton(self.titleBar)
        self.btnClose.setObjectName('btnClose')
        self.btnClose.setSizePolicy(spButtons)

        self.vboxFrame.addWidget(self.titleBar)

        self.windowContent = QWidget(self.windowFrame)
        self.vboxFrame.addWidget(self.windowContent)

        self.vboxWindow.addWidget(self.windowFrame)

        if PLATFORM == "Darwin":
            self.hboxTitle.addWidget(self.btnClose)
            self.hboxTitle.addWidget(self.btnMinimize)
            self.hboxTitle.addWidget(self.btnRestore)
            self.hboxTitle.addWidget(self.btnMaximize)
            self.hboxTitle.addWidget(self.lblTitle)
        else:
            self.hboxTitle.addWidget(self.lblTitle)
            self.hboxTitle.addWidget(self.btnMinimize)
            self.hboxTitle.addWidget(self.btnRestore)
            self.hboxTitle.addWidget(self.btnMaximize)
            self.hboxTitle.addWidget(self.btnClose)

        # set window flags
        self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint
                            | Qt.WindowSystemMenuHint)

        if QT_VERSION >= (5, ):
            self.setAttribute(Qt.WA_TranslucentBackground)

        # set stylesheet
        with open(_FL_STYLESHEET) as stylesheet:
            self.setStyleSheet(stylesheet.read())

        # automatically connect slots
        QMetaObject.connectSlotsByName(self)
Ejemplo n.º 3
0
    def __init__(self, parent, text):
        QWidget.__init__(self, parent)

        self.text_editor = QTextEdit(self)
        self.text_editor.setText(text)
        self.text_editor.setReadOnly(True)

        # Type frame
        type_layout = QHBoxLayout()
        type_label = QLabel(_("Import as"))
        type_layout.addWidget(type_label)
        data_btn = QRadioButton(_("data"))
        data_btn.setChecked(True)
        self._as_data= True
        type_layout.addWidget(data_btn)
        code_btn = QRadioButton(_("code"))
        self._as_code = False
        type_layout.addWidget(code_btn)
        txt_btn = QRadioButton(_("text"))
        type_layout.addWidget(txt_btn)

        h_spacer = QSpacerItem(40, 20,
                               QSizePolicy.Expanding, QSizePolicy.Minimum)
        type_layout.addItem(h_spacer)
        type_frame = QFrame()
        type_frame.setLayout(type_layout)

        # Opts frame
        grid_layout = QGridLayout()
        grid_layout.setSpacing(0)

        col_label = QLabel(_("Column separator:"))
        grid_layout.addWidget(col_label, 0, 0)
        col_w = QWidget()
        col_btn_layout = QHBoxLayout()
        self.tab_btn = QRadioButton(_("Tab"))
        self.tab_btn.setChecked(False)
        col_btn_layout.addWidget(self.tab_btn)
        self.ws_btn = QRadioButton(_("Whitespace"))
        self.ws_btn.setChecked(False)
        col_btn_layout.addWidget(self.ws_btn)
        other_btn_col = QRadioButton(_("other"))
        other_btn_col.setChecked(True)
        col_btn_layout.addWidget(other_btn_col)
        col_w.setLayout(col_btn_layout)
        grid_layout.addWidget(col_w, 0, 1)
        self.line_edt = QLineEdit(",")
        self.line_edt.setMaximumWidth(30)
        self.line_edt.setEnabled(True)
        other_btn_col.toggled.connect(self.line_edt.setEnabled)
        grid_layout.addWidget(self.line_edt, 0, 2)

        row_label = QLabel(_("Row separator:"))
        grid_layout.addWidget(row_label, 1, 0)
        row_w = QWidget()
        row_btn_layout = QHBoxLayout()
        self.eol_btn = QRadioButton(_("EOL"))
        self.eol_btn.setChecked(True)
        row_btn_layout.addWidget(self.eol_btn)
        other_btn_row = QRadioButton(_("other"))
        row_btn_layout.addWidget(other_btn_row)
        row_w.setLayout(row_btn_layout)
        grid_layout.addWidget(row_w, 1, 1)
        self.line_edt_row = QLineEdit(";")
        self.line_edt_row.setMaximumWidth(30)
        self.line_edt_row.setEnabled(False)
        other_btn_row.toggled.connect(self.line_edt_row.setEnabled)
        grid_layout.addWidget(self.line_edt_row, 1, 2)

        grid_layout.setRowMinimumHeight(2, 15)

        other_group = QGroupBox(_("Additional options"))
        other_layout = QGridLayout()
        other_group.setLayout(other_layout)

        skiprows_label = QLabel(_("Skip rows:"))
        other_layout.addWidget(skiprows_label, 0, 0)
        self.skiprows_edt = QLineEdit('0')
        self.skiprows_edt.setMaximumWidth(30)
        intvalid = QIntValidator(0, len(to_text_string(text).splitlines()),
                                 self.skiprows_edt)
        self.skiprows_edt.setValidator(intvalid)
        other_layout.addWidget(self.skiprows_edt, 0, 1)

        other_layout.setColumnMinimumWidth(2, 5)

        comments_label = QLabel(_("Comments:"))
        other_layout.addWidget(comments_label, 0, 3)
        self.comments_edt = QLineEdit('#')
        self.comments_edt.setMaximumWidth(30)
        other_layout.addWidget(self.comments_edt, 0, 4)

        self.trnsp_box = QCheckBox(_("Transpose"))
        #self.trnsp_box.setEnabled(False)
        other_layout.addWidget(self.trnsp_box, 1, 0, 2, 0)

        grid_layout.addWidget(other_group, 3, 0, 2, 0)

        opts_frame = QFrame()
        opts_frame.setLayout(grid_layout)

        data_btn.toggled.connect(opts_frame.setEnabled)
        data_btn.toggled.connect(self.set_as_data)
        code_btn.toggled.connect(self.set_as_code)
#        self.connect(txt_btn, SIGNAL("toggled(bool)"),
#                     self, SLOT("is_text(bool)"))

        # Final layout
        layout = QVBoxLayout()
        layout.addWidget(type_frame)
        layout.addWidget(self.text_editor)
        layout.addWidget(opts_frame)
        self.setLayout(layout)
Ejemplo n.º 4
0
    def _setupUi(self):
        label = QLabel('<h3>'+self.title+'</h3>', self)
        label.setStyleSheet("""
            min-height:1.55em; max-height: 1.55em;
            qproperty-alignment: 'AlignVCenter | AlignRight';
            background-color: qlineargradient(spread:pad, x1:1, y1:0.0227273,
                              x2:0, y2:0, stop:0 rgba(173, 190, 207, 255),
                              stop:1 rgba(213, 213, 213, 255));""")

        self.gb_status = QGroupBox('Status', self)
        self.gb_status.setLayout(self._setupStatusLayout())

        self.wid_optics = QWidget()
        lay_optics = QGridLayout(self.wid_optics)
        lay_optics.setContentsMargins(0, 0, 0, 0)
        self.gb_optprm = QGroupBox(
            'ΔTune' if self.param == 'tune' else 'Chromaticity', self)
        self.gb_optprm.setLayout(self._setupOpticsParamLayout())
        if self.param == 'tune':
            self.pb_updref = PyDMPushButton(
                self, label='Update Reference', pressValue=1,
                init_channel=self.ioc_prefix.substitute(propty='SetNewRefKL-Cmd'))
            self.pb_updref.setStyleSheet('min-height:2.4em; max-height:2.4em;')
            lay_optics.addWidget(self.pb_updref, 0, 0, 1, 2)
            lay_optics.addWidget(self.gb_optprm, 1, 0)

            if self.acc == 'SI':
                self.gb_digmon = QGroupBox('Tune Monitor', self)
                self.gb_digmon.setLayout(self._setupDigMonLayout())
                lay_optics.addWidget(self.gb_digmon, 1, 1)
                lay_optics.setColumnStretch(0, 3)
                lay_optics.setColumnStretch(1, 1)
        else:
            lay_optics.addWidget(self.gb_optprm, 0, 0)

        self.gb_fams = QGroupBox('Families', self)
        self.gb_fams.setLayout(self._setupFamiliesLayout())
        self.gb_fams.setSizePolicy(QSzPly.Preferred, QSzPly.Expanding)

        self.gb_iocctrl = QGroupBox('IOC Control', self)
        self.gb_iocctrl.setLayout(self._setupIOCControlLayout())

        cwt = QWidget()
        self.setCentralWidget(cwt)
        if self.acc == 'SI':
            vlay1 = QVBoxLayout()
            vlay1.setAlignment(Qt.AlignTop)
            vlay1.addWidget(self.wid_optics)
            vlay1.addWidget(self.gb_fams)
            lay = QGridLayout(cwt)
            lay.addWidget(label, 0, 0, 1, 2)
            lay.addLayout(vlay1, 1, 0, alignment=Qt.AlignTop)
            lay.addWidget(self.gb_iocctrl, 1, 1)
            lay.addWidget(self.gb_status, 2, 0, 1, 2)
            lay.setColumnStretch(0, 1)
            lay.setColumnStretch(1, 1)
            lay.setRowStretch(0, 1)
            lay.setRowStretch(1, 15)
            lay.setRowStretch(2, 5)
        else:
            lay = QVBoxLayout(cwt)
            lay.addWidget(label)
            lay.addWidget(self.wid_optics)
            lay.addWidget(self.gb_fams)
            lay.addWidget(self.gb_iocctrl)
            lay.addWidget(self.gb_status)

        self.setStyleSheet("""
            PyDMLabel{
                qproperty-alignment: AlignCenter;
            }""")
Ejemplo n.º 5
0
    def __init__(self, items, itemHeader=None):
        super().__init__(emptyDateValid=False)

        if itemHeader is None:
            itemHeader = self.headerLabels

        self.table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.table.insertColumn(self.table.columnCount())
        self.table.setHorizontalHeaderLabels([""] + self.headerLabels)
        self.headerLabelColumnOffset = 1

        self.rows = []

        for rowNum, item in enumerate(items):
            self.table.insertRow(rowNum)
            col = 0

            checkBox = QCheckBox()
            checkBox.setChecked(True)
            checkBox.setToolTip("Uncheck to remove this data")
            # have to make a widget with a layout and add the check box to
            # the layout in order to have the check box centred...
            widget = QWidget()
            layout = QVBoxLayout()
            layout.addWidget(checkBox)
            layout.setAlignment(Qt.AlignCenter)
            widget.setLayout(layout)
            self.table.setCellWidget(rowNum, col, widget)
            col += 1

            tableItems = {}
            for idx in range(item.columnCount()):
                if itemHeader[idx] in self.headerLabels:
                    text = item.text(idx)
                    tableItem = QTableWidgetItem(text)
                    tableItem.setTextAlignment(Qt.AlignCenter)
                    tableItem.setFlags(Qt.ItemIsEditable | Qt.ItemIsEnabled)
                    self.table.setItem(rowNum, col, tableItem)
                    tableItems[itemHeader[idx]] = tableItem
                    col += 1

            self.rows.append(Row(item.index, tableItems, checkBox))
            col += 1

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)

        self.okButton = self.buttonBox.button(QDialogButtonBox.Ok)
        self.okButton.clicked.connect(self.accept)
        cancelButton = self.buttonBox.button(QDialogButtonBox.Cancel)
        cancelButton.clicked.connect(self.reject)

        scrollArea = QScrollArea()
        scrollArea.setWidget(self.table)

        layout = QVBoxLayout()
        layout.addWidget(scrollArea)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

        # set the table size
        # i don't know why this is such a faff
        pad = 2
        self.table.resizeRowsToContents()
        self.table.resizeColumnsToContents()
        # manually add the widths of each column for width
        # then do the same for the height
        # getting the `length` of the header items did not work
        width = pad
        for i in range(self.table.columnCount()):
            width += self.table.columnWidth(i)
        # add some extra width, in case there's a vertical scroll bar
        # (scrollArea.verticalScrollBar().width() is too much...)
        width += 30
        # start with one row height for the header
        # directly getting the header height is completely wrong
        height = self.table.rowHeight(0) + pad
        for i in range(self.table.rowCount()):
            height += self.table.rowHeight(i)
        # then set the table's minimum size
        self.table.setMinimumSize(width, height)

        self.setWindowTitle("Edit or remove data")
Ejemplo n.º 6
0
    def add_color_scheme_stack(self, scheme_name, custom=False):
        """Add a stack for a given scheme and connects the CONF values."""
        color_scheme_groups = [(_('Text'), [
            "normal",
            "comment",
            "string",
            "number",
            "keyword",
            "builtin",
            "definition",
            "instance",
        ]),
                               (_('Highlight'), [
                                   "currentcell", "currentline", "occurrence",
                                   "matched_p", "unmatched_p", "ctrlclick"
                               ]),
                               (_('Background'), ["background", "sideareas"])]

        parent = self.parent
        line_edit = parent.create_lineedit(_("Scheme name:"),
                                           '{0}/name'.format(scheme_name))

        self.widgets[scheme_name] = {}

        # Widget setup
        line_edit.label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.setWindowTitle(_('Color scheme editor'))

        # Layout
        name_layout = QHBoxLayout()
        name_layout.addWidget(line_edit.label)
        name_layout.addWidget(line_edit.textbox)
        self.scheme_name_textbox[scheme_name] = line_edit.textbox

        if not custom:
            line_edit.textbox.setDisabled(True)
        if not self.isVisible():
            line_edit.setVisible(False)

        cs_layout = QVBoxLayout()
        cs_layout.addLayout(name_layout)

        h_layout = QHBoxLayout()
        v_layout = QVBoxLayout()

        for index, item in enumerate(color_scheme_groups):
            group_name, keys = item
            group_layout = QGridLayout()

            for row, key in enumerate(keys):
                option = "{0}/{1}".format(scheme_name, key)
                value = self.parent.get_option(option)
                name = syntaxhighlighters.COLOR_SCHEME_KEYS[key]

                if is_text_string(value):
                    label, clayout = parent.create_coloredit(
                        name,
                        option,
                        without_layout=True,
                    )
                    label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
                    group_layout.addWidget(label, row + 1, 0)
                    group_layout.addLayout(clayout, row + 1, 1)

                    # Needed to update temp scheme to obtain instant preview
                    self.widgets[scheme_name][key] = [clayout]
                else:
                    label, clayout, cb_bold, cb_italic = parent.create_scedit(
                        name,
                        option,
                        without_layout=True,
                    )
                    label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
                    group_layout.addWidget(label, row + 1, 0)
                    group_layout.addLayout(clayout, row + 1, 1)
                    group_layout.addWidget(cb_bold, row + 1, 2)
                    group_layout.addWidget(cb_italic, row + 1, 3)

                    # Needed to update temp scheme to obtain instant preview
                    self.widgets[scheme_name][key] = [
                        clayout, cb_bold, cb_italic
                    ]

            group_box = QGroupBox(group_name)
            group_box.setLayout(group_layout)

            if index == 0:
                h_layout.addWidget(group_box)
            else:
                v_layout.addWidget(group_box)

        h_layout.addLayout(v_layout)
        cs_layout.addLayout(h_layout)

        stackitem = QWidget()
        stackitem.setLayout(cs_layout)
        self.stack.addWidget(stackitem)
        self.order.append(scheme_name)
Ejemplo n.º 7
0
    def __init__(self, parent):
        SpyderPluginWidget.__init__(self, parent)

        self.tabwidget = None
        self.menu_actions = None

        self.help = None  # Help plugin
        self.historylog = None  # History log plugin
        self.variableexplorer = None  # Variable explorer plugin

        self.python_count = 0
        self.terminal_count = 0

        # Python startup file selection
        if not osp.isfile(self.get_option('pythonstartup', '')):
            self.set_option('pythonstartup', SCIENTIFIC_STARTUP)
        # default/custom settings are mutually exclusive:
        self.set_option('pythonstartup/custom',
                        not self.get_option('pythonstartup/default'))

        self.shellwidgets = []
        self.filenames = []
        self.icons = []
        self.runfile_args = ""

        # Initialize plugin
        self.initialize_plugin()

        layout = QVBoxLayout()
        self.tabwidget = Tabs(self, self.menu_actions)
        if hasattr(self.tabwidget, 'setDocumentMode')\
           and not sys.platform == 'darwin':
            # Don't set document mode to true on OSX because it generates
            # a crash when the console is detached from the main window
            # Fixes Issue 561
            self.tabwidget.setDocumentMode(True)
        self.tabwidget.currentChanged.connect(self.refresh_plugin)
        self.tabwidget.move_data.connect(self.move_tab)
        self.main.sig_pythonpath_changed.connect(self.set_path)

        self.tabwidget.set_close_function(self.close_console)

        if sys.platform == 'darwin':
            tab_container = QWidget()
            tab_container.setObjectName('tab-container')
            tab_layout = QHBoxLayout(tab_container)
            tab_layout.setContentsMargins(0, 0, 0, 0)
            tab_layout.addWidget(self.tabwidget)
            layout.addWidget(tab_container)
        else:
            layout.addWidget(self.tabwidget)

        # Find/replace widget
        self.find_widget = FindReplace(self)
        self.find_widget.hide()
        self.register_widget_shortcuts(self.find_widget)

        layout.addWidget(self.find_widget)

        self.setLayout(layout)

        # Accepting drops
        self.setAcceptDrops(True)
Ejemplo n.º 8
0
    def add_table(self):
        """Add table with info about files to be recovered."""
        table = QTableWidget(len(self.data), 3, self)
        self.table = table

        labels = [_('Original file'), _('Autosave file'), _('Actions')]
        table.setHorizontalHeaderLabels(labels)
        table.verticalHeader().hide()

        table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        table.setSelectionMode(QTableWidget.NoSelection)

        # Show horizontal grid lines
        table.setShowGrid(False)
        table.setStyleSheet('::item { border-bottom: 1px solid gray }')

        for idx, (original, autosave) in enumerate(self.data):
            self.add_label_to_table(idx, 0, file_data_to_str(original))
            self.add_label_to_table(idx, 1, file_data_to_str(autosave))

            widget = QWidget()
            layout = QHBoxLayout()

            tooltip = _('Recover the autosave file to its original location, '
                        'replacing the original if it exists.')
            button = QPushButton(_('Restore'))
            button.setToolTip(tooltip)
            button.clicked.connect(
                lambda checked, my_idx=idx: self.restore(my_idx))
            layout.addWidget(button)

            tooltip = _('Delete the autosave file.')
            button = QPushButton(_('Discard'))
            button.setToolTip(tooltip)
            button.clicked.connect(
                lambda checked, my_idx=idx: self.discard(my_idx))
            layout.addWidget(button)

            tooltip = _('Display the autosave file (and the original, if it '
                        'exists) in Spyder\'s Editor. You will have to move '
                        'or delete it manually.')
            button = QPushButton(_('Open'))
            button.setToolTip(tooltip)
            button.clicked.connect(
                lambda checked, my_idx=idx: self.open_files(my_idx))
            layout.addWidget(button)

            widget.setLayout(layout)
            self.table.setCellWidget(idx, 2, widget)

        table.resizeRowsToContents()
        table.resizeColumnsToContents()

        # Need to add the "+ 2" because otherwise the table scrolls a tiny
        # amount; no idea why
        width = table.horizontalHeader().length() + 2
        height = (table.verticalHeader().length() +
                  table.horizontalHeader().height() + 2)
        table.setFixedSize(width, height)
        self.layout.addWidget(table)
Ejemplo n.º 9
0
    def setup_page(self):
        # Variables
        newcb = self.create_checkbox

        # Widgets
        general_widget = QWidget()

        # General options group
        basic_group = QGroupBox(_("General options"))
        check_show_hidden_files = newcb(_("Show hidden files"), 'show_hidden')
        check_single_click = newcb(_("Single click to open files"),
                                   'single_click_to_open')
        basic_layout = QVBoxLayout()
        basic_layout.addWidget(check_show_hidden_files)
        basic_layout.addWidget(check_single_click)
        basic_group.setLayout(basic_layout)

        # Filter options group
        filter_group = QGroupBox(_("Filter settings"))
        description_label = QLabel(
            _('Filter files by name, extension, or more using '
              '<a href="https://en.wikipedia.org/wiki/Glob_(programming)">glob '
              'patterns.</a> Please enter the glob patterns of the files you '
              'want to show, separated by commas.'))
        description_label.setOpenExternalLinks(True)
        description_label.setWordWrap(True)
        self.edit_filename_filters = self.create_textedit(
            '',
            'name_filters',
            tip=("Enter values separated by commas"),
            content_type=list,
        )

        self.edit_filename_filters.setEnabled(True)

        reset_btn = QPushButton(_("Reset to default values"))
        reset_btn.clicked.connect(self.reset_to_default)
        filter_layout = QVBoxLayout()
        filter_layout.addWidget(description_label)
        filter_layout.addWidget(self.edit_filename_filters)
        filter_layout.addWidget(reset_btn)
        filter_group.setLayout(filter_layout)

        associations_widget = QWidget()
        self.edit_file_associations = self.create_textedit(
            '',
            'file_associations',
            content_type=dict,
        )
        file_associations = FileAssociationsWidget()

        # Widget setup
        file_associations.load_values(self.get_option('file_associations'))
        # The actual config data is stored on this text edit set to invisible
        self.edit_file_associations.setVisible(False)

        layout = QVBoxLayout()
        layout.addWidget(basic_group)
        layout.addWidget(filter_group)
        general_widget.setLayout(layout)

        layout_file = QVBoxLayout()
        layout_file.addWidget(file_associations)
        layout_file.addWidget(self.edit_file_associations)
        associations_widget.setLayout(layout_file)

        tabs = QTabWidget()
        tabs.addTab(self.create_tab(general_widget), _("General"))
        tabs.addTab(self.create_tab(associations_widget),
                    _("File associations"))

        tab_layout = QVBoxLayout()
        tab_layout.addWidget(tabs)

        self.setLayout(tab_layout)

        # Signals
        file_associations.sig_data_changed.connect(self.update_associations)
Ejemplo n.º 10
0
    def setupUi(self):
        """Set up the UI during initialization."""
        self.setWindowFlags(Qt.SubWindow)
        self.setMinimumWidth(self.MIN_WIDTH)
        self.setMaximumWidth(self.MIN_WIDTH)
        self.setMinimumHeight(40)
        self.setSizeGripEnabled(False)
        self.setModal(False)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setContentsMargins(2, 2, 2, 2)
        self.verticalLayout.setSpacing(0)

        self.row1_widget = QWidget(self)
        self.row1 = QHBoxLayout(self.row1_widget)
        self.row1.setContentsMargins(12, 12, 12, 8)
        self.row1.setSpacing(4)
        self.severity_icon = QLabel(self.row1_widget)
        self.severity_icon.setObjectName("severity_icon")
        self.severity_icon.setMinimumWidth(30)
        self.severity_icon.setMaximumWidth(30)
        self.row1.addWidget(self.severity_icon, alignment=Qt.AlignTop)
        self.message = QElidingLabel()
        self.message.setWordWrap(True)
        self.message.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.message.setMinimumWidth(self.MIN_WIDTH - 200)
        self.message.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Expanding
        )
        self.row1.addWidget(self.message, alignment=Qt.AlignTop)
        self.expand_button = QPushButton(self.row1_widget)
        self.expand_button.setObjectName("expand_button")
        self.expand_button.setCursor(Qt.PointingHandCursor)
        self.expand_button.setMaximumWidth(20)
        self.expand_button.setFlat(True)

        self.row1.addWidget(self.expand_button, alignment=Qt.AlignTop)
        self.close_button = QPushButton(self.row1_widget)
        self.close_button.setObjectName("close_button")
        self.close_button.setCursor(Qt.PointingHandCursor)
        self.close_button.setMaximumWidth(20)
        self.close_button.setFlat(True)

        self.row1.addWidget(self.close_button, alignment=Qt.AlignTop)
        self.verticalLayout.addWidget(self.row1_widget, 1)
        self.row2_widget = QWidget(self)
        self.row2_widget.hide()
        self.row2 = QHBoxLayout(self.row2_widget)
        self.source_label = QLabel(self.row2_widget)
        self.source_label.setObjectName("source_label")
        self.row2.addWidget(self.source_label, alignment=Qt.AlignBottom)
        self.row2.addStretch()
        self.row2.setContentsMargins(12, 2, 16, 12)
        self.row2_widget.setMaximumHeight(34)
        self.row2_widget.setStyleSheet(
            'QPushButton{'
            'padding: 4px 12px 4px 12px; '
            'font-size: 11px;'
            'min-height: 18px; border-radius: 0;}'
        )
        self.verticalLayout.addWidget(self.row2_widget, 0)
        self.setProperty('expanded', False)
        self.resize(self.MIN_WIDTH, 40)
Ejemplo n.º 11
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.icon = QWidget(parent=self)
Ejemplo n.º 12
0
    def _setupUi(self):
        ld_clkmis = QLabel('Clock missing', alignment=Qt.AlignCenter)
        led_clkmis = SiriusLedAlert(self, self.dev_pref+':CLKMISS')
        lb_clkmis = PyDMLabel(self, self.dev_pref+':CLKMISS_COUNT')

        ld_pllulk = QLabel('PLL Unlocked', alignment=Qt.AlignCenter)
        led_pllulk = SiriusLedAlert(self, self.dev_pref+':PLL_UNLOCK')
        lb_pllulk = PyDMLabel(self, self.dev_pref+':PLL_UNLOCK_COUNT')

        ld_dcmulk = QLabel('DCM unlocked', alignment=Qt.AlignCenter)
        led_dcmulk = SiriusLedAlert(self, self.dev_pref+':DCM_UNLOCK')
        lb_dcmulk = PyDMLabel(self, self.dev_pref+':DCM_UNLOCK_COUNT')

        ld_avcovr = QLabel('ADC Overrange', alignment=Qt.AlignCenter)
        led_avcovr = SiriusLedAlert(self, self.dev_pref+':ADC_OVR')
        lb_avcovr = PyDMLabel(self, self.dev_pref+':ADC_OVR_COUNT')

        ld_outsat = QLabel('Output satured', alignment=Qt.AlignCenter)
        led_outsat = SiriusLedAlert(self, self.dev_pref+':SAT')
        lb_outsat = PyDMLabel(self, self.dev_pref+':SAT_COUNT')

        ld_fiderr = QLabel('Fiducial Error', alignment=Qt.AlignCenter)
        led_fiderr = SiriusLedAlert(self, self.dev_pref+':FID_ERR')
        lb_fiderr = PyDMLabel(self, self.dev_pref+':FID_ERR_COUNT')

        ld_intvl = QLabel('Interval [s]', alignment=Qt.AlignCenter)
        lb_intvl = PyDMLabel(self, self.dev_pref+':RST_COUNT')
        pb_intvl = SiriusPushButton(
            self, init_channel=self.dev_pref+':CNTRST', pressValue=1,
            releaseValue=0)
        pb_intvl.setText('Reset')
        pb_intvl.setToolTip('Reset Counts')
        pb_intvl.setIcon(qta.icon('fa5s.sync'))
        pb_intvl.setObjectName('conf')

        wid = QWidget(self)
        set_bbb_color(wid, self._device)
        lay = QGridLayout(wid)
        lay.setContentsMargins(0, 0, 0, 0)
        if self._is_resumed:
            lay.addWidget(
                QLabel('<h3>Status</h3>', self, alignment=Qt.AlignCenter),
                0, 0, 1, 3)
            lay.addItem(
                QSpacerItem(1, 10, QSzPlcy.Ignored, QSzPlcy.Fixed), 1, 0)
        lay.addWidget(
            QLabel('<h4>Description</h4>', self, alignment=Qt.AlignCenter),
            2, 1)
        lay.addWidget(
            QLabel('<h4>Count</h4>', self, alignment=Qt.AlignCenter), 2, 2)
        lay.addWidget(led_clkmis, 3, 0)
        lay.addWidget(ld_clkmis, 3, 1)
        lay.addWidget(lb_clkmis, 3, 2)
        lay.addWidget(led_pllulk, 4, 0)
        lay.addWidget(ld_pllulk, 4, 1)
        lay.addWidget(lb_pllulk, 4, 2)
        lay.addWidget(led_dcmulk, 5, 0)
        lay.addWidget(ld_dcmulk, 5, 1)
        lay.addWidget(lb_dcmulk, 5, 2)
        lay.addWidget(led_avcovr, 6, 0)
        lay.addWidget(ld_avcovr, 6, 1)
        lay.addWidget(lb_avcovr, 6, 2)
        lay.addWidget(led_outsat, 7, 0)
        lay.addWidget(ld_outsat, 7, 1)
        lay.addWidget(lb_outsat, 7, 2)
        lay.addWidget(led_fiderr, 8, 0)
        lay.addWidget(ld_fiderr, 8, 1)
        lay.addWidget(lb_fiderr, 8, 2)
        lay.addItem(QSpacerItem(1, 10, QSzPlcy.Ignored, QSzPlcy.Fixed), 8, 0)
        hlay = QHBoxLayout()
        lay.addLayout(hlay, 9, 0, 1, 3)
        hlay.addWidget(ld_intvl)
        hlay.addWidget(lb_intvl)
        hlay.addStretch()
        hlay.addWidget(pb_intvl)

        mainlay = QHBoxLayout(self)
        mainlay.setContentsMargins(0, 0, 0, 0)
        mainlay.addWidget(wid)
Ejemplo n.º 13
0
    def create_widgets(self):
        """creates the menu objects"""
        # Name
        self.name_label = QLabel("Title:")
        self.name_edit = QLineEdit(str(self._default_name))
        self.name_button = QPushButton("Default")

        # Min
        self.min_label = QLabel("Min:")
        self.min_edit = QLineEdit(str(self._default_min))
        self.min_button = QPushButton("Default")

        # Max
        self.max_label = QLabel("Max:")
        self.max_edit = QLineEdit(str(self._default_max))
        self.max_button = QPushButton("Default")

        #---------------------------------------
        # Format
        self.format_label = QLabel("Format (e.g. %.3f, %g, %.6e):")
        self.format_edit = QLineEdit(str(self._format))
        self.format_button = QPushButton("Default")

        #---------------------------------------
        # Scale
        self.scale_label = QLabel("True Scale:")
        self.scale_edit = QLineEdit(str(self._scale))
        self.scale_button = QPushButton("Default")
        if self._icase_disp is None:
            self.scale_label.setVisible(False)
            self.scale_edit.setVisible(False)
            self.scale_button.setVisible(False)

        # Phase
        self.phase_label = QLabel("Phase (deg):")
        self.phase_edit = QLineEdit(str(self._phase))
        self.phase_button = QPushButton("Default")
        if self._icase_disp is None or self._default_phase is None:
            self.phase_label.setVisible(False)
            self.phase_edit.setVisible(False)
            self.phase_button.setVisible(False)
            self.phase_edit.setText('0.0')

        #---------------------------------------
        self.arrow_scale_label = QLabel("Arrow Scale:")
        self.arrow_scale_edit = QLineEdit(str(self._arrow_scale))
        self.arrow_scale_button = QPushButton("Default")
        if self._icase_vector is None:
            self.arrow_scale_label.setVisible(False)
            self.arrow_scale_edit.setVisible(False)
            self.arrow_scale_button.setVisible(False)

        #tip = QtGui.QToolTip()
        #tip.setTe
        #self.format_edit.toolTip(tip)

        #---------------------------------------
        # nlabels
        self.nlabels_label = QLabel("Number of Labels:")
        self.nlabels_edit = QLineEdit(str(self._nlabels))
        self.nlabels_button = QPushButton("Default")

        self.labelsize_label = QLabel("Label Size:")
        self.labelsize_edit = QLineEdit(str(self._labelsize))
        self.labelsize_button = QPushButton("Default")

        self.ncolors_label = QLabel("Number of Colors:")
        self.ncolors_edit = QLineEdit(str(self._ncolors))
        self.ncolors_button = QPushButton("Default")

        self.colormap_label = QLabel("Color Map:")
        self.colormap_edit = QComboBox(self)
        self.colormap_button = QPushButton("Default")
        for key in colormap_keys:
            self.colormap_edit.addItem(key)
        self.colormap_edit.setCurrentIndex(colormap_keys.index(self._colormap))

        # --------------------------------------------------------------
        # the header
        self.grid2_title = QLabel("Color Scale:")

        # red/blue or blue/red
        self.low_to_high_radio = QRadioButton('Low -> High')
        self.high_to_low_radio = QRadioButton('High -> Low')
        widget = QWidget(self)
        low_to_high_group = QButtonGroup(widget)
        low_to_high_group.addButton(self.low_to_high_radio)
        low_to_high_group.addButton(self.high_to_low_radio)
        self.low_to_high_radio.setChecked(self._default_is_low_to_high)
        self.high_to_low_radio.setChecked(not self._default_is_low_to_high)

        # horizontal / vertical
        self.horizontal_radio = QRadioButton("Horizontal")
        self.vertical_radio = QRadioButton("Vertical")
        widget = QWidget(self)
        horizontal_vertical_group = QButtonGroup(widget)
        horizontal_vertical_group.addButton(self.horizontal_radio)
        horizontal_vertical_group.addButton(self.vertical_radio)
        self.horizontal_radio.setChecked(self._default_is_horizontal)
        self.vertical_radio.setChecked(not self._default_is_horizontal)

        # on / off
        self.show_radio = QRadioButton("Show")
        self.hide_radio = QRadioButton("Hide")
        widget = QWidget(self)
        show_hide_group = QButtonGroup(widget)
        show_hide_group.addButton(self.show_radio)
        show_hide_group.addButton(self.hide_radio)
        self.show_radio.setChecked(self._default_is_shown)
        self.hide_radio.setChecked(not self._default_is_shown)

        # --------------------------------------------------------------

        if self._icase_fringe is None:
            self.name_label.setVisible(False)
            self.name_edit.setVisible(False)
            self.name_button.setVisible(False)

        if not self._is_fringe:
            self.max_label.hide()
            self.min_label.hide()
            self.max_edit.hide()
            self.min_edit.hide()
            self.max_button.hide()
            self.min_button.hide()

            self.format_label.hide()
            self.format_edit.hide()
            self.format_button.hide()

            self.nlabels_label.hide()
            self.nlabels_edit.hide()
            self.nlabels_button.hide()

            self.ncolors_label.hide()
            self.ncolors_edit.hide()
            self.ncolors_button.hide()

            self.grid2_title.hide()
            self.vertical_radio.hide()
            self.horizontal_radio.hide()
            self.show_radio.hide()
            self.hide_radio.hide()
            self.low_to_high_radio.hide()
            self.high_to_low_radio.hide()

            self.colormap_label.hide()
            self.colormap_edit.hide()
            self.colormap_button.hide()

        self.animate_button = QPushButton('Create Animation')
        #self.advanced_button = QPushButton('Advanced')

        if self._default_icase_disp is None: # or self._default_icase_vector is None:
            self.animate_button.setEnabled(False)
            self.animate_button.setToolTip(ANIMATE_TOOLTIP_OFF)
        else:
            self.animate_button.setEnabled(True)
            self.animate_button.setToolTip(ANIMATE_TOOLTIP_ON)

        # closing
        self.apply_button = QPushButton("Apply")
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")
Ejemplo n.º 14
0
    def setup_page(self):
        newcb = self.create_checkbox

        # --- Display tab ---
        showtabbar_box = newcb(_("Show tab bar"), 'show_tab_bar')
        showclassfuncdropdown_box = newcb(
            _("Show selector for classes and functions"),
            'show_class_func_dropdown')
        showindentguides_box = newcb(_("Show indent guides"), 'indent_guides')
        linenumbers_box = newcb(_("Show line numbers"), 'line_numbers')
        blanks_box = newcb(_("Show blank spaces"), 'blank_spaces')
        underline_errors_box = newcb(_("Underline errors and warnings"),
                                     'underline_errors')
        currentline_box = newcb(_("Highlight current line"),
                                'highlight_current_line')
        currentcell_box = newcb(_("Highlight current cell"),
                                'highlight_current_cell')
        wrap_mode_box = newcb(_("Wrap lines"), 'wrap')
        scroll_past_end_box = newcb(_("Scroll past the end"),
                                    'scroll_past_end')

        edgeline_box = newcb(_("Show vertical lines at"), 'edge_line')
        edgeline_edit = self.create_lineedit(
            "",
            'edge_line_columns',
            tip=("Enter values separated by commas"),
            alignment=Qt.Horizontal,
            regex="[0-9]+(,[0-9]+)*")
        edgeline_edit_label = QLabel(_("characters"))
        edgeline_box.toggled.connect(edgeline_edit.setEnabled)
        edgeline_box.toggled.connect(edgeline_edit_label.setEnabled)
        edgeline_edit.setEnabled(self.get_option('edge_line'))
        edgeline_edit_label.setEnabled(self.get_option('edge_line'))

        occurrence_box = newcb(_("Highlight occurrences after"),
                               'occurrence_highlighting')
        occurrence_spin = self.create_spinbox(
            "",
            _(" ms"),
            'occurrence_highlighting/timeout',
            min_=100,
            max_=1000000,
            step=100)
        occurrence_box.toggled.connect(occurrence_spin.spinbox.setEnabled)
        occurrence_box.toggled.connect(occurrence_spin.slabel.setEnabled)
        occurrence_spin.spinbox.setEnabled(
            self.get_option('occurrence_highlighting'))
        occurrence_spin.slabel.setEnabled(
            self.get_option('occurrence_highlighting'))

        display_g_layout = QGridLayout()
        display_g_layout.addWidget(edgeline_box, 0, 0)
        display_g_layout.addWidget(edgeline_edit.textbox, 0, 1)
        display_g_layout.addWidget(edgeline_edit_label, 0, 2)
        display_g_layout.addWidget(occurrence_box, 1, 0)
        display_g_layout.addWidget(occurrence_spin.spinbox, 1, 1)
        display_g_layout.addWidget(occurrence_spin.slabel, 1, 2)

        display_h_layout = QHBoxLayout()
        display_h_layout.addLayout(display_g_layout)
        display_h_layout.addStretch(1)

        display_layout = QVBoxLayout()
        display_layout.addWidget(showtabbar_box)
        display_layout.addWidget(showclassfuncdropdown_box)
        display_layout.addWidget(showindentguides_box)
        display_layout.addWidget(linenumbers_box)
        display_layout.addWidget(blanks_box)
        display_layout.addWidget(underline_errors_box)
        display_layout.addWidget(currentline_box)
        display_layout.addWidget(currentcell_box)
        display_layout.addWidget(wrap_mode_box)
        display_layout.addWidget(scroll_past_end_box)
        display_layout.addLayout(display_h_layout)

        display_widget = QWidget()
        display_widget.setLayout(display_layout)

        # --- Source code tab ---
        closepar_box = newcb(
            _("Automatic insertion of parentheses, braces and brackets"),
            'close_parentheses')
        close_quotes_box = newcb(_("Automatic insertion of closing quotes"),
                                 'close_quotes')
        add_colons_box = newcb(
            _("Automatic insertion of colons after 'for', 'if', 'def', etc"),
            'add_colons')
        autounindent_box = newcb(
            _("Automatic indentation after 'else', 'elif', etc."),
            'auto_unindent')
        tab_mode_box = newcb(
            _("Tab always indent"),
            'tab_always_indent',
            default=False,
            tip=_("If enabled, pressing Tab will always indent,\n"
                  "even when the cursor is not at the beginning\n"
                  "of a line (when this option is enabled, code\n"
                  "completion may be triggered using the alternate\n"
                  "shortcut: Ctrl+Space)"))
        strip_mode_box = newcb(
            _("Automatically strip trailing spaces on changed lines"),
            'strip_trailing_spaces_on_modify',
            default=True,
            tip=
            _("If enabled, modified lines of code (excluding strings)\n"
              "will have their trailing whitespace stripped when leaving them.\n"
              "If disabled, only whitespace added by Spyder will be stripped."
              ))
        ibackspace_box = newcb(_("Intelligent backspace"),
                               'intelligent_backspace',
                               default=True)
        removetrail_box = newcb(
            _("Automatically remove trailing spaces when saving files"),
            'always_remove_trailing_spaces',
            default=False)

        indent_chars_box = self.create_combobox(
            _("Indentation characters: "),
            ((_("2 spaces"), '*  *'), (_("3 spaces"), '*   *'),
             (_("4 spaces"), '*    *'), (_("5 spaces"), '*     *'),
             (_("6 spaces"), '*      *'), (_("7 spaces"), '*       *'),
             (_("8 spaces"), '*        *'), (_("Tabulations"), '*\t*')),
            'indent_chars')
        tabwidth_spin = self.create_spinbox(_("Tab stop width:"), _("spaces"),
                                            'tab_stop_width_spaces', 4, 1, 8,
                                            1)

        def enable_tabwidth_spin(index):
            if index == 7:  # Tabulations
                tabwidth_spin.plabel.setEnabled(True)
                tabwidth_spin.spinbox.setEnabled(True)
            else:
                tabwidth_spin.plabel.setEnabled(False)
                tabwidth_spin.spinbox.setEnabled(False)

        indent_chars_box.combobox.currentIndexChanged.connect(
            enable_tabwidth_spin)

        indent_tab_grid_layout = QGridLayout()
        indent_tab_grid_layout.addWidget(indent_chars_box.label, 0, 0)
        indent_tab_grid_layout.addWidget(indent_chars_box.combobox, 0, 1)
        indent_tab_grid_layout.addWidget(tabwidth_spin.plabel, 1, 0)
        indent_tab_grid_layout.addWidget(tabwidth_spin.spinbox, 1, 1)
        indent_tab_grid_layout.addWidget(tabwidth_spin.slabel, 1, 2)

        indent_tab_layout = QHBoxLayout()
        indent_tab_layout.addLayout(indent_tab_grid_layout)
        indent_tab_layout.addStretch(1)

        sourcecode_layout = QVBoxLayout()
        sourcecode_layout.addWidget(closepar_box)
        sourcecode_layout.addWidget(autounindent_box)
        sourcecode_layout.addWidget(add_colons_box)
        sourcecode_layout.addWidget(close_quotes_box)
        sourcecode_layout.addWidget(tab_mode_box)
        sourcecode_layout.addWidget(ibackspace_box)
        sourcecode_layout.addWidget(removetrail_box)
        sourcecode_layout.addWidget(strip_mode_box)
        sourcecode_layout.addLayout(indent_tab_layout)

        sourcecode_widget = QWidget()
        sourcecode_widget.setLayout(sourcecode_layout)

        # --- Run code tab ---
        saveall_box = newcb(_("Save all files before running script"),
                            'save_all_before_run')
        focus_box = newcb(
            _("Maintain focus in the Editor after running cells "
              "or selections"), 'focus_to_editor')
        run_cell_box = newcb(
            _("Copy full cell contents to the console when "
              "running code cells"), 'run_cell_copy')

        run_layout = QVBoxLayout()
        run_layout.addWidget(saveall_box)
        run_layout.addWidget(focus_box)
        run_layout.addWidget(run_cell_box)

        run_widget = QWidget()
        run_widget.setLayout(run_layout)

        # --- Advanced tab ---
        # -- Templates
        template_btn = self.create_button(_("Edit template for new files"),
                                          self.plugin.edit_template)

        # -- Autosave
        autosave_group = QGroupBox(_('Autosave'))
        autosave_checkbox = newcb(
            _('Automatically save a copy of files with unsaved changes'),
            'autosave_enabled')
        autosave_spinbox = self.create_spinbox(_('Autosave interval: '),
                                               _('seconds'),
                                               'autosave_interval',
                                               min_=1,
                                               max_=3600)
        autosave_checkbox.toggled.connect(autosave_spinbox.setEnabled)

        autosave_layout = QVBoxLayout()
        autosave_layout.addWidget(autosave_checkbox)
        autosave_layout.addWidget(autosave_spinbox)
        autosave_group.setLayout(autosave_layout)

        # -- Docstring
        docstring_group = QGroupBox(_('Docstring type'))

        numpy_url = "<a href='{}'>Numpy</a>".format(NUMPYDOC)
        googledoc_url = "<a href='{}'>Google</a>".format(GOOGLEDOC)
        docstring_label = QLabel(
            _("Here you can select the type of docstrings ({} or {}) you "
              "want the editor to automatically introduce when pressing "
              "<tt>{}</tt> after a function/method/class "
              "declaration.").format(numpy_url, googledoc_url,
                                     DOCSTRING_SHORTCUT))
        docstring_label.setOpenExternalLinks(True)
        docstring_label.setWordWrap(True)

        docstring_combo_choices = (
            (_("Numpy"), 'Numpydoc'),
            (_("Google"), 'Googledoc'),
        )
        docstring_combo = self.create_combobox("Type:",
                                               docstring_combo_choices,
                                               'docstring_type')

        docstring_layout = QVBoxLayout()
        docstring_layout.addWidget(docstring_label)
        docstring_layout.addWidget(docstring_combo)
        docstring_group.setLayout(docstring_layout)

        # -- Annotations
        annotations_group = QGroupBox(_("Annotations"))
        annotations_label = QLabel(
            _("Display a marker to the left of line numbers when the "
              "following annotations appear at the beginning of a comment: "
              "<tt>TODO, FIXME, XXX, HINT, TIP, @todo, HACK, BUG, OPTIMIZE, "
              "!!!, ???</tt>"))
        annotations_label.setWordWrap(True)
        todolist_box = newcb(_("Display code annotations"), 'todo_list')

        annotations_layout = QVBoxLayout()
        annotations_layout.addWidget(annotations_label)
        annotations_layout.addWidget(todolist_box)
        annotations_group.setLayout(annotations_layout)

        # -- EOL
        eol_group = QGroupBox(_("End-of-line characters"))
        eol_label = QLabel(
            _("When opening a text file containing "
              "mixed end-of-line characters (this may "
              "raise syntax errors in the consoles "
              "on Windows platforms), Spyder may fix the "
              "file automatically."))
        eol_label.setWordWrap(True)
        check_eol_box = newcb(_("Fix automatically and show warning "
                                "message box"),
                              'check_eol_chars',
                              default=True)
        convert_eol_on_save_box = newcb(_("On Save: convert EOL characters"
                                          " to"),
                                        'convert_eol_on_save',
                                        default=False)
        eol_combo_choices = (
            (_("LF (UNIX)"), 'LF'),
            (_("CRLF (Windows)"), 'CRLF'),
            (_("CR (Mac)"), 'CR'),
        )
        convert_eol_on_save_combo = self.create_combobox(
            "",
            eol_combo_choices,
            ('convert_eol_on_'
             'save_to'),
        )
        convert_eol_on_save_box.toggled.connect(
            convert_eol_on_save_combo.setEnabled)
        convert_eol_on_save_combo.setEnabled(
            self.get_option('convert_eol_on_save'))

        eol_on_save_layout = QHBoxLayout()
        eol_on_save_layout.addWidget(convert_eol_on_save_box)
        eol_on_save_layout.addWidget(convert_eol_on_save_combo)

        eol_layout = QVBoxLayout()
        eol_layout.addWidget(eol_label)
        eol_layout.addWidget(check_eol_box)
        eol_layout.addLayout(eol_on_save_layout)
        eol_group.setLayout(eol_layout)

        # --- Tabs ---
        tabs = QTabWidget()
        tabs.addTab(self.create_tab(display_widget), _("Display"))
        tabs.addTab(self.create_tab(sourcecode_widget), _("Source code"))
        tabs.addTab(self.create_tab(run_widget), _('Run code'))
        tabs.addTab(
            self.create_tab(template_btn, autosave_group, docstring_group,
                            annotations_group, eol_group),
            _("Advanced settings"))

        vlayout = QVBoxLayout()
        vlayout.addWidget(tabs)
        self.setLayout(vlayout)
Ejemplo n.º 15
0
    def setup_ui(self):
        self.resize(1080, 640)
        vlay_1 = QVBoxLayout(self)
        self.h_splitter = QSplitter(self)
        vlay_1.addWidget(self.h_splitter)
        self.h_splitter.setOrientation(Qt.Horizontal)
        self.v_splitter = QSplitter(self.h_splitter)
        self.v_splitter.setOrientation(Qt.Vertical)
        self.v_splitter.setMinimumWidth(500)

        installed = QWidget(self.v_splitter)
        lay = QVBoxLayout(installed)
        lay.setContentsMargins(0, 2, 0, 2)
        self.installed_label = QLabel(trans._("Installed Plugins"))
        self.packages_filter = QLineEdit()
        self.packages_filter.setPlaceholderText(trans._("filter..."))
        self.packages_filter.setMaximumWidth(350)
        self.packages_filter.setClearButtonEnabled(True)
        mid_layout = QVBoxLayout()
        mid_layout.addWidget(self.packages_filter)
        mid_layout.addWidget(self.installed_label)
        lay.addLayout(mid_layout)

        self.installed_list = QPluginList(installed, self.installer)
        self.packages_filter.textChanged.connect(self.installed_list.filter)
        lay.addWidget(self.installed_list)

        uninstalled = QWidget(self.v_splitter)
        lay = QVBoxLayout(uninstalled)
        lay.setContentsMargins(0, 2, 0, 2)
        self.avail_label = QLabel(trans._("Available Plugins"))
        mid_layout = QHBoxLayout()
        mid_layout.addWidget(self.avail_label)
        mid_layout.addStretch()
        lay.addLayout(mid_layout)
        self.available_list = QPluginList(uninstalled, self.installer)
        self.packages_filter.textChanged.connect(self.available_list.filter)
        lay.addWidget(self.available_list)

        self.stdout_text = QTextEdit(self.v_splitter)
        self.stdout_text.setReadOnly(True)
        self.stdout_text.setObjectName("pip_install_status")
        self.stdout_text.hide()

        buttonBox = QHBoxLayout()
        self.working_indicator = QLabel(trans._("loading ..."), self)
        sp = self.working_indicator.sizePolicy()
        sp.setRetainSizeWhenHidden(True)
        self.working_indicator.setSizePolicy(sp)
        self.process_error_indicator = QLabel(self)
        self.process_error_indicator.setObjectName("error_label")
        self.process_error_indicator.hide()
        load_gif = str(Path(napari.resources.__file__).parent / "loading.gif")
        mov = QMovie(load_gif)
        mov.setScaledSize(QSize(18, 18))
        self.working_indicator.setMovie(mov)
        mov.start()

        visibility_direct_entry = not running_as_constructor_app()
        self.direct_entry_edit = QLineEdit(self)
        self.direct_entry_edit.installEventFilter(self)
        self.direct_entry_edit.setPlaceholderText(
            trans._('install by name/url, or drop file...'))
        self.direct_entry_edit.setVisible(visibility_direct_entry)
        self.direct_entry_btn = QPushButton(trans._("Install"), self)
        self.direct_entry_btn.setVisible(visibility_direct_entry)
        self.direct_entry_btn.clicked.connect(self._install_packages)

        self.show_status_btn = QPushButton(trans._("Show Status"), self)
        self.show_status_btn.setFixedWidth(100)

        self.cancel_all_btn = QPushButton(trans._("cancel all actions"), self)
        self.cancel_all_btn.setObjectName("remove_button")
        self.cancel_all_btn.setVisible(False)
        self.cancel_all_btn.clicked.connect(lambda: self.installer.cancel())

        self.close_btn = QPushButton(trans._("Close"), self)
        self.close_btn.clicked.connect(self.accept)
        self.close_btn.setObjectName("close_button")
        buttonBox.addWidget(self.show_status_btn)
        buttonBox.addWidget(self.working_indicator)
        buttonBox.addWidget(self.direct_entry_edit)
        buttonBox.addWidget(self.direct_entry_btn)
        if not visibility_direct_entry:
            buttonBox.addStretch()
        buttonBox.addWidget(self.process_error_indicator)
        buttonBox.addSpacing(20)
        buttonBox.addWidget(self.cancel_all_btn)
        buttonBox.addSpacing(20)
        buttonBox.addWidget(self.close_btn)
        buttonBox.setContentsMargins(0, 0, 4, 0)
        vlay_1.addLayout(buttonBox)

        self.show_status_btn.setCheckable(True)
        self.show_status_btn.setChecked(False)
        self.show_status_btn.toggled.connect(self._toggle_status)

        self.v_splitter.setStretchFactor(1, 2)
        self.h_splitter.setStretchFactor(0, 2)

        self.packages_filter.setFocus()
Ejemplo n.º 16
0
    def __init__(self, parent=None):
        """ Initialization and set up
        """
        # Base class
        QMainWindow.__init__(self, parent)

        # Mantid configuration
        config = ConfigService.Instance()
        self._instrument = config["default.instrument"]

        # Central widget
        self.centralwidget = QWidget(self)

        # UI Window (from Qt Designer)
        self.ui = load_ui(__file__, 'MainWindow.ui', baseinstance=self)
        mpl_layout = QVBoxLayout()
        self.ui.graphicsView.setLayout(mpl_layout)
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.ui.mainplot = self.fig.add_subplot(111, projection='mantid')
        mpl_layout.addWidget(self.canvas)

        # Do initialize plotting
        vecx, vecy, xlim, ylim = self.computeMock()

        self.mainline = self.ui.mainplot.plot(vecx, vecy, 'r-')

        leftx = [xlim[0], xlim[0]]
        lefty = [ylim[0], ylim[1]]
        self.leftslideline = self.ui.mainplot.plot(leftx, lefty, 'b--')
        rightx = [xlim[1], xlim[1]]
        righty = [ylim[0], ylim[1]]
        self.rightslideline = self.ui.mainplot.plot(rightx, righty, 'g--')
        upperx = [xlim[0], xlim[1]]
        uppery = [ylim[1], ylim[1]]
        self.upperslideline = self.ui.mainplot.plot(upperx, uppery, 'b--')
        lowerx = [xlim[0], xlim[1]]
        lowery = [ylim[0], ylim[0]]
        self.lowerslideline = self.ui.mainplot.plot(lowerx, lowery, 'g--')

        self.canvas.mpl_connect('button_press_event', self.on_mouseDownEvent)

        # Set up horizontal slide (integer) and string value
        self._leftSlideValue = 0
        self._rightSlideValue = 99

        self.ui.horizontalSlider.setRange(0, 100)
        self.ui.horizontalSlider.setValue(self._leftSlideValue)
        self.ui.horizontalSlider.setTracking(True)
        self.ui.horizontalSlider.setTickPosition(QSlider.NoTicks)
        self.ui.horizontalSlider.valueChanged.connect(self.move_leftSlider)

        self.ui.horizontalSlider_2.setRange(0, 100)
        self.ui.horizontalSlider_2.setValue(self._rightSlideValue)
        self.ui.horizontalSlider_2.setTracking(True)
        self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks)
        self.ui.horizontalSlider_2.valueChanged.connect(self.move_rightSlider)

        # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"),
        #         self.set_startTime)
        self.ui.lineEdit_3.setValidator(QDoubleValidator(self.ui.lineEdit_3))
        self.ui.pushButton_setT0.clicked.connect(self.set_startTime)
        # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"),
        #         self.set_stopTime)
        self.ui.lineEdit_4.setValidator(QDoubleValidator(self.ui.lineEdit_4))
        self.ui.pushButton_setTf.clicked.connect(self.set_stopTime)

        # File loader
        self.scanEventWorkspaces()
        self.ui.pushButton_refreshWS.clicked.connect(self.scanEventWorkspaces)
        self.ui.pushButton_browse.clicked.connect(self.browse_File)
        self.ui.pushButton_load.clicked.connect(self.load_File)
        self.ui.pushButton_3.clicked.connect(self.use_existWS)

        # Set up time
        self.ui.lineEdit_3.setValidator(QDoubleValidator(self.ui.lineEdit_3))
        self.ui.lineEdit_4.setValidator(QDoubleValidator(self.ui.lineEdit_4))

        # Filter by time
        self.ui.pushButton_filterTime.clicked.connect(self.filterByTime)

        # Filter by log value
        self.ui.lineEdit_5.setValidator(QDoubleValidator(self.ui.lineEdit_5))
        self.ui.lineEdit_6.setValidator(QDoubleValidator(self.ui.lineEdit_6))
        self.ui.lineEdit_7.setValidator(QDoubleValidator(self.ui.lineEdit_7))
        self.ui.lineEdit_8.setValidator(QDoubleValidator(self.ui.lineEdit_8))
        self.ui.lineEdit_9.setValidator(QDoubleValidator(self.ui.lineEdit_9))

        self.ui.lineEdit_5.textChanged.connect(self.set_minLogValue)
        self.ui.lineEdit_6.textChanged.connect(self.set_maxLogValue)

        dirchangeops = ["Both", "Increase", "Decrease"]
        self.ui.comboBox_4.addItems(dirchangeops)

        logboundops = ["Centre", "Left"]
        self.ui.comboBox_5.addItems(logboundops)

        self.ui.pushButton_4.clicked.connect(self.plotLogValue)

        self.ui.pushButton_filterLog.clicked.connect(self.filterByLogValue)

        # Set up help button
        self.ui.helpBtn.clicked.connect(self.helpClicked)

        # Set up vertical slide
        self._upperSlideValue = 99
        self._lowerSlideValue = 0

        self.ui.verticalSlider.setRange(0, 100)
        self.ui.verticalSlider.setValue(self._upperSlideValue)
        self.ui.verticalSlider.setTracking(True)
        self.ui.verticalSlider.valueChanged.connect(self.move_upperSlider)

        self.ui.verticalSlider_2.setRange(0, 100)
        self.ui.verticalSlider_2.setValue(self._lowerSlideValue)
        self.ui.verticalSlider_2.setTracking(True)
        self.ui.verticalSlider_2.valueChanged.connect(self.move_lowerSlider)

        # Set up for filtering (advanced setup)
        self._tofcorrection = False
        self.ui.checkBox_fastLog.setChecked(False)
        self.ui.checkBox_filterByPulse.setChecked(False)
        self.ui.checkBox_from1.setChecked(False)
        self.ui.checkBox_groupWS.setChecked(True)

        self.ui.comboBox_tofCorr.currentIndexChanged.connect(self.showHideEi)
        self.ui.pushButton_refreshCorrWSList.clicked.connect(self._searchTableWorkspaces)

        self.ui.lineEdit_Ei.setValidator(QDoubleValidator(self.ui.lineEdit_Ei))

        self.ui.label_Ei.hide()
        self.ui.lineEdit_Ei.hide()
        self.ui.label_Ei_2.hide()
        self.ui.comboBox_corrWS.hide()
        self.ui.pushButton_refreshCorrWSList.hide()

        # Set up for workspaces
        self._dataWS = None
        self._sampleLogNames = []
        self._sampleLog = None

        # Side information
        self.ui.label_mean.hide()
        self.ui.label_meanvalue.hide()
        self.ui.label_avg.hide()
        self.ui.label_timeAvgValue.hide()
        self.ui.label_freq.hide()
        self.ui.label_freqValue.hide()
        self.ui.label_logname.hide()
        self.ui.label_lognamevalue.hide()
        self.ui.label_logsize.hide()
        self.ui.label_logsizevalue.hide()

        # Default
        self._defaultdir = os.getcwd()

        # register startup
        mantid.UsageService.registerFeatureUsage(mantid.kernel.FeatureType.Interface, "EventFilter", False)
Ejemplo n.º 17
0
    def insert_row(self,
                   row=-1,
                   title='',
                   sample_runs='',
                   sample_mass_density='N/A',
                   sample_chemical_formula='N/A',
                   packing_fraction='N/A',
                   align_and_focus_args={},
                   sample_placzek_arguments={},
                   normalization_placzek_arguments={}):
        self.table_ui.insertRow(row)
        self.set_row_height(row, COLUMN_DEFAULT_HEIGHT)

        _list_ui_to_unlock = [self.table_ui]

        _dimension_widgets = {'label': None, 'value': 'N/A', 'units': None}
        _full_dimension_widgets = {
            'radius': copy.deepcopy(_dimension_widgets),
            'radius2': copy.deepcopy(_dimension_widgets),
            'height': copy.deepcopy(_dimension_widgets)
        }
        _text_button = {'text': None, 'button': None}
        _mass_density_options = {'value': "N/A", "selected": False}
        _mass_density_infos = {
            'number_density': copy.deepcopy(_mass_density_options),
            'mass_density': copy.deepcopy(_mass_density_options),
            'mass': copy.deepcopy(_mass_density_options),
            'molecular_mass': np.NaN,
            'total_number_of_atoms': np.NaN,
        }
        _material_infos = {'mantid_format': None, 'addie_format': None}
        _mass_density_infos['mass_density']["selected"] = True

        _master_table_row_ui = {
            'active': None,
            'title': None,
            'sample': {
                'runs': None,
                'background': {
                    'runs': None,
                    'background': None,
                },
                'material': copy.deepcopy(_text_button),
                'material_infos': copy.deepcopy(_material_infos),
                'mass_density': copy.deepcopy(_text_button),
                'mass_density_infos': copy.deepcopy(_mass_density_infos),
                'packing_fraction': None,
                'geometry': copy.deepcopy(_full_dimension_widgets),
                'shape': None,
                'abs_correction': None,
                'mult_scat_correction': None,
                'inelastic_correction': None,
                'placzek_button': None,
                'placzek_infos': None,
            },
            'normalization': {
                'runs': None,
                'background': {
                    'runs': None,
                    'background': None,
                },
                'material': copy.deepcopy(_text_button),
                'material_infos': copy.deepcopy(_material_infos),
                'mass_density': copy.deepcopy(_text_button),
                'mass_density_infos': copy.deepcopy(_mass_density_infos),
                'packing_fraction': None,
                'geometry': copy.deepcopy(_full_dimension_widgets),
                'shape': None,
                'abs_correction': None,
                'mult_scat_correction': None,
                'inelastic_correction': None,
                'placzek_button': None,
                'placzek_infos': None,
            },
            'align_and_focus_args_button': None,
            'align_and_focus_args_infos': {},
            'align_and_focus_args_use_global': True,
        }

        random_key = self.generate_random_key()
        self.key = random_key

        # block main table events
        self.table_ui.blockSignals(True)

        # column 0 (active or not checkBox)
        _layout = QHBoxLayout()
        _widget = QCheckBox()
        _widget.setCheckState(QtCore.Qt.Checked)
        _widget.setEnabled(True)
        _master_table_row_ui['active'] = _widget
        _spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                              QSizePolicy.Minimum)
        _layout.addItem(_spacer)
        _layout.addWidget(_widget)
        _spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                              QSizePolicy.Minimum)
        _layout.addItem(_spacer)
        _layout.addStretch()
        _new_widget = QWidget()
        _new_widget.setLayout(_layout)
        _widget.stateChanged.connect(
            lambda state=0, key=random_key: self.main_window.
            master_table_select_state_changed(state, key))
        column = 0
        self.table_ui.setCellWidget(row, column, _new_widget)

        # sample

        column += 1
        # column 1 - title
        _item = QTableWidgetItem(title)
        _master_table_row_ui['title'] = _item
        self.table_ui.setItem(row, column, _item)

        # column 2 - sample runs
        column += 1
        _item = QTableWidgetItem(sample_runs)
        _master_table_row_ui['sample']['runs'] = _item
        self.table_ui.setItem(row, column, _item)

        # column 3 - background runs
        column += 1
        _item = QTableWidgetItem("")
        _master_table_row_ui['sample']['background']['runs'] = _item
        self.table_ui.setItem(row, column, _item)

        # column 4 - background background
        column += 1
        _item = QTableWidgetItem("")
        _master_table_row_ui['sample']['background']['background'] = _item
        self.table_ui.setItem(row, column, _item)

        # column 5 - material (chemical formula)
        column += 1
        clean_sample_chemical_formula = format_chemical_formula_equation(
            sample_chemical_formula)
        _material_text = QLineEdit(clean_sample_chemical_formula)
        _material_text = QLabel(clean_sample_chemical_formula)
        _material_button = QPushButton("...")
        _material_button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _material_button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _material_button.pressed.connect(
            lambda key=random_key: self.main_window.
            master_table_sample_material_button_pressed(key))

        _verti_layout = QVBoxLayout()
        _verti_layout.addWidget(_material_text)
        _verti_layout.addWidget(_material_button)
        _material_widget = QWidget()
        _material_widget.setLayout(_verti_layout)
        self.table_ui.setCellWidget(row, column, _material_widget)
        _master_table_row_ui['sample']['material']['text'] = _material_text
        _master_table_row_ui['sample']['material']['button'] = _material_button

        # column 6 - mass density
        column += 1
        _mass_text = QLineEdit(sample_mass_density)
        _mass_text.returnPressed.connect(
            lambda key=random_key: self.main_window.
            master_table_sample_mass_density_line_edit_entered(key))

        _mass_units = QLabel("g/cc")
        _top_widget = QWidget()
        _top_layout = QHBoxLayout()
        _top_layout.addWidget(_mass_text)
        _top_layout.addWidget(_mass_units)
        _top_widget.setLayout(_top_layout)
        _mass_button = QPushButton("...")
        _mass_button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _mass_button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _mass_button.pressed.connect(
            lambda key=random_key: self.main_window.
            master_table_sample_mass_density_button_pressed(key))
        _verti_layout = QVBoxLayout()
        _verti_layout.addWidget(_top_widget)
        _verti_layout.addWidget(_mass_button)
        _mass_widget = QWidget()
        _mass_widget.setLayout(_verti_layout)
        self.table_ui.setCellWidget(row, column, _mass_widget)
        _master_table_row_ui['sample']['mass_density']['text'] = _mass_text
        _master_table_row_ui['sample']['mass_density']['button'] = _mass_button

        # column 7 - packing fraction
        column += 1
        if packing_fraction == "N/A":
            packing_fraction = "{}".format(self.main_window.packing_fraction)
        _item = QTableWidgetItem(packing_fraction)
        _master_table_row_ui['sample']['packing_fraction'] = _item
        self.table_ui.setItem(row, column, _item)

        # column 8 - shape (cylinder or sphere)
        column += 1
        _layout = QHBoxLayout()
        _layout.setContentsMargins(0, 0, 0, 0)
        _widget = QComboBox()
        _shape_default_index = 0
        _widget.currentIndexChanged.connect(
            lambda index=_shape_default_index, key=random_key: self.main_window
            .master_table_sample_shape_changed(index, key))
        _list_ui_to_unlock.append(_widget)
        _widget.blockSignals(True)
        _widget.addItem("Cylinder")
        _widget.addItem("Sphere")
        _widget.addItem("Hollow Cylinder")
        _master_table_row_ui['sample']['shape'] = _widget
        _layout.addWidget(_widget)
        _w = QWidget()
        _w.setLayout(_layout)
        self.table_ui.setCellWidget(row, column, _w)

        # column 9 - dimensions
        column += 1

        # layout 1
        _grid_layout = QGridLayout()

        _label1 = QLabel("Radius:")
        _grid_layout.addWidget(_label1, 1, 0)
        _value1 = QLabel("N/A")
        _grid_layout.addWidget(_value1, 1, 1)
        _dim1 = QLabel("cm")
        _grid_layout.addWidget(_dim1, 1, 2)

        _label2 = QLabel("Radius:")
        _label2.setVisible(False)
        _grid_layout.addWidget(_label2, 2, 0)
        _value2 = QLabel("N/A")
        _value2.setVisible(False)
        _grid_layout.addWidget(_value2, 2, 1)
        _dim2 = QLabel("cm")
        _dim2.setVisible(False)
        _grid_layout.addWidget(_dim2, 2, 2)

        _label3 = QLabel("Height:")
        _grid_layout.addWidget(_label3, 3, 0)
        _value3 = QLabel("N/A")
        _grid_layout.addWidget(_value3, 3, 1)
        _dim3 = QLabel("cm")
        _grid_layout.addWidget(_dim3, 3, 2)

        _master_table_row_ui['sample']['geometry']['radius']['value'] = _value1
        _master_table_row_ui['sample']['geometry']['radius2'][
            'value'] = _value2
        _master_table_row_ui['sample']['geometry']['height']['value'] = _value3

        _master_table_row_ui['sample']['geometry']['radius']['label'] = _label1
        _master_table_row_ui['sample']['geometry']['radius2'][
            'label'] = _label2
        _master_table_row_ui['sample']['geometry']['height']['label'] = _label3

        _master_table_row_ui['sample']['geometry']['radius']['units'] = _dim1
        _master_table_row_ui['sample']['geometry']['radius2']['units'] = _dim2
        _master_table_row_ui['sample']['geometry']['height']['units'] = _dim3

        _geometry_widget = QWidget()
        _geometry_widget.setLayout(_grid_layout)

        _set_dimensions_button = QPushButton("...")
        _set_dimensions_button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _set_dimensions_button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _verti_layout = QVBoxLayout()
        _verti_layout.addWidget(_geometry_widget)
        _verti_layout.addWidget(_set_dimensions_button)
        _verti_widget = QWidget()
        _verti_widget.setLayout(_verti_layout)

        _set_dimensions_button.pressed.connect(
            lambda key=random_key: self.main_window.
            master_table_sample_dimensions_setter_button_pressed(key))

        self.table_ui.setCellWidget(row, column, _verti_widget)

        # column 10 - abs. correction
        column += 1
        _layout = QHBoxLayout()
        _layout.setContentsMargins(0, 0, 0, 0)
        _widget = QComboBox()
        _shape_default_value = 0
        list_abs_correction = self.get_absorption_correction_list(
            shape=_shape_default_value)
        _widget.currentIndexChanged.connect(
            lambda value=list_abs_correction[0], key=random_key: self.
            main_window.master_table_sample_abs_correction_changed(value, key))
        _widget.blockSignals(True)
        _list_ui_to_unlock.append(_widget)
        for _item in list_abs_correction:
            _widget.addItem(_item)
        _master_table_row_ui['sample']['abs_correction'] = _widget
        _layout.addWidget(_widget)
        _w = QWidget()
        _w.setLayout(_layout)
        self.table_ui.setCellWidget(row, column, _w)

        # column 11 - multi. scattering correction
        column += 1
        _layout = QHBoxLayout()
        _layout.setContentsMargins(0, 0, 0, 0)
        _widget = QComboBox()
        list_multi_scat_correction = self.get_multi_scat_correction_list(
            shape=_shape_default_value)
        _widget.currentIndexChanged.connect(
            lambda value=list_multi_scat_correction[
                0], key=random_key: self.main_window.
            master_table_sample_multi_scattering_correction_changed(
                value, key))
        _widget.blockSignals(True)
        _list_ui_to_unlock.append(_widget)
        for _item in list_multi_scat_correction:
            _widget.addItem(_item)
        _master_table_row_ui['sample']['mult_scat_correction'] = _widget
        _layout.addWidget(_widget)
        _w = QWidget()
        _w.setLayout(_layout)
        self.table_ui.setCellWidget(row, column, _w)

        # column 12 - inelastic correction
        column += 1
        _layout = QHBoxLayout()
        _layout.setContentsMargins(0, 0, 0, 0)
        _widget1 = QComboBox()
        _widget1.setMinimumHeight(20)
        list_inelastic_correction = self.get_inelastic_scattering_list(
            shape=_shape_default_value)
        for _item in list_inelastic_correction:
            _widget1.addItem(_item)
        _master_table_row_ui['sample']['inelastic_correction'] = _widget1
        _button = QPushButton("...")
        _button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _button.pressed.connect(
            lambda key=random_key: self.main_window.
            master_table_sample_placzek_button_pressed(key))
        _master_table_row_ui['sample']['placzek_button'] = _button
        _button.setVisible(False)
        _master_table_row_ui['sample']['placzek_button'] = _button
        _layout.addWidget(_widget1)
        _layout.addWidget(_button)
        _widget = QWidget()
        _widget.setLayout(_layout)
        _default_value = 'None'
        _widget1.currentIndexChanged.connect(
            lambda value=_default_value, key=random_key: self.main_window.
            master_table_sample_inelastic_correction_changed(value, key))
        _widget.blockSignals(True)
        _list_ui_to_unlock.append(_widget)
        self.table_ui.setCellWidget(row, column, _widget)

        # save default placzek settings
        _sample_formated_placzek_default = self.formated_placzek_default(
            sample_placzek_arguments)
        _master_table_row_ui['sample'][
            'placzek_infos'] = _sample_formated_placzek_default

        ## normalization

        # column 13 - sample runs
        column += 1
        _item = QTableWidgetItem("")
        self.table_ui.setItem(row, column, _item)

        # column 14 - background runs
        column += 1
        _item = QTableWidgetItem("")
        self.table_ui.setItem(row, column, _item)

        # column 15 - background background
        column += 1
        _item = QTableWidgetItem("")
        self.table_ui.setItem(row, column, _item)

        # column 16 - material (chemical formula)
        column += 1
        #_material_text = QLineEdit("")
        _material_text = QLabel("N/A")
        _material_button = QPushButton("...")
        _material_button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _material_button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _material_button.pressed.connect(
            lambda key=random_key: self.main_window.
            master_table_normalization_material_button_pressed(key))
        _verti_layout = QVBoxLayout()
        _verti_layout.addWidget(_material_text)
        _verti_layout.addWidget(_material_button)
        _material_widget = QWidget()
        _material_widget.setLayout(_verti_layout)
        self.table_ui.setCellWidget(row, column, _material_widget)
        _master_table_row_ui['normalization']['material'][
            'text'] = _material_text
        _master_table_row_ui['normalization']['material'][
            'button'] = _material_button

        # column 17 - mass density
        column += 1
        _mass_text = QLineEdit("N/A")
        _mass_text.returnPressed.connect(
            lambda key=random_key: self.main_window.
            master_table_normalization_mass_density_line_edit_entered(key))
        _mass_units = QLabel("g/cc")
        _top_widget = QWidget()
        _top_layout = QHBoxLayout()
        _top_layout.addWidget(_mass_text)
        _top_layout.addWidget(_mass_units)
        _top_widget.setLayout(_top_layout)
        _mass_button = QPushButton("...")
        _mass_button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _mass_button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _mass_button.pressed.connect(
            lambda key=random_key: self.main_window.
            master_table_normalization_mass_density_button_pressed(key))
        _verti_layout = QVBoxLayout()
        _verti_layout.addWidget(_top_widget)
        _verti_layout.addWidget(_mass_button)
        _mass_widget = QWidget()
        _mass_widget.setLayout(_verti_layout)
        self.table_ui.setCellWidget(row, column, _mass_widget)
        _master_table_row_ui['normalization']['mass_density'][
            'text'] = _mass_text
        _master_table_row_ui['normalization']['mass_density'][
            'button'] = _mass_button

        # column 18 - packing fraction
        column += 1
        _item = QTableWidgetItem("")
        self.table_ui.setItem(row, column, _item)

        # column 19 - shape (cylinder or sphere)
        column += 1
        _layout = QHBoxLayout()
        _layout.setContentsMargins(0, 0, 0, 0)
        _widget = QComboBox()
        _widget.currentIndexChanged.connect(
            lambda value=_shape_default_value, key=random_key: self.main_window
            .master_table_normalization_shape_changed(value, key))
        _widget.blockSignals(True)
        _list_ui_to_unlock.append(_widget)
        _widget.addItem("Cylinder")
        _widget.addItem("Sphere")
        _widget.addItem("Hollow Cylinder")
        _master_table_row_ui['normalization']['shape'] = _widget
        _layout.addWidget(_widget)
        _w = QWidget()
        _w.setLayout(_layout)
        self.table_ui.setCellWidget(row, column, _w)

        # column 20 - dimensions
        column += 1

        # layout 1
        _grid_layout = QGridLayout()

        _label1 = QLabel("Radius:")
        _grid_layout.addWidget(_label1, 1, 0)
        _value1 = QLabel("N/A")
        _grid_layout.addWidget(_value1, 1, 1)
        _dim1 = QLabel("cm")
        _grid_layout.addWidget(_dim1, 1, 2)

        _label2 = QLabel("Radius:")
        _label2.setVisible(False)
        _grid_layout.addWidget(_label2, 2, 0)
        _value2 = QLabel("N/A")
        _value2.setVisible(False)
        _grid_layout.addWidget(_value2, 2, 1)
        _dim2 = QLabel("cm")
        _dim2.setVisible(False)
        _grid_layout.addWidget(_dim2, 2, 2)

        _label3 = QLabel("Height:")
        _grid_layout.addWidget(_label3, 3, 0)
        _value3 = QLabel("N/A")
        _grid_layout.addWidget(_value3, 3, 1)
        _dim3 = QLabel("cm")
        _grid_layout.addWidget(_dim3, 3, 2)

        _master_table_row_ui['normalization']['geometry']['radius'][
            'value'] = _value1
        _master_table_row_ui['normalization']['geometry']['radius2'][
            'value'] = _value2
        _master_table_row_ui['normalization']['geometry']['height'][
            'value'] = _value3

        _master_table_row_ui['normalization']['geometry']['radius'][
            'label'] = _label1
        _master_table_row_ui['normalization']['geometry']['radius2'][
            'label'] = _label2
        _master_table_row_ui['normalization']['geometry']['height'][
            'label'] = _label3

        _master_table_row_ui['normalization']['geometry']['radius'][
            'units'] = _dim1
        _master_table_row_ui['normalization']['geometry']['radius2'][
            'units'] = _dim2
        _master_table_row_ui['normalization']['geometry']['height'][
            'units'] = _dim3

        _geometry_widget = QWidget()
        _geometry_widget.setLayout(_grid_layout)

        _set_dimensions_button = QPushButton("...")
        _set_dimensions_button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _set_dimensions_button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _verti_layout = QVBoxLayout()
        _verti_layout.addWidget(_geometry_widget)
        _verti_layout.addWidget(_set_dimensions_button)
        _verti_widget = QWidget()
        _verti_widget.setLayout(_verti_layout)

        _set_dimensions_button.pressed.connect(
            lambda key=random_key: self.main_window.
            master_table_normalization_dimensions_setter_button_pressed(
                key))  # noqa

        self.table_ui.setCellWidget(row, column, _verti_widget)

        # column 21 - abs. correction
        column += 1
        _layout = QHBoxLayout()
        _layout.setContentsMargins(0, 0, 0, 0)
        _widget = QComboBox()
        _widget.currentIndexChanged.connect(
            lambda value=list_abs_correction[0], key=random_key: self.
            main_window.master_table_normalization_abs_correction_changed(
                value, key))  # noqa
        _widget.blockSignals(True)
        _list_ui_to_unlock.append(_widget)
        for _item in list_abs_correction:
            _widget.addItem(_item)
        _widget.setCurrentIndex(0)
        _master_table_row_ui['normalization']['abs_correction'] = _widget
        _layout.addWidget(_widget)
        _w = QWidget()
        _w.setLayout(_layout)
        self.table_ui.setCellWidget(row, column, _w)

        # column 24 - multi. scattering correction
        column += 1
        _layout = QHBoxLayout()
        _layout.setContentsMargins(0, 0, 0, 0)
        _widget = QComboBox()
        _widget.currentIndexChanged.connect(
            lambda value=list_multi_scat_correction[
                0], key=random_key: self.main_window.
            master_table_normalization_multi_scattering_correction_changed(
                value, key))  # noqa
        _widget.blockSignals(True)
        _list_ui_to_unlock.append(_widget)
        for _item in list_multi_scat_correction:
            _widget.addItem(_item)
        _widget.setCurrentIndex(0)
        _master_table_row_ui['normalization']['mult_scat_correction'] = _widget
        _layout.addWidget(_widget)
        _w = QWidget()
        _w.setLayout(_layout)
        self.table_ui.setCellWidget(row, column, _w)

        # column 22 - inelastic correction
        column += 1
        _layout = QHBoxLayout()
        _layout.setContentsMargins(0, 0, 0, 0)
        _widget1 = QComboBox()
        _widget1.setMinimumHeight(20)
        list_inelastic_correction = self.get_inelastic_scattering_list(
            shape=_shape_default_value)
        for _item in list_inelastic_correction:
            _widget1.addItem(_item)
        _widget1.setCurrentIndex(0)
        _master_table_row_ui['normalization'][
            'inelastic_correction'] = _widget1
        _button = QPushButton("...")
        _button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _button.pressed.connect(
            lambda key=random_key: self.main_window.
            master_table_normalization_placzek_button_pressed(key))
        _master_table_row_ui['normalization']['placzek_button'] = _button
        _button.setVisible(False)
        _layout.addWidget(_widget1)
        _layout.addWidget(_button)
        _widget = QWidget()
        _widget.setLayout(_layout)
        _default_value = 'None'
        _widget1.currentIndexChanged.connect(
            lambda value=_default_value, key=random_key: self.main_window.
            master_table_normalization_inelastic_correction_changed(
                value, key))  # noqa
        _widget.blockSignals(True)
        _list_ui_to_unlock.append(_widget)
        self.table_ui.setCellWidget(row, column, _widget)

        # automatically populate placzek infos with default values
        _norm_formated_placzek_default = self.formated_placzek_default(
            normalization_placzek_arguments)
        _master_table_row_ui['normalization'][
            'placzek_infos'] = _norm_formated_placzek_default

        # column 23 - key/value pair
        column += 1
        _layout = QHBoxLayout()
        _spacer_kv1 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        _layout.addItem(_spacer_kv1)
        _button = QPushButton("...")
        _layout.addWidget(_button)
        _button.setFixedWidth(CONFIG_BUTTON_WIDTH)
        _button.setFixedHeight(CONFIG_BUTTON_HEIGHT)
        _button.pressed.connect(lambda key=random_key: self.main_window.
                                master_table_keyvalue_button_pressed(key))
        _new_widget = QWidget()
        _new_widget.setLayout(_layout)
        self.table_ui.setCellWidget(row, column, _new_widget)
        _master_table_row_ui['align_and_focus_args_button'] = _button
        _spacer_kv2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        _layout.addItem(_spacer_kv2)
        _layout.addStretch()

        align_and_focus_args = self.add_global_key_value_to_local_key_value(
            align_and_focus_args)
        _master_table_row_ui[
            'align_and_focus_args_infos'] = align_and_focus_args

        # Recap.

        self.main_window.master_table_list_ui[
            random_key] = _master_table_row_ui
        self.unlock_signals_ui(list_ui=_list_ui_to_unlock)
        self.main_window.check_status_of_right_click_buttons()
Ejemplo n.º 18
0
    def createSpace(self, size=5):
        """Creates a widget that can be used as spacing on  a panel."""
        qw = QWidget()
        qw.setMinimumSize(QSize(size, size))

        return qw
Ejemplo n.º 19
0
def test_view(simple_workflow_with_intents, qtbot):
    # Tests ingesting an internally run workflow, projecting it, storing it in a model
    # and using a CanvasView to display it

    plugin_manager.qt_is_safe = True
    plugin_manager.initialize_types()
    plugin_manager.collect_plugins()

    pc = next(
        filter(lambda task: task.name == 'plot_canvas', plugin_manager._tasks))
    plugin_manager._load_plugin(pc)
    plugin_manager._instantiate_plugin(pc)

    ic = next(
        filter(lambda task: task.name == 'image_canvas',
               plugin_manager._tasks))
    plugin_manager._load_plugin(ic)
    plugin_manager._instantiate_plugin(ic)

    plot_intent_task = next(
        filter(lambda task: task.name == 'PlotIntent', plugin_manager._tasks))
    plugin_manager._load_plugin(plot_intent_task)
    plugin_manager._instantiate_plugin(plot_intent_task)
    image_intent_task = next(
        filter(lambda task: task.name == 'ImageIntent', plugin_manager._tasks))
    plugin_manager._load_plugin(image_intent_task)
    plugin_manager._instantiate_plugin(image_intent_task)

    execution.executor = LocalExecutor()
    ensemble_model = EnsembleModel()
    intents_model = IntentsModel()
    intents_model.setSourceModel(ensemble_model)

    data_selector_view = DataSelectorView()
    data_selector_view.setModel(ensemble_model)

    stacked_canvas_view = StackedCanvasView()
    stacked_canvas_view.setModel(intents_model)

    widget = QWidget()
    layout = QHBoxLayout()
    layout.addWidget(stacked_canvas_view)
    layout.addWidget(data_selector_view)
    widget.setLayout(layout)

    def showResult(*result):
        ensemble = Ensemble()
        doc_generator = ingest_result_set(simple_workflow_with_intents, result)

        documents = list(doc_generator)
        catalog = BlueskyInMemoryCatalog()
        catalog.upsert(documents[0][1], documents[-1][1], ingest_result_set,
                       [simple_workflow_with_intents, result], {})
        catalog = catalog[-1]

        ensemble.append_catalog(catalog)
        ensemble_model.add_ensemble(ensemble, project_intents)
        qtbot.wait(1000)
        root = ensemble_model.index(0, 0, QModelIndex())
        ensemble_model.setData(root.child(0, 0), True, Qt.CheckStateRole)

    widget.setMinimumSize(800, 600)
    widget.show()
    qtbot.addWidget(widget)

    workflow_editor = WorkflowEditor(simple_workflow_with_intents,
                                     callback_slot=showResult)
    workflow_editor.run_workflow()

    qtbot.wait(7000)
Ejemplo n.º 20
0
    def _setupMainBarWidget(self):
        # Shift
        machshift_pvname = SiriusPVName(
            'AS-Glob:AP-MachShift:Mode-Sel').substitute(prefix=self._prefix)
        self._cb_shift = SiriusEnumComboBox(self, machshift_pvname)
        self._lb_shift = MachShiftLabel(self, prefix=self._prefix)
        self._lb_shift.setStyleSheet(
            'QLabel{max-height: 2em; min-width: 7em;}')
        self.wid_shift = QGroupBox('Mach.Shift', self)
        lay_shift = QVBoxLayout(self.wid_shift)
        lay_shift.addWidget(self._cb_shift)
        lay_shift.addWidget(self._lb_shift)

        # Injection System
        self.wid_is_summ = InjSysStbyControlWidget(self, is_summary=True)
        self.wid_injsys = QGroupBox('Inj.System', self)
        lay_injsys = QGridLayout(self.wid_injsys)
        lay_injsys.setContentsMargins(0, 0, 0, 0)
        lay_injsys.addWidget(self.wid_is_summ, 0, 0)
        # self.wid_is_full = InjSysStbyControlWidget(self, is_summary=False)
        # self.wid_is_full.setVisible(False)
        # lay_injsys.addWidget(self.wid_is_full, 0, 0)
        # self._icon_expd = qta.icon('fa5s.plus')
        # self._icon_comp = qta.icon('fa5s.minus')
        # self.bt_is_tgl = QPushButton(self._icon_expd, '', self)
        # self.bt_is_tgl.clicked.connect(self._handle_injsys_details_vis)
        # self.bt_is_tgl.setObjectName('bt')
        # self.bt_is_tgl.setStyleSheet("""
        #     #bt{
        #         min-width: 0.8em; max-width: 0.8em;
        #         min-height: 0.8em; max-height: 0.8em;
        #         icon-size:12px;}
        # """)
        # lay_injsys.addWidget(
        #     self.bt_is_tgl, 0, 1, alignment=Qt.AlignRight | Qt.AlignBottom)

        # EGun
        egun_dev = SiriusPVName('LI-01:EG-TriggerPS').substitute(
            prefix=self._prefix)
        self._sb_eguntrg = PyDMStateButton(
            self, egun_dev.substitute(propty_name='enable'))
        self._led_eguntrg = SiriusLedState(
            self, egun_dev.substitute(propty_name='enablereal'))
        self._led_eguntrg.setStyleSheet(
            'QLed{min-width: 1.29em; max-width: 1.29em;}')
        self.wid_egun = self._create_groupwidget('EGun Trig.', [
            self._sb_eguntrg,
        ], [
            self._led_eguntrg,
        ])

        # Injection
        self._pb_tiinj = EVGInjectionButton(self, self._prefix)
        self._pb_topup = PyDMStateButton(
            self,
            init_channel=self._inj_prefix.substitute(propty='TopUpState-Sel'))
        self._pb_topup.setVisible(False)
        self._led_injti = EVGInjectionLed(self, self._prefix)
        self._lb_injcnt = PyDMLabel(self)
        self._lb_injcnt.setToolTip(
            'Count injection pulses when Egun Trigger is enabled.')
        ch_injcnt = SiriusPVName(
            'AS-Glob:AP-CurrInfo:InjCount-Mon').substitute(prefix=self._prefix)
        self._lb_injcnt.channel = ch_injcnt
        self._lb_injcnt.setStyleSheet('QLabel{max-width: 3.5em;}')
        hbox_injsts = QHBoxLayout()
        hbox_injsts.setContentsMargins(0, 0, 0, 0)
        hbox_injsts.addWidget(self._led_injti)
        hbox_injsts.addWidget(self._lb_injcnt)
        self.wid_inj = QGroupBox('Injection', self)
        lay_inj = QGridLayout(self.wid_inj)
        lay_inj.setAlignment(Qt.AlignCenter)
        lay_inj.addWidget(self._pb_tiinj, 0, 0)
        lay_inj.addWidget(self._pb_topup, 0, 0)
        lay_inj.addLayout(hbox_injsts, 1, 0)

        # Current
        curr_pvname = SiriusPVName(
            'SI-Glob:AP-CurrInfo:Current-Mon').substitute(prefix=self._prefix)
        self._lb_curr = PyDMLabel(self, curr_pvname)
        self._lb_curr.showUnits = True
        self._lb_curr.setStyleSheet("""
            QLabel{
                font-size: 18pt; qproperty-alignment: AlignCenter;
                min-width: 5.5em; max-width: 5.5em;
        }""")
        self.wid_curr = QGroupBox('Current', self)
        lay_curr = QHBoxLayout(self.wid_curr)
        lay_curr.addWidget(self._lb_curr)

        # TopUp status
        self._lb_tusts = PyDMLabel(
            self, self._inj_prefix.substitute(propty='TopUpState-Sts'))
        self._lb_tusts.setAlignment(Qt.AlignCenter)
        self._lb_tusts.setStyleSheet('QLabel{max-height:2em;}')
        self._ld_tunow = QLabel('Now:',
                                self,
                                alignment=Qt.AlignRight | Qt.AlignVCenter)
        self._lb_tunow = ClockLabel(self)
        self._lb_tunow.setStyleSheet('QLabel{max-height:2em;}')
        self._ld_tunxt = QLabel('Next:',
                                self,
                                alignment=Qt.AlignRight | Qt.AlignVCenter)
        self._lb_tunxt = SiriusLabel(
            self, self._inj_prefix.substitute(propty='TopUpNextInj-Mon'))
        self._lb_tunxt.displayFormat = SiriusLabel.DisplayFormat.Time
        self._lb_tunxt.setAlignment(Qt.AlignCenter)
        self._lb_tunxt.setStyleSheet('QLabel{max-height:2em;}')
        self._pb_round = PyDMPushButton(
            self,
            label='',
            icon=qta.icon('mdi.tilde'),
            pressValue=1,
            init_channel=self._inj_prefix.substitute(
                propty='TopUpNextInjRound-Cmd'))
        self._pb_round.setObjectName('but')
        self._pb_round.setStyleSheet(
            '#but{min-width:18px; max-width:18px; icon-size:16px;}')
        self.wid_tusts = QGroupBox('Top-up status')
        self.wid_tusts.setVisible(False)
        lay_tusts = QGridLayout(self.wid_tusts)
        lay_tusts.addWidget(self._lb_tusts, 0, 0, 1, 2)
        lay_tusts.addWidget(self._ld_tunow, 1, 0)
        lay_tusts.addWidget(self._lb_tunow, 1, 1)
        lay_tusts.addWidget(self._ld_tunxt, 2, 0)
        lay_tusts.addWidget(self._lb_tunxt, 2, 1)
        lay_tusts.addWidget(self._pb_round, 2, 2)

        wid = QWidget()
        lay = QGridLayout(wid)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(self.wid_shift, 0, 0)
        lay.addWidget(self.wid_injsys, 0, 1)
        lay.addWidget(self.wid_egun, 0, 2)
        lay.addWidget(self.wid_inj, 0, 3)
        lay.addWidget(self.wid_tusts, 0, 4)
        lay.addWidget(self.wid_curr, 0, 5)
        lay.setColumnStretch(0, 3)
        lay.setColumnStretch(1, 2)
        lay.setColumnStretch(2, 2)
        lay.setColumnStretch(3, 2)
        lay.setColumnStretch(4, 4)
        lay.setColumnStretch(5, 3)
        wid.setStyleSheet('.QLabel{min-height: 1em; max-height: 1em;}')
        return wid
Ejemplo n.º 21
0
    def __init__(self, viewer):
        super().__init__()
        self.setAttribute(Qt.WA_DeleteOnClose)

        QCoreApplication.setAttribute(
            Qt.AA_UseStyleSheetPropagationInWidgetStyles, True)

        self.viewer = viewer
        self.dims = QtDims(self.viewer.dims)
        self.controls = QtControls(self.viewer)
        self.layers = QtLayerList(self.viewer.layers)
        self.layerButtons = QtLayerButtons(self.viewer)
        self.viewerButtons = QtViewerButtons(self.viewer)
        self._console = None

        layerList = QWidget()
        layerList.setObjectName('layerList')
        layerListLayout = QVBoxLayout()
        layerListLayout.addWidget(self.layerButtons)
        layerListLayout.addWidget(self.layers)
        layerListLayout.addWidget(self.viewerButtons)
        layerListLayout.setContentsMargins(8, 4, 8, 6)
        layerList.setLayout(layerListLayout)
        self.dockLayerList = QtViewerDockWidget(
            self,
            layerList,
            name='layer list',
            area='left',
            allowed_areas=['left', 'right'],
        )
        self.dockLayerControls = QtViewerDockWidget(
            self,
            self.controls,
            name='layer controls',
            area='left',
            allowed_areas=['left', 'right'],
        )
        self.dockConsole = QtViewerDockWidget(
            self,
            QWidget(),
            name='console',
            area='bottom',
            allowed_areas=['top', 'bottom'],
            shortcut='Ctrl+Shift+C',
        )
        self.dockConsole.setVisible(False)
        # because the console is loaded lazily in the @getter, this line just
        # gets (or creates) the console when the dock console is made visible.
        self.dockConsole.visibilityChanged.connect(lambda visible: self.console
                                                   if visible else None)
        self.dockLayerControls.visibilityChanged.connect(self._constrain_width)
        self.dockLayerList.setMaximumWidth(258)
        self.dockLayerList.setMinimumWidth(258)

        self.dockPerformance = self._create_performance_dock_widget()

        # This dictionary holds the corresponding vispy visual for each layer
        self.layer_to_visual = {}
        self.viewerButtons.consoleButton.clicked.connect(
            self.toggle_console_visibility)

        self.canvas = SceneCanvas(keys=None, vsync=True, parent=self)
        self.canvas.events.ignore_callback_errors = False
        self.canvas.events.draw.connect(self.dims.enable_play)
        self.canvas.native.setMinimumSize(QSize(200, 200))
        self.canvas.context.set_depth_func('lequal')

        self.canvas.connect(self.on_mouse_move)
        self.canvas.connect(self.on_mouse_press)
        self.canvas.connect(self.on_mouse_release)
        self.canvas.connect(self.on_key_press)
        self.canvas.connect(self.on_key_release)

        self.view = self.canvas.central_widget.add_view()
        self._update_camera()

        main_widget = QWidget()
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(10, 22, 10, 2)
        main_layout.addWidget(self.canvas.native)
        main_layout.addWidget(self.dims)
        main_layout.setSpacing(10)
        main_widget.setLayout(main_layout)

        self.setOrientation(Qt.Vertical)
        self.addWidget(main_widget)

        self._last_visited_dir = str(Path.home())

        self._cursors = {
            'cross': Qt.CrossCursor,
            'forbidden': Qt.ForbiddenCursor,
            'pointing': Qt.PointingHandCursor,
            'standard': QCursor(),
        }

        self._update_palette()

        self.viewer.events.interactive.connect(self._on_interactive)
        self.viewer.events.cursor.connect(self._on_cursor)
        self.viewer.events.reset_view.connect(self._on_reset_view)
        self.viewer.events.palette.connect(self._update_palette)
        self.viewer.layers.events.reordered.connect(self._reorder_layers)
        self.viewer.layers.events.added.connect(self._add_layer)
        self.viewer.layers.events.removed.connect(self._remove_layer)
        self.viewer.dims.events.camera.connect(
            lambda event: self._update_camera())
        # stop any animations whenever the layers change
        self.viewer.events.layers_change.connect(lambda x: self.dims.stop())

        self.setAcceptDrops(True)
Ejemplo n.º 22
0
    def _setupSettingsWidget(self):
        # group of labels to set the same stylesheet
        labelsdesc, labelsmon = list(), list()

        # Mode
        self._ld_injmode = QLabel('Mode', self)
        labelsdesc.append(self._ld_injmode)
        self._cb_injmode = SiriusEnumComboBox(
            self, self._inj_prefix.substitute(propty='Mode-Sel'))
        self._lb_injmode = PyDMLabel(
            self, self._inj_prefix.substitute(propty='Mode-Sts'))
        self._lb_injmode.showUnits = True
        labelsmon.append(self._lb_injmode)

        # Target current
        self._ld_currtgt = QLabel('Target Curr.', self)
        labelsdesc.append(self._ld_currtgt)
        self._sb_currtgt = SiriusSpinbox(
            self, self._inj_prefix.substitute(propty='TargetCurrent-SP'))
        self._sb_currtgt.showStepExponent = False
        self._lb_currtgt = PyDMLabel(
            self, self._inj_prefix.substitute(propty='TargetCurrent-RB'))
        self._lb_currtgt.showUnits = True
        labelsmon.append(self._lb_currtgt)

        # mode specific configurations
        self.wid_dcdtls = self._setupDecayModeWidget()
        self.wid_tudtls = self._setupTopUpModeWidget()
        self.wid_tudtls.setVisible(False)

        # Mon
        self._ld_injset = QLabel('Setup ok', self)
        labelsdesc.append(self._ld_injset)
        self._led_injset = InjDiagLed(self)

        # Type
        self._ld_injtype = QLabel('Type', self)
        labelsdesc.append(self._ld_injtype)
        self._cb_injtype = SiriusEnumComboBox(
            self, self._inj_prefix.substitute(propty='Type-Sel'))
        self._lb_injtype = PyDMLabel(
            self, self._inj_prefix.substitute(propty='Type-Sts'))
        labelsmon.append(self._lb_injtype)
        self._lb_injtype_mon = PyDMLabel(
            self, self._inj_prefix.substitute(propty='Type-Mon'))
        labelsmon.append(self._lb_injtype_mon)
        self._ch_injtype = SiriusConnectionSignal(
            self._inj_prefix.substitute(propty='Type-Sel'))
        self._ch_injtype.new_value_signal[int].connect(
            self._handle_injtype_settings_vis)

        # Single bunch bias voltage
        self._ld_sbbias = QLabel('SB Bias Voltage', self)
        labelsdesc.append(self._ld_sbbias)
        self._sb_sbbias = SiriusSpinbox(
            self, self._inj_prefix.substitute(propty='SglBunBiasVolt-SP'))
        self._sb_sbbias.showStepExponent = False
        self._lb_sbbias = PyDMLabel(
            self, self._inj_prefix.substitute(propty='SglBunBiasVolt-RB'))
        self._lb_sbbias.showUnits = True
        labelsmon.append(self._lb_sbbias)
        self._ld_sbbias.setVisible(False)
        self._sb_sbbias.setVisible(False)
        self._lb_sbbias.setVisible(False)

        # Multi bunch bias voltage
        self._ld_mbbias = QLabel('MB Bias Volt.', self)
        labelsdesc.append(self._ld_mbbias)
        self._sb_mbbias = SiriusSpinbox(
            self, self._inj_prefix.substitute(propty='MultBunBiasVolt-SP'))
        self._sb_mbbias.showStepExponent = False
        self._lb_mbbias = PyDMLabel(
            self, self._inj_prefix.substitute(propty='MultBunBiasVolt-RB'))
        self._lb_mbbias.showUnits = True
        labelsmon.append(self._lb_mbbias)

        # bias voltage mon
        ch_bias_mon = SiriusPVName('LI-01:EG-BiasPS').substitute(
            prefix=self._prefix, propty_name='voltinsoft')
        self._lb_bias_mon = PyDMLabel(self, ch_bias_mon)
        self._lb_bias_mon.showUnits = True
        labelsmon.append(self._lb_bias_mon)

        # Filament current op value
        self._ld_filaopcurr = QLabel('Fila.Op. Curr.', self)
        labelsdesc.append(self._ld_filaopcurr)
        self._sb_filaopcurr = SiriusSpinbox(
            self, self._inj_prefix.substitute(propty='FilaOpCurr-SP'))
        self._sb_filaopcurr.showStepExponent = False
        self._lb_filaopcurr = PyDMLabel(
            self, self._inj_prefix.substitute(propty='FilaOpCurr-RB'))
        self._lb_filaopcurr.showUnits = True
        labelsmon.append(self._lb_filaopcurr)
        ch_filacurr_mon = SiriusPVName('LI-01:EG-FilaPS').substitute(
            prefix=self._prefix, propty_name='currentinsoft')
        self._lb_filaopcurr_mon = PyDMLabel(self, ch_filacurr_mon)
        self._lb_filaopcurr_mon.showUnits = True
        labelsmon.append(self._lb_filaopcurr_mon)

        # High voltage op value
        self._ld_hvopvolt = QLabel('HV.Op. Volt.', self)
        labelsdesc.append(self._ld_hvopvolt)
        self._sb_hvopvolt = SiriusSpinbox(
            self, self._inj_prefix.substitute(propty='HVOpVolt-SP'))
        self._sb_hvopvolt.showStepExponent = False
        self._lb_hvopvolt = PyDMLabel(
            self, self._inj_prefix.substitute(propty='HVOpVolt-RB'))
        self._lb_hvopvolt.showUnits = True
        labelsmon.append(self._lb_hvopvolt)
        ch_hvvolt_mon = SiriusPVName('LI-01:EG-HVPS').substitute(
            prefix=self._prefix, propty_name='voltinsoft')
        self._lb_hvopvolt_mon = PyDMLabel(self, ch_hvvolt_mon)
        self._lb_hvopvolt_mon.showUnits = True
        labelsmon.append(self._lb_hvopvolt_mon)

        # header
        ld_sp = QLabel('<h4>SP</h4>', self, alignment=Qt.AlignCenter)
        ld_rb = QLabel('<h4>RB</h4>', self, alignment=Qt.AlignCenter)
        ld_mon = QLabel('<h4>Mon</h4>', self, alignment=Qt.AlignCenter)

        # Bucket list
        self._wid_bl = BucketList(self,
                                  prefix=self._prefix,
                                  min_size=15,
                                  show_graph=True)
        self._wid_bl.setSizePolicy(QSzPlcy.Preferred, QSzPlcy.MinimumExpanding)

        wid1 = QWidget()
        wid1.setSizePolicy(QSzPlcy.Preferred, QSzPlcy.Fixed)
        glay1 = QGridLayout(wid1)
        glay1.setAlignment(Qt.AlignTop)
        glay1.addWidget(self._ld_injset, 0, 0)
        glay1.addWidget(self._led_injset, 0, 1)
        glay1.addWidget(self._ld_injmode, 1, 0)
        glay1.addWidget(self._cb_injmode, 1, 1)
        glay1.addWidget(self._lb_injmode, 1, 2)
        glay1.addWidget(self._ld_currtgt, 2, 0)
        glay1.addWidget(self._sb_currtgt, 2, 1)
        glay1.addWidget(self._lb_currtgt, 2, 2)
        glay1.addWidget(self.wid_tudtls, 3, 0, 2, 3)
        glay1.addWidget(self.wid_dcdtls, 3, 0, 2, 3)
        glay1.setColumnStretch(0, 3)
        glay1.setColumnStretch(1, 2)
        glay1.setColumnStretch(2, 2)

        wid2 = QWidget()
        wid2.setSizePolicy(QSzPlcy.Preferred, QSzPlcy.Fixed)
        glay2 = QGridLayout(wid2)
        glay2.setAlignment(Qt.AlignTop)
        glay2.addWidget(ld_sp, 0, 1)
        glay2.addWidget(ld_rb, 0, 2)
        glay2.addWidget(ld_mon, 0, 3)
        glay2.addWidget(self._ld_injtype, 1, 0)
        glay2.addWidget(self._cb_injtype, 1, 1)
        glay2.addWidget(self._lb_injtype, 1, 2)
        glay2.addWidget(self._lb_injtype_mon, 1, 3)
        glay2.addWidget(self._ld_sbbias, 2, 0)
        glay2.addWidget(self._sb_sbbias, 2, 1)
        glay2.addWidget(self._lb_sbbias, 2, 2)
        glay2.addWidget(self._ld_mbbias, 2, 0)
        glay2.addWidget(self._sb_mbbias, 2, 1)
        glay2.addWidget(self._lb_mbbias, 2, 2)
        glay2.addWidget(self._lb_bias_mon, 2, 3)
        glay2.addWidget(self._ld_filaopcurr, 4, 0)
        glay2.addWidget(self._sb_filaopcurr, 4, 1)
        glay2.addWidget(self._lb_filaopcurr, 4, 2)
        glay2.addWidget(self._lb_filaopcurr_mon, 4, 3)
        glay2.addWidget(self._ld_hvopvolt, 5, 0)
        glay2.addWidget(self._sb_hvopvolt, 5, 1)
        glay2.addWidget(self._lb_hvopvolt, 5, 2)
        glay2.addWidget(self._lb_hvopvolt_mon, 5, 3)
        glay2.setColumnStretch(0, 3)
        glay2.setColumnStretch(1, 2)
        glay2.setColumnStretch(2, 2)
        glay2.setColumnStretch(3, 2)

        wid = QGroupBox('Settings')
        lay = QGridLayout(wid)
        lay.addWidget(wid1, 0, 0, alignment=Qt.AlignTop)
        lay.addWidget(wid2, 0, 1, alignment=Qt.AlignTop)
        lay.addWidget(self._wid_bl, 1, 0, 1, 2)
        lay.setColumnStretch(0, 3)
        lay.setColumnStretch(1, 4)

        for lbl in labelsdesc:
            lbl.setStyleSheet("""
                QLabel{
                    min-width: 6.5em; max-width: 6.5em; min-height: 1.5em;
                    qproperty-alignment: 'AlignRight | AlignVCenter';
                }""")
        for lbl in labelsmon:
            lbl.setStyleSheet("PyDMLabel{qproperty-alignment: AlignCenter;}")

        return wid
Ejemplo n.º 23
0
    def make_right_navbar(self):
        """
        Creates the widgets in the right navbar.
        """
        # make layout
        layout = QVBoxLayout()

        # Add label
        layout.addWidget(QLabel("Add actors"))

        # Add buttons
        for bname in self.right_navbar_button_names:
            btn = QPushButton(bname.capitalize(), self)
            btn.setObjectName(bname.replace(" ", "_"))
            self.buttons[bname.replace(" ", "_")] = btn
            layout.addWidget(btn)

        # Add label
        lbl = QLabel("Actors")
        lbl.setObjectName("LabelWithBorder")
        layout.addWidget(lbl)

        # add list widget
        self.actors_list = QListWidget()
        self.actors_list.setObjectName("actors_list")
        layout.addWidget(self.actors_list)

        # Add label
        lbl = QLabel("Actor properties")
        lbl.setObjectName("LabelWithBorder")
        layout.addWidget(lbl)

        # Actor Alpha
        alphalabel = QLabel("Alpha")
        alphalabel.setObjectName("PropertyName")
        self.alpha_textbox = QLineEdit(self)
        self.alpha_textbox.setObjectName("Property")
        layout.addWidget(alphalabel)
        layout.addWidget(self.alpha_textbox)

        # Actor Color
        colorlabel = QLabel("Color")
        colorlabel.setObjectName("PropertyName")
        self.color_textbox = QLineEdit(self)
        self.color_textbox.setObjectName("Property")
        layout.addWidget(colorlabel)
        layout.addWidget(self.color_textbox)

        # Add label
        lbl = QLabel("Show structures tree")
        lbl.setObjectName("LabelWithBorder")
        layout.addWidget(lbl)

        btn = QPushButton("Show structures tree", self)
        self.buttons[btn.text().lower().replace(" ", "_")] = btn
        layout.addWidget(btn)

        # set spacing
        layout.addStretch(5)
        layout.setSpacing(20)

        # make widget
        widget = QWidget()
        widget.setObjectName("RightNavbar")
        widget.setLayout(layout)

        return widget
Ejemplo n.º 24
0
    def _setupRawReadings(self):
        self.label_waveread = QLabel('<h3>Current Raw Readings</h3>',
                                     self,
                                     alignment=Qt.AlignCenter)

        self.wavegraph = PyDMWaveformPlot(self)
        self.wavegraph.setLabels(left='Current [mA]', bottom='Index')
        channel = 'FAKE:Readings'
        self.rawreadings_channel = SignalChannel(
            self.dcct_prefix.substitute(propty='RawReadings-Mon'))
        self.rawreadings_channel.new_value_signal[np.ndarray].connect(
            self._updateRawBuffer)
        self.wavegraph.addChannel(y_channel=channel,
                                  name='Current Raw Readings',
                                  color='blue',
                                  lineWidth=2,
                                  lineStyle=Qt.SolidLine)
        self.wavegraph.autoRangeX = True
        self.wavegraph.autoRangeY = True
        self.wavegraph.backgroundColor = QColor(255, 255, 255)
        self.wavegraph.showLegend = False
        self.wavegraph.showXGrid = True
        self.wavegraph.showYGrid = True
        self.wavegraph.plotItem.showButtons()
        self.wavecurve = self.wavegraph.curveAtIndex(0)

        wid = QWidget()
        lay = QGridLayout(wid)
        lay.setAlignment(Qt.AlignTop)
        lay.setRowStretch(0, 1)
        lay.setRowStretch(1, 9)
        lay.addWidget(self.label_waveread, 0, 0)
        lay.addWidget(self.wavegraph, 1, 0)

        # Smoothing
        evgname = SiriusPVName(_LLTimeSearch.get_evg_name())
        self._evnt_dly = SignalChannel(
            evgname.substitute(prefix=self.prefix,
                               propty='Dig' + self.device.sec + 'Delay-RB'))
        self._evnt_dly.new_value_signal[float].connect(self.updateRawXAxis)
        self._trig_dly = SignalChannel(
            self.dcct_prefix.substitute(dis='TI', propty='Delay-RB'))
        self._trig_dly.new_value_signal[float].connect(self.updateRawXAxis)
        self._smpl_cnt = SignalChannel(
            self.dcct_prefix.substitute(propty='FastSampleCnt-RB'))
        self._smpl_cnt.new_value_signal[float].connect(self.updateRawXAxis)
        self._meas_per = SignalChannel(
            self.dcct_prefix.substitute(propty='FastMeasPeriod-RB'))
        self._meas_per.new_value_signal[float].connect(self.updateRawXAxis)

        self.cb_timeaxis = QCheckBox('Use time axis', self)
        self.cb_timeaxis.setChecked(True)
        self.cb_timeaxis.stateChanged.connect(self.updateRawXAxis)
        self.cb_timeaxis.setLayoutDirection(Qt.RightToLeft)
        lay.addWidget(self.cb_timeaxis, 2, 0, alignment=Qt.AlignLeft)
        lay.setRowStretch(2, 1)

        l_smoothmethod = QLabel('Method: ', self)
        self.cb_smoothmethod = QComboBox(self)
        self.cb_smoothmethod.addItems(['Average', 'Median'])
        self.cb_smoothmethod.currentTextChanged.connect(
            self.setRawSmoothMethod)

        l_smoothnracq = QLabel('Nr.Acqs.: ', self)
        self.sb_smoothnracq = QSpinBoxPlus(self)
        self.sb_smoothnracq.setValue(1)
        self.sb_smoothnracq.valueChanged.connect(self.setRawSmoothNrAcq)

        l_smoothbuff = QLabel('Buffer Size: ', self)
        l_smoothbuff.setSizePolicy(QSzPly.Minimum, QSzPly.Preferred)
        self.label_buffsize = QLabel('', self)
        self.label_buffsize.setStyleSheet('min-width:3em; max-width:3em;')
        self.pb_resetbuff = QPushButton(qta.icon('mdi.delete-empty'), '', self)
        self.pb_resetbuff.setToolTip('Reset buffer')
        self.pb_resetbuff.setObjectName('resetbuff')
        self.pb_resetbuff.setStyleSheet(
            "#resetbuff{min-width:25px; max-width:25px; icon-size:20px;}")
        self.pb_resetbuff.clicked.connect(self.resetRawBuffer)
        hlay_buff = QHBoxLayout()
        hlay_buff.addWidget(self.label_buffsize)
        hlay_buff.addWidget(self.pb_resetbuff)

        l_down = QLabel('Downsampling: ', self)
        self.sb_down = QSpinBoxPlus(self)
        self.sb_down.setValue(1)
        self.sb_down.valueChanged.connect(self.setRawDownsampling)

        gbox_smooth = QGroupBox('Smoothing of Readings')
        glay_smooth = QGridLayout(gbox_smooth)
        glay_smooth.addWidget(l_smoothmethod, 0, 0)
        glay_smooth.addWidget(self.cb_smoothmethod, 0, 1)
        glay_smooth.addWidget(l_smoothnracq, 1, 0)
        glay_smooth.addWidget(self.sb_smoothnracq, 1, 1)
        glay_smooth.addWidget(QLabel(''), 0, 2)
        glay_smooth.addWidget(l_smoothbuff, 0, 3)
        glay_smooth.addLayout(hlay_buff, 0, 4, 1, 2)
        glay_smooth.addWidget(l_down, 1, 3)
        glay_smooth.addWidget(self.sb_down, 1, 4, 1, 2)
        glay_smooth.setColumnStretch(0, 10)
        glay_smooth.setColumnStretch(1, 10)
        glay_smooth.setColumnStretch(2, 2)
        glay_smooth.setColumnStretch(3, 10)
        glay_smooth.setColumnStretch(4, 5)
        glay_smooth.setColumnStretch(5, 5)
        lay.addWidget(gbox_smooth, 3, 0)
        lay.setRowStretch(3, 3)
        gbox_smooth.setStyleSheet("""
            .QLabel{
                qproperty-alignment: 'AlignVCenter | AlignRight';}
            QPushButton{
                min-width:3em; max-width:3em;}""")

        return wid
Ejemplo n.º 25
0
    def setup_page(self):
        newcb = self.create_checkbox

        # --- Introspection ---
        # Basic features group
        basic_features_group = QGroupBox(_("Basic features"))
        completion_box = newcb(_("Enable code completion"), 'code_completion')
        enable_hover_hints_box = newcb(
            _("Enable hover hints"),
            'enable_hover_hints',
            tip=_("If enabled, hovering the mouse pointer over an object\n"
                  "name will display that object's signature and/or\n"
                  "docstring (if present)."))
        goto_definition_box = newcb(
            _("Enable Go to definition"),
            'jedi_definition',
            tip=_("If enabled, left-clicking on an object name while \n"
                  "pressing the {} key will go to that object's definition\n"
                  "(if resolved).".format(self.CTRL)))
        follow_imports_box = newcb(
            _("Follow imports when going to a "
              "definition"), 'jedi_definition/follow_imports')
        show_signature_box = newcb(_("Show calltips"), 'jedi_signature_help')

        basic_features_layout = QVBoxLayout()
        basic_features_layout.addWidget(completion_box)
        basic_features_layout.addWidget(enable_hover_hints_box)
        basic_features_layout.addWidget(goto_definition_box)
        basic_features_layout.addWidget(follow_imports_box)
        basic_features_layout.addWidget(show_signature_box)
        basic_features_group.setLayout(basic_features_layout)

        # Advanced group
        advanced_group = QGroupBox(_("Advanced"))
        modules_textedit = self.create_textedit(
            _("Preload the following modules to make completion faster "
              "and more accurate:"), 'preload_modules')
        if is_dark_interface():
            modules_textedit.textbox.setStyleSheet(
                "border: 1px solid #32414B;")

        advanced_layout = QVBoxLayout()
        advanced_layout.addWidget(modules_textedit)
        advanced_group.setLayout(advanced_layout)

        # --- Linting ---
        # Linting options
        linting_label = QLabel(
            _("Spyder can optionally highlight syntax "
              "errors and possible problems with your "
              "code in the editor."))
        linting_label.setOpenExternalLinks(True)
        linting_label.setWordWrap(True)
        linting_check = self.create_checkbox(_("Enable basic linting"),
                                             'pyflakes')

        linting_complexity_box = self.create_checkbox(
            _("Enable complexity linting with "
              "the Mccabe package"), 'mccabe')

        # Linting layout
        linting_layout = QVBoxLayout()
        linting_layout.addWidget(linting_label)
        linting_layout.addWidget(linting_check)
        linting_layout.addWidget(linting_complexity_box)
        linting_widget = QWidget()
        linting_widget.setLayout(linting_layout)

        # --- Code style tab ---
        # Code style label
        pep_url = (
            '<a href="https://www.python.org/dev/peps/pep-0008">PEP 8</a>')
        code_style_codes_url = _(
            "<a href='http://pycodestyle.pycqa.org/en/stable"
            "/intro.html#error-codes'>pycodestyle error codes</a>")
        code_style_label = QLabel(
            _("Spyder can use pycodestyle to analyze your code for "
              "conformance to the {} convention. You can also "
              "manually show or hide specific warnings by their "
              "{}.").format(pep_url, code_style_codes_url))
        code_style_label.setOpenExternalLinks(True)
        code_style_label.setWordWrap(True)

        # Code style checkbox
        self.code_style_check = self.create_checkbox(
            _("Enable code style linting"), 'pycodestyle')

        # Code style options
        self.code_style_filenames_match = self.create_lineedit(
            _("Only check filenames matching these patterns:"),
            'pycodestyle/filename',
            alignment=Qt.Horizontal,
            word_wrap=False,
            placeholder=_("Check Python files: *.py"))
        self.code_style_exclude = self.create_lineedit(
            _("Exclude files or directories matching these patterns:"),
            'pycodestyle/exclude',
            alignment=Qt.Horizontal,
            word_wrap=False,
            placeholder=_("Exclude all test files: (?!test_).*\\.py"))
        code_style_select = self.create_lineedit(
            _("Show the following errors or warnings:").format(
                code_style_codes_url),
            'pycodestyle/select',
            alignment=Qt.Horizontal,
            word_wrap=False,
            placeholder=_("Example codes: E113, W391"))
        code_style_ignore = self.create_lineedit(
            _("Ignore the following errors or warnings:"),
            'pycodestyle/ignore',
            alignment=Qt.Horizontal,
            word_wrap=False,
            placeholder=_("Example codes: E201, E303"))
        code_style_max_line_length = self.create_spinbox(
            _("Maximum allowed line length:"),
            None,
            'pycodestyle/max_line_length',
            min_=10,
            max_=500,
            step=1,
            tip=_("Default is 79"))

        # Code style layout
        code_style_g_layout = QGridLayout()
        code_style_g_layout.addWidget(self.code_style_filenames_match.label, 1,
                                      0)
        code_style_g_layout.addWidget(self.code_style_filenames_match.textbox,
                                      1, 1)
        code_style_g_layout.addWidget(self.code_style_exclude.label, 2, 0)
        code_style_g_layout.addWidget(self.code_style_exclude.textbox, 2, 1)
        code_style_g_layout.addWidget(code_style_select.label, 3, 0)
        code_style_g_layout.addWidget(code_style_select.textbox, 3, 1)
        code_style_g_layout.addWidget(code_style_ignore.label, 4, 0)
        code_style_g_layout.addWidget(code_style_ignore.textbox, 4, 1)
        code_style_g_layout.addWidget(code_style_max_line_length.plabel, 5, 0)
        code_style_g_layout.addWidget(code_style_max_line_length.spinbox, 5, 1)

        # Set Code style options enabled/disabled
        code_style_g_widget = QWidget()
        code_style_g_widget.setLayout(code_style_g_layout)
        code_style_g_widget.setEnabled(self.get_option('pycodestyle'))
        self.code_style_check.toggled.connect(code_style_g_widget.setEnabled)

        # Code style layout
        code_style_layout = QVBoxLayout()
        code_style_layout.addWidget(code_style_label)
        code_style_layout.addWidget(self.code_style_check)
        code_style_layout.addWidget(code_style_g_widget)

        code_style_widget = QWidget()
        code_style_widget.setLayout(code_style_layout)

        # --- Docstring tab ---
        # Docstring style label
        numpy_url = ("<a href='https://numpydoc.readthedocs.io/en/"
                     "latest/format.html'>Numpy</a>")
        pep257_url = (
            "<a href='https://www.python.org/dev/peps/pep-0257/'>PEP 257</a>")
        docstring_style_codes = _(
            "<a href='http://www.pydocstyle.org/en/stable"
            "/error_codes.html'>page</a>")
        docstring_style_label = QLabel(
            _("Here you can decide if you want to perform style analysis on "
              "your docstrings according to the {} or {} conventions. You can "
              "also decide if you want to show or ignore specific errors, "
              "according to the codes found on this {}.").format(
                  numpy_url, pep257_url, docstring_style_codes))
        docstring_style_label.setOpenExternalLinks(True)
        docstring_style_label.setWordWrap(True)

        # Docstring style checkbox
        self.docstring_style_check = self.create_checkbox(
            _("Enable docstring style linting"), 'pydocstyle')

        # Docstring style options
        docstring_style_convention = self.create_combobox(
            _("Choose the convention used to lint docstrings: "),
            (("Numpy", 'numpy'), ("PEP 257", 'pep257'), ("Custom", 'custom')),
            'pydocstyle/convention')
        self.docstring_style_select = self.create_lineedit(
            _("Show the following errors:"),
            'pydocstyle/select',
            alignment=Qt.Horizontal,
            word_wrap=False,
            placeholder=_("Example codes: D413, D414"))
        self.docstring_style_ignore = self.create_lineedit(
            _("Ignore the following errors:"),
            'pydocstyle/ignore',
            alignment=Qt.Horizontal,
            word_wrap=False,
            placeholder=_("Example codes: D107, D402"))
        self.docstring_style_match = self.create_lineedit(
            _("Only check filenames matching these patterns:"),
            'pydocstyle/match',
            alignment=Qt.Horizontal,
            word_wrap=False,
            placeholder=_("Skip test files: (?!test_).*\\.py"))
        self.docstring_style_match_dir = self.create_lineedit(
            _("Only check in directories matching these patterns:"),
            'pydocstyle/match_dir',
            alignment=Qt.Horizontal,
            word_wrap=False,
            placeholder=_("Skip dot directories: [^\\.].*"))

        # Custom option handling
        docstring_style_convention.combobox.currentTextChanged.connect(
            self.setup_docstring_style_convention)
        current_convention = docstring_style_convention.combobox.currentText()
        self.setup_docstring_style_convention(current_convention)

        # Docstring style layout
        docstring_style_g_layout = QGridLayout()
        docstring_style_g_layout.addWidget(docstring_style_convention.label, 1,
                                           0)
        docstring_style_g_layout.addWidget(docstring_style_convention.combobox,
                                           1, 1)
        docstring_style_g_layout.addWidget(self.docstring_style_select.label,
                                           2, 0)
        docstring_style_g_layout.addWidget(self.docstring_style_select.textbox,
                                           2, 1)
        docstring_style_g_layout.addWidget(self.docstring_style_ignore.label,
                                           3, 0)
        docstring_style_g_layout.addWidget(self.docstring_style_ignore.textbox,
                                           3, 1)
        docstring_style_g_layout.addWidget(self.docstring_style_match.label, 4,
                                           0)
        docstring_style_g_layout.addWidget(self.docstring_style_match.textbox,
                                           4, 1)
        docstring_style_g_layout.addWidget(
            self.docstring_style_match_dir.label, 5, 0)
        docstring_style_g_layout.addWidget(
            self.docstring_style_match_dir.textbox, 5, 1)

        # Set Docstring style options enabled/disabled
        docstring_style_g_widget = QWidget()
        docstring_style_g_widget.setLayout(docstring_style_g_layout)
        docstring_style_g_widget.setEnabled(self.get_option('pydocstyle'))
        self.docstring_style_check.toggled.connect(
            docstring_style_g_widget.setEnabled)

        # Docstring style layout
        docstring_style_layout = QVBoxLayout()
        docstring_style_layout.addWidget(docstring_style_label)
        docstring_style_layout.addWidget(self.docstring_style_check)
        docstring_style_layout.addWidget(docstring_style_g_widget)

        docstring_style_widget = QWidget()
        docstring_style_widget.setLayout(docstring_style_layout)

        # --- Advanced tab ---
        # Advanced label
        advanced_label = QLabel(
            _("<b>Warning</b>: Only modify these values if "
              "you know what you're doing!"))
        advanced_label.setWordWrap(True)
        advanced_label.setAlignment(Qt.AlignJustify)

        # Advanced options
        self.advanced_command_launch = self.create_lineedit(
            _("Command to launch the Python language server: "),
            'advanced/command_launch',
            alignment=Qt.Horizontal,
            word_wrap=False)
        self.advanced_host = self.create_lineedit(
            _("IP Address and port to bind the server to: "),
            'advanced/host',
            alignment=Qt.Horizontal,
            word_wrap=False)
        self.advanced_port = self.create_spinbox(":",
                                                 "",
                                                 'advanced/port',
                                                 min_=1,
                                                 max_=65535,
                                                 step=1)
        self.external_server = self.create_checkbox(
            _("This is an external server"), 'advanced/external')
        self.use_stdio = self.create_checkbox(
            _("Use stdio pipes to communicate with server"), 'advanced/stdio')
        self.use_stdio.stateChanged.connect(self.disable_tcp)
        self.external_server.stateChanged.connect(self.disable_stdio)

        # Advanced layout
        advanced_g_layout = QGridLayout()
        advanced_g_layout.addWidget(self.advanced_command_launch.label, 1, 0)
        advanced_g_layout.addWidget(self.advanced_command_launch.textbox, 1, 1)
        advanced_g_layout.addWidget(self.advanced_host.label, 2, 0)

        advanced_host_port_g_layout = QGridLayout()
        advanced_host_port_g_layout.addWidget(self.advanced_host.textbox, 1, 0)
        advanced_host_port_g_layout.addWidget(self.advanced_port.plabel, 1, 1)
        advanced_host_port_g_layout.addWidget(self.advanced_port.spinbox, 1, 2)
        advanced_g_layout.addLayout(advanced_host_port_g_layout, 2, 1)

        advanced_widget = QWidget()
        advanced_layout = QVBoxLayout()
        advanced_layout.addWidget(advanced_label)
        advanced_layout.addSpacing(12)
        advanced_layout.addLayout(advanced_g_layout)
        advanced_layout.addWidget(self.external_server)
        advanced_layout.addWidget(self.use_stdio)
        advanced_widget.setLayout(advanced_layout)

        # --- Other servers tab ---
        # Section label
        servers_label = QLabel(
            _("Spyder uses the <a href=\"{lsp_url}\">Language Server "
              "Protocol</a> to provide code completion and linting "
              "for its Editor. Here, you can setup and configure LSP servers "
              "for languages other than Python, so Spyder can provide such "
              "features for those languages as well.").format(lsp_url=LSP_URL))
        servers_label.setOpenExternalLinks(True)
        servers_label.setWordWrap(True)
        servers_label.setAlignment(Qt.AlignJustify)

        # Servers table
        table_group = QGroupBox(_('Available servers:'))
        self.table = LSPServerTable(self, text_color=ima.MAIN_FG_COLOR)
        self.table.setMaximumHeight(150)
        table_layout = QVBoxLayout()
        table_layout.addWidget(self.table)
        table_group.setLayout(table_layout)

        # Buttons
        self.reset_btn = QPushButton(_("Reset to default values"))
        self.new_btn = QPushButton(_("Set up a new server"))
        self.delete_btn = QPushButton(_("Delete currently selected server"))
        self.delete_btn.setEnabled(False)

        # Slots connected to buttons
        self.new_btn.clicked.connect(self.create_new_server)
        self.reset_btn.clicked.connect(self.reset_to_default)
        self.delete_btn.clicked.connect(self.delete_server)

        # Buttons layout
        btns = [self.new_btn, self.delete_btn, self.reset_btn]
        buttons_layout = QGridLayout()
        for i, btn in enumerate(btns):
            buttons_layout.addWidget(btn, i, 1)
        buttons_layout.setColumnStretch(0, 1)
        buttons_layout.setColumnStretch(1, 2)
        buttons_layout.setColumnStretch(2, 1)

        # Combined layout
        servers_widget = QWidget()
        servers_layout = QVBoxLayout()
        servers_layout.addSpacing(-10)
        servers_layout.addWidget(servers_label)
        servers_layout.addWidget(table_group)
        servers_layout.addSpacing(10)
        servers_layout.addLayout(buttons_layout)
        servers_widget.setLayout(servers_layout)

        # --- Tabs organization ---
        self.tabs = QTabWidget()
        self.tabs.addTab(self.create_tab(basic_features_group, advanced_group),
                         _('Introspection'))
        self.tabs.addTab(self.create_tab(linting_widget), _('Linting'))
        self.tabs.addTab(self.create_tab(code_style_widget), _('Code style'))
        self.tabs.addTab(self.create_tab(docstring_style_widget),
                         _('Docstring style'))
        self.tabs.addTab(self.create_tab(advanced_widget), _('Advanced'))
        self.tabs.addTab(self.create_tab(servers_widget), _('Other languages'))

        vlayout = QVBoxLayout()
        vlayout.addWidget(self.tabs)
        self.setLayout(vlayout)
Ejemplo n.º 26
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent=parent)

        self._shortcuts_summary_title = _("Spyder Keyboard ShortCuts")

        # Calculate font and amount of elements in each column according screen size
        width, height = self.get_screen_resolution()
        font_size = height / 80
        font_size = max(min(font_size, MAX_FONT_SIZE), MIN_FONT_SIZE)
        shortcuts_column = (height - 8 * font_size) / (font_size + 16)

        # Widgets
        style = """
            QDialog {
              margin:0px;
              padding:0px;
              border-radius: 2px;
            }"""
        self.setStyleSheet(style)

        font_names = QFont()
        font_names.setPointSize(font_size)
        font_names.setBold(True)

        font_keystr = QFont()
        font_keystr.setPointSize(font_size)

        font_title = QFont()
        font_title.setPointSize(font_size + 2)
        font_title.setBold(True)

        title_label = QLabel(self._shortcuts_summary_title)
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setFont(font_title)

        # iter over shortcuts and create GroupBox for each context
        # with shortcuts in a grid

        columns_layout = QHBoxLayout()
        added_shortcuts = 0
        group = None
        # group shortcuts by context
        shortcuts = groupby(sorted(iter_shortcuts()), key=itemgetter(0))

        for context, group_shortcuts in shortcuts:
            for i, (context, name, keystr) in enumerate(group_shortcuts):
                # start of every column
                if added_shortcuts == 0:
                    column_layout = QVBoxLayout()

                # at start of new context add previous context group
                if i == 0 and added_shortcuts > 0:
                    column_layout.addWidget(group)

                # create group at start of column or context
                if added_shortcuts == 0 or i == 0:
                    if context == '_': context = 'Global'

                    group = QGroupBox(context.capitalize())
                    group.setFont(font_names)

                    group_layout = QGridLayout()
                    group.setLayout(group_layout)

                    # Count space for titles
                    added_shortcuts += 1

                # Widgets
                label_name = QLabel(name.capitalize().replace('_', ' '))
                label_name.setFont(font_names)

                keystr = QKeySequence(keystr).toString(QKeySequence.NativeText)
                label_keystr = QLabel(keystr)
                label_keystr.setFont(font_keystr)

                group_layout.addWidget(label_name, i, 0)
                group_layout.addWidget(label_keystr, i, 1)

                added_shortcuts += 1

                if added_shortcuts >= shortcuts_column:
                    column_layout.addWidget(group)
                    columns_layout.addLayout(column_layout)
                    added_shortcuts = 0

        column_layout.addWidget(group)
        column_layout.addStretch()  # avoid lasts sections to appear too big
        columns_layout.addLayout(column_layout)

        # Scroll widget
        self.scroll_widget = QWidget()
        self.scroll_widget.setLayout(columns_layout)
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidget(self.scroll_widget)

        # widget setup
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowOpacity(0.95)

        # layout
        self._layout = QVBoxLayout()
        self._layout.addWidget(title_label)

        self._layout.addWidget(self.scroll_area)
        self.setLayout(self._layout)

        self.setGeometry(0, 0, width, height)
Ejemplo n.º 27
0
    def setup(
        self,
        check_all=None,
        exclude_private=None,
        exclude_uppercase=None,
        exclude_capitalized=None,
        exclude_unsupported=None,
        excluded_names=None,
        exclude_callables_and_modules=None,
        minmax=None,
        dataframe_format=None,
        show_callable_attributes=None,
        show_special_attributes=None,
    ):
        """
        Setup the namespace browser with provided settings.

        Args:
            dataframe_format (string): default floating-point format for 
                DataFrame editor
        """
        assert self.shellwidget is not None

        self.check_all = check_all
        self.exclude_private = exclude_private
        self.exclude_uppercase = exclude_uppercase
        self.exclude_capitalized = exclude_capitalized
        self.exclude_unsupported = exclude_unsupported
        self.exclude_callables_and_modules = exclude_callables_and_modules
        self.excluded_names = excluded_names
        self.minmax = minmax
        self.dataframe_format = dataframe_format
        self.show_callable_attributes = show_callable_attributes
        self.show_special_attributes = show_special_attributes

        if self.editor is not None:
            self.editor.setup_menu(minmax)
            self.editor.set_dataframe_format(dataframe_format)
            self.exclude_private_action.setChecked(exclude_private)
            self.exclude_uppercase_action.setChecked(exclude_uppercase)
            self.exclude_capitalized_action.setChecked(exclude_capitalized)
            self.exclude_unsupported_action.setChecked(exclude_unsupported)
            self.exclude_callables_and_modules_action.setChecked(
                exclude_callables_and_modules)
            self.refresh_table()
            return

        self.editor = RemoteCollectionsEditorTableView(
            self,
            data=None,
            minmax=minmax,
            shellwidget=self.shellwidget,
            dataframe_format=dataframe_format,
            show_callable_attributes=show_callable_attributes,
            show_special_attributes=show_special_attributes)

        self.editor.sig_option_changed.connect(self.sig_option_changed.emit)
        self.editor.sig_files_dropped.connect(self.import_data)
        self.editor.sig_free_memory.connect(self.sig_free_memory.emit)

        self.setup_option_actions(exclude_private, exclude_uppercase,
                                  exclude_capitalized, exclude_unsupported,
                                  exclude_callables_and_modules)

        # Setup toolbar layout.

        self.tools_layout = QHBoxLayout()
        toolbar = self.setup_toolbar()
        for widget in toolbar:
            self.tools_layout.addWidget(widget)
        self.tools_layout.addStretch()

        # Show loading widget
        self.loading_widget = create_waitspinner(size=16, parent=self)
        self.editor.sig_open_editor.connect(self.loading_widget.start)
        self.editor.sig_editor_shown.connect(self.loading_widget.stop)
        self.tools_layout.addWidget(self.loading_widget)

        # Options button actions addition and addition to layout
        self.setup_options_button()

        # Setup layout.

        layout = create_plugin_layout(self.tools_layout, self.editor)

        # Fuzzy search layout
        finder_layout = QHBoxLayout()
        close_button = create_toolbutton(self,
                                         triggered=self.show_finder,
                                         icon=ima.icon('DialogCloseButton'))
        text_finder = NamespacesBrowserFinder(self.editor,
                                              callback=self.editor.set_regex,
                                              main=self,
                                              regex_base=VALID_VARIABLE_CHARS)
        self.editor.finder = text_finder
        finder_layout.addWidget(close_button)
        finder_layout.addWidget(text_finder)
        finder_layout.setContentsMargins(0, 0, 0, 0)
        self.finder = QWidget(self)
        self.finder.text_finder = text_finder
        self.finder.setLayout(finder_layout)
        self.finder.setVisible(False)

        layout.addWidget(self.finder)

        self.setLayout(layout)

        # Local shortcuts
        self.shortcuts = self.create_shortcuts()

        self.sig_option_changed.connect(self.option_changed)
Ejemplo n.º 28
0
    def setup_ui(self):
        self.setWindowTitle('Neuroport DBS - Electrodes Depth')
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.move(WINDOWDIMS_DEPTH[0], WINDOWDIMS_DEPTH[1])
        self.setFixedSize(WINDOWDIMS_DEPTH[2], WINDOWDIMS_DEPTH[3])

        self.show()

        self.plot_widget = QWidget()
        self.setCentralWidget(self.plot_widget)

        # define Qt GUI elements
        v_layout = QVBoxLayout()
        v_layout.setSpacing(0)
        v_layout.setContentsMargins(10, 0, 10, 10)

        h_layout = QHBoxLayout()

        self.comboBox_com_port = QComboBox()
        h_layout.addWidget(self.comboBox_com_port)

        self.pushButton_open = QPushButton("Open")
        h_layout.addWidget(self.pushButton_open)
        h_layout.addStretch()

        self.label_offset = QLabel("Offset: ")
        h_layout.addWidget(self.label_offset)

        self.doubleSpinBox_offset = QDoubleSpinBox()
        self.doubleSpinBox_offset.setMinimum(-100.00)
        self.doubleSpinBox_offset.setMaximum(100.00)
        self.doubleSpinBox_offset.setSingleStep(1.00)
        self.doubleSpinBox_offset.setDecimals(2)
        self.doubleSpinBox_offset.setValue(-10.00)
        self.doubleSpinBox_offset.setFixedWidth(60)
        h_layout.addWidget(self.doubleSpinBox_offset)

        h_layout.addStretch()

        h_layout.addWidget(QLabel("Stream to :"))

        self.chk_NSP = QCheckBox("NSP")
        self.chk_NSP.setChecked(True)
        h_layout.addWidget(self.chk_NSP)

        h_layout.addSpacing(5)

        self.chk_LSL = QCheckBox("LSL")
        self.chk_LSL.clicked.connect(self.on_chk_LSL_clicked)
        self.chk_LSL.click(
        )  # default is enabled, click call to trigger LSL stream creation.
        h_layout.addWidget(self.chk_LSL)

        h_layout.addSpacing(5)

        send_btn = QPushButton("Send")
        send_btn.clicked.connect(self.send)

        h_layout.addWidget(send_btn)
        h_layout.addSpacing(5)

        quit_btn = QPushButton('X')
        quit_btn.setMaximumWidth(20)
        quit_btn.clicked.connect(QApplication.instance().quit)

        quit_btn.setStyleSheet("QPushButton { color: white; "
                               "background-color : red; "
                               "border-color : red; "
                               "border-width: 2px}")

        h_layout.addWidget(quit_btn)

        v_layout.addLayout(h_layout)

        # define Qt GUI elements
        # add a frame for the LCD numbers
        self.lcd_frame = QFrame()
        self.lcd_frame.setFrameShape(1)
        lcd_layout = QGridLayout()
        self.lcd_frame.setLayout(lcd_layout)

        # RAW reading from DDU
        self.raw_ddu = QLCDNumber()
        self.raw_ddu.setDigitCount(7)
        self.raw_ddu.setFrameShape(0)
        self.raw_ddu.setSmallDecimalPoint(True)
        self.raw_ddu.setFixedHeight(50)
        self.raw_ddu.display("{0:.3f}".format(0))
        lcd_layout.addWidget(self.raw_ddu, 0, 3, 2, 3)

        self.offset_ddu = QLCDNumber()
        self.offset_ddu.setDigitCount(7)
        self.offset_ddu.setFixedHeight(150)
        self.offset_ddu.display("{0:.3f}".format(-10))
        self.offset_ddu.setFrameShape(0)
        lcd_layout.addWidget(self.offset_ddu, 2, 0, 5, 6)
        v_layout.addWidget(self.lcd_frame)

        self.plot_widget.setLayout(v_layout)

        # Populate control panel items
        for port in serial.tools.list_ports.comports():
            self.comboBox_com_port.addItem(port.device)
        self.comboBox_com_port.addItem("cbsdk playback")

        # Connect signals & slots
        self.pushButton_open.clicked.connect(self.on_open_clicked)
        self.comboBox_com_port.currentIndexChanged.connect(
            self.on_comboBox_com_port_changed)
Ejemplo n.º 29
0
import sys, time
from qtpy.QtWidgets import QApplication, QWidget, QLabel, QComboBox

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QWidget()
    b = QLabel(w)
    b.setText("Hello World!")

    w.setGeometry(500, 500, 700, 750)
    b.move(550, 520)
    w.setWindowTitle("PyQt")
    w.show()
    ql = QComboBox(w)
    ql.addItem("sdada")
    ql.addItem("sdada")
    ql.addItem("sdada")
    ql.show()
    sys.exit(app.exec_())

    sys.exit(app.exec_())
Ejemplo n.º 30
0
    def _setupUi(self):
        # timeplot
        self.title_plot = QLabel('Total Dose Rate (γ + n) [µSv/h]',
                                 self,
                                 alignment=Qt.AlignCenter)
        self.title_plot.setStyleSheet(
            'QLabel{font-size: 52pt; font-weight: bold;}')

        timespan = 30 * 60  # [s]
        self.timeplot = SiriusTimePlot(parent=self,
                                       background='w',
                                       show_tooltip=True)
        self.timeplot.timeSpan = timespan
        self.timeplot.bufferSize = 4 * 60 * 60 * 10
        self.timeplot.autoRangeY = True
        self.timeplot.minYRange = 0.0
        self.timeplot.showXGrid = True
        self.timeplot.showYGrid = True
        self.timeplot.maxRedrawRate = 2
        color = QColor(30, 30, 30)
        self.timeplot.plotItem.getAxis('bottom').setPen(color)
        self.timeplot.plotItem.getAxis('bottom').setGrid(255)
        self.timeplot.plotItem.getAxis('bottom').setTextPen(color)
        self.timeplot.plotItem.getAxis('left').setPen(color)
        self.timeplot.plotItem.getAxis('left').setGrid(255)
        self.timeplot.plotItem.getAxis('left').setTextPen(color)
        self.timeplot.setLabel('left', text='Dose Rate [µSv/h]')
        self.timeplot.setObjectName('timeplot')
        self.timeplot.setStyleSheet(
            '#timeplot{min-width:12em; min-height: 10em;}')
        self.timeplot.bufferReset.connect(self._fill_refline)
        self.timeplot.timeSpanChanged.connect(self._fill_refline)
        t_end = Time.now()
        t_init = t_end - timespan

        widplot = QWidget()
        widplot.setSizePolicy(QSzPol.Expanding, QSzPol.Expanding)
        layplot = QGridLayout(widplot)
        layplot.setHorizontalSpacing(10)
        layplot.setVerticalSpacing(10)
        layplot.addWidget(self.title_plot, 0, 0)
        layplot.addWidget(self.timeplot, 1, 0)

        # panel
        self.title_grid = QLabel('Integrated Dose in 4h [µSv]',
                                 self,
                                 alignment=Qt.AlignCenter)
        self.title_grid.setStyleSheet(
            'QLabel{font-size: 52pt; font-weight: bold;}')
        self.lb_warn = QLabel('Restart\nwindow')
        self.lb_warn.setStyleSheet('color: red; border: 0.1em solid red;')
        self.lb_warn.setVisible(False)
        laytitle = QHBoxLayout()
        laytitle.addWidget(self.title_grid, 6)
        laytitle.addWidget(self.lb_warn, 1)

        widgrid = QWidget()
        widgrid.setSizePolicy(QSzPol.Maximum, QSzPol.Expanding)
        self.pannel = widgrid
        laygrid = QGridLayout(widgrid)
        laygrid.setHorizontalSpacing(10)
        laygrid.setVerticalSpacing(10)
        colnum = 3
        laygrid.addLayout(laytitle, 0, 0, 1, colnum)

        for i, mon in enumerate(self._mon_order):
            local = self._mon2locv[mon]
            color = self._colors[i]
            pvname = self._prefix + ('-' if self._prefix else '')
            pvname += 'RAD:' + mon + ':TotalDoseRate'
            row, col = i // colnum + 1, i % colnum

            coloro = QColor(color) if isinstance(color, str) \
                else QColor(*color)
            self.timeplot.addYChannel(pvname,
                                      name=pvname,
                                      color=coloro,
                                      lineWidth=6)
            curve = self.timeplot.curveAtIndex(-1)
            self._curves[mon] = curve
            self.timeplot.fill_curve_with_archdata(self._curves[mon],
                                                   pvname,
                                                   t_init=t_init.get_iso8601(),
                                                   t_end=t_end.get_iso8601())

            cbx = QCheckBox(self)
            cbx.setChecked(True)
            cbx.stateChanged.connect(curve.setVisible)
            cbx.setSizePolicy(QSzPol.Maximum, QSzPol.Maximum)
            pal = cbx.palette()
            pal.setColor(QPalette.Base, coloro)
            pal.setColor(QPalette.Text, Qt.white)
            cbx.setPalette(pal)
            self._cb_show[mon] = cbx

            lbl = PyDMLabel(self, pvname + ':Dose')
            lbl.alarmSensitiveBorder = False
            lbl.setStyleSheet('QLabel{font-size: 52pt;}')
            lbl.showUnits = True
            self._pvs_labels[mon] = lbl

            frame = SiriusAlarmFrame(self, pvname + ':Dose')
            frame.add_widget(cbx)
            frame.add_widget(lbl)

            desc = QLabel(local, self, alignment=Qt.AlignCenter)
            desc.setSizePolicy(QSzPol.Preferred, QSzPol.Maximum)
            desc.setStyleSheet(
                'QLabel{background-color:black; color:white;font-size:26pt;}')
            self._desc_labels[mon] = desc

            wid = QWidget()
            wid.setObjectName('wid')
            wid.setStyleSheet('#wid{border: 1px solid black; '
                              'min-width: 7.5em; max-width: 7.5em;}')
            widlay = QVBoxLayout(wid)
            widlay.setSpacing(0)
            widlay.setContentsMargins(1, 1, 1, 1)
            widlay.addWidget(frame)
            widlay.addWidget(desc)

            laygrid.addWidget(wid, row, col)

        laygrid.setColumnStretch(0, 1)
        laygrid.setColumnStretch(1, 1)
        laygrid.setColumnStretch(2, 1)

        self.timeplot.addYChannel('Reference',
                                  color='black',
                                  lineWidth=6,
                                  lineStyle=Qt.DashLine)
        self.refline = self.timeplot.curveAtIndex(-1)
        self._fill_refline()

        lay = QGridLayout(self)
        lay.setSpacing(20)
        lay.addWidget(widplot, 0, 0)
        lay.addWidget(widgrid, 0, 1)

        self.setStyleSheet("""
            PyDMLabel{
                qproperty-alignment: AlignCenter; font-weight: bold;
            }
            QCheckBox::indicator {
                width: 0.7em;
                height: 0.7em;
            }""")

        self._timer = QTimer()
        self._timer.timeout.connect(self._update_graph_ref)
        self._timer.setInterval(2000)
        self._timer.start()