def _device(self, node, channel): attrs = ['name', 'path', 'description', 'hidden', 'groups'] msgBox = QDialog() msgBox.setWindowTitle("Device Information For {}".format(node.name)) msgBox.setMinimumWidth(400) vb = QVBoxLayout() msgBox.setLayout(vb) fl = QFormLayout() fl.setRowWrapPolicy(QFormLayout.DontWrapRows) fl.setFormAlignment(Qt.AlignHCenter | Qt.AlignTop) fl.setLabelAlignment(Qt.AlignRight) vb.addLayout(fl) pb = QPushButton('Close') pb.pressed.connect(msgBox.close) vb.addWidget(pb) for a in attrs: le = QLineEdit() le.setReadOnly(True) le.setText(str(getattr(node,a))) fl.addRow(a,le) le = QLineEdit() le.setReadOnly(True) le.setText(channel.address) fl.addRow('PyDM Path',le) msgBox.exec()
def _specViewLayout(self): dev = self.device.substitute(dev='TuneProc') # Mode lbl_mode = QLabel('Mode', self) self.cb_mode = PyDMEnumComboBox(self, dev.substitute(propty='SpecMode-Sel')) self.lb_mode = PyDMLabel(self, dev.substitute(propty='SpecMode-Sts')) hbox_mode = QHBoxLayout() hbox_mode.addWidget(self.cb_mode) hbox_mode.addWidget(self.lb_mode) # Time window lbl_timewdw = QLabel('Time Window [ms]', self) self.le_timewdw = PyDMLineEdit(self, dev.substitute(propty='SpecTime-SP')) self.le_timewdw.precisionFromPV = True self.lb_timewdw = PyDMLabel(self, dev.substitute(propty='SpecTime-RB')) hbox_timewdw = QHBoxLayout() hbox_timewdw.addWidget(self.le_timewdw) hbox_timewdw.addWidget(self.lb_timewdw) lay = QFormLayout() lay.setLabelAlignment(Qt.AlignRight) lay.setFormAlignment(Qt.AlignCenter) lay.addRow(lbl_mode, hbox_mode) lay.addRow(lbl_timewdw, hbox_timewdw) return lay
def setup_mainwidget(self): lblRunFile = QLabel('Run File') self.lineRunFile = QLineEdit() lblOpenFile = QLabel('Open File') self.lineOpenFile = QLineEdit() fbox = QFormLayout() fbox.addRow(lblRunFile, self.lineRunFile) fbox.addRow(lblOpenFile, self.lineOpenFile) text = "# myprint(self.database) \n" +\ "# myprint(self.treebase)" self.code_view = QPlainTextEdit(text, self) # font = QFont() # font.setFamily(_fromUtf8("FreeMono")) # self.code_view.setFont(font) vbox = QVBoxLayout() vbox.addLayout(fbox) vbox.addWidget(self.code_view) self.mainwidget = QWidget(self) self.mainwidget.setLayout(vbox) # connect syntax highlighter self.pyhigh = PythonHighlighter(self.code_view.document()) self.code_view.textChanged.connect(self.highlightWhileTyping)
def _setupConfigurationWidget(self): statebutton_Test = PyDMStateButton( self, self.dcct_prefix.substitute(propty='Test-Sel')) statebutton_Test.shape = 1 statebutton_Test.setStyleSheet('min-width:6em; max-width:6em;') label_Test = PyDMLabel(self, self.dcct_prefix.substitute(propty='Test-Sts')) hlay_test = QHBoxLayout() hlay_test.addWidget(statebutton_Test) hlay_test.addWidget(label_Test) self.bt_dl = PyDMPushButton( parent=self, pressValue=1, icon=qta.icon('fa5s.sync'), init_channel=self.dcct_prefix.substitute(propty='Download-Cmd')) self.bt_dl.setObjectName('bt_dl') self.bt_dl.setStyleSheet( '#bt_dl{min-width:25px; max-width:25px; icon-size:20px;}') gbox_test = QGroupBox('Configurations') lay = QFormLayout(gbox_test) lay.setLabelAlignment(Qt.AlignRight) lay.setFormAlignment(Qt.AlignCenter) lay.addRow('Enable test current: ', hlay_test) lay.addRow('Download Configurations: ', self.bt_dl) return gbox_test
def setupUi(self, lista, query): formLayout = QFormLayout() groupBox = QGroupBox(f"Resultado de la búsqueda: {query}") labelLis = [] comboList = [] for i in range(len(lista)): f = open(lista[i]['name'], 'r', encoding='utf-8') jsonData = json.loads(f.read()) f.close() labelLis.append( QLabel( f'{jsonData["title"]} --- {round(float(lista[i]["distance"])*100, 2)}% --- {jsonData["categoria"]}' )) buttonOpen = QPushButton("Abrir noticia") buttonOpen.clicked.connect(self.make_openFile(lista[i]["name"])) comboList.append(buttonOpen) formLayout.addRow(labelLis[i], comboList[i]) groupBox.setLayout(formLayout) scroll = QScrollArea(self) scroll.setWidget(groupBox) scroll.setWidgetResizable(True) scroll.setMinimumHeight(600) scroll.setMinimumWidth(1200) layout = QVBoxLayout(self) layout.addWidget(scroll) self.setWindowTitle("Noticias") self.resize(1200, 600) self.show() self.exec_()
class AttributesWidget(QWidget): """Shows info about device.""" def __init__(self, bot, parent): super(AttributesWidget, self).__init__(parent) self.bot = bot self.widgets = [] self.widget_layout = QHBoxLayout(self) self.setLayout(self.widget_layout) # widget with labels self.info_widget = QWidget(self) self.info_widget_layout = QFormLayout(self.info_widget) self.info_widget.setLayout(self.info_widget_layout) self.widget_layout.addWidget(self.info_widget) # widget with actions - remote shell, powershell, remote screen... self.actions_widget = QWidget(self) self.actions_widget_layout = QFormLayout(self.actions_widget) self.actions_widget.setLayout(self.actions_widget_layout) @Slot(Bot) def update_attributes(self, bot): # update labels with info about bot self.widgets.clear() for var, val in vars(bot).items(): label = QLabel(self.info_widget) label.setText(" ".join(var.split("_")).capitalize()) field = QLabel(self.info_widget) field.setText(str(val)) self.widgets.append({"label": label, "field": field}) self.info_widget_layout.addRow(label, field)
def get_orbitdetails_widget(self, parent): """.""" grp_bx = QWidget(parent) grp_bx.setLayout(QVBoxLayout()) lbl = CALabel('OfflineOrb:', grp_bx) combo = OfflineOrbControl( grp_bx, self.device, self.ctrls, prefix=self.prefix, acc=self.acc) rules = ( '[{"name": "EnblRule", "property": "Visible", ' + '"expression": "not ch[0]", "channels": [{"channel": "' + self.devpref.substitute(propty='SOFBMode-Sts') + '", "trigger": true}]}]') combo.rules = rules lbl.rules = rules fbl = QFormLayout() grp_bx.layout().addLayout(fbl) fbl.addRow(lbl, combo) grp_bx.layout().addStretch() hbl = QHBoxLayout() grp_bx.layout().addLayout(hbl) fbl = QFormLayout() hbl.addItem(fbl) lbl = QLabel('Orbit [Hz]', grp_bx, alignment=Qt.AlignCenter) wid = self.create_pair(grp_bx, 'OrbAcqRate') fbl.addRow(lbl, wid) lbl = QLabel('Kicks [Hz]', grp_bx, alignment=Qt.AlignCenter) wid = self.create_pair(grp_bx, 'KickAcqRate') fbl.addRow(lbl, wid) wid = QWidget(grp_bx) wid.setStyleSheet('max-width:6em;') hbl.addWidget(wid) vbl = QVBoxLayout(wid) vbl.setContentsMargins(0, 0, 0, 0) lab = QLabel('Sync. Injection', wid, alignment=Qt.AlignCenter) vbl.addWidget(lab) hbl = QHBoxLayout() hbl.setContentsMargins(0, 0, 0, 0) vbl.addItem(hbl) spt = PyDMStateButton( wid, self.devpref.substitute(propty='SyncWithInjection-Sel')) rdb = SiriusLedState( wid, self.devpref.substitute(propty='SyncWithInjection-Sts')) hbl.addWidget(spt) hbl.addWidget(rdb) grp_bx.layout().addStretch() fbl = QFormLayout() grp_bx.layout().addLayout(fbl) lbl = QLabel('Smooth Method', grp_bx, alignment=Qt.AlignCenter) wid = self.create_pair_sel(grp_bx, 'SmoothMethod') fbl.addRow(lbl, wid) if self.isring: lbl = QLabel('Extend Ring', grp_bx, alignment=Qt.AlignCenter) wid = self.create_pair(grp_bx, 'RingSize') fbl.addRow(lbl, wid) return grp_bx
def __init__(self, parent: MainWindow, plotter: pv.Plotter, show: bool = True) -> None: """Initialize the scaling dialog.""" super(ScaleAxesDialog, self).__init__(parent) self.setGeometry(300, 300, 50, 50) self.setMinimumWidth(500) self.signal_close.connect(self.close) self.plotter = plotter self.plotter.app_window.signal_close.connect(self.close) self.x_slider_group = RangeGroup(parent, self.update_scale, value=plotter.scale[0]) self.y_slider_group = RangeGroup(parent, self.update_scale, value=plotter.scale[1]) self.z_slider_group = RangeGroup(parent, self.update_scale, value=plotter.scale[2]) form_layout = QFormLayout(self) form_layout.addRow("X Scale", self.x_slider_group) form_layout.addRow("Y Scale", self.y_slider_group) form_layout.addRow("Z Scale", self.z_slider_group) self.setLayout(form_layout) if show: # pragma: no cover self.show()
def _get_size_widget(self, parent): gb_size = QGroupBox('Size [px / mm]', parent) fl_size = QFormLayout(gb_size) wid = QWidget(gb_size) wid.setLayout(QHBoxLayout()) xave = SiriusLabel(wid, init_channel=self._dev+':BeamSizeX-Mon') xavemm = SiriusLabel(wid, init_channel=self._dev+':BeamSizemmX-Mon') xave.setAlignment(Qt.AlignVCenter | Qt.AlignRight) xavemm.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) sep = QLabel('/', wid) sep.setStyleSheet('max-width:0.7em;') wid.layout().addWidget(xave) wid.layout().addWidget(sep) wid.layout().addWidget(xavemm) fl_size.addRow(QLabel( 'X =', gb_size, alignment=Qt.AlignBottom), wid) wid = QWidget(gb_size) wid.setLayout(QHBoxLayout()) yave = SiriusLabel(wid, init_channel=self._dev+':BeamSizeY-Mon') yavemm = SiriusLabel(wid, init_channel=self._dev+':BeamSizemmY-Mon') yave.setAlignment(Qt.AlignVCenter | Qt.AlignRight) yavemm.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) sep = QLabel('/', wid) sep.setStyleSheet('max-width:0.7em;') wid.layout().addWidget(yave) wid.layout().addWidget(sep) wid.layout().addWidget(yavemm) fl_size.addRow(QLabel( 'Y =', gb_size, alignment=Qt.AlignBottom), wid) return gb_size
def create_controls(self): self.setWindowTitle(tr(self.plugin.name)) vbox = QVBoxLayout() form = QFormLayout() for Name, (enabled, url) in self.packages.items(): name = Name.lower() cbo = QComboBox() if enabled: branches = get_branches(name, url) for n, b in branches.items(): cbo.addItem(n, b) if not check_git_repo(name): cbo.insertItem(0, "<Select to change>", None) cbo.setCurrentIndex(0) self._prev_indices[cbo] = 0 cbo.currentIndexChanged.connect( partial(self._cbo_changed, cbo)) else: cbo.setEditText("<git repository>") cbo.setToolTip(tr( "This is installed in a git repository but we're set to " "not use git.")) cbo.setEnabled(enabled) form.addRow(Name + ':', cbo) vbox.addLayout(form) vbox.addWidget(QLabel(tr( "You should restart the application if you make any changes!"))) btns = QDialogButtonBox(QDialogButtonBox.Ok, Qt.Horizontal, self) btns.accepted.connect(self.accept) vbox.addWidget(btns) self.setLayout(vbox)
def _command(self, node, channel): attrs = ['name', 'path', 'description', 'hidden', 'groups', 'enum', 'typeStr', 'disp'] if node.isinstance(pyrogue.RemoteCommand): attrs += ['offset', 'bitSize', 'bitOffset', 'varBytes'] msgBox = QDialog() msgBox.setWindowTitle("Command Information For {}".format(node.name)) msgBox.setMinimumWidth(400) vb = QVBoxLayout() msgBox.setLayout(vb) fl = QFormLayout() fl.setRowWrapPolicy(QFormLayout.DontWrapRows) fl.setFormAlignment(Qt.AlignHCenter | Qt.AlignTop) fl.setLabelAlignment(Qt.AlignRight) vb.addLayout(fl) pb = QPushButton('Close') pb.pressed.connect(msgBox.close) vb.addWidget(pb) for a in attrs: le = QLineEdit() le.setReadOnly(True) le.setText(str(getattr(node,a))) fl.addRow(a,le) le = QLineEdit() le.setReadOnly(True) le.setText(channel.address) fl.addRow('PyDM Path',le) msgBox.exec()
class UiUnitChangeDialog(QDialog): def __init__(self, parent=None): super(UiUnitChangeDialog, self).__init__(parent) # Dialog settings self.setWindowTitle("Change Plot Units") self.layout_vertical = QVBoxLayout(self) self.form_layout = QFormLayout() self.layout_vertical.addLayout(self.form_layout) # Flux unit self.label_flux_unit = QLabel(self) self.line_edit_flux_unit = QLineEdit(self) self.label_flux_unit.setText("Flux Unit") self.form_layout.addRow(self.label_flux_unit, self.line_edit_flux_unit) # Dispersion unit self.label_disp_unit = QLabel(self) self.line_edit_disp_unit = QLineEdit(self) self.label_disp_unit.setText("Dispersion Unit") self.form_layout.addRow(self.label_disp_unit, self.line_edit_disp_unit) self.button_box = QDialogButtonBox(self) self.button_box.setOrientation(Qt.Horizontal) self.button_box.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.layout_vertical.addWidget(self.button_box) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject)
def _setupStrengthWidget(self): scrollarea = QScrollArea() self.nconfig_data = QWidget() flay_configdata = QFormLayout() psnames = self._get_PSNames() self._map_psnames2wigdets = dict() for ps in psnames: ps = SiriusPVName(ps) if ps in ramp.BoosterRamp.PSNAME_DIPOLES: ps_value = QLabel(str(self.norm_config[ps])+' GeV', self) flay_configdata.addRow(QLabel(ps + ': ', self), ps_value) else: ps_value = QDoubleSpinBoxPlus(self.nconfig_data) ps_value.setDecimals(6) ps_value.setMinimum(-10000) ps_value.setMaximum(10000) ps_value.setValue(self.norm_config[ps]) ps_value.valueChanged.connect(self._handleStrenghtsSet) if ps.dev in {'QD', 'QF', 'QS'}: unit_txt = '1/m' elif ps.dev in {'SD', 'SF'}: unit_txt = '1/m²' else: unit_txt = 'urad' label_unit = QLabel(unit_txt, self) label_unit.setStyleSheet("min-width:2.5em; max-width:2.5em;") hb = QHBoxLayout() hb.addWidget(ps_value) hb.addWidget(label_unit) flay_configdata.addRow(QLabel(ps + ': ', self), hb) ps_value.setObjectName(ps) ps_value.setStyleSheet("min-height:1.29em; max-height:1.29em;") self._map_psnames2wigdets[ps] = ps_value self.nconfig_data.setObjectName('data') self.nconfig_data.setStyleSheet(""" #data{background-color: transparent;}""") self.nconfig_data.setLayout(flay_configdata) scrollarea.setWidget(self.nconfig_data) self.cb_checklims = QCheckBox('Set limits according to energy', self) self.cb_checklims.setChecked(False) self.cb_checklims.stateChanged.connect(self._handleStrengtsLimits) self.bt_graph = QPushButton(qta.icon('mdi.chart-line'), '', self) self.bt_graph.clicked.connect(self._show_kicks_graph) gbox = QGroupBox() gbox.setObjectName('strengths') gbox.setStyleSheet('#strengths{min-width:20em;}') glay = QGridLayout() glay.addWidget(scrollarea, 0, 0, 1, 2) glay.addWidget(self.cb_checklims, 1, 0, alignment=Qt.AlignLeft) glay.addWidget(self.bt_graph, 1, 1, alignment=Qt.AlignRight) gbox.setLayout(glay) return gbox
def __init__(self, parent=None): super().__init__(parent=parent) self.setTitle("Select peak") layout = QFormLayout() layout.setFieldGrowthPolicy(0) self.peak_select = QComboBox() layout.addRow(QLabel("Peak"), self.peak_select) self.setLayout(layout)
def _setup_status_wid(self): status_layout = QFormLayout(self.status_wid) status_layout.setHorizontalSpacing(20) status_layout.setVerticalSpacing(20) for bit, label in enumerate(_cstime.Const.HLTrigStatusLabels): led = SiriusLedAlert(self, self.get_pvname('Status-Mon'), bit) lab = QLabel(label, self) status_layout.addRow(led, lab)
def create_controls(self): """ Create UI controls. """ vbox = QVBoxLayout() form = QFormLayout() self.num_angle = QDoubleSpinBox() self.num_angle.setValue(0.0) self.num_angle.setMinimum(-360) self.num_angle.setMaximum(360) form.addRow(tr("Angle:"), self.num_angle) vbox.addLayout(form) self.gbo_preview = QGroupBox(tr("Preview")) self.gbo_preview.setCheckable(True) self.gbo_preview.setChecked(False) gbo_vbox = QVBoxLayout() self.chk_grid = QCheckBox(tr("Grid")) self.chk_grid.setChecked(False) self.num_grid = QSpinBox() self.num_grid.setValue(4) self.num_grid.setMinimum(1) self.num_grid.setEnabled(False) self.chk_grid.toggled[bool].connect(self.num_grid.setEnabled) gbo_vbox.addWidget(self.chk_grid) gbo_vbox.addWidget(self.num_grid) self.gbo_preview.setLayout(gbo_vbox) vbox.addWidget(self.gbo_preview) self.gbo_preview.toggled[bool].connect(self.set_preview) self.gbo_output = QGroupBox(tr("Output")) self.opt_new = QRadioButton(tr("New signal")) self.opt_replace = QRadioButton(tr("In place")) self.opt_new.setChecked(True) gbo_vbox2 = QVBoxLayout() gbo_vbox2.addWidget(self.opt_new) gbo_vbox2.addWidget(self.opt_replace) self.gbo_output.setLayout(gbo_vbox2) vbox.addWidget(self.gbo_output) self.chk_reshape = QCheckBox(tr("Resize to fit")) self.chk_reshape.setChecked(False) vbox.addWidget(self.chk_reshape) self.btn_ok = QPushButton(tr("&OK")) self.btn_ok.setDefault(True) self.btn_ok.clicked.connect(self.accept) self.btn_cancel = QPushButton(tr("&Cancel")) self.btn_cancel.clicked.connect(self.reject) hbox = QHBoxLayout() hbox.addWidget(self.btn_ok) hbox.addWidget(self.btn_cancel) vbox.addLayout(hbox) vbox.addStretch(1) self.setLayout(vbox)
def _create_settings_widgets(self, settings): """ Create a widget for a settings instance, containing label/editor pairs for each setting in the current level of the passed QSettings instance. The key of the setting is used as the label, but it's capitalized and underscores are replaced by spaces. """ wrap = QWidget(self) form = QFormLayout() hint_lookup = Settings() for k in settings.allKeys(): if k.startswith("_"): continue # Ignore hidden keys v = settings.value(k) # Read value label = k.capitalize().replace('_', ' ') abs_key = settings.group() + '/' + k self._initial_values[abs_key] = v # Store initial value hints = hint_lookup.get_enum_hint(abs_key) # Check for enum hints # Create a fitting editor widget based on value type: if hints is not None: w = QComboBox() w.addItems(hints) w.setEditable(True) w.setEditText(v) w.editTextChanged.connect(partial(self._on_setting_changed, abs_key, w)) elif isinstance(v, str): if v.lower() in ('true', 'false'): w = QCheckBox() w.setChecked(v.lower() == 'true') w.toggled.connect(partial(self._on_setting_changed, abs_key, w)) else: w = QLineEdit(v) w.textChanged.connect(partial(self._on_setting_changed, abs_key, w)) elif isinstance(v, int): w = QSpinBox() w.setRange(np.iinfo(np.int32).min, np.iinfo(np.int32).max) w.setValue(v) w.valueChanged.connect(partial(self._on_setting_changed, abs_key, w)) elif isinstance(v, float): w = QDoubleSpinBox() w.setRange(np.finfo(np.float32).min, np.finfo(np.float32).max) w.setValue(v) w.valueChanged.connect(partial(self._on_setting_changed, abs_key, w)) else: w = QLineEdit(str(v)) w.textChanged.connect(partial(self._on_setting_changed, abs_key, w)) self._lut[abs_key] = w form.addRow(label, w) wrap.setLayout(form) return wrap
class FrameWidget(QWidget): """Widget for interatviely making animations using the napari viewer.""" def __init__(self, parent=None): super().__init__(parent=parent) self.animation = self.parentWidget().animation self._layout = QFormLayout(parent=self) self._init_steps() self._init_ease() self._add_callbacks() def _init_steps(self): self.stepsSpinBox = QSpinBox() self.stepsSpinBox.setRange(1, 100000) self.stepsSpinBox.setValue(15) self._layout.addRow("Steps", self.stepsSpinBox) def _init_ease(self): self.easeComboBox = QComboBox() self.easeComboBox.addItems([e.name.lower() for e in Easing]) index = self.easeComboBox.findText("linear", Qt.MatchFixedString) self.easeComboBox.setCurrentIndex(index) self._layout.addRow("Ease", self.easeComboBox) def get_easing_func(self): easing_name = str(self.easeComboBox.currentText()) return Easing[easing_name.upper()] def update_from_animation(self): """update state of self to reflect animation state at current key frame""" self._update_steps_spin_box() self._update_ease_combo_box() def _update_steps_spin_box(self): """update state of steps spin box to reflect animation state at current key frame""" self.stepsSpinBox.setValue(self.animation.current_key_frame.steps) def _update_animation_steps(self, event): """update state of 'steps' at current key-frame to reflect GUI state""" self.animation.current_key_frame.steps = self.stepsSpinBox.value() def _update_ease_combo_box(self): """update state of ease combo box to reflect animation state at current key frame""" ease = self.animation.current_key_frame.ease name = _easing_func_to_name(ease) index = self.easeComboBox.findText(name, Qt.MatchFixedString) self.easeComboBox.setCurrentIndex(index) def _update_animation_ease(self, event): """update state of 'ease' at current key-frame to reflect GUI state""" self.animation.current_key_frame.ease = self.get_easing_func() def _add_callbacks(self): """add callbacks to steps and ease widgets""" self.stepsSpinBox.valueChanged.connect(self._update_animation_steps) self.easeComboBox.currentIndexChanged.connect( self._update_animation_ease)
def _create_settings_widgets(self, settings): """ Create a widget for a settings instance, containing label/editor pairs for each setting in the current level of the passed QSettings instance. The key of the setting is used as the label, but it's capitalized and underscores are replaced by spaces. """ wrap = QWidget(self) form = QFormLayout() hint_lookup = Settings() for k in settings.allKeys(): if k.startswith("_"): continue # Ignore hidden keys v = settings.value(k) # Read value label = k.capitalize().replace('_', ' ') abs_key = settings.group() + '/' + k self._initial_values[abs_key] = v # Store initial value hints = hint_lookup.get_enum_hint(abs_key) # Check for enum hints # Create a fitting editor widget based on value type: if hints is not None: w = QComboBox() w.addItems(hints) w.setEditable(True) w.setEditText(v) w.editTextChanged.connect( partial(self._on_setting_changed, abs_key, w)) elif isinstance(v, str): if v.lower() in ('true', 'false'): w = QCheckBox() w.setChecked(v.lower() == 'true') w.toggled.connect( partial(self._on_setting_changed, abs_key, w)) else: w = QLineEdit(v) w.textChanged.connect( partial(self._on_setting_changed, abs_key, w)) elif isinstance(v, int): w = QSpinBox() w.setRange(np.iinfo(np.int32).min, np.iinfo(np.int32).max) w.setValue(v) w.valueChanged.connect( partial(self._on_setting_changed, abs_key, w)) elif isinstance(v, float): w = QDoubleSpinBox() w.setRange(np.finfo(np.float32).min, np.finfo(np.float32).max) w.setValue(v) w.valueChanged.connect( partial(self._on_setting_changed, abs_key, w)) else: w = QLineEdit(str(v)) w.textChanged.connect( partial(self._on_setting_changed, abs_key, w)) self._lut[abs_key] = w form.addRow(label, w) wrap.setLayout(form) return wrap
def __init__(self, properties: BaseSerializableClass, parent=None): super().__init__(parent) self.properties = properties self.widget_list = [] layout = QFormLayout() for key, val in properties.__annotations__.items(): name = key.replace("_", " ").capitalize() widget = self.get_widget(val) layout.addRow(name, widget) self.widget_list.append((key, widget)) self.setLayout(layout)
class FFTConfig(BaseWidget): def __init__(self, parent=None, prefix='', bpm='', data_prefix='ACQ', position=True): super().__init__(parent=parent, prefix=prefix, bpm=bpm, data_prefix=data_prefix) self.position = False self.setupui() def setupui(self): self.fl = QFormLayout(self) self.fl.setLabelAlignment(Qt.AlignVCenter) self._add_row('FFTData-RB.SPAN', 'Number of points') self._add_row('FFTData-RB.INDX', 'Start Index') self._add_row('FFTData-RB.MXIX', 'Maximum Index') self._add_row('FFTData-RB.WIND', 'Window type', enum=True) self._add_row('FFTData-RB.CDIR', 'Direction', enum=True) self._add_row('FFTData-RB.ASUB', 'Subtract Avg', enum=True) pb = PyDMPushButton(self, label='Calculate', pressValue=1) self._make_connections(pb, 'FFTData-RB.PROC') self.fl.addRow(pb) def _add_row(self, pv, label, enum=False): CLASS = PyDMEnumComboBox if enum else SiriusSpinbox wid = CLASS(self) self._make_connections(wid, pv) if not enum: wid.showStepExponent = False lab = QLabel(label) lab.setStyleSheet("""min-width:8em;""") self.fl.addRow(lab, wid) def _make_connections(self, wid, pv): if self.position: names = ('X', 'Y', 'Q', 'SUM') else: names = ('A', 'B', 'C', 'D') wid.channel = self.get_pvname(names[0] + pv) for name in names[1:]: chan = SiriusConnectionSignal(self.get_pvname(name + pv)) wid.send_value_signal[int].connect( chan.send_value_signal[int].emit) wid.send_value_signal[float].connect( chan.send_value_signal[float].emit) chan.new_value_signal[int].connect(wid.channelValueChanged) chan.new_value_signal[float].connect(wid.channelValueChanged) self._chans.append(chan)
def __init__(self): SimulationConfigPanel.__init__(self, EnsembleExperiment) layout = QFormLayout() self._case_selector = CaseSelector() layout.addRow("Current case:", self._case_selector) run_path_label = QLabel("<b>%s</b>" % getRunPath()) addHelpToWidget(run_path_label, "config/simulation/runpath") layout.addRow("Runpath:", run_path_label) number_of_realizations_label = QLabel("<b>%d</b>" % getRealizationCount()) addHelpToWidget(number_of_realizations_label, "config/ensemble/num_realizations") layout.addRow(QLabel("Number of realizations:"), number_of_realizations_label) self._active_realizations_field = StringBox( ActiveRealizationsModel(), "config/simulation/active_realizations", ) self._active_realizations_field.setValidator( RangeStringArgument(getRealizationCount()), ) layout.addRow("Active realizations", self._active_realizations_field) self.setLayout(layout) self._active_realizations_field.getValidationSupport( ).validationChanged.connect(self.simulationConfigurationChanged) self._case_selector.currentIndexChanged.connect( self._realizations_from_fs) self._realizations_from_fs() # update with the current case
def __init__(self, parent=None, emphasized=False): super().__init__(parent) self.setProperty('emphasized', emphasized) self.tab1 = QWidget() self.tab1.setProperty('emphasized', emphasized) self.tab2 = QWidget() self.tab2.setProperty('emphasized', emphasized) self.addTab(self.tab1, "Tab 1") self.addTab(self.tab2, "Tab 2") layout = QFormLayout() layout.addRow("Height", QSpinBox()) layout.addRow("Weight", QDoubleSpinBox()) self.setTabText(0, "Tab 1") self.tab1.setLayout(layout) layout2 = QFormLayout() sex = QHBoxLayout() sex.addWidget(QRadioButton("Male")) sex.addWidget(QRadioButton("Female")) layout2.addRow(QLabel("Sex"), sex) layout2.addRow("Date of Birth", QLineEdit()) self.setTabText(1, "Tab 2") self.tab2.setLayout(layout2) self.setWindowTitle("tab demo")
def __init__(self, parent=None): QWidget.__init__(self) self.tfPlot = TransferFunctionPlot() self.modelCombo = QComboBox() self.modelCombo.addItems(AvailableModels) self.quantityCombo = QComboBox() self.quantityCombo.addItems(['Impedance', 'Admittance']) self.fMinSb = QDoubleSpinBox() self.fMinSb.setRange(0.1, 1E6) self.fMaxSb = QDoubleSpinBox() self.fMaxSb.setRange(10, 1E6) self.fMinSb.setKeyboardTracking(False) self.fMaxSb.setKeyboardTracking(False) self.fMinSb.valueChanged.connect(self.fMinSb.setMinimum) self.fMaxSb.valueChanged.connect(self.fMaxSb.setMaximum) self.fMinSb.setValue(1) self.fMaxSb.setValue(250E3) self.shuntSb = QDoubleSpinBox() self.shuntSb.setDecimals(4) self.shuntSb.setKeyboardTracking(False) self.shuntSb.setRange(0.010, 10) self.shuntSb.setSuffix(u' m\u03A9') self.shuntSb.setValue(0.257) l = QFormLayout() l.addRow('Model', self.modelCombo) l.addRow('Quantity', self.quantityCombo) l.addRow('f (min)', self.fMinSb) l.addRow('f (max)', self.fMaxSb) l.addRow('Shunt resistance', self.shuntSb) self.setLayout(l)
def _configLayout(self): self.bt_rst = PyDMPushButton( parent=self, init_channel=self.device.substitute(propty='Rst-Cmd'), pressValue=1, icon=qta.icon('fa5s.sync')) self.bt_rst.setObjectName('bt_rst') self.bt_rst.setStyleSheet( '#bt_rst{min-width:25px; max-width:25px; icon-size:20px;}') lay = QFormLayout() lay.setLabelAlignment(Qt.AlignRight) lay.setFormAlignment(Qt.AlignCenter) lay.addRow('Restore Default', self.bt_rst) return lay
def creategroupbox(self): wid = QGroupBox('Detailed Status', self) fbl = QFormLayout(wid) if self.is_orb: items = self._csorb.StsLblsOrb._fields name = 'Orb' else: items = self._csorb.StsLblsCorr._fields name = 'Corr' channel = self.devpref.substitute(propty=name + 'Status-Mon') for bit, label in enumerate(items): led = SiriusLedAlert(self, channel, bit) lab = QLabel(label, self) fbl.addRow(led, lab) return wid
def __init__(self, parent=None): super().__init__(parent) layout = QFormLayout() layout.setFieldGrowthPolicy(0) self.plot_param = QComboBox() self.plot_param.addItems([ "dspacing-center", "d-reference", "Center", "Height", "FWHM", "Mixing", "Intensity", "strain", "stress" ]) self.plot_param.setCurrentIndex(self.plot_param.findText('strain')) layout.addRow(QLabel("Plot"), self.plot_param) self.measure_dir = QComboBox() self.measure_dir.addItems(["11", "22", "33"]) layout.addRow(QLabel("Measurement Direction "), self.measure_dir) self.setLayout(layout)
def __init__(self, parent=None): super().__init__(parent) self.setTitle("Mechanical Constants") layout = QFormLayout() validator = QDoubleValidator() validator.setBottom(0) self.youngModulus = QLineEdit() self.youngModulus.setValidator(validator) self.poissonsRatio = QLineEdit() self.poissonsRatio.setValidator(validator) layout.addRow(QLabel("Young Modulus, E (GPa)"), self.youngModulus) layout.addRow(QLabel("Poisson's ratio, ν"), self.poissonsRatio) self.setLayout(layout)
def __init__(self): SimulationConfigPanel.__init__(self, SingleTestRun) self.setObjectName("Single_test_run_panel") layout = QFormLayout() case_selector = CaseSelector() layout.addRow("Current case:", case_selector) run_path_label = QLabel("<b>%s</b>" % getRunPath()) addHelpToWidget(run_path_label, "config/simulation/runpath") layout.addRow("Runpath:", run_path_label) self._active_realizations_model = ActiveRealizationsModel() self.setLayout(layout)
def __init__(self, parent): super().__init__(parent) # Create colored icon using theme self._image = QLabel() self._image.setObjectName("logo_silhouette") self._image.setMinimumSize(300, 300) self._label = QtWelcomeLabel( trans. _("Drag image(s) here to open\nor\nUse the menu shortcuts below:")) # Widget setup self.setAutoFillBackground(True) self.setAcceptDrops(True) self._image.setAlignment(Qt.AlignCenter) self._label.setAlignment(Qt.AlignCenter) # Layout text_layout = QVBoxLayout() text_layout.addWidget(self._label) # TODO: Use action manager for shortcut query and handling shortcut_layout = QFormLayout() sc = QKeySequence('Ctrl+O', QKeySequence.PortableText).toString( QKeySequence.NativeText) shortcut_layout.addRow( QtShortcutLabel(sc), QtShortcutLabel(trans._("open image(s)")), ) self._shortcut_label = QtShortcutLabel("") shortcut_layout.addRow( self._shortcut_label, QtShortcutLabel(trans._("show all key bindings")), ) shortcut_layout.setSpacing(0) layout = QVBoxLayout() layout.addStretch() layout.setSpacing(30) layout.addWidget(self._image) layout.addLayout(text_layout) layout.addLayout(shortcut_layout) layout.addStretch() self.setLayout(layout) self._show_shortcuts_updated() action_manager.events.shorcut_changed.connect( self._show_shortcuts_updated)
class StringDictWidget(QWidget): """Show dict in key-value form.""" def __init__(self, parent): super(StringDictWidget, self).__init__(parent) self.setContentsMargins(11, 11, 11, 11) self.widget_layout = QFormLayout(self) self.widget_layout.setContentsMargins(0, 0, 0, 0) self.setLayout(self.widget_layout) def addEntry(self, key, value): key_label = QLabel(self) key_label.setText(str(key)) value_label = QLabel(self) value_label.setText(str(value)) self.widget_layout.addRow(key_label, value_label)
class TaskOptionsGroupBox(QGroupBox): def __init__(self, parent): super(TaskOptionsGroupBox, self).__init__(parent) self.widget_layout = QFormLayout(self) self.setLayout(self.widget_layout) self.setTitle("Time") self.time_label = QLabel(self) self.time_label.setText("Execute: ") self.time_now = QRadioButton(self) self.time_now.setText("Immediately") self.time_now.setChecked(True) self.time_schedule = QRadioButton(self) self.time_schedule.setText("Schedule") self.schedule_select = QDateTimeEdit(self) self.schedule_select.setDateTime(QDateTime.currentDateTime()) self.schedule_select.setEnabled(False) self.user_activity_label = QLabel(self) self.user_activity_label.setText("User activity") self.user_activity_combo = QComboBox(self) self.user_activity_combo.addItems([ "0 - Disabled", "1 - Low", "2 - Normal", "3 - Medium", "4 - High", "5 - Very high" ]) self.widget_layout.addRow(self.time_label, None) self.widget_layout.addRow(self.time_now, None) self.widget_layout.addRow(self.time_schedule, self.schedule_select) self.widget_layout.addRow(self.user_activity_label, self.user_activity_combo) self.time_schedule.toggled.connect(self.on_time_schedule_toggled) @Slot(bool) def on_time_schedule_toggled(self, state): if state: self.schedule_select.setEnabled(True) else: self.schedule_select.setEnabled(False) def get_options(self): resp = { "user_activity": self.user_activity_combo.currentText().split(" - ")[0] } if self.time_now.isChecked(): resp["time"] = "now" elif self.time_schedule.isChecked(): resp["time"] = self.schedule_select.dateTime().toString() return resp
def setup_chamber_design(): # master layout master = QVBoxLayout() # master group box self.gb_chamber = QGroupBox(self.tr("Chamber Design")) # nozzle settings button self.btn_nozzle_settings = QPushButton(self.tr("Edit Nozzle")) self.btn_nozzle_settings.setMinimumHeight(50) master.addWidget(self.btn_nozzle_settings) # nozzle info pane fl_nozzle_info = QFormLayout() gb_nozzle = QGroupBox(self.tr("Nozzle Info")) gb_nozzle.setLayout(fl_nozzle_info) self.lbl_nozzle_throat = QLabel() fl_nozzle_info.addRow(QLabel(self.tr("Throat Diameter:")), self.lbl_nozzle_throat) self.lbl_nozzle_exit = QLabel() fl_nozzle_info.addRow(QLabel(self.tr("Exit Diameter:")), self.lbl_nozzle_exit) self.lbl_nozzle_expansion_ratio = QLabel() fl_nozzle_info.addRow(QLabel(self.tr("Expansion Ratio:")), self.lbl_nozzle_expansion_ratio) # add group box to master master.addWidget(gb_nozzle) master.addStretch() # overall motor info pane fl_motor_info = QFormLayout() gb_motor = QGroupBox(self.tr("Motor Info")) gb_motor.setLayout(fl_motor_info) self.lbl_kn = QLabel() fl_motor_info.addRow(QLabel(self.tr("Kn:")), self.lbl_kn) self.lbl_port_throat = QLabel() fl_motor_info.addRow(QLabel(self.tr("Port/Throat Ratio:")), self.lbl_port_throat) master.addWidget(gb_motor) self.gb_chamber.setLayout(master)
def create_controls(self): self.txt_name = QLineEdit() self.chk_menu = QCheckBox(tr("Menu entry")) self.chk_menu.setChecked(True) self.chk_toolbar = QCheckBox(tr("Toolbar button")) self.chk_toolbar.setChecked(True) self.txt_category = QLineEdit() self.chk_icon = QCheckBox() self.chk_toolbar.setChecked(False) self.txt_iconpath = QLineEdit() self.btn_browse_icon = QPushButton("...") self.txt_iconpath.setEnabled(False) self.btn_browse_icon.setEnabled(False) btns = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, QtCore.Qt.Horizontal) self.chk_menu.toggled.connect(self.checks_changed) self.chk_toolbar.toggled.connect(self.checks_changed) self.chk_icon.toggled.connect(self.checks_changed) self.btn_browse_icon.clicked.connect(self.browse_icon) btns.accepted.connect(self.accept) btns.rejected.connect(self.reject) hbox = QHBoxLayout() for w in [self.chk_icon, self.txt_iconpath, self.btn_browse_icon]: hbox.addWidget(w) form = QFormLayout() form.addRow(tr("Name"), self.txt_name) form.addRow(self.chk_menu, self.chk_toolbar) form.addRow(tr("Category"), self.txt_category) form.addRow(tr("Icon"), hbox) vbox = QVBoxLayout(self) vbox.addLayout(form) vbox.addWidget(btns) self.setLayout(vbox)
def __init__(self, *args, **kwargs): super(MainWidget, self).__init__(*args, **kwargs) #Widgets self.label_Title1 = QLabel() self.label_Title1.setText("INGRESE LOS DATOS") self.label_Title2 = QLabel() self.label_Title2.setText("DATOS BOMBILLOS ESTANDAR") self.label_Title3 = QLabel() self.label_Title3.setText("DATOS BOMBILLOS LED") self.label_Data1 = QLabel() self.label_Data1.setText("Costo de la electricidad (kW/hora)") self.label_Data2 = QLabel() self.label_Data2.setText("Numero de bombillos a reemplazar") self.label_Data3 = QLabel() self.label_Data3.setText("Vatios del bombillo existente") self.label_Data4 = QLabel() self.label_Data4.setText("Numero de Horas por Dia encendido") self.label_Data5 = QLabel() self.label_Data5.setText("Vida util bombillo actual") self.label_Data6 = QLabel() self.label_Data6.setText("Costo Bombillo actual") self.label_Data7 = QLabel() self.label_Data7.setText("Costo estimado mantenimiento por bombillo") self.label_Data8 = QLabel() self.label_Data8.setText("Vatios del bombillo LED") self.label_Data9 = QLabel() self.label_Data9.setText("Vida util estimada del bombillo") self.label_Data10 = QLabel() self.label_Data10.setText("Costo del bombillo led") #Widgets Titulos del Form self.label_Titlef1 = QLabel() self.label_Titlef1.setText("INFORMACION DE COSTOS CALCULADOS") self.label_Titlef2 = QLabel() self.label_Titlef2.setText("INFORMACION DE AHORROS CALCULADOS") self.line_Data1 = QLineEdit() #self.line_Data1.setValidator() self.line_Data2 = QLineEdit() self.line_Data2.setValidator(QIntValidator()) self.line_Data3 = QLineEdit() self.line_Data3.setValidator(QIntValidator()) self.line_Data4 = QLineEdit() self.line_Data4.setValidator(QIntValidator()) self.line_Data5 = QLineEdit() self.line_Data5.setValidator(QIntValidator()) self.line_Data6 = QLineEdit() #self.line_Data6.setValidator() self.line_Data7 = QLineEdit() #self.line_Data7.setValidator() self.line_Data8 = QLineEdit() #self.line_Data8.setValidator() self.line_Data9 = QLineEdit() #self.line_Data9.setValidator() self.line_Data10 = QLineEdit() #self.line_Data10.setValidator() #Widget Informacion Calculada Form1 Costos self.line_Inf1 = QLineEdit() self.line_Inf1.setValidator(QIntValidator()) self.line_Inf2 = QLineEdit() self.line_Inf2.setValidator(QIntValidator()) self.line_Inf3 = QLineEdit() self.line_Inf3.setValidator(QIntValidator()) self.line_Inf4 = QLineEdit() self.line_Inf4.setValidator(QIntValidator()) self.line_Inf5 = QLineEdit() self.line_Inf5.setValidator(QIntValidator()) self.line_Inf6 = QLineEdit() self.line_Inf6.setValidator(QIntValidator()) self.line_Inf7 = QLineEdit() self.line_Inf7.setValidator(QIntValidator()) self.line_Inf8 = QLineEdit() self.line_Inf8.setValidator(QIntValidator()) self.line_Inf9 = QLineEdit() self.line_Inf9.setValidator(QIntValidator()) #Widget Informacion Calculada Form2 Ahorros self.line_Sav1 = QLineEdit() self.line_Sav1.setValidator(QIntValidator()) self.line_Sav2 = QLineEdit() self.line_Sav2.setValidator(QIntValidator()) self.line_Sav3 = QLineEdit() self.line_Sav3.setValidator(QIntValidator()) self.line_Sav4 = QLineEdit() self.line_Sav4.setValidator(QIntValidator()) self.line_Sav5 = QLineEdit() self.line_Sav5.setValidator(QIntValidator()) self.line_Sav6 = QLineEdit() self.line_Sav6.setValidator(QIntValidator()) self.button_Calc = QPushButton('Calcular Ahorro', parent=self) self.button_Impr = QPushButton('Imprimir', parent=self) #Layouts layout = QGridLayout() layout.addWidget(self.label_Title1,0,0) layout.addWidget(self.label_Data1,1,0) layout.addWidget(self.line_Data1,1,1) layout.addWidget(self.label_Title2,2,0) layout.addWidget(self.label_Data2,3,0) layout.addWidget(self.line_Data2,3,1) layout.addWidget(self.label_Data5,3,2) layout.addWidget(self.line_Data5,3,3) layout.addWidget(self.label_Data3,4,0) layout.addWidget(self.line_Data3,4,1) layout.addWidget(self.label_Data6,4,2) layout.addWidget(self.line_Data6,4,3) layout.addWidget(self.label_Data4,5,0) layout.addWidget(self.line_Data4,5,1) layout.addWidget(self.label_Data7,5,2) layout.addWidget(self.line_Data7,5,3) layout.addWidget(self.label_Title3,6,0) layout.addWidget(self.label_Data8,7,0) layout.addWidget(self.line_Data8,7,1) layout.addWidget(self.label_Data10,7,2) layout.addWidget(self.line_Data10,7,3) layout.addWidget(self.label_Data9,8,0) layout.addWidget(self.line_Data9,8,1) layout.addWidget(self.button_Calc,8,3) layout1 = QFormLayout() layout1.addRow("Horas por año",self.line_Inf1) layout1.addRow("Costo de Energia por Dia",self.line_Inf2) layout1.addRow("Costo de Energia por Año",self.line_Inf3) layout1.addRow("Costo total de la Compra",self.line_Inf4) layout1.addRow("Costo Total de la compra con mantenimiento",self.line_Inf5) layout1.addRow("Costo Reemplazo Actuales Año",self.line_Inf6) layout1.addRow("Costo Energia por Dia LED",self.line_Inf7) layout1.addRow("Costo de Energia por Año LED",self.line_Inf8) layout1.addRow("Costo Total de la Compra LED",self.line_Inf9) layout2 = QFormLayout() layout2.addRow("Ahorro Energia Anual",self.line_Sav1) layout2.addRow("Ahorro Energia Mensual",self.line_Sav2) layout2.addRow("Periodo Retorno Inversion en Años",self.line_Sav3) layout2.addRow("Periodo Retorno Inversion en Meses",self.line_Sav4) layout2.addWidget(self.button_Impr) #Layout Horizontal Titulos del Form self.LayoutTitle = QHBoxLayout() self.LayoutTitle.addWidget(self.label_Titlef1) self.LayoutTitle.addWidget(self.label_Titlef2) ### Layout HOrizontal que une los dos Form self.LayoutForm = QHBoxLayout() self.LayoutForm.addLayout(layout1) self.LayoutForm.addLayout(layout2) ## LAyout Vertical Final self.myLayout = QVBoxLayout() self.myLayout.setMargin(20) self.myLayout.addLayout(layout) self.myLayout.addLayout(self.LayoutTitle) self.myLayout.addLayout(self.LayoutForm) self.setLayout(self.myLayout) # Signals self.button_Calc.clicked.connect(self.result_method)
def setup_grain_design(): # grain table view master = QHBoxLayout(self) master.addWidget(QTableView()) # grain design controls controls = QVBoxLayout(self) # add a push button self.btn_new_grain = QPushButton(self.tr("New Grain")) self.btn_new_grain.setMinimumHeight(50) controls.addWidget(self.btn_new_grain) # add a dividing line line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) controls.addSpacing(5) controls.addWidget(line) # rest of the controls buttons self.btn_edit_grain = QPushButton(self.tr("Edit")) self.btn_edit_grain.setMinimumHeight(30) controls.addWidget(self.btn_edit_grain) self.btn_delete_Grain = QPushButton(self.tr("Delete")) self.btn_delete_Grain.setMinimumHeight(30) controls.addWidget(self.btn_delete_Grain) # move grain up and down moveup = QHBoxLayout() self.btn_move_up = QToolButton() self.btn_move_up.setArrowType(Qt.UpArrow) moveup.addWidget(self.btn_move_up) moveup.addWidget(QLabel(self.tr("Move Up"))) controls.addLayout(moveup) movedown = QHBoxLayout() self.btn_move_down = QToolButton() self.btn_move_down.setArrowType(Qt.DownArrow) movedown.addWidget(self.btn_move_down) movedown.addWidget(QLabel(self.tr("Move Down"))) controls.addLayout(movedown) controls.addStretch() # add info for motor design fl_propellant_info = QFormLayout() gb_motor_info = QGroupBox(self.tr("Propellant Info")) gb_motor_info.setLayout(fl_propellant_info) self.lbl_num_grains = QLabel() fl_propellant_info.addRow(QLabel(self.tr("Number of Segments:")), self.lbl_num_grains) self.lbl_motor_dia = QLabel() fl_propellant_info.addRow(QLabel(self.tr("Motor Diameter:")), self.lbl_motor_dia) self.lbl_motor_len = QLabel() fl_propellant_info.addRow(QLabel(self.tr("Propellant Length:")), self.lbl_motor_len) self.lbl_prop_mass = QLabel() fl_propellant_info.addRow(QLabel(self.tr("Propellant Mass:")), self.lbl_prop_mass) self.lbl_volume_loading = QLabel() fl_propellant_info.addRow(QLabel(self.tr("Volume Loading:")), self.lbl_volume_loading) # set group box's layout controls.addWidget(gb_motor_info) # setup master layout master.addLayout(controls) self.gb_design = QGroupBox(self.tr("Grain Design")) self.gb_design.setLayout(master)
class FormWidget(QWidget): update_buttons = Signal() def __init__(self, data, comment="", parent=None): QWidget.__init__(self, parent) from copy import deepcopy self.data = deepcopy(data) self.widgets = [] self.formlayout = QFormLayout(self) if comment: self.formlayout.addRow(QLabel(comment)) self.formlayout.addRow(QLabel(" ")) if DEBUG_FORMLAYOUT: print("\n"+("*"*80)) print("DATA:", self.data) print("*"*80) print("COMMENT:", comment) print("*"*80) def get_dialog(self): """Return FormDialog instance""" dialog = self.parent() while not isinstance(dialog, QDialog): dialog = dialog.parent() return dialog def setup(self): for label, value in self.data: if DEBUG_FORMLAYOUT: print("value:", value) if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QLabel(" "), QLabel(" ")) self.widgets.append(None) continue elif label is None: # Comment self.formlayout.addRow(QLabel(value)) self.widgets.append(None) continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif text_to_qcolor(value).isValid(): field = ColorLayout(QColor(value), self) elif is_text_string(value): if '\n' in value: for linesep in (os.linesep, '\n'): if linesep in value: value = value.replace(linesep, u"\u2029") field = QTextEdit(value, self) else: field = QLineEdit(value, self) elif isinstance(value, (list, tuple)): value = list(value) # in case this is a tuple selindex = value.pop(0) field = QComboBox(self) if isinstance(value[0], (list, tuple)): keys = [ key for key, _val in value ] value = [ val for _key, val in value ] else: keys = value field.addItems(value) if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, int): print("Warning: '%s' index is invalid (label: "\ "%s, value: %s)" % (selindex, label, value), file=STDERR) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QCheckBox(self) field.setCheckState(Qt.Checked if value else Qt.Unchecked) elif isinstance(value, float): field = QLineEdit(repr(value), self) field.setValidator(QDoubleValidator(field)) dialog = self.get_dialog() dialog.register_float_field(field) field.textChanged.connect(lambda text: dialog.update_buttons()) elif isinstance(value, int): field = QSpinBox(self) field.setRange(-1e9, 1e9) field.setValue(value) elif isinstance(value, datetime.datetime): field = QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QDateEdit(self) field.setDate(value) else: field = QLineEdit(repr(value), self) self.formlayout.addRow(label, field) self.widgets.append(field) def get(self): valuelist = [] for index, (label, value) in enumerate(self.data): field = self.widgets[index] if label is None: # Separator / Comment continue elif tuple_to_qfont(value) is not None: value = field.get_font() elif is_text_string(value): if isinstance(field, QTextEdit): value = to_text_string(field.toPlainText() ).replace(u"\u2029", os.linesep) else: value = to_text_string(field.text()) elif isinstance(value, (list, tuple)): index = int(field.currentIndex()) if isinstance(value[0], int): # Return an int index, if initialization was an int value = index else: value = value[index+1] if isinstance(value, (list, tuple)): value = value[0] elif isinstance(value, bool): value = field.checkState() == Qt.Checked elif isinstance(value, float): value = float(field.text()) elif isinstance(value, int): value = int(field.value()) elif isinstance(value, datetime.datetime): value = field.dateTime() try: value = value.toPyDateTime() # PyQt except AttributeError: value = value.toPython() # PySide elif isinstance(value, datetime.date): value = field.date() try: value = value.toPyDate() # PyQt except AttributeError: value = value.toPython() # PySide else: value = eval(str(field.text())) valuelist.append(value) return valuelist
def __init__(self, presenter, parent = None, name = '', isMD=False, noExp = 0): super(SampleLogsView, self).__init__(parent) self.presenter = presenter self.setWindowTitle("{} sample logs".format(name)) self.setWindowFlags(Qt.Window) # Create sample log table self.table = QTableView() self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.clicked.connect(self.presenter.clicked) self.table.doubleClicked.connect(self.presenter.doubleClicked) self.table.contextMenuEvent = self.tableMenu self.addWidget(self.table) frame_right = QFrame() layout_right = QVBoxLayout() #Add full_time and experimentinfo options layout_options = QHBoxLayout() if isMD: layout_options.addWidget(QLabel("Experiment Info #")) self.experimentInfo = QSpinBox() self.experimentInfo.setMaximum(noExp-1) self.experimentInfo.valueChanged.connect(self.presenter.changeExpInfo) layout_options.addWidget(self.experimentInfo) self.full_time = QCheckBox("Relative Time") self.full_time.setChecked(True) self.full_time.stateChanged.connect(self.presenter.plot_logs) layout_options.addWidget(self.full_time) layout_right.addLayout(layout_options) # Sample log plot self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.canvas.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) self.canvas.mpl_connect('button_press_event', self.presenter.plot_clicked) self.ax = self.fig.add_subplot(111, projection='mantid') layout_right.addWidget(self.canvas) # Sample stats self.create_stats_widgets() layout_stats = QFormLayout() layout_stats.addRow('', QLabel("Log Statistics")) layout_stats.addRow('Min:', self.stats_widgets["minimum"]) layout_stats.addRow('Max:', self.stats_widgets["maximum"]) layout_stats.addRow('Mean:', self.stats_widgets["mean"]) layout_stats.addRow('Median:', self.stats_widgets["median"]) layout_stats.addRow('Std Dev:', self.stats_widgets["standard_deviation"]) layout_stats.addRow('Time Avg:', self.stats_widgets["time_mean"]) layout_stats.addRow('Time Std Dev:', self.stats_widgets["time_standard_deviation"]) layout_stats.addRow('Duration:', self.stats_widgets["duration"]) layout_right.addLayout(layout_stats) frame_right.setLayout(layout_right) self.addWidget(frame_right) self.setStretchFactor(0,1) self.resize(1200,800) self.show()
def __init__(self, parent, username, password, token, remember=False, remember_token=False): QDialog.__init__(self, parent) title = _("Sign in to Github") self.resize(415, 375) self.setWindowTitle(title) self.setWindowFlags( self.windowFlags() & ~Qt.WindowContextHelpButtonHint) # Header html = ('<html><head/><body><p align="center">' '{title}</p></body></html>') lbl_html = QLabel(html.format(title=title)) lbl_html.setStyleSheet('font-size: 16px;') # Tabs self.tabs = QTabWidget() # Basic form layout basic_form_layout = QFormLayout() basic_form_layout.setContentsMargins(-1, 0, -1, -1) basic_lbl_msg = QLabel(_("For regular users, i.e. users <b>without</b>" " two-factor authentication enabled")) basic_lbl_msg.setWordWrap(True) basic_lbl_msg.setAlignment(Qt.AlignJustify) lbl_user = QLabel(_("Username:"******"", QWidget()) lbl_password = QLabel(_("Password: "******"Remember me")) self.cb_remember.setToolTip(_("Spyder will save your credentials " "safely")) self.cb_remember.setChecked(remember) basic_form_layout.setWidget(4, QFormLayout.FieldRole, self.cb_remember) # Basic auth tab basic_auth = QWidget() basic_layout = QVBoxLayout() basic_layout.addSpacerItem(QSpacerItem(QSpacerItem(0, 8))) basic_layout.addWidget(basic_lbl_msg) basic_layout.addSpacerItem( QSpacerItem(QSpacerItem(0, 50, vPolicy=QSizePolicy.Expanding))) basic_layout.addLayout(basic_form_layout) basic_layout.addSpacerItem( QSpacerItem(QSpacerItem(0, 50, vPolicy=QSizePolicy.Expanding))) basic_auth.setLayout(basic_layout) self.tabs.addTab(basic_auth, _("Password Only")) # Token form layout token_form_layout = QFormLayout() token_form_layout.setContentsMargins(-1, 0, -1, -1) token_lbl_msg = QLabel(_("For users <b>with</b> two-factor " "authentication enabled, or who prefer a " "per-app token authentication.<br><br>" "You can go <b><a href=\"{}\">here</a></b> " "and click \"Generate token\" at the bottom " "to create a new token to use for this, with " "the appropriate permissions.").format( TOKEN_URL)) token_lbl_msg.setOpenExternalLinks(True) token_lbl_msg.setWordWrap(True) token_lbl_msg.setAlignment(Qt.AlignJustify) lbl_token = QLabel("Token: ") token_form_layout.setWidget(1, QFormLayout.LabelRole, lbl_token) self.le_token = QLineEdit() self.le_token.setEchoMode(QLineEdit.Password) self.le_token.textChanged.connect(self.update_btn_state) token_form_layout.setWidget(1, QFormLayout.FieldRole, self.le_token) self.cb_remember_token = None # Same validation as with cb_remember if self.is_keyring_available() and valid_py_os: self.cb_remember_token = QCheckBox(_("Remember token")) self.cb_remember_token.setToolTip(_("Spyder will save your " "token safely")) self.cb_remember_token.setChecked(remember_token) token_form_layout.setWidget(3, QFormLayout.FieldRole, self.cb_remember_token) # Token auth tab token_auth = QWidget() token_layout = QVBoxLayout() token_layout.addSpacerItem(QSpacerItem(QSpacerItem(0, 8))) token_layout.addWidget(token_lbl_msg) token_layout.addSpacerItem( QSpacerItem(QSpacerItem(0, 50, vPolicy=QSizePolicy.Expanding))) token_layout.addLayout(token_form_layout) token_layout.addSpacerItem( QSpacerItem(QSpacerItem(0, 50, vPolicy=QSizePolicy.Expanding))) token_auth.setLayout(token_layout) self.tabs.addTab(token_auth, _("Access Token")) # Sign in button self.bt_sign_in = QPushButton(_("Sign in")) self.bt_sign_in.clicked.connect(self.accept) self.bt_sign_in.setDisabled(True) # Main layout layout = QVBoxLayout() layout.addWidget(lbl_html) layout.addWidget(self.tabs) layout.addWidget(self.bt_sign_in) self.setLayout(layout) # Final adjustments if username and password: self.le_user.setText(username) self.le_password.setText(password) self.bt_sign_in.setFocus() elif username: self.le_user.setText(username) self.le_password.setFocus() elif token: self.le_token.setText(token) else: self.le_user.setFocus() self.setFixedSize(self.width(), self.height()) self.le_password.installEventFilter(self) self.le_user.installEventFilter(self) self.tabs.currentChanged.connect(self.update_btn_state)
voltage = ManualFacet(type=float, units='volts') current = ManualFacet(type=float, units='amps') if __name__ == '__main__': ps = MyPowerSupply() ps.observe('voltage', print) app = QApplication(sys.argv) win = QMainWindow() w = QWidget(win) win.setCentralWidget(w) fbox = QFormLayout() box1 = ps.facets.voltage.create_widget() fbox.addRow('Voltage', box1) box2 = ps.facets.current.create_widget() fbox.addRow('Current', box2) def set_box(event): box1.setUValue(event.new) ps.observe('voltage', set_box) def f(): ps.voltage = '12 V' #box2.uValueChanged.connect(f) w.setLayout(fbox) win.show() app.exec_()