def __init__(self, parent, prefix = None, suffix = None, option = None, min_ = None, max_ = None, step = None, tip = None, value = None, changed =None): super(MyDoubleSpinBox, self).__init__(parent) if prefix: plabel = QLabel(prefix) else: plabel = None if suffix: slabel = QLabel(suffix) else: slabel = None spinbox = QDoubleSpinBox(parent) if min_ is not None: spinbox.setMinimum(min_) if max_ is not None: spinbox.setMaximum(max_) if step is not None: spinbox.setSingleStep(step) if tip is not None: spinbox.setToolTip(tip) layout = QHBoxLayout() for subwidget in (plabel, spinbox, slabel): if subwidget is not None: layout.addWidget(subwidget) if value is not None: spinbox.setValue(value) if changed is not None: self.connect(spinbox, SIGNAL('valueChanged(double)'), changed) layout.addStretch(1) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.spin = spinbox
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) self.label_ip = QLabel("IP") self.lineedit_ip = QLineEdit() layout.addRow(self.label_ip, self.lineedit_ip) self.label_port = QLabel("Port") self.spinbox_port = QSpinBox() self.spinbox_port.setMinimum(0) self.spinbox_port.setMaximum(65535) layout.addRow(self.label_port, self.spinbox_port) self.label_password = QLabel("Password") self.lineedit_password = QLineEdit() layout.addRow(self.label_password, self.lineedit_password) self.label_mount = QLabel("Mount") self.lineedit_mount = QLineEdit() layout.addRow(self.label_mount, self.lineedit_mount) # # Audio Quality # self.label_audio_quality = QLabel("Audio Quality") self.spinbox_audio_quality = QDoubleSpinBox() self.spinbox_audio_quality.setMinimum(0.0) self.spinbox_audio_quality.setMaximum(1.0) self.spinbox_audio_quality.setSingleStep(0.1) self.spinbox_audio_quality.setDecimals(1) self.spinbox_audio_quality.setValue(0.3) # Default value 0.3 # # Video Quality # self.label_video_quality = QLabel("Video Quality (kb/s)") self.spinbox_video_quality = QSpinBox() self.spinbox_video_quality.setMinimum(0) self.spinbox_video_quality.setMaximum(16777215) self.spinbox_video_quality.setValue(2400) # Default value 2400 def get_video_quality_layout(self): layout_video_quality = QHBoxLayout() layout_video_quality.addWidget(self.label_video_quality) layout_video_quality.addWidget(self.spinbox_video_quality) return layout_video_quality def get_audio_quality_layout(self): layout_audio_quality = QHBoxLayout() layout_audio_quality.addWidget(self.label_audio_quality) layout_audio_quality.addWidget(self.spinbox_audio_quality) return layout_audio_quality
def createEditor( self, parent, option, index ): if index.column() == DESCRIPCION: combo = QComboBox( parent ) combo.setEditable( True ) value = index.data().toString() self.filtrados.append( value ) self.proxymodel.setFilterRegExp( self.filter() ) combo.setModel( self.proxymodel ) combo.setModelColumn( 1 ) combo.setCompleter( self.completer ) return combo elif index.column() == BANCO: combo = QComboBox( parent ) #combo.setEditable(True) combo.setModel( self.bancosmodel ) combo.setModelColumn( 1 ) #combo.setCompleter(self.completer) return combo elif index.column() == MONTO: doublespinbox = QDoubleSpinBox( parent ) doublespinbox.setMinimum( -1000000 ) doublespinbox.setMaximum( 1000000 ) doublespinbox.setDecimals( 4 ) doublespinbox.setAlignment( Qt.AlignHCenter ) return doublespinbox elif index.column() == REFERENCIA: textbox = QStyledItemDelegate.createEditor( self, parent, option, index ) textbox.setAlignment( Qt.AlignHCenter ) return textbox
def _getSpinbox(self, minvalue, maxvalue, step, nullable = True, value = 0): ''' Get a combobox filled with the given values :param values: The values as key = value, value = description or text :type values: Dict :returns: A combobox :rtype: QWidget ''' widget = QWidget() spinbox = QDoubleSpinBox() spinbox.setMinimum(minvalue) spinbox.setMaximum(maxvalue) spinbox.setSingleStep(step) spinbox.setDecimals(len(str(step).split('.')[1]) if len(str(step).split('.'))==2 else 0) if nullable: spinbox.setMinimum(minvalue - step) spinbox.setValue(spinbox.minimum()) spinbox.setSpecialValueText(str(QSettings().value('qgis/nullValue', 'NULL' ))) if value is not None: spinbox.setValue(value) layout = QHBoxLayout(widget) layout.addWidget(spinbox, 1); layout.setAlignment(Qt.AlignCenter); layout.setContentsMargins(5,0,5,0); widget.setLayout(layout); return widget
def _getSpinbox(self, minvalue, maxvalue, step, nullable=True, value=0): ''' Get a combobox filled with the given values :param values: The values as key = value, value = description or text :type values: Dict :returns: A combobox :rtype: QWidget ''' widget = QWidget() spinbox = QDoubleSpinBox() spinbox.setMinimum(minvalue) spinbox.setMaximum(maxvalue) spinbox.setSingleStep(step) spinbox.setDecimals( len(str(step).split('.')[1]) if len(str(step).split('.')) == 2 else 0) if nullable: spinbox.setMinimum(minvalue - step) spinbox.setValue(spinbox.minimum()) spinbox.setSpecialValueText( str(QSettings().value('qgis/nullValue', 'NULL'))) if value is not None: spinbox.setValue(value) layout = QHBoxLayout(widget) layout.addWidget(spinbox, 1) layout.setAlignment(Qt.AlignCenter) layout.setContentsMargins(5, 0, 5, 0) widget.setLayout(layout) return widget
def createEditor(self, parent, option, index): """ Creates the combobox inside a parent. :param parent: The container of the combobox :type parent: QWidget :param option: QStyleOptionViewItem class is used to describe the parameters used to draw an item in a view widget. :type option: Object :param index: The index where the combobox will be added. :type index: QModelIndex :return: The combobox :rtype: QComboBox """ if index.column() == 0: str_combo = QComboBox(parent) str_combo.setObjectName(unicode(index.row())) return str_combo elif index.column() == 1: spinbox = QDoubleSpinBox(parent) spinbox.setObjectName(unicode(index.row())) spinbox.setMinimum(0.00) spinbox.setSuffix('%') spinbox.setMaximum(100.00) return spinbox
def create_doublespinbox(self, prefix, suffix, option, min_=None, max_=None, step=None, tip=None): if prefix: plabel = QLabel(prefix) else: plabel = None if suffix: slabel = QLabel(suffix) else: slabel = None spinbox = QDoubleSpinBox() if min_ is not None: spinbox.setMinimum(min_) if max_ is not None: spinbox.setMaximum(max_) if step is not None: spinbox.setSingleStep(step) if tip is not None: spinbox.setToolTip(tip) self.spinboxes[spinbox] = option layout = QHBoxLayout() for subwidget in (plabel, spinbox, slabel): if subwidget is not None: layout.addWidget(subwidget) layout.addStretch(1) layout.setContentsMargins(0, 0, 0, 0) widget = QWidget(self) widget.setLayout(layout) widget.spin = spinbox return widget
def createEditor(self, parent, option, index): """ Creates the combobox inside a parent. :param parent: The container of the combobox :type parent: QWidget :param option: QStyleOptionViewItem class is used to describe the parameters used to draw an item in a view widget. :type option: Object :param index: The index where the combobox will be added. :type index: QModelIndex :return: The combobox :rtype: QComboBox """ if index.column() == 0: str_combo = QComboBox(parent) str_combo.insertItem(0, " ") for id, type in self.str_type_set_data().iteritems(): str_combo.addItem(type, id) if self.str_type_id is not None: str_combo.setCurrentIndex(self.str_type_id) return str_combo elif index.column() == 1: spinbox = QDoubleSpinBox(parent) spinbox.setObjectName(unicode(index.row())) spinbox.setMinimum(0.00) spinbox.setSuffix('%') spinbox.setMaximum(100.00) return spinbox
class XicWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) v = QVBoxLayout() f = QFormLayout() self.mzTolSpinBox = QDoubleSpinBox(self) self.mzTolSpinBox.setMaximum(100) self.mzTolSpinBox.setMinimum(1) self.mzTolSpinBox.setValue(10) f.addRow("mz tolerance(ppm):", self.mzTolSpinBox) self.mzSpinBox = QDoubleSpinBox(self) self.mzSpinBox.setMaximum(2000.0) self.mzSpinBox.setMinimum(300.0) self.mzSpinBox.setValue(500.0) f.addRow("requested m/z:", self.mzSpinBox) v.addLayout(f) self.plotButton = QPushButton("Plot") v.addWidget(self.plotButton) self.setLayout(v)
class FloatParameterWidget(NumericParameterWidget): """Widget class for Float parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A FloatParameter object. :type parameter: FloatParameter """ super(FloatParameterWidget, self).__init__(parameter, parent) self._input = QDoubleSpinBox() self._input.setDecimals(self._parameter.precision) self._input.setValue(self._parameter.value) self._input.setMinimum(self._parameter.minimum_allowed_value) self._input.setMaximum(self._parameter.maximum_allowed_value) self._input.setSingleStep(10**-self._parameter.precision) # is it possible to use dynamic precision ? string_min_value = '%.*f' % (self._parameter.precision, self._parameter.minimum_allowed_value) string_max_value = '%.*f' % (self._parameter.precision, self._parameter.maximum_allowed_value) tool_tip = 'Choose a number between %s and %s' % (string_min_value, string_max_value) self._input.setToolTip(tool_tip) self._input.setSizePolicy(self._spin_box_size_policy) self._inner_input_layout.addWidget(self._input) self._inner_input_layout.addWidget(self._unit_widget)
class FloatParameterWidget(NumericParameterWidget): """Widget class for Float parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A FloatParameter object. :type parameter: FloatParameter """ super(FloatParameterWidget, self).__init__(parameter, parent) self._input = QDoubleSpinBox() self._input.setDecimals(self._parameter.precision) self._input.setMinimum(self._parameter.minimum_allowed_value) self._input.setMaximum(self._parameter.maximum_allowed_value) self._input.setValue(self._parameter.value) self._input.setSingleStep( 10 ** -self._parameter.precision) # is it possible to use dynamic precision ? string_min_value = '%.*f' % ( self._parameter.precision, self._parameter.minimum_allowed_value) string_max_value = '%.*f' % ( self._parameter.precision, self._parameter.maximum_allowed_value) tool_tip = 'Choose a number between %s and %s' % ( string_min_value, string_max_value) self._input.setToolTip(tool_tip) self._input.setSizePolicy(self._spin_box_size_policy) self.inner_input_layout.addWidget(self._input) self.inner_input_layout.addWidget(self._unit_widget)
def createEditor(self, type, parent): if type != QVariant.Double: raise ValueError("This factory only creates editor for doubles") w = QDoubleSpinBox(parent) w.setDecimals(5) w.setMinimum(0.0001) w.setMaximum(10000) return w
def createDoubleSpinBox(self, variable_name, variable_value, variable_type, analysis_module_variables_model): spinner = QDoubleSpinBox() spinner.setMinimumWidth(75) spinner.setMaximum(analysis_module_variables_model.getVariableMaximumValue(variable_name)) spinner.setMinimum(analysis_module_variables_model.getVariableMinimumValue(variable_name)) spinner.setSingleStep(analysis_module_variables_model.getVariableStepValue(variable_name)) spinner.setValue(variable_value) spinner.valueChanged.connect(partial(self.valueChanged,variable_name, variable_type, spinner)) return spinner;
def createDoubleSpinBox(self, variable_name, variable_value, variable_type, analysis_module_variables_model): spinner = QDoubleSpinBox() spinner.setMinimumWidth(75) spinner.setMaximum(analysis_module_variables_model.getVariableMaximumValue(variable_name)) spinner.setMinimum(analysis_module_variables_model.getVariableMinimumValue(variable_name)) spinner.setSingleStep(analysis_module_variables_model.getVariableStepValue(variable_name)) spinner.setValue(variable_value) spinner.valueChanged.connect(partial(self.valueChanged, variable_name, variable_type, spinner)) return spinner;
def _create_widget(cls, c, parent): dsb = QDoubleSpinBox(parent) dsb.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name)) #Set ranges dsb.setMinimum(float(c.minimum)) dsb.setMaximum(float(c.maximum)) return dsb
def _set_up_opt_spin_box(self): check_box = QCheckBox() spin_box = QDoubleSpinBox() spin_box.setDecimals(5) spin_box.setSingleStep(0.01) spin_box.setMinimum(-sys.float_info.max) spin_box.setMaximum(sys.float_info.max) spin_box.setDisabled(True) check_box.toggled.connect(spin_box.setEnabled) return check_box, spin_box
def createWidget(self, qt_parent=None): """ Return an editor widget suitable for editing the data type. For example, for QDateTime return a QDateTimeEdit(parent) """ sb = QDoubleSpinBox(qt_parent) sb.setFrame(False) sb.setMinimum(-float_info.max) sb.setMaximum(float_info.max) return sb
def extra_keywords_to_widgets(extra_keyword_definition): """Create widgets for extra keyword. :param extra_keyword_definition: An extra keyword definition. :type extra_keyword_definition: dict :return: QCheckBox and The input widget :rtype: (QCheckBox, QWidget) """ # Check box check_box = QCheckBox(extra_keyword_definition['name']) check_box.setToolTip(extra_keyword_definition['description']) check_box.setChecked(True) # Input widget if extra_keyword_definition['type'] == float: input_widget = QDoubleSpinBox() input_widget.setMinimum(extra_keyword_definition['minimum']) input_widget.setMaximum(extra_keyword_definition['maximum']) input_widget.setSuffix(extra_keyword_definition['unit_string']) elif extra_keyword_definition['type'] == int: input_widget = QSpinBox() input_widget.setMinimum(extra_keyword_definition['minimum']) input_widget.setMaximum(extra_keyword_definition['maximum']) input_widget.setSuffix(extra_keyword_definition['unit_string']) elif extra_keyword_definition['type'] == unicode: if extra_keyword_definition.get('options'): input_widget = QComboBox() options = extra_keyword_definition['options'] for option in options: input_widget.addItem( option['name'], option['key'], ) default_option_index = input_widget.findData( extra_keyword_definition['default_option']) input_widget.setCurrentIndex(default_option_index) else: input_widget = QLineEdit() elif extra_keyword_definition['type'] == datetime: input_widget = QDateTimeEdit() input_widget.setCalendarPopup(True) input_widget.setDisplayFormat('hh:mm:ss, d MMM yyyy') input_widget.setDateTime(datetime.now()) else: raise Exception input_widget.setToolTip(extra_keyword_definition['description']) # Signal # noinspection PyUnresolvedReferences check_box.stateChanged.connect(input_widget.setEnabled) return check_box, input_widget
def _create_widget(cls, c, parent, host=None): dsb = QDoubleSpinBox(parent) dsb.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name)) # Set decimal places dsb.setDecimals(c.scale) # Set ranges dsb.setMinimum(float(c.minimum)) dsb.setMaximum(float(c.maximum)) return dsb
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) # # Audio Quality # self.label_audio_quality = QLabel("Audio Quality") self.spinbox_audio_quality = QDoubleSpinBox() self.spinbox_audio_quality.setMinimum(0.0) self.spinbox_audio_quality.setMaximum(1.0) self.spinbox_audio_quality.setSingleStep(0.1) self.spinbox_audio_quality.setDecimals(1) self.spinbox_audio_quality.setValue(0.3) # Default value 0.3 # # Video Quality # self.label_video_quality = QLabel("Video Quality (kb/s)") self.spinbox_video_quality = QSpinBox() self.spinbox_video_quality.setMinimum(0) self.spinbox_video_quality.setMaximum(16777215) self.spinbox_video_quality.setValue(2400) # Default value 2400 # # Misc. # self.label_matterhorn = QLabel("Matterhorn Metadata") self.label_matterhorn.setToolTip( "Generates Matterhorn Metadata in XML format") self.checkbox_matterhorn = QCheckBox() layout.addRow(self.label_matterhorn, self.checkbox_matterhorn) def get_video_quality_layout(self): layout_video_quality = QHBoxLayout() layout_video_quality.addWidget(self.label_video_quality) layout_video_quality.addWidget(self.spinbox_video_quality) return layout_video_quality def get_audio_quality_layout(self): layout_audio_quality = QHBoxLayout() layout_audio_quality.addWidget(self.label_audio_quality) layout_audio_quality.addWidget(self.spinbox_audio_quality) return layout_audio_quality
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) # # Audio Quality # self.label_audio_quality = QLabel("Audio Quality") self.spinbox_audio_quality = QDoubleSpinBox() self.spinbox_audio_quality.setMinimum(0.0) self.spinbox_audio_quality.setMaximum(1.0) self.spinbox_audio_quality.setSingleStep(0.1) self.spinbox_audio_quality.setDecimals(1) self.spinbox_audio_quality.setValue(0.3) # Default value 0.3 # # Video Quality # self.label_video_quality = QLabel("Video Quality (kb/s)") self.spinbox_video_quality = QSpinBox() self.spinbox_video_quality.setMinimum(0) self.spinbox_video_quality.setMaximum(16777215) self.spinbox_video_quality.setValue(2400) # Default value 2400 # # Misc. # self.label_matterhorn = QLabel("Matterhorn Metadata") self.label_matterhorn.setToolTip("Generates Matterhorn Metadata in XML format") self.checkbox_matterhorn = QCheckBox() layout.addRow(self.label_matterhorn, self.checkbox_matterhorn) def get_video_quality_layout(self): layout_video_quality = QHBoxLayout() layout_video_quality.addWidget(self.label_video_quality) layout_video_quality.addWidget(self.spinbox_video_quality) return layout_video_quality def get_audio_quality_layout(self): layout_audio_quality = QHBoxLayout() layout_audio_quality.addWidget(self.label_audio_quality) layout_audio_quality.addWidget(self.spinbox_audio_quality) return layout_audio_quality
def testTemperatureSubscriber(): from PyQt4.QtGui import QApplication, QDoubleSpinBox app = QApplication([]) widget = QDoubleSpinBox() widget.setDecimals(7) widget.setMinimum(0) widget.setMaximum(1000) widget.setSuffix(' K') widget.setReadOnly(True) sub = TemperatureSubscriber(widget) sub.adrTemperatureReceived.connect(widget.setValue) widget.show() sub.start() app.exec_()
def createEditor( self, parent, _option, index ): if index.column() in ( CODCUENTA, NCUENTA ): value = index.model().index( index.row(), 0 ).data().toString() self.removeFromFilter( value ) self.proxymodel.setFilterRegExp( self.filter() ) sp = SearchPanel( self.proxymodel, parent, self.showTable ) sp.setColumn( index.column() ) return sp elif index.column() == MONTO: doublespinbox = QDoubleSpinBox( parent ) doublespinbox.setMinimum( -1000000 ) doublespinbox.setMaximum( 1000000 ) doublespinbox.setDecimals( 4 ) return doublespinbox
class DoubleSpinBox(QWidget): def __init__(self, id, text, **kwargs): QWidget.__init__(self) self.id = id self.widget = QDoubleSpinBox(**kwargs) label = QLabel(text) hbox = HBoxLayout() hbox.addWidget(label) hbox.addWidget(self.widget) self.setLayout(hbox) self.widget.setMaximum(999999999) self.widget.setMinimum(-999999999) def parameterValues(self): return {self.id:self.widget.value()}
def _create_user_value(self): layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) check_box = QCheckBox() spin_box = QDoubleSpinBox() spin_box.setDecimals(5) spin_box.setSingleStep(0.01) spin_box.setMinimum(-sys.float_info.max) spin_box.setMaximum(sys.float_info.max) spin_box.setDisabled(True) check_box.toggled.connect(spin_box.setEnabled) layout.addWidget(check_box) layout.addWidget(spin_box) return check_box, spin_box, layout
def addTableRow(self, row=None, enabled=True, f=10, A=0.1, phase=0.0, bw=5, order=8): table = self.table if row == None: row = table.rowCount() if row < 1: row = 0 table.insertRow(row) cb = QCheckBox() cb.setChecked(enabled) self.setTableCellWidget(row, 'active', cb) frequencySb = QDoubleSpinBox() frequencySb.setMinimum(1.0) frequencySb.setMaximum(self.fMax) frequencySb.setSingleStep(0.01) frequencySb.setDecimals(2) frequencySb.setValue(f) self.setTableCellWidget(row, 'f', frequencySb) amplitudeSb = AmplitudeSpinBox() amplitudeSb.setValue(A) amplitudeSb.valueChanged.connect(lambda v: self.amplitudeChanged(row, v)) self.setTableCellWidget(row, 'A', amplitudeSb) phaseSb = PhaseSpinBox() phaseSb.setValue(phase) self.setTableCellWidget(row, 'phase', phaseSb) bwSb = QDoubleSpinBox() bwSb.setMinimum(0.1) bwSb.setMaximum(1000) bwSb.setValue(bw) bwSb.setSuffix(' Hz') self.setTableCellWidget(row, 'bw', bwSb) orderSb = QSpinBox() orderSb.setMinimum(1) orderSb.setMaximum(10) orderSb.setValue(order) self.setTableCellWidget(row, 'order', orderSb) self.setTableCellWidget(row, 'X', QFloatDisplay()) self.setTableCellWidget(row, 'Y', QFloatDisplay()) self.setTableCellWidget(row, 'R', QFloatDisplay()) self.setTableCellWidget(row, 'Theta', QFloatDisplay())
def __init__(self, parent, prefix=None, suffix=None, option=None, min_=None, max_=None, step=None, tip=None, value=None, changed=None): super(MyDoubleSpinBox, self).__init__(parent) if prefix: plabel = QLabel(prefix) else: plabel = None if suffix: slabel = QLabel(suffix) else: slabel = None spinbox = QDoubleSpinBox(parent) if min_ is not None: spinbox.setMinimum(min_) if max_ is not None: spinbox.setMaximum(max_) if step is not None: spinbox.setSingleStep(step) if tip is not None: spinbox.setToolTip(tip) layout = QHBoxLayout() for subwidget in (plabel, spinbox, slabel): if subwidget is not None: layout.addWidget(subwidget) if value is not None: spinbox.setValue(value) if changed is not None: self.connect(spinbox, SIGNAL('valueChanged(double)'), changed) layout.addStretch(1) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.spin = spinbox
def createEditor( self, parent, option, index ): if index.column() in ( CODCUENTA, NCUENTA ): model = index.model() self.proxymodel.setSourceModel( self.accounts ) current = model.data( model.index( index.row(), IDCUENTA ) ) self.proxymodel.setFilterRegExp( self.filter( model, current ) ) sp = super( AccountsSelectorDelegate, self ).createEditor( parent, option, index ) sp.setColumnHidden( IDCUENTA ) return sp elif index.column() == MONTO: doublespinbox = QDoubleSpinBox( parent ) doublespinbox.setMinimum( -100000000000 ) doublespinbox.setMaximum( 100000000000 ) doublespinbox.setDecimals( 4 ) return doublespinbox
class IntervalSpinner(QWidget): def __init__(self, parent, min_=1, max_=1000, step=1, round_option=True): QWidget.__init__(self, parent) layout = QVBoxLayout(self) hlayout = QHBoxLayout() self.start = QDoubleSpinBox(self) self.start.setMinimum(min_) self.start.setMaximum(max_) self.end = QDoubleSpinBox(self) self.end.setMinimum(min_) self.end.setMaximum(max_) self.end.setValue(max_) self.start.setSingleStep(step) self.end.setSingleStep(step) self.start.valueChanged.connect(self.on_value_start_changed) self.end.valueChanged.connect(self.on_value_end_changed) hlayout.addWidget(self.start) hlayout.addWidget(self.end) layout.addLayout(hlayout) if round_option: self.integerCheckBox = QCheckBox("Round to integer values", self) layout.addWidget(self.integerCheckBox) def on_value_start_changed(self, val): if self.end.value() < val: self.end.setValue(val) def on_value_end_changed(self, val): if self.start.value() > val: self.start.setValue(val) def getMin(self): return self.start.value() def getMax(self): return self.end.value() def getRound(self): return self.integerCheckBox.isChecked()
class EkdTimePropertie(EkdPropertie): """ Définition de la propriété correspondant à un conteur ou une valeur de temps """ def __init__(self, prop, name, value, minimum=0, maximum=100, section=None ): super(EkdTimePropertie, self).__init__(prop, name, value, EkdPropertie.TIME, section) self.label = QLabel(name) self.widget = QDoubleSpinBox() self.widget.setValue(float(value)) self.widget.setMaximum(maximum) self.widget.setMinimum(minimum) # Quand on change la valeur de la propriété, on met à jour EkdConfig self.connect(self.widget, SIGNAL("valueChanged(double)"), self.updateNum) def updateNum(self, val): self.value = val EkdConfig.set(self.section, self.id, self.value) #print "Debug:: TIMER %s | value %s | value Ekd config %s | section %s" % (self.id, self.value, EkdConfig.get(self.section, self.id), self.section) EkdPrint(u"Debug:: TIMER %s | value %s | value Ekd config %s | section %s" % (self.id, self.value, EkdConfig.get(self.section, self.id), self.section))
class AnalogConfigLayout(QFormLayout): rangeChanged = pyqtSignal() def __init__(self, showSampleRateSb=False, settings=None, parent=None): super(AnalogConfigLayout, self).__init__(parent) self.deviceCombo = QComboBox() self.deviceCombo.setObjectName('deviceCombo') self.addRow('&Device', self.deviceCombo) self.channelCombo = QComboBox() self.channelCombo.setObjectName('channelCombo') self.addRow('&Channel', self.channelCombo) self.rangeCombo = QComboBox() self.rangeCombo.setObjectName('rangeCombo') self.addRow('&Range', self.rangeCombo) if showSampleRateSb: self.sampleRateSb = QDoubleSpinBox() self.sampleRateSb.setSuffix(' kHz') self.sampleRateSb.setMinimum(0.001) self.sampleRateSb.setDecimals(3) self.sampleRateSb.setValue(1) self.sampleRateSb.setObjectName('sampleRateSb') self.addRow('&Sample rate', self.sampleRateSb) else: self.sampleRateSb = None self._ranges = [] self.deviceCombo.currentIndexChanged.connect(self.deviceChanged) self.populateDevices() self.rangeCombo.currentIndexChanged.connect(self.rangeChanged) self.deviceCombo.setContextMenuPolicy(Qt.CustomContextMenu) self.deviceCombo.customContextMenuRequested.connect(self.contextMenu) def contextMenu(self, point): globalPos = self.deviceCombo.mapToGlobal(point) menu = QMenu() refreshAction = QAction("&Refresh", menu) menu.addAction(refreshAction) selected = menu.exec_(globalPos) if selected == refreshAction: self.populateDevices() def populateDevices(self): self.deviceCombo.clear() system = daq.System() devices = system.findDevices() for dev in devices: self.deviceCombo.addItem(dev) def deviceChanged(self): self.channelCombo.clear() for channel in self.channels(): self.channelCombo.addItem(channel) self.rangeCombo.clear() self._ranges = self.ranges() for r in self._ranges: self.rangeCombo.addItem('%+.2f -> %+.2f V' % (r.min, r.max)) if self.sampleRateSb is not None: fmax = self.maxSampleRate() self.sampleRateSb.setMaximum(1E-3 * fmax) def maxSampleRate(self): raise NotImplementedError def device(self): t = self.deviceCombo.currentText() if len(t): return str(t) else: return None def channel(self): return str(self.channelCombo.currentText()) def voltageRange(self): i = self.rangeCombo.currentIndex() return None if i < 0 else self._ranges[i] def restoreSettings(self, s=None): if s is None: s = QSettings() try: device = s.value('device', '', type=str) i = self.deviceCombo.findText(device) self.deviceCombo.setCurrentIndex(i) except: pass channel = s.value('channel', '', type=str) i = self.channelCombo.findText(channel) self.channelCombo.setCurrentIndex(i) voltageRange = s.value('range', '', type=str) i = self.rangeCombo.findText(voltageRange) self.rangeCombo.setCurrentIndex(i) def saveSettings(self, s=None): if s is None: s = QSettings() s.setValue('device', self.device()) s.setValue('channel', self.channel()) s.setValue('range', self.rangeCombo.currentText())
class TraceWindow(QMainWindow): def __init__(self, params_pipe, number_pipe, data_pipe, mads_pipe, peaks_pipe, probe_path=None, screen_resolution=None): QMainWindow.__init__(self) # Receive parameters. params = params_pipe[0].recv() self.probe = load_probe(probe_path) self._nb_samples = params['nb_samples'] self._sampling_rate = params['sampling_rate'] self._display_list = list(range(self.probe.nb_channels)) self._params = { 'nb_samples': self._nb_samples, 'sampling_rate': self._sampling_rate, 'time': { 'min': 10.0, # ms 'max': 1000.0, # ms 'init': 100.0, # ms }, 'voltage': { 'min': 10.0, # µV 'max': 10e+3, # µV 'init': 20.0, # µV }, 'mads': { 'min': 0.0, # µV 'max': 100, # µV 'init': 3, # µV }, 'channels': self._display_list } self._canvas = TraceCanvas(probe_path=probe_path, params=self._params) central_widget = self._canvas.native # Create controls widgets. label_time = QLabel() label_time.setText(u"time") label_time_unit = QLabel() label_time_unit.setText(u"ms") self._dsp_time = QDoubleSpinBox() self._dsp_time.setMinimum(self._params['time']['min']) self._dsp_time.setMaximum(self._params['time']['max']) self._dsp_time.setValue(self._params['time']['init']) self._dsp_time.valueChanged.connect(self._on_time_changed) label_display_mads = QLabel() label_display_mads.setText(u"Display Mads") self._display_mads = QCheckBox() self._display_mads.stateChanged.connect(self._on_mads_display) label_display_peaks = QLabel() label_display_peaks.setText(u"Display Peaks") self._display_peaks = QCheckBox() self._display_peaks.stateChanged.connect(self._on_peaks_display) label_mads = QLabel() label_mads.setText(u"Mads") label_mads_unit = QLabel() label_mads_unit.setText(u"unit") self._dsp_mads = QDoubleSpinBox() self._dsp_mads.setMinimum(self._params['mads']['min']) self._dsp_mads.setMaximum(self._params['mads']['max']) self._dsp_mads.setValue(self._params['mads']['init']) self._dsp_mads.valueChanged.connect(self._on_mads_changed) label_voltage = QLabel() label_voltage.setText(u"voltage") label_voltage_unit = QLabel() label_voltage_unit.setText(u"µV") self._dsp_voltage = QDoubleSpinBox() self._dsp_voltage.setMinimum(self._params['voltage']['min']) self._dsp_voltage.setMaximum(self._params['voltage']['max']) self._dsp_voltage.setValue(self._params['voltage']['init']) self._dsp_voltage.valueChanged.connect(self._on_voltage_changed) # Color spikes self._color_spikes = QCheckBox() self._color_spikes.setText('See Spikes color') self._color_spikes.setCheckState(Qt.Checked) self._color_spikes.stateChanged.connect(self.display_spikes_color) # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291)) spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create controls grid. grid = QGridLayout() # # Add time row. grid.addWidget(label_time, 0, 0) grid.addWidget(self._dsp_time, 0, 1) grid.addWidget(label_time_unit, 0, 2) # # Add voltage row. grid.addWidget(label_voltage, 1, 0) grid.addWidget(self._dsp_voltage, 1, 1) grid.addWidget(label_voltage_unit, 1, 2) # # Add Mads widgets grid.addWidget(label_display_mads, 3, 0) grid.addWidget(self._display_mads, 3, 1) grid.addWidget(label_mads, 4, 0) grid.addWidget(self._dsp_mads, 4, 1) grid.addWidget(label_mads_unit, 4, 2) grid.addWidget(self._color_spikes, 5, 0) # # Add spacer. grid.addItem(spacer) # # Create info group. controls_group = QGroupBox() controls_group.setLayout(grid) self._selection_channels = QListWidget() self._selection_channels.setSelectionMode( QAbstractItemView.ExtendedSelection ) for i in range(self.probe.nb_channels): item = QListWidgetItem("Channel %i" % i) self._selection_channels.addItem(item) self._selection_channels.item(i).setSelected(True) def add_channel(): items = self._selection_channels.selectedItems() self._display_list = [] for i in range(len(items)): self._display_list.append(i) self._on_channels_changed() # self._selection_channels.itemClicked.connect(add_channel) nb_channel = self.probe.nb_channels self._selection_channels.itemSelectionChanged.connect(lambda: self.selected_channels(nb_channel)) # Create info grid. channels_grid = QGridLayout() # # Add Channel selection # grid.addWidget(label_selection, 3, 0) channels_grid.addWidget(self._selection_channels, 0, 1) # # Add spacer. channels_grid.addItem(spacer) # Create controls group. channels_group = QGroupBox() channels_group.setLayout(channels_grid) # # Create controls dock. channels_dock = QDockWidget() channels_dock.setWidget(channels_group) channels_dock.setWindowTitle("Channels selection") # # Create controls dock. control_dock = QDockWidget() control_dock.setWidget(controls_group) control_dock.setWindowTitle("Controls") # Create info widgets. label_time = QLabel() label_time.setText(u"time") self._label_time_value = QLineEdit() self._label_time_value.setText(u"0") self._label_time_value.setReadOnly(True) self._label_time_value.setAlignment(Qt.AlignRight) label_time_unit = QLabel() label_time_unit.setText(u"s") info_buffer_label = QLabel() info_buffer_label.setText(u"buffer") self._info_buffer_value_label = QLineEdit() self._info_buffer_value_label.setText(u"0") self._info_buffer_value_label.setReadOnly(True) self._info_buffer_value_label.setAlignment(Qt.AlignRight) info_buffer_unit_label = QLabel() info_buffer_unit_label.setText(u"") info_probe_label = QLabel() info_probe_label.setText(u"probe") info_probe_value_label = QLineEdit() info_probe_value_label.setText(u"{}".format(probe_path)) info_probe_value_label.setReadOnly(True) # TODO place the following info in another grid? info_probe_unit_label = QLabel() info_probe_unit_label.setText(u"") info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create info grid. info_grid = QGridLayout() # # Time row. info_grid.addWidget(label_time, 0, 0) info_grid.addWidget(self._label_time_value, 0, 1) info_grid.addWidget(label_time_unit, 0, 2) # # Buffer row. info_grid.addWidget(info_buffer_label, 1, 0) info_grid.addWidget(self._info_buffer_value_label, 1, 1) info_grid.addWidget(info_buffer_unit_label, 1, 2) # # Probe row. info_grid.addWidget(info_probe_label, 2, 0) info_grid.addWidget(info_probe_value_label, 2, 1) info_grid.addWidget(info_probe_unit_label, 2, 2) # # Spacer. info_grid.addItem(info_spacer) # Create info group. info_group = QGroupBox() info_group.setLayout(info_grid) # Create info dock. info_dock = QDockWidget() info_dock.setWidget(info_group) info_dock.setWindowTitle("Info") # Create thread. thread = Thread(number_pipe, data_pipe, mads_pipe, peaks_pipe) thread.number_signal.connect(self._number_callback) thread.reception_signal.connect(self._reception_callback) thread.start() # Add dockable windows. self.addDockWidget(Qt.LeftDockWidgetArea, control_dock) self.addDockWidget(Qt.LeftDockWidgetArea, info_dock) self.addDockWidget(Qt.LeftDockWidgetArea, channels_dock) # Set central widget. self.setCentralWidget(central_widget) # Set window size. if screen_resolution is not None: screen_width = screen_resolution.width() screen_height = screen_resolution.height() self.resize(screen_width, screen_height) # Set window title. self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display") print(" ") # TODO remove? def _number_callback(self, number): text = u"{}".format(number) self._info_buffer_value_label.setText(text) text = u"{:8.3f}".format(float(number) * float(self._nb_samples) / self._sampling_rate) self._label_time_value.setText(text) return def _reception_callback(self, data, mads, peaks): self._canvas.on_reception(data, mads, peaks) return def _on_time_changed(self): time = self._dsp_time.value() self._canvas.set_time(time) return def _on_voltage_changed(self): voltage = self._dsp_voltage.value() self._canvas.set_voltage(voltage) return def _on_mads_changed(self): mads = self._dsp_mads.value() self._canvas.set_mads(mads) return def _on_mads_display(self): value = self._display_mads.isChecked() self._canvas.show_mads(value) return def _on_peaks_display(self): value = self._display_peaks.isChecked() self._canvas.show_peaks(value) return def _on_channels_changed(self): self._canvas.set_channels(self._display_list) return def display_spikes_color(self, s): self._canvas.color_spikes(s) def selected_channels(self, max_channel): # print(self._selection_channels.selectedItems()) list_channel = [] for i in range(max_channel): if self._selection_channels.item(i).isSelected(): list_channel.append(i) self._canvas.selected_channels(list_channel) return
def initAppletDrawerUi(self): """ Overridden from base class (LayerViewerGui) """ op = self.topLevelOperatorView def configure_update_handlers(qt_signal, op_slot): qt_signal.connect(self.configure_operator_from_gui) op_slot.notifyDirty(self.configure_gui_from_operator) self.__cleanup_fns.append( partial(op_slot.unregisterDirty, self.configure_gui_from_operator)) def control_layout(label_text, widget): row_layout = QHBoxLayout() row_layout.addWidget(QLabel(label_text)) row_layout.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding)) row_layout.addWidget(widget) return row_layout drawer_layout = QVBoxLayout() channel_box = QSpinBox() def set_channel_box_range(*args): if sip.isdeleted(channel_box): return channel_box.setMinimum(0) channel_box.setMaximum(op.Input.meta.getTaggedShape()['c'] - 1) set_channel_box_range() op.Input.notifyMetaChanged(set_channel_box_range) configure_update_handlers(channel_box.valueChanged, op.ChannelSelection) drawer_layout.addLayout(control_layout("Input Channel", channel_box)) self.channel_box = channel_box threshold_box = QDoubleSpinBox() threshold_box.setDecimals(2) threshold_box.setMinimum(0.00) threshold_box.setMaximum(1.0) threshold_box.setSingleStep(0.1) configure_update_handlers(threshold_box.valueChanged, op.Pmin) drawer_layout.addLayout(control_layout("Threshold", threshold_box)) self.threshold_box = threshold_box membrane_size_box = QSpinBox() membrane_size_box.setMinimum(0) membrane_size_box.setMaximum(1000000) configure_update_handlers(membrane_size_box.valueChanged, op.MinMembraneSize) drawer_layout.addLayout( control_layout("Min Membrane Size", membrane_size_box)) self.membrane_size_box = membrane_size_box seed_presmoothing_box = QDoubleSpinBox() seed_presmoothing_box.setDecimals(1) seed_presmoothing_box.setMinimum(0.0) seed_presmoothing_box.setMaximum(10.0) seed_presmoothing_box.setSingleStep(0.1) configure_update_handlers(seed_presmoothing_box.valueChanged, op.SigmaMinima) drawer_layout.addLayout( control_layout("Presmooth before seeds", seed_presmoothing_box)) self.seed_presmoothing_box = seed_presmoothing_box seed_method_combo = QComboBox() seed_method_combo.addItem("Connected") seed_method_combo.addItem("Clustered") configure_update_handlers(seed_method_combo.currentIndexChanged, op.GroupSeeds) drawer_layout.addLayout( control_layout("Seed Labeling", seed_method_combo)) self.seed_method_combo = seed_method_combo watershed_presmoothing_box = QDoubleSpinBox() watershed_presmoothing_box.setDecimals(1) watershed_presmoothing_box.setMinimum(0.0) watershed_presmoothing_box.setMaximum(10.0) watershed_presmoothing_box.setSingleStep(0.1) configure_update_handlers(watershed_presmoothing_box.valueChanged, op.SigmaWeights) drawer_layout.addLayout( control_layout("Presmooth before watershed", watershed_presmoothing_box)) self.watershed_presmoothing_box = watershed_presmoothing_box superpixel_size_box = QSpinBox() superpixel_size_box.setMinimum(0) superpixel_size_box.setMaximum(1000000) configure_update_handlers(superpixel_size_box.valueChanged, op.MinSegmentSize) drawer_layout.addLayout( control_layout("Min Superpixel Size", superpixel_size_box)) self.superpixel_size_box = superpixel_size_box enable_debug_box = QCheckBox() configure_update_handlers(enable_debug_box.toggled, op.EnableDebugOutputs) drawer_layout.addLayout( control_layout("Show Debug Layers", enable_debug_box)) self.enable_debug_box = enable_debug_box compute_button = QPushButton("Update Watershed", clicked=self.onUpdateWatershedsButton) drawer_layout.addWidget(compute_button) drawer_layout.setSpacing(0) drawer_layout.addSpacerItem( QSpacerItem(0, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)) # Finally, the whole drawer widget drawer = QWidget(parent=self) drawer.setLayout(drawer_layout) # Save these members for later use self._drawer = drawer # Initialize everything with the operator's initial values self.configure_gui_from_operator()
def setup_thresholds_panel(self, classification): """Setup threshold panel in the right panel. :param classification: Classification definition. :type classification: dict """ # Set text in the label layer_purpose = self.parent.step_kw_purpose.selected_purpose() layer_subcategory = self.parent.step_kw_subcategory.\ selected_subcategory() if is_raster_layer(self.parent.layer): statistics = self.parent.layer.dataProvider().bandStatistics( 1, QgsRasterBandStats.All, self.parent.layer.extent(), 0) description_text = continuous_raster_question % ( layer_purpose['name'], layer_subcategory['name'], classification['name'], statistics.minimumValue, statistics.maximumValue) else: field_name = self.parent.step_kw_field.selected_fields() field_index = self.parent.layer.fieldNameIndex(field_name) min_value_layer = self.parent.layer.minimumValue(field_index) max_value_layer = self.parent.layer.maximumValue(field_index) description_text = continuous_vector_question % ( layer_purpose['name'], layer_subcategory['name'], field_name, classification['name'], min_value_layer, max_value_layer) # Set description description_label = QLabel(description_text) description_label.setWordWrap(True) self.right_layout.addWidget(description_label) if self.thresholds: thresholds = self.thresholds else: thresholds = self.parent.get_existing_keyword('thresholds') selected_unit = self.parent.step_kw_unit.selected_unit()['key'] self.threshold_classes = OrderedDict() classes = classification.get('classes') # Sort by value, put the lowest first classes = sorted(classes, key=lambda the_key: the_key['value']) grid_layout_thresholds = QGridLayout() for i, the_class in enumerate(classes): class_layout = QHBoxLayout() # Class label class_label = QLabel(the_class['name']) # Min label min_label = QLabel(tr('Min >')) # Min value as double spin min_value_input = QDoubleSpinBox() # TODO(IS) We can set the min and max depends on the unit, later min_value_input.setMinimum(0) min_value_input.setMaximum(999999) if thresholds.get(self.active_exposure['key']): exposure_thresholds = thresholds.get( self.active_exposure['key']) if exposure_thresholds.get(classification['key']): exposure_thresholds_classifications = exposure_thresholds\ .get(classification['key']) min_value_input.setValue( exposure_thresholds_classifications['classes'][ the_class['key']][0]) else: default_min = the_class['numeric_default_min'] if isinstance(default_min, dict): default_min = the_class[ 'numeric_default_min'][selected_unit] min_value_input.setValue(default_min) else: default_min = the_class['numeric_default_min'] if isinstance(default_min, dict): default_min = the_class[ 'numeric_default_min'][selected_unit] min_value_input.setValue(default_min) min_value_input.setSingleStep(0.1) # Max label max_label = QLabel(tr('Max <=')) # Max value as double spin max_value_input = QDoubleSpinBox() # TODO(IS) We can set the min and max depends on the unit, later max_value_input.setMinimum(0) max_value_input.setMaximum(999999) if thresholds.get(self.active_exposure['key']): exposure_thresholds = thresholds.get( self.active_exposure['key']) if exposure_thresholds.get(classification['key']): exposure_thresholds_classifications = exposure_thresholds \ .get(classification['key']) max_value_input.setValue( exposure_thresholds_classifications['classes'][ the_class['key']][1]) else: default_max = the_class['numeric_default_max'] if isinstance(default_max, dict): default_max = the_class[ 'numeric_default_max'][selected_unit] max_value_input.setValue(default_max) else: default_max = the_class['numeric_default_max'] if isinstance(default_max, dict): default_max = the_class[ 'numeric_default_max'][selected_unit] max_value_input.setValue(default_max) max_value_input.setSingleStep(0.1) # Add to class_layout class_layout.addWidget(min_label) class_layout.addWidget(min_value_input) class_layout.addWidget(max_label) class_layout.addWidget(max_value_input) class_layout.setStretch(0, 1) class_layout.setStretch(1, 2) class_layout.setStretch(2, 1) class_layout.setStretch(3, 2) # Add to grid_layout grid_layout_thresholds.addWidget(class_label, i, 0) grid_layout_thresholds.addLayout(class_layout, i, 1) self.threshold_classes[the_class['key']] = [ min_value_input, max_value_input] grid_layout_thresholds.setColumnStretch(0, 1) grid_layout_thresholds.setColumnStretch(0, 2) def min_max_changed(double_spin_index, mode): """Slot when min or max value change. :param double_spin_index: The index of the double spin. :type double_spin_index: int :param mode: The flag to indicate the min or max value. :type mode: int """ if mode == MAX_VALUE_MODE: current_max_value = self.threshold_classes.values()[ double_spin_index][1] target_min_value = self.threshold_classes.values()[ double_spin_index + 1][0] if current_max_value.value() != target_min_value.value(): target_min_value.setValue(current_max_value.value()) elif mode == MIN_VALUE_MODE: current_min_value = self.threshold_classes.values()[ double_spin_index][0] target_max_value = self.threshold_classes.values()[ double_spin_index - 1][1] if current_min_value.value() != target_max_value.value(): target_max_value.setValue(current_min_value.value()) # Set behaviour for k, v in self.threshold_classes.items(): index = self.threshold_classes.keys().index(k) if index < len(self.threshold_classes) - 1: # Max value changed v[1].valueChanged.connect(partial( min_max_changed, double_spin_index=index, mode=MAX_VALUE_MODE)) if index > 0: # Min value v[0].valueChanged.connect(partial( min_max_changed, double_spin_index=index, mode=MIN_VALUE_MODE)) grid_layout_thresholds.setSpacing(0) self.right_layout.addLayout(grid_layout_thresholds)
class TaskGeneratorDialog(QDialog): def __init__(self, nbprocessors): QDialog.__init__(self) self.layout = QVBoxLayout(self) self.taskset = None # Utilizations: vbox_utilizations = QVBoxLayout() group = QGroupBox("Task Utilizations:") hbox = QHBoxLayout() hbox.addWidget(QLabel("Generator:", self)) self.comboGenerator = QComboBox() self.comboGenerator.addItem("RandFixedSum") self.comboGenerator.addItem("UUniFast-Discard") self.comboGenerator.addItem("Kato's method") self.comboGenerator.currentIndexChanged.connect(self.generator_changed) hbox.addWidget(self.comboGenerator) vbox_utilizations.addLayout(hbox) # Load slider + spinner: hbox_load = QHBoxLayout() sld = _DoubleSlider(QtCore.Qt.Horizontal, self) sld.setMinimum(0) sld.setMaximum(32) self.spin_load = QDoubleSpinBox(self) self.spin_load.setMinimum(0) self.spin_load.setMaximum(32) self.spin_load.setSingleStep(0.1) hbox_load.addWidget(QLabel("Total utilization: ", self)) hbox_load.addWidget(sld) hbox_load.addWidget(self.spin_load) sld.doubleValueChanged.connect(self.spin_load.setValue) self.spin_load.valueChanged.connect(sld.setValue) self.spin_load.setValue(nbprocessors / 2.) vbox_utilizations.addLayout(hbox_load) # Number of periodic tasks: self.hbox_tasks = QHBoxLayout() self.spin_tasks = QSpinBox(self) self.spin_tasks.setMinimum(0) self.spin_tasks.setMaximum(999) # That's arbitrary. self.hbox_tasks.addWidget(QLabel("Number of periodic tasks: ", self)) self.hbox_tasks.addStretch(1) self.hbox_tasks.addWidget(self.spin_tasks) vbox_utilizations.addLayout(self.hbox_tasks) # Number of sporadic tasks: self.hbox_sporadic_tasks = QHBoxLayout() self.spin_sporadic_tasks = QSpinBox(self) self.spin_sporadic_tasks.setMinimum(0) self.spin_sporadic_tasks.setMaximum(999) # That's arbitrary. self.hbox_sporadic_tasks.addWidget( QLabel("Number of sporadic tasks: ", self)) self.hbox_sporadic_tasks.addStretch(1) self.hbox_sporadic_tasks.addWidget(self.spin_sporadic_tasks) vbox_utilizations.addLayout(self.hbox_sporadic_tasks) # Min / Max utilizations self.hbox_utilizations = QHBoxLayout() self.hbox_utilizations.addWidget(QLabel("Min/Max utilizations: ", self)) self.interval_utilization = IntervalSpinner( self, min_=0, max_=1, step=.01, round_option=False) self.hbox_utilizations.addWidget(self.interval_utilization) vbox_utilizations.addLayout(self.hbox_utilizations) group.setLayout(vbox_utilizations) self.layout.addWidget(group) # Periods: vbox_periods = QVBoxLayout() group = QGroupBox("Task Periods:") # Log uniform self.lunif = QRadioButton("log-uniform distribution between:") vbox_periods.addWidget(self.lunif) self.lunif.setChecked(True) self.lunif_interval = IntervalSpinner(self) self.lunif_interval.setEnabled(self.lunif.isChecked()) self.lunif.toggled.connect(self.lunif_interval.setEnabled) vbox_periods.addWidget(self.lunif_interval) # Uniform self.unif = QRadioButton("uniform distribution between:") vbox_periods.addWidget(self.unif) self.unif_interval = IntervalSpinner(self) self.unif_interval.setEnabled(self.unif.isChecked()) self.unif.toggled.connect(self.unif_interval.setEnabled) vbox_periods.addWidget(self.unif_interval) # Discrete discrete = QRadioButton("chosen among these (space separated) values:") vbox_periods.addWidget(discrete) self.periods = QLineEdit(self) self.periods.setValidator(QRegExpValidator( QRegExp("^\\d*(\.\\d*)?( \\d*(\.\\d*)?)*$"))) vbox_periods.addWidget(self.periods) self.periods.setEnabled(discrete.isChecked()) discrete.toggled.connect(self.periods.setEnabled) vbox_periods.addStretch(1) group.setLayout(vbox_periods) self.layout.addWidget(group) buttonBox = QDialogButtonBox() cancel = buttonBox.addButton(QDialogButtonBox.Cancel) generate = buttonBox.addButton("Generate", QDialogButtonBox.AcceptRole) cancel.clicked.connect(self.reject) generate.clicked.connect(self.generate) self.layout.addWidget(buttonBox) self.show_randfixedsum_options() def generator_changed(self, value): if value == 2: self.show_kato_options() else: self.show_randfixedsum_options() def show_randfixedsum_options(self): for i in range(self.hbox_utilizations.count()): self.hbox_utilizations.itemAt(i).widget().hide() for i in range(self.hbox_tasks.count()): if self.hbox_tasks.itemAt(i).widget(): self.hbox_tasks.itemAt(i).widget().show() for i in range(self.hbox_sporadic_tasks.count()): if self.hbox_sporadic_tasks.itemAt(i).widget(): self.hbox_sporadic_tasks.itemAt(i).widget().show() def show_kato_options(self): for i in range(self.hbox_utilizations.count()): if self.hbox_utilizations.itemAt(i).widget(): self.hbox_utilizations.itemAt(i).widget().show() for i in range(self.hbox_tasks.count()): if self.hbox_tasks.itemAt(i).widget(): self.hbox_tasks.itemAt(i).widget().hide() for i in range(self.hbox_sporadic_tasks.count()): if self.hbox_sporadic_tasks.itemAt(i).widget(): self.hbox_sporadic_tasks.itemAt(i).widget().hide() def get_min_utilization(self): return self.interval_utilization.getMin() def get_max_utilization(self): return self.interval_utilization.getMax() def generate(self): if self.comboGenerator.currentIndex() == 0: n = self.get_nb_tasks() u = StaffordRandFixedSum(n, self.get_utilization(), 1) elif self.comboGenerator.currentIndex() == 1: n = self.get_nb_tasks() u = UUniFastDiscard(n, self.get_utilization(), 1) else: u = gen_kato_utilizations(1, self.get_min_utilization(), self.get_max_utilization(), self.get_utilization()) n = len(u[0]) p_types = self.get_periods() if p_types[0] == "unif": p = gen_periods_uniform(n, 1, p_types[1], p_types[2], p_types[3]) elif p_types[0] == "lunif": p = gen_periods_loguniform(n, 1, p_types[1], p_types[2], p_types[3]) else: p = gen_periods_discrete(n, 1, p_types[1]) if u and p: self.taskset = gen_tasksets(u, p)[0] self.accept() elif not u: QMessageBox.warning( self, "Generation failed", "Please check the utilization and the number of tasks.") else: QMessageBox.warning( self, "Generation failed", "Pleache check the periods.") def get_nb_tasks(self): return self.spin_tasks.value() + self.spin_sporadic_tasks.value() def get_nb_periodic_tasks(self): return self.spin_tasks.value() def get_nb_sporadic_tasks(self): return self.spin_sporadic_tasks.value() def get_utilization(self): return self.spin_load.value() def get_periods(self): if self.unif.isChecked(): return ("unif", self.unif_interval.getMin(), self.unif_interval.getMax(), self.unif_interval.getRound()) elif self.lunif.isChecked(): return ("lunif", self.lunif_interval.getMin(), self.lunif_interval.getMax(), self.lunif_interval.getRound()) else: return ("discrete", map(float, str(self.periods.text()).split()))
class DefaultSelectParameterWidget(SelectParameterWidget): """Widget class for Default Select Parameter.""" def __init__(self, parameter, parent=None): """Constructor :param parameter: A DefaultSelectParameter object. :type parameter: DefaultSelectParameter """ super(DefaultSelectParameterWidget, self).__init__(parameter, parent) self.default_layout = QHBoxLayout() self.radio_button_layout = QHBoxLayout() self.radio_button_widget = QWidget() self.default_label = QLabel(tr('Default')) # Create radio button group self.default_input_button_group = QButtonGroup() # Define string enabler for radio button self.radio_button_enabler = self.input.itemData(0, Qt.UserRole) for i in range(len(self._parameter.default_labels)): if '%s' in self._parameter.default_labels[i]: label = (self._parameter.default_labels[i] % self._parameter.default_values[i]) else: label = self._parameter.default_labels[i] radio_button = QRadioButton(label) self.radio_button_layout.addWidget(radio_button) self.default_input_button_group.addButton(radio_button, i) if self._parameter.default_value == \ self._parameter.default_values[i]: radio_button.setChecked(True) # Create double spin box for custom value self.custom_value = QDoubleSpinBox() if self._parameter.default_values[-1]: self.custom_value.setValue(self._parameter.default_values[-1]) has_min = False if self._parameter.minimum is not None: has_min = True self.custom_value.setMinimum(self._parameter.minimum) has_max = False if self._parameter.maximum is not None: has_max = True self.custom_value.setMaximum(self._parameter.maximum) if has_min and has_max: step = (self._parameter.maximum - self._parameter.minimum) / 100.0 self.custom_value.setSingleStep(step) self.radio_button_layout.addWidget(self.custom_value) self.toggle_custom_value() # Reset the layout self.input_layout.setParent(None) self.help_layout.setParent(None) self.label.setParent(None) self.inner_input_layout.setParent(None) self.input_layout = QGridLayout() self.input_layout.setSpacing(0) self.input_layout.addWidget(self.label, 0, 0) self.input_layout.addLayout(self.inner_input_layout, 0, 1) self.input_layout.addWidget(self.default_label, 1, 0) self.input_layout.addLayout(self.radio_button_layout, 1, 1) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) # check every added combobox, it could have been toggled by # the existing keyword self.toggle_input() # Connect # noinspection PyUnresolvedReferences self.input.currentIndexChanged.connect(self.toggle_input) self.default_input_button_group.buttonClicked.connect( self.toggle_custom_value) def raise_invalid_type_exception(self): message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) err = ValueError(message) return err def get_parameter(self): """Obtain list parameter object from the current widget state. :returns: A DefaultSelectParameter from the current state of widget. """ current_index = self.input.currentIndex() selected_value = self.input.itemData(current_index, Qt.UserRole) if hasattr(selected_value, 'toPyObject'): selected_value = selected_value.toPyObject() try: self._parameter.value = selected_value except ValueError: err = self.raise_invalid_type_exception() raise err radio_button_checked_id = self.default_input_button_group.checkedId() # No radio button checked, then default value = None if radio_button_checked_id == -1: self._parameter.default = None # The last radio button (custom) is checked, get the value from the # line edit elif (radio_button_checked_id == len(self._parameter.default_values) - 1): self._parameter.default_values[radio_button_checked_id] \ = self.custom_value.value() self._parameter.default = self.custom_value.value() else: self._parameter.default = self._parameter.default_values[ radio_button_checked_id] return self._parameter def set_default(self, default): """Set default value by item's string. :param default: The default. :type default: str, int :returns: True if success, else False. :rtype: bool """ # Find index of choice try: default_index = self._parameter.default_values.index(default) self.default_input_button_group.button(default_index).setChecked( True) except ValueError: last_index = len(self._parameter.default_values) - 1 self.default_input_button_group.button(last_index).setChecked(True) self.custom_value.setValue(default) self.toggle_custom_value() def toggle_custom_value(self): radio_button_checked_id = self.default_input_button_group.checkedId() if (radio_button_checked_id == len(self._parameter.default_values) - 1): self.custom_value.setDisabled(False) else: self.custom_value.setDisabled(True) def toggle_input(self): """Change behaviour of radio button based on input.""" current_index = self.input.currentIndex() # If current input is not a radio button enabler, disable radio button. if self.input.itemData(current_index, Qt.UserRole) != (self.radio_button_enabler): self.disable_radio_button() # Otherwise, enable radio button. else: self.enable_radio_button() def set_selected_radio_button(self): """Set selected radio button to 'Do not report'.""" dont_use_button = self.default_input_button_group.button( len(self._parameter.default_values) - 2) dont_use_button.setChecked(True) def disable_radio_button(self): """Disable radio button group and custom value input area.""" checked = self.default_input_button_group.checkedButton() if checked: self.default_input_button_group.setExclusive(False) checked.setChecked(False) self.default_input_button_group.setExclusive(True) for button in self.default_input_button_group.buttons(): button.setDisabled(True) self.custom_value.setDisabled(True) def enable_radio_button(self): """Enable radio button and custom value input area then set selected radio button to 'Do not report'. """ for button in self.default_input_button_group.buttons(): button.setEnabled(True) self.set_selected_radio_button() self.custom_value.setEnabled(True)
class TaskGeneratorDialog(QDialog): def __init__(self, nbprocessors): QDialog.__init__(self) self.layout = QVBoxLayout(self) self.taskset = None # Utilizations: vbox_utilizations = QVBoxLayout() group = QGroupBox("Task Utilizations:") hbox = QHBoxLayout() hbox.addWidget(QLabel("Generator:", self)) self.comboGenerator = QComboBox() self.comboGenerator.addItem("RandFixedSum") self.comboGenerator.addItem("UUniFast-Discard") self.comboGenerator.addItem("Kato's method") self.comboGenerator.currentIndexChanged.connect(self.generator_changed) hbox.addWidget(self.comboGenerator) vbox_utilizations.addLayout(hbox) # Load slider + spinner: hbox_load = QHBoxLayout() sld = _DoubleSlider(QtCore.Qt.Horizontal, self) sld.setMinimum(0) sld.setMaximum(32) self.spin_load = QDoubleSpinBox(self) self.spin_load.setMinimum(0) self.spin_load.setMaximum(32) self.spin_load.setSingleStep(0.1) hbox_load.addWidget(QLabel("Total utilization: ", self)) hbox_load.addWidget(sld) hbox_load.addWidget(self.spin_load) sld.doubleValueChanged.connect(self.spin_load.setValue) self.spin_load.valueChanged.connect(sld.setValue) self.spin_load.setValue(nbprocessors / 2.) vbox_utilizations.addLayout(hbox_load) # Number of periodic tasks: self.hbox_tasks = QHBoxLayout() self.spin_tasks = QSpinBox(self) self.spin_tasks.setMinimum(0) self.spin_tasks.setMaximum(999) # That's arbitrary. self.hbox_tasks.addWidget(QLabel("Number of periodic tasks: ", self)) self.hbox_tasks.addStretch(1) self.hbox_tasks.addWidget(self.spin_tasks) vbox_utilizations.addLayout(self.hbox_tasks) # Number of sporadic tasks: self.hbox_sporadic_tasks = QHBoxLayout() self.spin_sporadic_tasks = QSpinBox(self) self.spin_sporadic_tasks.setMinimum(0) self.spin_sporadic_tasks.setMaximum(999) # That's arbitrary. self.hbox_sporadic_tasks.addWidget( QLabel("Number of sporadic tasks: ", self)) self.hbox_sporadic_tasks.addStretch(1) self.hbox_sporadic_tasks.addWidget(self.spin_sporadic_tasks) vbox_utilizations.addLayout(self.hbox_sporadic_tasks) # Min / Max utilizations self.hbox_utilizations = QHBoxLayout() self.hbox_utilizations.addWidget(QLabel("Min/Max utilizations: ", self)) self.interval_utilization = IntervalSpinner(self, min_=0, max_=1, step=.01, round_option=False) self.hbox_utilizations.addWidget(self.interval_utilization) vbox_utilizations.addLayout(self.hbox_utilizations) group.setLayout(vbox_utilizations) self.layout.addWidget(group) # Periods: vbox_periods = QVBoxLayout() group = QGroupBox("Task Periods:") # Log uniform self.lunif = QRadioButton("log-uniform distribution between:") vbox_periods.addWidget(self.lunif) self.lunif.setChecked(True) self.lunif_interval = IntervalSpinner(self) self.lunif_interval.setEnabled(self.lunif.isChecked()) self.lunif.toggled.connect(self.lunif_interval.setEnabled) vbox_periods.addWidget(self.lunif_interval) # Uniform self.unif = QRadioButton("uniform distribution between:") vbox_periods.addWidget(self.unif) self.unif_interval = IntervalSpinner(self) self.unif_interval.setEnabled(self.unif.isChecked()) self.unif.toggled.connect(self.unif_interval.setEnabled) vbox_periods.addWidget(self.unif_interval) # Discrete discrete = QRadioButton("chosen among these (space separated) values:") vbox_periods.addWidget(discrete) self.periods = QLineEdit(self) self.periods.setValidator( QRegExpValidator(QRegExp("^\\d*(\.\\d*)?( \\d*(\.\\d*)?)*$"))) vbox_periods.addWidget(self.periods) self.periods.setEnabled(discrete.isChecked()) discrete.toggled.connect(self.periods.setEnabled) vbox_periods.addStretch(1) group.setLayout(vbox_periods) self.layout.addWidget(group) buttonBox = QDialogButtonBox() cancel = buttonBox.addButton(QDialogButtonBox.Cancel) generate = buttonBox.addButton("Generate", QDialogButtonBox.AcceptRole) cancel.clicked.connect(self.reject) generate.clicked.connect(self.generate) self.layout.addWidget(buttonBox) self.show_randfixedsum_options() def generator_changed(self, value): if value == 2: self.show_kato_options() else: self.show_randfixedsum_options() def show_randfixedsum_options(self): for i in range(self.hbox_utilizations.count()): self.hbox_utilizations.itemAt(i).widget().hide() for i in range(self.hbox_tasks.count()): if self.hbox_tasks.itemAt(i).widget(): self.hbox_tasks.itemAt(i).widget().show() for i in range(self.hbox_sporadic_tasks.count()): if self.hbox_sporadic_tasks.itemAt(i).widget(): self.hbox_sporadic_tasks.itemAt(i).widget().show() def show_kato_options(self): for i in range(self.hbox_utilizations.count()): if self.hbox_utilizations.itemAt(i).widget(): self.hbox_utilizations.itemAt(i).widget().show() for i in range(self.hbox_tasks.count()): if self.hbox_tasks.itemAt(i).widget(): self.hbox_tasks.itemAt(i).widget().hide() for i in range(self.hbox_sporadic_tasks.count()): if self.hbox_sporadic_tasks.itemAt(i).widget(): self.hbox_sporadic_tasks.itemAt(i).widget().hide() def get_min_utilization(self): return self.interval_utilization.getMin() def get_max_utilization(self): return self.interval_utilization.getMax() def generate(self): if self.comboGenerator.currentIndex() == 0: n = self.get_nb_tasks() u = StaffordRandFixedSum(n, self.get_utilization(), 1) elif self.comboGenerator.currentIndex() == 1: n = self.get_nb_tasks() u = UUniFastDiscard(n, self.get_utilization(), 1) else: u = gen_kato_utilizations(1, self.get_min_utilization(), self.get_max_utilization(), self.get_utilization()) n = len(u[0]) p_types = self.get_periods() if p_types[0] == "unif": p = gen_periods_uniform(n, 1, p_types[1], p_types[2], p_types[3]) elif p_types[0] == "lunif": p = gen_periods_loguniform(n, 1, p_types[1], p_types[2], p_types[3]) else: p = gen_periods_discrete(n, 1, p_types[1]) if u and p: self.taskset = gen_tasksets(u, p)[0] self.accept() elif not u: QMessageBox.warning( self, "Generation failed", "Please check the utilization and the number of tasks.") else: QMessageBox.warning(self, "Generation failed", "Pleache check the periods.") def get_nb_tasks(self): return self.spin_tasks.value() + self.spin_sporadic_tasks.value() def get_nb_periodic_tasks(self): return self.spin_tasks.value() def get_nb_sporadic_tasks(self): return self.spin_sporadic_tasks.value() def get_utilization(self): return self.spin_load.value() def get_periods(self): if self.unif.isChecked(): return ("unif", self.unif_interval.getMin(), self.unif_interval.getMax(), self.unif_interval.getRound()) elif self.lunif.isChecked(): return ("lunif", self.lunif_interval.getMin(), self.lunif_interval.getMax(), self.lunif_interval.getRound()) else: return ("discrete", map(float, str(self.periods.text()).split()))
class TemplateWindow(QMainWindow): def __init__(self, params_pipe, number_pipe, templates_pipe, spikes_pipe, probe_path=None, screen_resolution=None): QMainWindow.__init__(self) # Receive parameters. params = params_pipe[0].recv() self.probe = load_probe(probe_path) self._nb_samples = params['nb_samples'] self._sampling_rate = params['sampling_rate'] self._display_list = [] self._params = { 'nb_samples': self._nb_samples, 'sampling_rate': self._sampling_rate, 'time': { 'min': 10.0, # ms 'max': 100.0, # ms 'init': 100.0, # ms }, 'voltage': { 'min': -200, # µV 'max': 20e+1, # µV 'init': 50.0, # µV }, 'templates': self._display_list } self._canvas_mea = MEACanvas(probe_path=probe_path, params=self._params) self._canvas_template = TemplateCanvas(probe_path=probe_path, params=self._params) self._canvas_rate = RateCanvas(probe_path=probe_path, params=self._params) self._canvas_isi = ISICanvas(probe_path=probe_path, params=self._params) self.cells = Cells({}) self._nb_buffer = 0 # TODO ISI self.isi_bin_width, self.isi_x_max = 2, 25.0 canvas_template_widget = self._canvas_template.native canvas_mea = self._canvas_mea.native canvas_rate = self._canvas_rate.native canvas_isi = self._canvas_isi.native # Create controls widgets. label_time = QLabel() label_time.setText(u"time") label_time_unit = QLabel() label_time_unit.setText(u"ms") self._dsp_time = QDoubleSpinBox() self._dsp_time.setMinimum(self._params['time']['min']) self._dsp_time.setMaximum(self._params['time']['max']) self._dsp_time.setValue(self._params['time']['init']) self._dsp_time.valueChanged.connect(self._on_time_changed) label_voltage = QLabel() label_voltage.setText(u"voltage") label_voltage_unit = QLabel() label_voltage_unit.setText(u"µV") self._dsp_voltage = QDoubleSpinBox() self._dsp_voltage.setMinimum(self._params['voltage']['min']) self._dsp_voltage.setMaximum(self._params['voltage']['max']) self._dsp_voltage.setValue(self._params['voltage']['init']) self._dsp_voltage.valueChanged.connect(self._on_voltage_changed) label_binsize = QLabel() label_binsize.setText(u"Bin size") label_binsize_unit = QLabel() label_binsize_unit.setText(u"second") self._dsp_binsize = QDoubleSpinBox() self._dsp_binsize.setRange(0.1, 10) self._dsp_binsize.setSingleStep(0.1) self.bin_size = 1 self._dsp_binsize.setValue(self.bin_size) self._dsp_binsize.valueChanged.connect(self._on_binsize_changed) label_zoomrates = QLabel() label_zoomrates.setText(u'Zoom rates') self._zoom_rates = QDoubleSpinBox() self._zoom_rates.setRange(1, 50) self._zoom_rates.setSingleStep(0.1) self._zoom_rates.setValue(1) self._zoom_rates.valueChanged.connect(self._on_zoomrates_changed) label_time_window = QLabel() label_time_window.setText(u'Time window rates') label_time_window_unit = QLabel() label_time_window_unit.setText(u'second') self._dsp_tw_rate = QDoubleSpinBox() self._dsp_tw_rate.setRange(1, 50) self._dsp_tw_rate.setSingleStep(self.bin_size) self._dsp_tw_rate.setValue(50 * self.bin_size) self._dsp_tw_rate.valueChanged.connect(self._on_time_window_changed) label_tw_from_start = QLabel() label_tw_from_start.setText('Time scale from start') self._tw_from_start = QCheckBox() self._tw_from_start.setChecked(True) self._selection_templates = QTableWidget() self._selection_templates.setSelectionMode( QAbstractItemView.ExtendedSelection ) self._selection_templates.setColumnCount(3) self._selection_templates.setVerticalHeaderLabels(['Nb template', 'Channel', 'Amplitude']) self._selection_templates.insertRow(0) self._selection_templates.setItem(0, 0, QTableWidgetItem('Nb template')) self._selection_templates.setItem(0, 1, QTableWidgetItem('Channel')) self._selection_templates.setItem(0, 2, QTableWidgetItem('Amplitude')) # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291)) # for i in range(self.nb_templates): # numRows = self.tableWidget.rowCount() # self.tableWidget.insertRow(numRows) # item = QTableWidgetItem("Template %i" % i) # self._selection_templates.addItem(item) # self._selection_templates.item(i).setSelected(False) spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create controls grid. grid = QGridLayout() # # Add time row. grid.addWidget(label_time, 0, 0) grid.addWidget(self._dsp_time, 0, 1) grid.addWidget(label_time_unit, 0, 2) # # Add voltage row. grid.addWidget(label_voltage, 1, 0) grid.addWidget(self._dsp_voltage, 1, 1) grid.addWidget(label_voltage_unit, 1, 2) # # Add binsize row. grid.addWidget(label_binsize, 2, 0) grid.addWidget(self._dsp_binsize, 2, 1) grid.addWidget(label_binsize_unit, 2, 2) # # Add zoom rate grid.addWidget(label_zoomrates, 3, 0) grid.addWidget(self._zoom_rates, 3, 1) # Add a double checkbox for time window grid.addWidget(label_time_window, 4, 0) grid.addWidget(self._dsp_tw_rate, 4, 1) grid.addWidget(label_time_window_unit, 4, 2) ## Add checkbox to display the rates from start grid.addWidget(label_tw_from_start, 5, 0) grid.addWidget(self._tw_from_start, 5, 1) # # Add spacer. grid.addItem(spacer) # # Create info group. controls_group = QGroupBox() controls_group.setLayout(grid) # Create info grid. templates_grid = QGridLayout() # # Add Channel selection # grid.addWidget(label_selection, 3, 0) templates_grid.addWidget(self._selection_templates, 0, 1) def add_template(): items = self._selection_templates.selectedItems() self._display_list = [] for i in range(len(items)): self._display_list.append(i) self._on_templates_changed() # self._selection_templates.itemClicked.connect(add_template) # Template selection signals self._selection_templates.itemSelectionChanged.connect(lambda: self.selected_templates( self.nb_templates)) # Checkbox to display all the rates self._tw_from_start.stateChanged.connect(self.time_window_rate_full) # self._selection_templates.itemPressed(0, 1).connect(self.sort_template()) # # Add spacer. templates_grid.addItem(spacer) # Create controls group. templates_group = QGroupBox() templates_group.setLayout(templates_grid) # # Create controls dock. templates_dock = QDockWidget() templates_dock.setWidget(templates_group) templates_dock.setWindowTitle("Channels selection") # # Create controls dock. control_dock = QDockWidget() control_dock.setWidget(controls_group) control_dock.setWindowTitle("Controls") # Create info widgets. label_time = QLabel() label_time.setText(u"time") self._label_time_value = QLineEdit() self._label_time_value.setText(u"0") self._label_time_value.setReadOnly(True) self._label_time_value.setAlignment(Qt.AlignRight) label_time_unit = QLabel() label_time_unit.setText(u"s") info_buffer_label = QLabel() info_buffer_label.setText(u"buffer") self._info_buffer_value_label = QLineEdit() self._info_buffer_value_label.setText(u"0") self._info_buffer_value_label.setReadOnly(True) self._info_buffer_value_label.setAlignment(Qt.AlignRight) info_buffer_unit_label = QLabel() info_buffer_unit_label.setText(u"") info_probe_label = QLabel() info_probe_label.setText(u"probe") info_probe_value_label = QLineEdit() info_probe_value_label.setText(u"{}".format(probe_path)) info_probe_value_label.setReadOnly(True) # TODO place the following info in another grid? info_probe_unit_label = QLabel() info_probe_unit_label.setText(u"") info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create info grid. info_grid = QGridLayout() # # Time row. info_grid.addWidget(label_time, 0, 0) info_grid.addWidget(self._label_time_value, 0, 1) info_grid.addWidget(label_time_unit, 0, 2) # # Buffer row. info_grid.addWidget(info_buffer_label, 1, 0) info_grid.addWidget(self._info_buffer_value_label, 1, 1) info_grid.addWidget(info_buffer_unit_label, 1, 2) # # Probe row. info_grid.addWidget(info_probe_label, 2, 0) info_grid.addWidget(info_probe_value_label, 2, 1) info_grid.addWidget(info_probe_unit_label, 2, 2) # # Spacer. info_grid.addItem(info_spacer) # Create info group. info_group = QGroupBox() info_group.setLayout(info_grid) # Create info dock. info_dock = QDockWidget() info_dock.setWidget(info_group) info_dock.setWindowTitle("Info") # Create thread. thread = Thread(number_pipe, templates_pipe, spikes_pipe) thread.number_signal.connect(self._number_callback) thread.reception_signal.connect(self._reception_callback) thread.start() # Add dockable windows. self.addDockWidget(Qt.LeftDockWidgetArea, control_dock) self.addDockWidget(Qt.LeftDockWidgetArea, info_dock) self.addDockWidget(Qt.LeftDockWidgetArea, templates_dock) # Add Grid Layout for canvas canvas_grid = QGridLayout() group_canv_temp = QDockWidget() group_canv_temp.setWidget(canvas_template_widget) group_canv_mea = QDockWidget() group_canv_mea.setWidget(canvas_mea) group_canv_rate = QDockWidget() group_canv_rate.setWidget(canvas_rate) group_canv_isi = QDockWidget() group_canv_isi.setWidget(canvas_isi) canvas_grid.addWidget(group_canv_temp, 0, 0) canvas_grid.addWidget(group_canv_mea, 0, 1) canvas_grid.addWidget(group_canv_rate, 1, 1) canvas_grid.addWidget(group_canv_isi, 1, 0) canvas_group = QGroupBox() canvas_group.setLayout(canvas_grid) # Set central widget. self.setCentralWidget(canvas_group) # Set window size. if screen_resolution is not None: screen_width = screen_resolution.width() screen_height = screen_resolution.height() self.resize(screen_width, screen_height) # Set window title. self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display") print(" ") # TODO remove? @property def nb_templates(self): return len(self.cells) def _number_callback(self, number): self._nb_buffer = float(number) text = u"{}".format(number) self._info_buffer_value_label.setText(text) text = u"{:8.3f}".format(self._nb_buffer * float(self._nb_samples) / self._sampling_rate) self._label_time_value.setText(text) return def _reception_callback(self, templates, spikes): bar = None if templates is not None: bar = [] for i in range(len(templates)): mask = spikes['templates'] == i template = load_template_from_dict(templates[i], self.probe) new_cell = Cell(template, Train([]), Amplitude([], [])) self.cells.append(new_cell) self._selection_templates.insertRow(self.nb_templates) bar += [template.center_of_mass(self.probe)] channel = template.channel amplitude = template.peak_amplitude() # self._selection_templates.setItem(self.nb_templates, 0, QTableWidgetItem("Template %d" %self.nb_templates)) # self._selection_templates.setItem(self.nb_templates, 1, QTableWidgetItem(str(bar))) self._selection_templates.setItem(self.nb_templates, 0, QTableWidgetItem(str(self.nb_templates))) self._selection_templates.setItem(self.nb_templates, 1, QTableWidgetItem(str(channel))) self._selection_templates.setItem(self.nb_templates, 2, QTableWidgetItem(str(amplitude))) # item = QListWidgetItem("Template %i" % self.nb_templates) # self._selection_templates.addItem(item) # self._selection_templates.item(i).setSelected(False) # self.nb_templates += 1 # print(bar.shape, bar) if spikes is not None: self.cells.add_spikes(spikes['spike_times'], spikes['amplitudes'], spikes['templates']) self.cells.set_t_max(self._nb_samples * self._nb_buffer / self._sampling_rate) to_display = self.cells.rate(self.bin_size) self._canvas_template.on_reception(templates, self.nb_templates) self._canvas_mea.on_reception_bary(bar, self.nb_templates) # TODO Cells rate self._canvas_rate.on_reception_rates(self.cells.rate(self.bin_size)) # TODO : ISI If we want to display the ISI also # isi = self.cells.interspike_interval_histogram(self.isi_bin_width, self.isi_x_max=25.0) isi = self.cells.interspike_interval_histogram(self.isi_bin_width, self.isi_x_max) self._canvas_isi.on_reception_isi(isi) return def _on_time_changed(self): time = self._dsp_time.value() self._canvas_template.set_time(time) self._dsp_tw_rate.setRange(1, int(time)) return def _on_binsize_changed(self): time = self._dsp_binsize.value() self.bin_size = time self._dsp_tw_rate.setSingleStep(self.bin_size) return def _on_zoomrates_changed(self): zoom_value = self._zoom_rates.value() self._canvas_rate.zoom_rates(zoom_value) return def _on_voltage_changed(self): voltage = self._dsp_voltage.value() self._canvas_template.set_voltage(voltage) return def _on_peaks_display(self): value = self._display_peaks.isChecked() self._canvas_template.show_peaks(value) return def _on_templates_changed(self): self._canvas_template.set_templates(self._display_list) return def selected_templates(self, max_templates): list_templates = [] list_channels = [] for i in range(max_templates + 1): if i != 0 and \ self._selection_templates.item(i, 0).isSelected() and \ self._selection_templates.item(i, 1).isSelected() and \ self._selection_templates.item(i, 2).isSelected(): list_templates.append(i - 1) list_channels.append(int(self._selection_templates.item(i, 1).text())) self._canvas_template.selected_templates(list_templates) self._canvas_mea.selected_channels(list_channels) self._canvas_mea.selected_templates(list_templates) self._canvas_rate.selected_cells(list_templates) self._canvas_isi.selected_cells(list_templates) return def time_window_rate_full(self): value = self._tw_from_start.isChecked() self._canvas_rate.time_window_full(value) return def _on_time_window_changed(self): tw_value = self._dsp_tw_rate.value() self._canvas_rate.time_window_value(tw_value, self.bin_size) return
def initAppletDrawerUi(self): """ Overridden from base class (LayerViewerGui) """ op = self.topLevelOperatorView def configure_update_handlers( qt_signal, op_slot ): qt_signal.connect( self.configure_operator_from_gui ) op_slot.notifyDirty( self.configure_gui_from_operator ) self.__cleanup_fns.append( partial( op_slot.unregisterDirty, self.configure_gui_from_operator ) ) def control_layout( label_text, widget ): row_layout = QHBoxLayout() row_layout.addWidget( QLabel(label_text) ) row_layout.addSpacerItem( QSpacerItem(10, 0, QSizePolicy.Expanding) ) row_layout.addWidget(widget) return row_layout drawer_layout = QVBoxLayout() channel_box = QSpinBox() def set_channel_box_range(*args): if sip.isdeleted(channel_box): return channel_box.setMinimum(0) channel_box.setMaximum( op.Input.meta.getTaggedShape()['c']-1 ) set_channel_box_range() op.Input.notifyMetaChanged( set_channel_box_range ) configure_update_handlers( channel_box.valueChanged, op.ChannelSelection ) drawer_layout.addLayout( control_layout( "Input Channel", channel_box ) ) self.channel_box = channel_box threshold_box = QDoubleSpinBox() threshold_box.setDecimals(2) threshold_box.setMinimum(0.00) threshold_box.setMaximum(1.0) threshold_box.setSingleStep(0.1) configure_update_handlers( threshold_box.valueChanged, op.Pmin ) drawer_layout.addLayout( control_layout( "Threshold", threshold_box ) ) self.threshold_box = threshold_box membrane_size_box = QSpinBox() membrane_size_box.setMinimum(0) membrane_size_box.setMaximum(1000000) configure_update_handlers( membrane_size_box.valueChanged, op.MinMembraneSize ) drawer_layout.addLayout( control_layout( "Min Membrane Size", membrane_size_box ) ) self.membrane_size_box = membrane_size_box seed_presmoothing_box = QDoubleSpinBox() seed_presmoothing_box.setDecimals(1) seed_presmoothing_box.setMinimum(0.0) seed_presmoothing_box.setMaximum(10.0) seed_presmoothing_box.setSingleStep(0.1) configure_update_handlers( seed_presmoothing_box.valueChanged, op.SigmaMinima ) drawer_layout.addLayout( control_layout( "Presmooth before seeds", seed_presmoothing_box ) ) self.seed_presmoothing_box = seed_presmoothing_box seed_method_combo = QComboBox() seed_method_combo.addItem("Connected") seed_method_combo.addItem("Clustered") configure_update_handlers( seed_method_combo.currentIndexChanged, op.GroupSeeds ) drawer_layout.addLayout( control_layout( "Seed Labeling", seed_method_combo ) ) self.seed_method_combo = seed_method_combo watershed_presmoothing_box = QDoubleSpinBox() watershed_presmoothing_box.setDecimals(1) watershed_presmoothing_box.setMinimum(0.0) watershed_presmoothing_box.setMaximum(10.0) watershed_presmoothing_box.setSingleStep(0.1) configure_update_handlers( watershed_presmoothing_box.valueChanged, op.SigmaWeights ) drawer_layout.addLayout( control_layout( "Presmooth before watershed", watershed_presmoothing_box ) ) self.watershed_presmoothing_box = watershed_presmoothing_box superpixel_size_box = QSpinBox() superpixel_size_box.setMinimum(0) superpixel_size_box.setMaximum(1000000) configure_update_handlers( superpixel_size_box.valueChanged, op.MinSegmentSize ) drawer_layout.addLayout( control_layout( "Min Superpixel Size", superpixel_size_box ) ) self.superpixel_size_box = superpixel_size_box preserve_pmaps_box = QCheckBox() configure_update_handlers( preserve_pmaps_box.toggled, op.PreserveMembranePmaps ) drawer_layout.addLayout( control_layout( "Preserve membrane probabilities", preserve_pmaps_box ) ) self.preserve_pmaps_box = preserve_pmaps_box enable_debug_box = QCheckBox() configure_update_handlers( enable_debug_box.toggled, op.EnableDebugOutputs ) drawer_layout.addLayout( control_layout( "Show Debug Layers", enable_debug_box ) ) self.enable_debug_box = enable_debug_box compute_button = QPushButton("Update Watershed", clicked=self.onUpdateWatershedsButton) drawer_layout.addWidget( compute_button ) drawer_layout.setSpacing(0) drawer_layout.addSpacerItem( QSpacerItem(0, 10, QSizePolicy.Minimum, QSizePolicy.Expanding) ) # Finally, the whole drawer widget drawer = QWidget(parent=self) drawer.setLayout(drawer_layout) # Save these members for later use self._drawer = drawer # Initialize everything with the operator's initial values self.configure_gui_from_operator()
class StyleChooser(QWidget): def __init__(self, area_supported=False): QWidget.__init__(self) self._style = PlotStyle("StyleChooser Internal Style") self._styles = STYLES if area_supported else STYLES_LINE_ONLY self.setMinimumWidth(140) self.setMaximumHeight(25) layout = QHBoxLayout() layout.setMargin(0) layout.setSpacing(2) self.line_chooser = QComboBox() self.line_chooser.setToolTip("Select line style.") for style in self._styles: self.line_chooser.addItem(*style) self.marker_chooser = QComboBox() self.marker_chooser.setToolTip("Select marker style.") for marker in MARKERS: self.marker_chooser.addItem(*marker) self.thickness_spinner = QDoubleSpinBox() self.thickness_spinner.setToolTip("Line thickness") self.thickness_spinner.setMinimum(0.1) self.thickness_spinner.setDecimals(1) self.thickness_spinner.setSingleStep(0.1) self.size_spinner = QDoubleSpinBox() self.size_spinner.setToolTip("Marker Size") self.size_spinner.setMinimum(0.1) self.size_spinner.setDecimals(1) self.size_spinner.setSingleStep(0.1) layout.addWidget(self.line_chooser) layout.addWidget(self.thickness_spinner) layout.addWidget(self.marker_chooser) layout.addWidget(self.size_spinner) self.setLayout(layout) self.line_chooser.currentIndexChanged.connect(self._updateStyle) self.marker_chooser.currentIndexChanged.connect(self._updateStyle) self.thickness_spinner.valueChanged.connect(self._updateStyle) self.size_spinner.valueChanged.connect(self._updateStyle) self._updateLineStyleAndMarker(self._style.line_style, self._style.marker, self._style.width, self._style.size) self._layout = layout def getItemSizes(self): line_style_combo_width = self._layout.itemAt(0).sizeHint().width() thickness_spinner_width = self._layout.itemAt(1).sizeHint().width() marker_combo_width = self._layout.itemAt(2).sizeHint().width() size_spinner_width = self._layout.itemAt(3).sizeHint().width() return line_style_combo_width, thickness_spinner_width, marker_combo_width, size_spinner_width def _findLineStyleIndex(self, line_style): for index, style in enumerate(self._styles): if style[1] == line_style: return index elif style[1] is None and line_style == "": return index return -1 def _findMarkerStyleIndex(self, marker): for index, style in enumerate(MARKERS): if style[1] == marker: return index elif style[1] is None and marker == "": return index return -1 def _updateLineStyleAndMarker(self, line_style, marker, thickness, size): self.line_chooser.setCurrentIndex(self._findLineStyleIndex(line_style)) self.marker_chooser.setCurrentIndex(self._findMarkerStyleIndex(marker)) self.thickness_spinner.setValue(thickness) self.size_spinner.setValue(size) def _updateStyle(self): self.marker_chooser.setEnabled(self.line_chooser.currentText() != "Area") line_style = self.line_chooser.itemData(self.line_chooser.currentIndex()) marker_style = self.marker_chooser.itemData(self.marker_chooser.currentIndex()) thickness = float(self.thickness_spinner.value()) size = float(self.size_spinner.value()) self._style.line_style = str(line_style.toString()) self._style.marker = str(marker_style.toString()) self._style.width = thickness self._style.size = size def setStyle(self, style): """ @type style: PlotStyle """ self._style.copyStyleFrom(style) self._updateLineStyleAndMarker(style.line_style, style.marker, style.width, style.size) def getStyle(self): """ @rtype: PlotStyle """ style = PlotStyle("Generated Style from StyleChooser") style.copyStyleFrom(self._style) return style def createLabelLayout(self, layout=None): if layout is None: layout = QHBoxLayout() titles = ["Line Style", "Width", "Marker Style", "Size"] sizes = self.getItemSizes() for title, size in zip(titles, sizes): label = QLabel(title) label.setFixedWidth(size) layout.addWidget(label) return layout
class DefaultSelectParameterWidget(SelectParameterWidget): """Widget class for Default Select Parameter.""" def __init__(self, parameter, parent=None): """Constructor :param parameter: A DefaultSelectParameter object. :type parameter: DefaultSelectParameter """ super(DefaultSelectParameterWidget, self).__init__(parameter, parent) self.default_layout = QHBoxLayout() self.radio_button_layout = QHBoxLayout() self.radio_button_widget = QWidget() self.default_label = QLabel(tr('Default')) # Create radio button group self.default_input_button_group = QButtonGroup() # Define string enabler for radio button self.radio_button_enabler = self.input.itemData(0, Qt.UserRole) for i in range(len(self._parameter.default_labels)): if '%s' in self._parameter.default_labels[i]: label = ( self._parameter.default_labels[i] % self._parameter.default_values[i]) else: label = self._parameter.default_labels[i] radio_button = QRadioButton(label) self.radio_button_layout.addWidget(radio_button) self.default_input_button_group.addButton(radio_button, i) if self._parameter.default_value == \ self._parameter.default_values[i]: radio_button.setChecked(True) # Create double spin box for custom value self.custom_value = QDoubleSpinBox() if self._parameter.default_values[-1]: self.custom_value.setValue(self._parameter.default_values[-1]) has_min = False if self._parameter.minimum is not None: has_min = True self.custom_value.setMinimum(self._parameter.minimum) has_max = False if self._parameter.maximum is not None: has_max = True self.custom_value.setMaximum(self._parameter.maximum) if has_min and has_max: step = (self._parameter.maximum - self._parameter.minimum) / 100.0 self.custom_value.setSingleStep(step) self.radio_button_layout.addWidget(self.custom_value) self.toggle_custom_value() # Reset the layout self.input_layout.setParent(None) self.help_layout.setParent(None) self.label.setParent(None) self.inner_input_layout.setParent(None) self.input_layout = QGridLayout() self.input_layout.setSpacing(0) self.input_layout.addWidget(self.label, 0, 0) self.input_layout.addLayout(self.inner_input_layout, 0, 1) self.input_layout.addWidget(self.default_label, 1, 0) self.input_layout.addLayout(self.radio_button_layout, 1, 1) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) # check every added combobox, it could have been toggled by # the existing keyword self.toggle_input() # Connect # noinspection PyUnresolvedReferences self.input.currentIndexChanged.connect(self.toggle_input) self.default_input_button_group.buttonClicked.connect( self.toggle_custom_value) def raise_invalid_type_exception(self): message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) err = ValueError(message) return err def get_parameter(self): """Obtain list parameter object from the current widget state. :returns: A DefaultSelectParameter from the current state of widget. """ current_index = self.input.currentIndex() selected_value = self.input.itemData(current_index, Qt.UserRole) if hasattr(selected_value, 'toPyObject'): selected_value = selected_value.toPyObject() try: self._parameter.value = selected_value except ValueError: err = self.raise_invalid_type_exception() raise err radio_button_checked_id = self.default_input_button_group.checkedId() # No radio button checked, then default value = None if radio_button_checked_id == -1: self._parameter.default = None # The last radio button (custom) is checked, get the value from the # line edit elif (radio_button_checked_id == len(self._parameter.default_values) - 1): self._parameter.default_values[radio_button_checked_id] \ = self.custom_value.value() self._parameter.default = self.custom_value.value() else: self._parameter.default = self._parameter.default_values[ radio_button_checked_id] return self._parameter def set_default(self, default): """Set default value by item's string. :param default: The default. :type default: str, int :returns: True if success, else False. :rtype: bool """ # Find index of choice try: default_index = self._parameter.default_values.index(default) self.default_input_button_group.button(default_index).setChecked( True) except ValueError: last_index = len(self._parameter.default_values) - 1 self.default_input_button_group.button(last_index).setChecked( True) self.custom_value.setValue(default) self.toggle_custom_value() def toggle_custom_value(self): radio_button_checked_id = self.default_input_button_group.checkedId() if (radio_button_checked_id == len(self._parameter.default_values) - 1): self.custom_value.setDisabled(False) else: self.custom_value.setDisabled(True) def toggle_input(self): """Change behaviour of radio button based on input.""" current_index = self.input.currentIndex() # If current input is not a radio button enabler, disable radio button. if self.input.itemData(current_index, Qt.UserRole) != ( self.radio_button_enabler): self.disable_radio_button() # Otherwise, enable radio button. else: self.enable_radio_button() def set_selected_radio_button(self): """Set selected radio button to 'Do not report'.""" dont_use_button = self.default_input_button_group.button( len(self._parameter.default_values) - 2) dont_use_button.setChecked(True) def disable_radio_button(self): """Disable radio button group and custom value input area.""" checked = self.default_input_button_group.checkedButton() if checked: self.default_input_button_group.setExclusive(False) checked.setChecked(False) self.default_input_button_group.setExclusive(True) for button in self.default_input_button_group.buttons(): button.setDisabled(True) self.custom_value.setDisabled(True) def enable_radio_button(self): """Enable radio button and custom value input area then set selected radio button to 'Do not report'. """ for button in self.default_input_button_group.buttons(): button.setEnabled(True) self.set_selected_radio_button() self.custom_value.setEnabled(True)
def __init__(self, parameter, parent=None): """Constructor. :param parameter: A GroupSelectParameter object. :type parameter: GroupSelectParameter """ QWidget.__init__(self, parent) self._parameter = parameter # Store spin box self.spin_boxes = {} # Create elements # Label (name) self.label = QLabel(self._parameter.name) # Layouts self.main_layout = QVBoxLayout() self.input_layout = QVBoxLayout() # _inner_input_layout must be filled with widget in the child class self.inner_input_layout = QVBoxLayout() self.radio_button_layout = QGridLayout() # Create radio button group self.input_button_group = QButtonGroup() # List widget self.list_widget = QListWidget() self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list_widget.setDragDropMode(QAbstractItemView.DragDrop) self.list_widget.setDefaultDropAction(Qt.MoveAction) self.list_widget.setEnabled(False) self.list_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) for i, key in enumerate(self._parameter.options): value = self._parameter.options[key] radio_button = QRadioButton(value.get('label')) self.radio_button_layout.addWidget(radio_button, i, 0) if value.get('type') == SINGLE_DYNAMIC: double_spin_box = QDoubleSpinBox() self.radio_button_layout.addWidget(double_spin_box, i, 1) double_spin_box.setValue(value.get('value', 0)) double_spin_box.setMinimum( value.get('constraint', {}).get('min', 0)) double_spin_box.setMaximum( value.get('constraint', {}).get('max', 1)) double_spin_box.setSingleStep( value.get('constraint', {}).get('step', 0.01)) step = double_spin_box.singleStep() if step > 1: precision = 0 else: precision = len(str(step).split('.')[1]) if precision > 3: precision = 3 double_spin_box.setDecimals(precision) self.spin_boxes[key] = double_spin_box # Enable spin box depends on the selected option if self._parameter.selected == key: double_spin_box.setEnabled(True) else: double_spin_box.setEnabled(False) elif value.get('type') == STATIC: static_value = value.get('value', 0) if static_value is not None: self.radio_button_layout.addWidget( QLabel(str(static_value)), i, 1) elif value.get('type') == MULTIPLE_DYNAMIC: selected_fields = value.get('value', []) if self._parameter.selected == key: self.list_widget.setEnabled(True) else: self.list_widget.setEnabled(False) self.input_button_group.addButton(radio_button, i) if self._parameter.selected == key: radio_button.setChecked(True) # Help text self.help_label = QLabel(self._parameter.help_text) self.help_label.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) self.help_label.setWordWrap(True) self.help_label.setAlignment(Qt.AlignTop) self.inner_input_layout.addLayout(self.radio_button_layout) self.inner_input_layout.addWidget(self.list_widget) # Put elements into layouts self.input_layout.addWidget(self.label) self.input_layout.addLayout(self.inner_input_layout) self.help_layout = QVBoxLayout() self.help_layout.addWidget(self.help_label) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) self.setLayout(self.main_layout) self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) # Update list widget self.update_list_widget() # Connect signal self.input_button_group.buttonClicked.connect( self.radio_buttons_clicked)
class GUI(QWidget): def __init__(self, parent=None): global f f = open(filename, "a") f.write("Widget init.\n") f.close() QWidget.__init__(self, parent, Qt.WindowStaysOnTopHint) self.__setup_gui__(self) self._flag = False self._change = False f = open(filename, "a") f.write("End of widget init.\n") f.close() def closeEvent(self, event): reply = QMessageBox.question(self, "Confirm", "Are you sure You want to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() def __setup_gui__(self, Dialog): global f f = open(filename, "a") f.write("Setup of gui.\n") f.close() Dialog.setObjectName("Dialog") Dialog.resize(270, 145) self.setWindowTitle("Map Layer") screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) self.Render = QPushButton("Render", Dialog) self.Render.setGeometry(QRect(85, 90, 100, 25)) self.Render.setObjectName("Render") self.comboBox = QComboBox(Dialog) self.comboBox.setGeometry(QRect(100, 34, 115, 18)) self.comboBox.setEditable(False) self.comboBox.setMaxVisibleItems(11) self.comboBox.setInsertPolicy(QComboBox.InsertAtBottom) self.comboBox.setObjectName("comboBox") self.comboBox.addItems([ "Google Roadmap", "Google Terrain", "Google Satellite", "Google Hybrid", "Yahoo Roadmap", "Yahoo Satellite", "Yahoo Hybrid", "Bing Roadmap", "Bing Satellite", "Bing Hybrid", "Open Street Maps" ]) self.comboBox.setCurrentIndex(10) self.label1 = QLabel("Source:", Dialog) self.label1.setGeometry(QRect(55, 35, 35, 16)) self.label1.setObjectName("label1") self.slider = QSlider(Dialog) self.slider.setOrientation(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(12) self.slider.setValue(4) self.slider.setGeometry(QRect(110, 61, 114, 16)) self.label2 = QLabel("Quality: " + str(self.slider.value()), Dialog) self.label2.setGeometry(QRect(47, 61, 54, 16)) self.label2.setObjectName("label2") self.doubleSpinBox = QDoubleSpinBox(Dialog) self.doubleSpinBox.setGeometry(QRect(160, 5, 40, 20)) self.doubleSpinBox.setDecimals(0) self.doubleSpinBox.setObjectName("doubleSpinBox") self.doubleSpinBox.setMinimum(10.0) self.doubleSpinBox.setValue(20.0) self.doubleSpinBox.setEnabled(False) self.checkBox = QCheckBox("Auto refresh", Dialog) self.checkBox.setGeometry(QRect(50, 6, 100, 20)) self.checkBox.setLayoutDirection(Qt.RightToLeft) self.checkBox.setObjectName("checkBox") self.progressBar = QProgressBar(Dialog) self.progressBar.setGeometry(QRect(5, 130, 260, 10)) self.progressBar.setProperty("value", 0) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") self.progressBar.setVisible(False) QObject.connect(self.Render, SIGNAL("clicked()"), Dialog.__repaint__) QMetaObject.connectSlotsByName(Dialog) QObject.connect(self.slider, SIGNAL("valueChanged(int)"), self.__update_slider_label__) QObject.connect(self.comboBox, SIGNAL("activated(int)"), self.__combobox_changed__) self.timerRepaint = QTimer() QObject.connect(self.checkBox, SIGNAL("clicked()"), self.__activate_timer__) QObject.connect(self.timerRepaint, SIGNAL("timeout()"), self.__on_timer__) f = open(filename, "a") f.write("End of setup of gui.\n") f.close() def __combobox_changed__(self): self._change = True def __activate_timer__(self): self.doubleSpinBox.setEnabled(self.checkBox.isChecked()) if self.checkBox.isChecked(): self.timerRepaint.start(self.doubleSpinBox.value() * 1000) self.Render.setEnabled(False) if _progress == 0: self.__repaint__() else: self.timerRepaint.stop() self.Render.setEnabled(True) def __get_net_size__(self): global f f = open(filename, "a") f.write("Geting net size...\n") f.close() if not os.path.exists(Paths["Screenshot"]): Visum.Graphic.Screenshot(Paths["Screenshot"]) size = Image.open(Paths["Screenshot"]).size f = open(filename, "a") f.write("Read net size:" + str(size) + ".\n") f.close() return size def __on_timer__(self): global _paramGlobal self._flag = False Visum.Graphic.MaximizeNetWindow() param = _paramGlobal _paramGlobal = Visum.Graphic.GetWindow() shift = abs((param[0] - _paramGlobal[0]) / (param[2] - param[0])) zoom = abs((param[2] - param[0]) / (_paramGlobal[2] - _paramGlobal[0]) - 1) print _windowSizeGlobal if _windowSizeGlobal[2:4] != Visum.Graphic.GetMainWindowPos()[2:4]: self.__get_net_size__() self._flag = True elif shift > 0.4 or zoom > 0.2: self._flag = True if self._flag or self._change and _progress == 0: self.__repaint__() self._change = False def __update_slider_label__(self, value): self.label2.setText("Quality: " + str(value)) self._change = True def __update_progress_bar__(self): if _progress != 0: self.progressBar.setVisible(True) self.progressBar.setValue(_progress) else: self.progressBar.setVisible(False) def __rebuild_paths__(self): global Paths Paths["Images"] = [] list = os.listdir(Paths["ScriptFolder"]) imageList = [] for i in range(len(list)): if list[i][-3:] == "png": imageList.append(list[i]) for i in range(len(imageList)): try: Visum.Graphic.Backgrounds.ItemByKey(imageList[i]) Paths["Images"].append(Paths["ScriptFolder"] + "\\" + imageList[i]) except: pass def __repaint__(self): global _progress, f if len(Visum.Graphic.Backgrounds.GetAll) != len(Paths["Images"]): self.__rebuild_paths__() if _progress == 0: f = open(filename, "a") f.write("Doing repaint...\n") f.close() QWebSettings.clearMemoryCaches() timer = QTimer() timer.start(100) QObject.connect(timer, SIGNAL("timeout()"), self.__update_progress_bar__) Main(self.comboBox.currentIndex(), Visum.Graphic.GetWindow(), self.slider.value() / 4.0, self.__get_net_size__()) Visum.Graphic.Draw() self.__update_progress_bar__() _progress = 0 QTimer().singleShot(1500, self.__update_progress_bar__) f = open(filename, "a") f.write("End of doing repaint.\n") f.close()
class Main(plugin.Plugin): " Main Class " def initialize(self, *args, **kwargs): " Init Main Class " super(Main, self).initialize(*args, **kwargs) self.chooser, self.process = QComboBox(), QProcess() self.chooser.addItems([' Ubuntu Unity QuickList .desktop ', ' KDE Plasma MetaData .desktop ', ' FreeDesktop Standard .desktop ']) self.chooser.currentIndexChanged.connect(self.on_index_changed) self.chooser.setToolTip('Select a target .desktop file format') # Standard FreeDesktop self.group1 = QGroupBox() self.group1.setTitle(' Standard ') self.ledVersion, self.ledCategories = QDoubleSpinBox(), QComboBox() self.ledVersion.setMinimum(0.1) self.ledVersion.setMaximum(999.9) self.ledVersion.setValue(1.0) self.ledVersion.setDecimals(1) self.ledType, self.ledName = QLineEdit('Application'), QLineEdit('App') self.ledGenericName = QLineEdit('Generic App') self.ledComment, self.ledIcon = QLineEdit('App'), QLineEdit('icon.svg') self.ledCategories.addItems(['Python Programming Language', 'Development', 'Ruby', 'C++', 'Amateur Radio', 'Communication', 'Cross Platform', 'Databases', 'Debug', 'Documentation', 'Editors', 'Education', 'Electronics', 'Email', 'Embebed Devices', 'Fonts', 'GNOME Desktop Environment', 'GNU R Statistical System', 'GObject Introspection Data', 'Games and Amusement', 'Gnustep Desktop Environtment', 'Graphics', 'Haskell Programming Language', 'Internationalization and Localization', 'Internet', 'Interpreted Computer Languages', 'KDE Software Compilation', 'Kernel and Modules', 'Libraries', 'Libraries - Development', 'Libraries - Old', 'Lisp Programming Language', 'Localization', 'Mathematics', 'Meta Packages', 'Miscelaneous - Graphical', 'Miscelaneous - Text Based', 'Mono/CLI Infraestructure', 'Multimedia', 'Networking', 'Newsgroups', 'OCaml Programming Language', 'PHP Programming Language', 'Perl Programming Language', 'Ruby Programming Language', 'Science', 'Shells', 'System Administration', 'TeX Authoring', 'Utilities', 'Version Control Systems', 'Video Software', 'Web Servers', 'Word Processing', 'Xfce Desktop Environment', 'Zope/Plone Environment']) self.ledExec, self.ledTryExec = QLineEdit('myapp'), QLineEdit('myapp') self.ledMymeType = QLineEdit('application/x-desktop') self.ledTerminal = QComboBox() self.ledTerminal.addItems(['False', 'True']) self.ledActions = QLineEdit('Next;Previous') self.ledOnlyShowIn = QLineEdit('Unity;KDE') self.ledNotShowIn = QLineEdit('Gnome2') vboxg1 = QVBoxLayout(self.group1) for each_widget in (QLabel('Version'), self.ledVersion, QLabel('Type'), self.ledType, QLabel('Name'), self.ledName, QLabel('GenericName'), self.ledGenericName, QLabel('Comment'), self.ledComment, QLabel('Icon'), self.ledIcon, QLabel('Categories'), self.ledCategories, QLabel('Exec'), self.ledExec, QLabel('TryExec'), self.ledTryExec, QLabel('MymeType'), self.ledMymeType, QLabel('Terminal'), self.ledTerminal, QLabel('Actions'), self.ledActions, QLabel('OnlyShowIn'), self.ledOnlyShowIn, QLabel('NotShowIn'), self.ledNotShowIn): vboxg1.addWidget(each_widget) # KDE Plasma self.group2 = QGroupBox() self.group2.setTitle(' KDE Plasma ') self.group2.setGraphicsEffect(QGraphicsBlurEffect(self)) self.ledEncoding, self.ledXPlasmaAPI = QComboBox(), QComboBox() self.ledEncoding.addItems(['UTF-8', 'ISO-8859-1']) self.ledServiceType = QLineEdit('Plasma/Applet') self.ledXPlasmaAPI.addItems([ 'Python', 'Javascript', 'Ruby', 'C++', 'HTML5', 'QML']) self.ledXPlasmaMainScript = QLineEdit('path/to/your/code.py') self.ledXKDEPluginInfoAuthor = QLineEdit(getuser()) self.ledXKDEPluginInfoEmail = QLineEdit(getuser() + '@gmail.com') self.ledXKDEPluginInfoName = QLineEdit('Hello-World') self.ledXKDEPluginInfoVersion = QLineEdit('1.0') self.ledXKDEPluginInfoWebsite = QLineEdit('http:plasma.kde.org') self.ledXKDEPluginInfoCategory = QComboBox() self.ledXKDEPluginInfoCategory.addItems(['Application Launchers', 'Accessibility', 'Astronomy', 'Date and Time', 'Development Tools', 'Education', 'Environment', 'Examples', 'File System', 'Fun and Games', 'Graphics', 'Language', 'Mapping', 'Multimedia', 'Online Services', 'System Information', 'Utilities', 'Windows and Tasks', 'Miscelaneous']) self.ledXKDEPluginInfoDepends = QLineEdit() self.ledXKDEPluginInfoLicense = QLineEdit('GPL') self.ledXKDEPluginInfoEnabledByDefault = QComboBox() self.ledXKDEPluginInfoEnabledByDefault.addItems(['True', 'False']) vboxg2 = QVBoxLayout(self.group2) for each_widget in ( QLabel('Encoding'), self.ledEncoding, QLabel('ServiceType'), self.ledServiceType, QLabel('X-Plasma-API'), self.ledXPlasmaAPI, QLabel('X-Plasma-MainScript'), self.ledXPlasmaMainScript, QLabel('X-KDE-PluginInfo-Author'), self.ledXKDEPluginInfoAuthor, QLabel('X-KDE-PluginInfo-Email'), self.ledXKDEPluginInfoEmail, QLabel('X-KDE-PluginInfo-Name'), self.ledXKDEPluginInfoName, QLabel('X-KDE-PluginInfo-Version'), self.ledXKDEPluginInfoVersion, QLabel('X-KDE-PluginInfo-Website'), self.ledXKDEPluginInfoWebsite, QLabel('X-KDE-PluginInfo-Category'), self.ledXKDEPluginInfoCategory, QLabel('X-KDE-PluginInfo-Depends'), self.ledXKDEPluginInfoDepends, QLabel('X-KDE-PluginInfo-License'), self.ledXKDEPluginInfoLicense, QLabel('X-KDE-PluginInfo-EnabledByDefault'), self.ledXKDEPluginInfoEnabledByDefault): vboxg2.addWidget(each_widget) # Ubuntu Unity self.ledXAyatanaDesktopShortcuts = QLineEdit('Next;Previous') self.checkbox1 = QCheckBox('Open .desktop file when done') self.checkbox2 = QCheckBox('Make .desktop file Executable') [a.setChecked(True) for a in (self.checkbox1, self.checkbox2)] self.button = QPushButton(' Make .Desktop File ! ') self.button.setMinimumSize(100, 50) self.button.clicked.connect(self.writeFile) glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) self.button.setGraphicsEffect(glow) glow.setEnabled(True) class TransientWidget(QWidget): ' persistant widget thingy ' def __init__(self, widget_list): ' init sub class ' super(TransientWidget, self).__init__() vbox = QVBoxLayout(self) for each_widget in widget_list: vbox.addWidget(each_widget) tw = TransientWidget((self.chooser, self.group1, self.group2, QLabel('X-Ayatana-Desktop-Shortcuts'), self.ledXAyatanaDesktopShortcuts, QLabel(''), self.checkbox1, self.checkbox2, self.button)) self.dock, self.scrollable = QDockWidget(), QScrollArea() self.scrollable.setWidgetResizable(True) self.scrollable.setWidget(tw) self.dock.setWindowTitle(__doc__) self.dock.setStyleSheet('QDockWidget::title{text-align: center;}') self.dock.setWidget(self.scrollable) ExplorerContainer().addTab(self.dock, "DotDesktop") QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__, ''.join((__doc__, __version__, __license__, 'by', __author__)))) def writeFile(self): ' write the .desktop file to disk ' UNITY = ''.join(a for a in iter(( 'OnlyShowIn=', str(self.ledOnlyShowIn.text()), linesep, 'NotShowIn=', str(self.ledNotShowIn.text()), linesep, 'X-Ayatana-Desktop-Shortcuts=', str(self.ledXAyatanaDesktopShortcuts.text()), linesep))) PLASMA = ''.join(a for a in iter(( 'OnlyShowIn=', str(self.ledOnlyShowIn.text()), linesep, 'NotShowIn=', str(self.ledNotShowIn.text()), linesep, 'Encoding=', str(self.ledEncoding.currentText()), linesep, 'ServiceTypes=', str(self.ledServiceType.text()), linesep, 'X-Plasma-API=', str(self.ledXPlasmaAPI.currentText()), linesep, 'X-Plasma-MainScript=', str(self.ledXPlasmaMainScript.text()), linesep, 'X-KDE-PluginInfo-Author=', str(self.ledXKDEPluginInfoAuthor.text()), linesep, 'X-KDE-PluginInfo-Email=', str(self.ledXKDEPluginInfoEmail.text()), linesep, 'X-KDE-PluginInfo-Name=', str(self.ledXKDEPluginInfoName.text()), linesep, 'X-KDE-PluginInfo-Version=', str(self.ledXKDEPluginInfoVersion.text()), linesep, 'X-KDE-PluginInfo-Website=', str(self.ledXKDEPluginInfoWebsite.text()), linesep, 'X-KDE-PluginInfo-Category=', str(self.ledXKDEPluginInfoCategory.currentText()), linesep, 'X-KDE-PluginInfo-Depends=', str(self.ledXKDEPluginInfoDepends.text()), linesep, 'X-KDE-PluginInfo-License=', str(self.ledXKDEPluginInfoLicense.text()), linesep, 'X-KDE-PluginInfo-EnabledByDefault=', str(self.ledXKDEPluginInfoEnabledByDefault.currentText()), linesep))) BASE = ''.join(a for a in iter(( '[Desktop Entry]', linesep, 'Version=', str(self.ledVersion.value()), linesep, 'Type=', str(self.ledType.text()), linesep, 'Name=', str(self.ledName.text()), linesep, 'Comment=', str(self.ledComment.text()), linesep, 'TryExec=', str(self.ledTryExec.text()), linesep, 'Exec=', str(self.ledExec.text()), linesep, 'Icon=', str(self.ledIcon.text()), linesep, 'MimeType=', str(self.ledMymeType.text()), linesep, 'Actions=', str(self.ledActions.text()), linesep, 'Terminal=', str(self.ledTerminal.currentText()), linesep))) ACTIONS * len(str(self.ledActions.text()).lower().strip().split(';')) fnm = str(QFileDialog.getSaveFileName(self.dock, '', '', "(*.desktop)")) with open(fnm, 'w') as f: if self.chooser.currentIndex() is 0 and fnm is not '': f.write(''.join(a for a in iter((BASE, UNITY, ACTIONS)))) elif self.chooser.currentIndex() is 1 and fnm is not '': f.write(''.join(a for a in iter((BASE, PLASMA)))) elif fnm is not '': f.write(BASE) if self.checkbox2.isChecked() and fnm is not '': try: chmod(fnm, 0775) # Py2 except: chmod(fnm, 0o775) # Py3 if self.checkbox1.isChecked() and fnm is not '': self.process.start('ninja-ide ' + fnm) if not self.process.waitForStarted(): print((" ERROR: FAIL: {} failed!".format(fnm))) return def on_index_changed(self): ' enable disable the qgroupbox if needed ' if self.chooser.currentIndex() is 1: self.group2.graphicsEffect().setEnabled(False) self.group2.setEnabled(True) else: self.group2.graphicsEffect().setEnabled(True) self.group2.setEnabled(False) if self.chooser.currentIndex() is 0: self.ledXAyatanaDesktopShortcuts.setEnabled(True) else: self.ledXAyatanaDesktopShortcuts.setEnabled(False)
class TradingWidget(QFrame): """简单交易组件""" signal = QtCore.pyqtSignal(type(Event())) directionList = [DIRECTION_LONG, DIRECTION_SHORT] offsetList = [OFFSET_OPEN, OFFSET_CLOSE, OFFSET_CLOSEYESTERDAY, OFFSET_CLOSETODAY] priceTypeList = [PRICETYPE_LIMITPRICE, PRICETYPE_VWAP, PRICETYPE_TWAP] exchangeList = [EXCHANGE_NONE, EXCHANGE_CFFEX, EXCHANGE_SHFE, EXCHANGE_DCE, EXCHANGE_CZCE, EXCHANGE_SSE, EXCHANGE_SZSE, EXCHANGE_SGE, EXCHANGE_HKEX, EXCHANGE_CSI, EXCHANGE_HKH, EXCHANGE_HKS, EXCHANGE_JZ, EXCHANGE_SPOT, EXCHANGE_IB, EXCHANGE_FX, EXCHANGE_INE, EXCHANGE_SMART, EXCHANGE_ICE, EXCHANGE_CME, EXCHANGE_NYMEX, EXCHANGE_GLOBEX, EXCHANGE_IDEALPRO] currencyList = [CURRENCY_NONE, CURRENCY_CNY, CURRENCY_USD] productClassList = [PRODUCT_NONE, PRODUCT_EQUITY, PRODUCT_FUTURES, PRODUCT_OPTION, PRODUCT_BOND, PRODUCT_FOREX] # ---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(TradingWidget, self).__init__(parent) self.mainEngine = mainEngine self.eventEngine = eventEngine self.symbol = '' self.signalemit = None self.initUi() self.connectSignal() # ---------------------------------------------------------------------- def initUi(self): """初始化界面""" self.setWindowTitle(u'交易') self.setMaximumWidth(500) self.setFrameShape(self.Box) # 设置边框 self.setLineWidth(1) # 左边部分 labelSymbol = QLabel(u'代码') labelName = QLabel(u'名称') labelDirection = QLabel(u'方向类型') labelOffset = QLabel(u'开平') labelPrice = QLabel(u'价格') labelVolume = QLabel(u'数量') labelPriceType = QLabel(u'价格类型') labelExchange = QLabel(u'交易所') labelCurrency = QLabel(u'货币') labelProductClass = QLabel(u'产品类型') labelUrgency = QLabel(u'紧急度') self.lineSymbol = QLineEdit() self.lineName = QLineEdit() self.comboDirection = QComboBox() self.comboDirection.addItems(self.directionList) self.comboOffset = QComboBox() self.comboOffset.addItem('') self.comboOffset.addItems(self.offsetList) self.comboOffset.setEnabled(False) self.tickOffset = QCheckBox(u'指定') self.spinPrice = QDoubleSpinBox() self.spinPrice.setDecimals(4) self.spinPrice.setMinimum(0) self.spinPrice.setMaximum(100000) self.spinVolume = QSpinBox() self.spinVolume.setMinimum(0) self.spinVolume.setMaximum(1000000) self.comboPriceType = QComboBox() self.comboPriceType.addItems(self.priceTypeList) self.comboExchange = QComboBox() self.comboExchange.addItems(self.exchangeList) self.comboExchange.setEnabled(False) self.comboCurrency = QComboBox() self.comboCurrency.addItems(self.currencyList) self.comboCurrency.setEnabled(False) self.comboProductClass = QComboBox() self.comboProductClass.addItems(self.productClassList) self.comboProductClass.setEnabled(False) self.spinUrgency = QSpinBox() self.spinUrgency.setMinimum(1) self.spinUrgency.setMaximum(9) self.spinUrgency.setSingleStep(1) self.spinUrgency.setValue(5) gridleft = QGridLayout() gridleft.addWidget(labelSymbol, 0, 0) gridleft.addWidget(labelName, 1, 0) gridleft.addWidget(labelDirection, 2, 0) gridleft.addWidget(labelOffset, 3, 0) gridleft.addWidget(labelPrice, 4, 0) gridleft.addWidget(labelVolume, 5, 0) gridleft.addWidget(labelPriceType, 6, 0) gridleft.addWidget(labelUrgency, 7, 0) gridleft.addWidget(labelExchange, 8, 0) gridleft.addWidget(labelProductClass, 9, 0) gridleft.addWidget(labelCurrency, 10, 0) gridleft.addWidget(self.lineSymbol, 0, 1) gridleft.addWidget(self.lineName, 1, 1) gridleft.addWidget(self.comboDirection, 2, 1) hbox1 = QHBoxLayout() hbox1.addWidget(self.comboOffset) lable1 = QLabel() hbox1.addWidget(lable1) hbox1.addWidget(self.tickOffset) hbox1.setStretchFactor(self.comboOffset, 4) hbox1.setStretchFactor(lable1, 1) hbox1.setStretchFactor(self.tickOffset, 3) gridleft.addItem(hbox1, 3, 1) gridleft.addWidget(self.spinPrice, 4, 1) gridleft.addWidget(self.spinVolume, 5, 1) gridleft.addWidget(self.comboPriceType, 6, 1) gridleft.addWidget(self.spinUrgency, 7, 1) gridleft.addWidget(self.comboExchange, 8, 1) gridleft.addWidget(self.comboProductClass, 9, 1) gridleft.addWidget(self.comboCurrency, 10, 1) # 右边部分 labelBid1 = QLabel(u'买一') labelBid2 = QLabel(u'买二') labelBid3 = QLabel(u'买三') labelBid4 = QLabel(u'买四') labelBid5 = QLabel(u'买五') labelAsk1 = QLabel(u'卖一') labelAsk2 = QLabel(u'卖二') labelAsk3 = QLabel(u'卖三') labelAsk4 = QLabel(u'卖四') labelAsk5 = QLabel(u'卖五') self.labelBidPrice1 = QLabel() self.labelBidPrice2 = QLabel() self.labelBidPrice3 = QLabel() self.labelBidPrice4 = QLabel() self.labelBidPrice5 = QLabel() self.labelBidVolume1 = QLabel() self.labelBidVolume2 = QLabel() self.labelBidVolume3 = QLabel() self.labelBidVolume4 = QLabel() self.labelBidVolume5 = QLabel() self.labelAskPrice1 = QLabel() self.labelAskPrice2 = QLabel() self.labelAskPrice3 = QLabel() self.labelAskPrice4 = QLabel() self.labelAskPrice5 = QLabel() self.labelAskVolume1 = QLabel() self.labelAskVolume2 = QLabel() self.labelAskVolume3 = QLabel() self.labelAskVolume4 = QLabel() self.labelAskVolume5 = QLabel() labelLast = QLabel(u'最新') self.labelLastPrice = QLabel() self.labelReturn = QLabel() self.labelLastPrice.setMinimumWidth(60) self.labelReturn.setMinimumWidth(60) gridRight = QGridLayout() gridRight.addWidget(labelAsk5, 0, 0) gridRight.addWidget(labelAsk4, 1, 0) gridRight.addWidget(labelAsk3, 2, 0) gridRight.addWidget(labelAsk2, 3, 0) gridRight.addWidget(labelAsk1, 4, 0) gridRight.addWidget(labelLast, 5, 0) gridRight.addWidget(labelBid1, 6, 0) gridRight.addWidget(labelBid2, 7, 0) gridRight.addWidget(labelBid3, 8, 0) gridRight.addWidget(labelBid4, 9, 0) gridRight.addWidget(labelBid5, 10, 0) gridRight.addWidget(self.labelAskPrice5, 0, 1) gridRight.addWidget(self.labelAskPrice4, 1, 1) gridRight.addWidget(self.labelAskPrice3, 2, 1) gridRight.addWidget(self.labelAskPrice2, 3, 1) gridRight.addWidget(self.labelAskPrice1, 4, 1) gridRight.addWidget(self.labelLastPrice, 5, 1) gridRight.addWidget(self.labelBidPrice1, 6, 1) gridRight.addWidget(self.labelBidPrice2, 7, 1) gridRight.addWidget(self.labelBidPrice3, 8, 1) gridRight.addWidget(self.labelBidPrice4, 9, 1) gridRight.addWidget(self.labelBidPrice5, 10, 1) gridRight.addWidget(self.labelAskVolume5, 0, 2) gridRight.addWidget(self.labelAskVolume4, 1, 2) gridRight.addWidget(self.labelAskVolume3, 2, 2) gridRight.addWidget(self.labelAskVolume2, 3, 2) gridRight.addWidget(self.labelAskVolume1, 4, 2) gridRight.addWidget(self.labelReturn, 5, 2) gridRight.addWidget(self.labelBidVolume1, 6, 2) gridRight.addWidget(self.labelBidVolume2, 7, 2) gridRight.addWidget(self.labelBidVolume3, 8, 2) gridRight.addWidget(self.labelBidVolume4, 9, 2) gridRight.addWidget(self.labelBidVolume5, 10, 2) # 发单按钮 buttonSendOrder = QPushButton(u'发单') buttonCancelAll = QPushButton(u'全撤') size = buttonSendOrder.sizeHint() buttonSendOrder.setMinimumHeight(size.height() * 2) # 把按钮高度设为默认两倍 buttonCancelAll.setMinimumHeight(size.height() * 2) # 整合布局 hbox = QHBoxLayout() hbox.addLayout(gridleft) hbox.addLayout(gridRight) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(buttonSendOrder) vbox.addWidget(buttonCancelAll) vbox.addStretch() self.setLayout(vbox) # 关联更新 buttonSendOrder.clicked.connect(self.sendOrder) buttonCancelAll.clicked.connect(self.cancelAll) self.lineSymbol.returnPressed.connect(self.updateSymbol) self.comboDirection.currentIndexChanged.connect(self.updateOffset) self.tickOffset.stateChanged.connect(self.updateOffset) self.labelAskPrice1.mouseDoubleClickEvent = self.ask1clicked self.labelAskPrice2.mouseDoubleClickEvent = self.ask2clicked self.labelAskPrice3.mouseDoubleClickEvent = self.ask3clicked self.labelAskPrice4.mouseDoubleClickEvent = self.ask4clicked self.labelAskPrice5.mouseDoubleClickEvent = self.ask5clicked self.labelBidPrice1.mouseDoubleClickEvent = self.bid1clicked self.labelBidPrice2.mouseDoubleClickEvent = self.bid2clicked self.labelBidPrice3.mouseDoubleClickEvent = self.bid3clicked self.labelBidPrice4.mouseDoubleClickEvent = self.bid4clicked self.labelBidPrice5.mouseDoubleClickEvent = self.bid5clicked self.labelLastPrice.mouseDoubleClickEvent = self.lastclicked def ask1clicked(self, a): self.askclicked(self.labelAskPrice1.text()) def ask2clicked(self, a): self.askclicked(self.labelAskPrice2.text()) def ask3clicked(self, a): self.askclicked(self.labelAskPrice3.text()) def ask4clicked(self, a): self.askclicked(self.labelAskPrice4.text()) def ask5clicked(self, a): self.askclicked(self.labelAskPrice5.text()) def bid1clicked(self, a): self.bidclicked(self.labelBidPrice1.text()) def bid2clicked(self, a): self.bidclicked(self.labelBidPrice2.text()) def bid3clicked(self, a): self.bidclicked(self.labelBidPrice3.text()) def bid4clicked(self, a): self.bidclicked(self.labelBidPrice4.text()) def bid5clicked(self, a): self.bidclicked(self.labelBidPrice5.text()) def lastclicked(self, a): self.setPrice(self.labelLastPrice.text()) def setPrice(self, text): result = False if text is not None and len(text) > 0: price = float(str(text)) if price > 0: self.spinPrice.setValue(price) result = True return result def askclicked(self, text): if self.setPrice(text): self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG)) self.updateOffset() def bidclicked(self, text): if self.setPrice(text): self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT)) self.updateOffset() def updateOffset(self): if self.tickOffset.checkState(): self.comboOffset.setEnabled(True) if self.comboProductClass.currentText() in (PRODUCT_EQUITY, PRODUCT_BOND): dir = self.comboDirection.currentText() if dir == DIRECTION_LONG: self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_OPEN) + 1) elif dir == DIRECTION_SHORT: self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1) elif self.comboOffset.currentIndex() == 0: self.comboOffset.setCurrentIndex(1) else: self.comboOffset.setEnabled(False) self.comboOffset.setCurrentIndex(0) # ---------------------------------------------------------------------- def updateSymbol(self): """合约变化""" # 读取组件数据 symbol = str(self.lineSymbol.text()) self.comboCurrency.setCurrentIndex(1) currency = safeUnicode(self.comboCurrency.currentText()) gatewayName = safeUnicode('quantos') # 查询合约 contract = self.mainEngine.getContract(symbol) # 清空价格数量 self.spinPrice.setValue(0) self.spinVolume.setValue(0) if contract: gatewayName = contract.gatewayName self.lineName.setText(contract.name) p = self.lineName.palette() p.setColor(self.lineName.foregroundRole(), QtGui.QColor('black')) self.lineName.setPalette(p) exchange = contract.exchange productClass = contract.productClass self.comboExchange.setCurrentIndex(self.exchangeList.index(exchange)) self.comboProductClass.setCurrentIndex(self.productClassList.index(productClass)) self.spinPrice.setSingleStep(contract.priceTick) self.spinVolume.setSingleStep(contract.lotsize) self.updateOffset() else: self.comboExchange.setCurrentIndex(0) self.comboProductClass.setCurrentIndex(0) productClass = safeUnicode(self.comboProductClass.currentText()) exchange = safeUnicode(self.comboExchange.currentText()) self.lineName.setText(u'不存在') p = self.lineName.palette() p.setColor(self.lineName.foregroundRole(), QtGui.QColor('red')) self.lineName.setPalette(p) # 清空行情显示 self.labelBidPrice1.setText('') self.labelBidPrice2.setText('') self.labelBidPrice3.setText('') self.labelBidPrice4.setText('') self.labelBidPrice5.setText('') self.labelBidVolume1.setText('') self.labelBidVolume2.setText('') self.labelBidVolume3.setText('') self.labelBidVolume4.setText('') self.labelBidVolume5.setText('') self.labelAskPrice1.setText('') self.labelAskPrice2.setText('') self.labelAskPrice3.setText('') self.labelAskPrice4.setText('') self.labelAskPrice5.setText('') self.labelAskVolume1.setText('') self.labelAskVolume2.setText('') self.labelAskVolume3.setText('') self.labelAskVolume4.setText('') self.labelAskVolume5.setText('') self.labelLastPrice.setText('') self.labelReturn.setText('') if contract: # 重新注册事件监听 if self.signalemit != None: self.eventEngine.unregister(EVENT_TICK + self.symbol, self.signalemit) self.signalemit = self.signal.emit self.eventEngine.register(EVENT_TICK + symbol, self.signalemit) # 订阅合约 self.mainEngine.subscribe(contract.symbol, gatewayName) # 更新组件当前交易的合约 self.symbol = symbol # ---------------------------------------------------------------------- def format_price(self, price): return int(price * 1000) / 1000 # ---------------------------------------------------------------------- def updateTick(self, event): """更新行情""" tick = event.dict_['data'] if tick.symbol == self.symbol: contract = self.mainEngine.getContract(tick.symbol) price_tick = contract.priceTick self.labelBidPrice1.setText(str(self.format_price(tick.bidPrice1))) self.labelAskPrice1.setText(str(self.format_price(tick.askPrice1))) self.labelBidVolume1.setText(str(tick.bidVolume1)) self.labelAskVolume1.setText(str(tick.askVolume1)) if tick.bidPrice2: self.labelBidPrice2.setText(str(self.format_price(tick.bidPrice2))) self.labelBidPrice3.setText(str(self.format_price(tick.bidPrice3))) self.labelBidPrice4.setText(str(self.format_price(tick.bidPrice4))) self.labelBidPrice5.setText(str(self.format_price(tick.bidPrice5))) self.labelAskPrice2.setText(str(self.format_price(tick.askPrice2))) self.labelAskPrice3.setText(str(self.format_price(tick.askPrice3))) self.labelAskPrice4.setText(str(self.format_price(tick.askPrice4))) self.labelAskPrice5.setText(str(self.format_price(tick.askPrice5))) self.labelBidVolume2.setText(str(tick.bidVolume2)) self.labelBidVolume3.setText(str(tick.bidVolume3)) self.labelBidVolume4.setText(str(tick.bidVolume4)) self.labelBidVolume5.setText(str(tick.bidVolume5)) self.labelAskVolume2.setText(str(tick.askVolume2)) self.labelAskVolume3.setText(str(tick.askVolume3)) self.labelAskVolume4.setText(str(tick.askVolume4)) self.labelAskVolume5.setText(str(tick.askVolume5)) self.labelLastPrice.setText(str(self.format_price(tick.lastPrice))) if self.spinPrice.value() < 0.000001 and tick.lastPrice > 0.000001: self.spinPrice.setValue(tick.lastPrice) if tick.preClosePrice: rt = (old_div(tick.lastPrice, tick.preClosePrice)) - 1 self.labelReturn.setText(('%.2f' % (rt * 100)) + '%') else: self.labelReturn.setText('') # ---------------------------------------------------------------------- def connectSignal(self): """连接Signal""" self.signal.connect(self.updateTick) # ---------------------------------------------------------------------- def sendOrder(self): """发单""" symbol = str(self.lineSymbol.text()).strip() exchange = safeUnicode(self.comboExchange.currentText()) price = self.spinPrice.value() volume = self.spinVolume.value() gatewayName = safeUnicode('quantos') if len(symbol) <= 0 or len(exchange) <= 0 or price <= 0 or volume <= 0: return # 查询合约 contract = self.mainEngine.getContract(symbol) if contract: gatewayName = contract.gatewayName exchange = contract.exchange # 保证有交易所代码 req = VtOrderReq() idx = symbol.find(".") if idx != -1: req.symbol = symbol[0:idx] else: req.symbol = symbol req.exchange = exchange req.price = price req.volume = volume req.direction = safeUnicode(self.comboDirection.currentText()) req.priceType = safeUnicode(self.comboPriceType.currentText()) req.offset = safeUnicode(self.comboOffset.currentText()) req.urgency = self.spinUrgency.value() req.productClass = safeUnicode(self.comboProductClass.currentText()) self.mainEngine.sendOrder(req, gatewayName) # ---------------------------------------------------------------------- def cancelAll(self): """一键撤销所有委托""" l = self.mainEngine.getAllWorkingOrders() for order in l: req = VtCancelOrderReq() req.symbol = order.symbol req.exchange = order.exchange req.frontID = order.frontID req.sessionID = order.sessionID req.orderID = order.taskID self.mainEngine.cancelOrder(req, order.gatewayName) # ---------------------------------------------------------------------- def closePosition(self, cell): """根据持仓信息自动填写交易组件""" # 读取持仓数据,cell是一个表格中的单元格对象 pos = cell.data symbol = pos.symbol # 更新交易组件的显示合约 self.lineSymbol.setText(symbol) self.updateSymbol() # 自动填写信息 self.comboPriceType.setCurrentIndex(self.priceTypeList.index(PRICETYPE_LIMITPRICE)) self.spinVolume.setValue(pos.enable) if pos.direction == DIRECTION_LONG or pos.direction == DIRECTION_NET: self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT)) else: self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG)) if self.comboProductClass.currentText() not in (PRODUCT_EQUITY, PRODUCT_BOND): self.tickOffset.setChecked(True) self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1) elif self.tickOffset.checkState(): self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1) # 价格留待更新后由用户输入,防止有误操作 def fillSymbol(self, cell): tick = cell.data self.lineSymbol.setText(tick.symbol) self.updateSymbol() if type(cell) in (BidCell, AskCell): price = str(cell.text()) if len(price) > 0: price = float(price) if price > 0: self.spinPrice.setValue(price) direction = DIRECTION_LONG if type(cell) is AskCell else DIRECTION_SHORT self.comboDirection.setCurrentIndex(self.directionList.index(direction)) self.updateOffset()
class PlotConfigPanel(QFrame): """A panel to interact with PlotConfig instances.""" plot_marker_styles = ["", ".", ",", "o", "*", "s", "+", "x", "p", "h", "H", "D", "d"] plot_line_styles = ["", "-", "--", "-.", ":"] def __init__(self, plot_config): QFrame.__init__(self) self.plot_config = plot_config self.connect(plot_config.signal_handler, SIGNAL('plotConfigChanged(PlotConfig)'), self._fetchValues) layout = QFormLayout() layout.setRowWrapPolicy(QFormLayout.WrapLongRows) self.chk_visible = QCheckBox() layout.addRow("Visible:", self.chk_visible) self.connect(self.chk_visible, SIGNAL('stateChanged(int)'), self._setVisibleState) self.plot_linestyle = QComboBox() self.plot_linestyle.addItems(self.plot_line_styles) self.connect(self.plot_linestyle, SIGNAL("currentIndexChanged(QString)"), self._setLineStyle) layout.addRow("Line style:", self.plot_linestyle) self.plot_marker_style = QComboBox() self.plot_marker_style.addItems(self.plot_marker_styles) self.connect(self.plot_marker_style, SIGNAL("currentIndexChanged(QString)"), self._setMarker) layout.addRow("Marker style:", self.plot_marker_style) self.alpha_spinner = QDoubleSpinBox(self) self.alpha_spinner.setMinimum(0.0) self.alpha_spinner.setMaximum(1.0) self.alpha_spinner.setDecimals(3) self.alpha_spinner.setSingleStep(0.01) self.connect(self.alpha_spinner, SIGNAL('valueChanged(double)'), self._setAlpha) layout.addRow("Blend factor:", self.alpha_spinner) self.color_picker = ColorPicker(plot_config) layout.addRow("Color:", self.color_picker) self.setLayout(layout) self._fetchValues(plot_config) def _fetchValues(self, plot_config): """Fetch values from a PlotConfig and insert into the panel.""" self.plot_config = plot_config #block signals to avoid updating the incoming plot_config state = self.plot_linestyle.blockSignals(True) linestyle_index = self.plot_line_styles.index(self.plot_config.linestyle) self.plot_linestyle.setCurrentIndex(linestyle_index) self.plot_linestyle.blockSignals(state) state = self.plot_marker_style.blockSignals(True) marker_index = self.plot_marker_styles.index(self.plot_config.marker) self.plot_marker_style.setCurrentIndex(marker_index) self.plot_marker_style.blockSignals(state) state = self.alpha_spinner.blockSignals(True) self.alpha_spinner.setValue(self.plot_config.alpha) self.alpha_spinner.blockSignals(state) state = self.chk_visible.blockSignals(True) self.chk_visible.setChecked(self.plot_config.is_visible) self.chk_visible.blockSignals(state) self.color_picker.update() #------------------------------------------- # update plot config from widgets #------------------------------------------- def _setLineStyle(self, linestyle): self.plot_config.linestyle = linestyle def _setMarker(self, marker): self.plot_config.marker = marker def _setAlpha(self, alpha): self.plot_config.alpha = alpha def _setVisibleState(self, state): self.plot_config.is_visible = state == 2
class CADOptionsToolbar_Arc(CADOptionsToolbar): def __init__(self, layer): super(CADOptionsToolbar_Arc, self).__init__() self.settings = QSettings() self.arc_featurePitch = self.settings.value("/CADDigitize/arc/pitch", 2, type=float) self.arc_featureAngle = self.settings.value("/CADDigitize/arc/angle", 1, type=int) self.arc_method = self.settings.value("/CADDigitize/arc/method", "pitch", type=str) self.arc_angleDirection = self.settings.value( "/CADDigitize/arc/direction", "ClockWise", type=str) if layer.geometryType() == 2: self.arc_polygonCreation = self.settings.value( "/CADDigitize/arc/polygon", "pie") self.ArcPolygonCombo = QComboBox(self.optionsToolBar) self.ArcPolygonCombo.addItems([ tr(u"Pie segment"), tr(u"Chord")]) self.ArcPolygonComboAction = self.optionsToolBar.addWidget( self.ArcPolygonCombo) if self.arc_polygonCreation == "pie": self.ArcPolygonCombo.setCurrentIndex(0) else: self.ArcPolygonCombo.setCurrentIndex(1) self.ArcPolygonCombo.currentIndexChanged["int"].connect( self.polygonArc) self.ArcAngleDirectionCombo = QComboBox(self.optionsToolBar) self.ArcAngleDirectionCombo.addItems([ tr(u"ClockWise"), tr(u"CounterClockWise")]) self.ArcAngleDirectionComboAction = self.optionsToolBar.addWidget( self.ArcAngleDirectionCombo) self.ArcFeatureCombo = QComboBox(self.optionsToolBar) self.ArcFeatureCombo.addItems([ tr(u"Pitch"), tr(u"Angle")]) self.ArcFeatureComboAction = self.optionsToolBar.addWidget( self.ArcFeatureCombo) self.ArcPitchSpin = QDoubleSpinBox(self.optionsToolBar) self.ArcPitchSpin.setMinimum(1) self.ArcPitchSpin.setMaximum(1000) self.ArcPitchSpin.setDecimals(1) self.ArcPitchSpin.setValue(self.arc_featurePitch) self.ArcPitchSpinAction = self.optionsToolBar.addWidget( self.ArcPitchSpin) self.ArcPitchSpin.setToolTip(tr(u"Pitch")) self.ArcPitchSpinAction.setEnabled(True) self.ArcAngleSpin = QDoubleSpinBox(self.optionsToolBar) self.ArcAngleSpin.setMinimum(1) self.ArcAngleSpin.setMaximum(3600) self.ArcAngleSpin.setDecimals(0) self.ArcAngleSpin.setValue(self.arc_featureAngle) self.ArcAngleSpinAction = self.optionsToolBar.addWidget( self.ArcAngleSpin) self.ArcAngleSpin.setToolTip(tr(u"Angle")) self.ArcAngleSpinAction.setEnabled(True) if self.arc_method == "pitch": self.ArcPitchSpin.setEnabled(True) self.ArcAngleSpin.setEnabled(False) self.ArcFeatureCombo.setCurrentIndex(0) else: self.ArcPitchSpin.setEnabled(False) self.ArcAngleSpin.setEnabled(True) self.ArcFeatureCombo.setCurrentIndex(1) if self.arc_angleDirection == "ClockWise": self.ArcAngleDirectionCombo.setCurrentIndex(0) else: self.ArcAngleDirectionCombo.setCurrentIndex(1) self.ArcPitchSpin.valueChanged["double"].connect( self.pitchSettings) self.ArcAngleSpin.valueChanged["double"].connect( self.angleSettings) self.ArcFeatureCombo.currentIndexChanged["int"].connect( self.featureArc) self.ArcAngleDirectionCombo.currentIndexChanged["int"].connect( self.angleDirectionArc) def polygonArc(self): if self.ArcPolygonCombo.currentIndex() == 0: self.settings.setValue("/CADDigitize/arc/polygon", "pie") else: self.settings.setValue("/CADDigitize/arc/polygon", "chord") def angleDirectionArc(self): if self.ArcAngleDirectionCombo.currentIndex() == 0: self.settings.setValue("/CADDigitize/arc/direction", "ClockWise") else: self.settings.setValue("/CADDigitize/arc/direction", "CounterClockWise") def angleSettings(self): self.arc_featureAngle = self.ArcAngleSpin.value() self.settings.setValue("/CADDigitize/arc/angle", self.arc_featureAngle) def pitchSettings(self): self.arc_featurePitch = self.ArcPitchSpin.value() self.settings.setValue("/CADDigitize/arc/pitch", self.arc_featurePitch) def featureArc(self): if self.ArcFeatureCombo.currentIndex() == 0: self.ArcPitchSpin.setEnabled(True) self.ArcAngleSpin.setEnabled(False) self.settings.setValue("/CADDigitize/arc/method", "pitch") else: self.ArcPitchSpin.setEnabled(False) self.ArcAngleSpin.setEnabled(True) self.settings.setValue("/CADDigitize/arc/method", "angle")
def set_widgets(self): """Set widgets on the Threshold tab.""" clear_layout(self.gridLayoutThreshold) # Set text in the label layer_purpose = self.parent.step_kw_purpose.selected_purpose() layer_subcategory = self.parent.step_kw_subcategory.\ selected_subcategory() classification = self.parent.step_kw_classification. \ selected_classification() if is_raster_layer(self.parent.layer): statistics = self.parent.layer.dataProvider().bandStatistics( 1, QgsRasterBandStats.All, self.parent.layer.extent(), 0) text = continuous_raster_question % ( layer_purpose['name'], layer_subcategory['name'], classification['name'], statistics.minimumValue, statistics.maximumValue) else: field_name = self.parent.step_kw_field.selected_fields() field_index = self.parent.layer.fieldNameIndex(field_name) min_value_layer = self.parent.layer.minimumValue(field_index) max_value_layer = self.parent.layer.maximumValue(field_index) text = continuous_vector_question % ( layer_purpose['name'], layer_subcategory['name'], field_name, classification['name'], min_value_layer, max_value_layer) self.lblThreshold.setText(text) thresholds = self.parent.get_existing_keyword('thresholds') selected_unit = self.parent.step_kw_unit.selected_unit()['key'] self.classes = OrderedDict() classes = classification.get('classes') # Sort by value, put the lowest first classes = sorted(classes, key=lambda k: k['value']) for i, the_class in enumerate(classes): class_layout = QHBoxLayout() # Class label class_label = QLabel(the_class['name']) # Min label min_label = QLabel(tr('Min >')) # Min value as double spin min_value_input = QDoubleSpinBox() # TODO(IS) We can set the min and max depends on the unit, later min_value_input.setMinimum(0) min_value_input.setMaximum(999999) if thresholds.get(the_class['key']): min_value_input.setValue(thresholds[the_class['key']][0]) else: default_min = the_class['numeric_default_min'] if isinstance(default_min, dict): default_min = the_class[ 'numeric_default_min'][selected_unit] min_value_input.setValue(default_min) min_value_input.setSingleStep(0.1) # Max label max_label = QLabel(tr('Max <=')) # Max value as double spin max_value_input = QDoubleSpinBox() # TODO(IS) We can set the min and max depends on the unit, later max_value_input.setMinimum(0) max_value_input.setMaximum(999999) if thresholds.get(the_class['key']): max_value_input.setValue(thresholds[the_class['key']][1]) else: default_max = the_class['numeric_default_max'] if isinstance(default_max, dict): default_max = the_class[ 'numeric_default_max'][selected_unit] max_value_input.setValue(default_max) max_value_input.setSingleStep(0.1) # Add to class_layout class_layout.addWidget(min_label) class_layout.addWidget(min_value_input) # class_layout.addStretch(1) class_layout.addWidget(max_label) class_layout.addWidget(max_value_input) # Add to grid_layout self.gridLayoutThreshold.addWidget(class_label, i, 0) self.gridLayoutThreshold.addLayout(class_layout, i, 1) self.classes[the_class['key']] = [min_value_input, max_value_input] self.gridLayoutThreshold.setSpacing(0) def min_max_changed(index, the_string): """Slot when min or max value change. :param index: The index of the double spin. :type index: int :param the_string: The flag to indicate the min or max value. :type the_string: str """ if the_string == 'Max value': current_max_value = self.classes.values()[index][1] target_min_value = self.classes.values()[index + 1][0] if current_max_value.value() != target_min_value.value(): target_min_value.setValue(current_max_value.value()) elif the_string == 'Min value': current_min_value = self.classes.values()[index][0] target_max_value = self.classes.values()[index - 1][1] if current_min_value.value() != target_max_value.value(): target_max_value.setValue(current_min_value.value()) # Set behaviour for k, v in self.classes.items(): index = self.classes.keys().index(k) if index < len(self.classes) - 1: # Max value changed v[1].valueChanged.connect(partial( min_max_changed, index=index, the_string='Max value')) if index > 0: # Min value v[0].valueChanged.connect(partial( min_max_changed, index=index, the_string='Min value'))
class Barometer(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletBarometer, *args) self.barometer = self.device self.has_calibrate = self.firmware_version == (1, 0, 0) self.has_averaging = self.firmware_version >= (2, 0, 2) self.moving_average_pressure = 25 self.average_pressure = 10 self.average_temperature = 10 self.cbe_air_pressure = CallbackEmulator(self.barometer.get_air_pressure, self.cb_air_pressure, self.increase_error_count) self.cbe_altitude = CallbackEmulator(self.barometer.get_altitude, self.cb_altitude, self.increase_error_count) self.chip_temperature_label = ChipTemperatureLabel() self.current_air_pressure = None # float, mbar self.current_altitude = None # float, m self.clear_graphs_button = QPushButton('Clear Graphs') plots = [('Air Pressure', Qt.red, lambda: self.current_air_pressure, '{:.3f} mbar (QFE)'.format)] self.air_pressure_plot_widget = PlotWidget('Air Pressure [mbar]', plots, self.clear_graphs_button) plots = [('Altitude', Qt.darkGreen, lambda: self.current_altitude, lambda value: '{:.2f} m ({:.2f} ft)'.format(value, value / 0.3048))] self.altitude_plot_widget = PlotWidget('Altitude [m]', plots, self.clear_graphs_button) if self.has_calibrate: self.calibrate_button = QPushButton('Calibrate Altitude') self.calibrate_button.clicked.connect(self.calibrate_clicked) else: self.reference_label = QLabel('Reference Air Pressure [mbar]:') self.reference_box = QDoubleSpinBox() self.reference_box.setMinimum(10) self.reference_box.setMaximum(1200) self.reference_box.setDecimals(3) self.reference_box.setValue(1013.25) self.reference_box.editingFinished.connect(self.reference_box_finished) self.use_current_button = QPushButton('Use Current') self.use_current_button.clicked.connect(self.use_current_clicked) if self.has_averaging: self.avg_pressure_box = QSpinBox() self.avg_pressure_box.setMinimum(0) self.avg_pressure_box.setMaximum(10) self.avg_pressure_box.setSingleStep(1) self.avg_pressure_box.setValue(10) self.avg_pressure_box.editingFinished.connect(self.avg_pressure_box_finished) self.avg_temperature_box = QSpinBox() self.avg_temperature_box.setMinimum(0) self.avg_temperature_box.setMaximum(255) self.avg_temperature_box.setSingleStep(1) self.avg_temperature_box.setValue(10) self.avg_temperature_box.editingFinished.connect(self.avg_temperature_box_finished) self.avg_moving_pressure_box = QSpinBox() self.avg_moving_pressure_box.setMinimum(0) self.avg_moving_pressure_box.setMaximum(25) self.avg_moving_pressure_box.setSingleStep(1) self.avg_moving_pressure_box.setValue(25) self.avg_moving_pressure_box.editingFinished.connect(self.avg_moving_pressure_box_finished) layout_h1 = QHBoxLayout() layout_h1.addWidget(self.air_pressure_plot_widget) layout_h1.addWidget(self.altitude_plot_widget) layout = QVBoxLayout(self) layout.addLayout(layout_h1) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout.addWidget(line) if self.has_calibrate: layout_h2 = QHBoxLayout() layout_h2.addWidget(self.chip_temperature_label) layout_h2.addStretch() layout_h2.addWidget(self.calibrate_button) layout_h2.addWidget(self.clear_graphs_button) else: layout_h2 = QHBoxLayout() layout_h2.addWidget(self.reference_label) layout_h2.addWidget(self.reference_box) layout_h2.addWidget(self.use_current_button) layout_h2.addStretch() layout_h2.addWidget(self.chip_temperature_label) layout_h2.addStretch() layout_h2.addWidget(self.clear_graphs_button) layout.addLayout(layout_h2) if self.has_averaging: layout_h3 = QHBoxLayout() layout_h3.addWidget(QLabel('Air Pressure Moving Average Length:')) layout_h3.addWidget(self.avg_moving_pressure_box) layout_h3.addStretch() layout_h3.addWidget(QLabel('Air Pressure Average Length:')) layout_h3.addWidget(self.avg_pressure_box) layout_h3.addStretch() layout_h3.addWidget(QLabel('Temperate Average Length:')) layout_h3.addWidget(self.avg_temperature_box) layout.addLayout(layout_h3) self.chip_temp_timer = QTimer() self.chip_temp_timer.timeout.connect(self.update_chip_temp) self.chip_temp_timer.setInterval(100) def start(self): async_call(self.barometer.get_air_pressure, None, self.cb_air_pressure, self.increase_error_count) async_call(self.barometer.get_altitude, None, self.cb_altitude, self.increase_error_count) self.cbe_air_pressure.set_period(100) self.cbe_altitude.set_period(100) if self.has_averaging: async_call(self.barometer.get_averaging, None, self.get_averaging_async, self.increase_error_count) if not self.has_calibrate: async_call(self.barometer.get_reference_air_pressure, None, self.get_reference_air_pressure_async, self.increase_error_count) self.air_pressure_plot_widget.stop = False self.altitude_plot_widget.stop = False self.update_chip_temp() self.chip_temp_timer.start() def stop(self): self.cbe_air_pressure.set_period(0) self.cbe_altitude.set_period(0) self.air_pressure_plot_widget.stop = True self.altitude_plot_widget.stop = True self.chip_temp_timer.stop() def destroy(self): pass def get_url_part(self): return 'barometer' @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletBarometer.DEVICE_IDENTIFIER def get_averaging_async(self, avg): moving_average_pressure, average_pressure, average_temperature = avg self.moving_average_pressure = moving_average_pressure self.average_pressure = average_pressure self.average_temperature = average_temperature self.avg_moving_pressure_box.setValue(moving_average_pressure) self.avg_pressure_box.setValue(average_pressure) self.avg_temperature_box.setValue(average_temperature) def avg_pressure_box_finished(self): self.average_pressure = self.avg_pressure_box.value() self.save_new_averaging() def avg_temperature_box_finished(self): self.average_temperature = self.avg_temperature_box.value() self.save_new_averaging() def avg_moving_pressure_box_finished(self): self.moving_average_pressure = self.avg_moving_pressure_box.value() self.save_new_averaging() def save_new_averaging(self): self.barometer.set_averaging(self.moving_average_pressure, self.average_pressure, self.average_temperature) def calibrate_clicked(self): try: # Call set_reference_air_pressure that has the same function ID as # calibrate_altitude the extra parameter will just be ignored self.barometer.set_reference_air_pressure(0) except ip_connection.Error: pass def get_reference_air_pressure_async(self, reference): self.reference_box.setValue(reference / 1000.0) def use_current_clicked(self): self.barometer.set_reference_air_pressure(0) async_call(self.barometer.get_reference_air_pressure, None, self.get_reference_air_pressure_async, self.increase_error_count) def reference_box_finished(self): self.barometer.set_reference_air_pressure(self.reference_box.value() * 1000.0) def update_chip_temp_async(self, temp): self.chip_temperature_label.setText('{:.2f}'.format(temp / 100.0)) def update_chip_temp(self): async_call(self.barometer.get_chip_temperature, None, self.update_chip_temp_async, self.increase_error_count) def cb_air_pressure(self, air_pressure): self.current_air_pressure = air_pressure / 1000.0 def cb_altitude(self, altitude): self.current_altitude = altitude / 100.0
def __init__(self, parameter, parent=None): """Constructor. :param parameter: A GroupSelectParameter object. :type parameter: GroupSelectParameter """ QWidget.__init__(self, parent) self._parameter = parameter # Store spin box self.spin_boxes = {} # Create elements # Label (name) self.label = QLabel(self._parameter.name) # Layouts self.main_layout = QVBoxLayout() self.input_layout = QVBoxLayout() # _inner_input_layout must be filled with widget in the child class self.inner_input_layout = QVBoxLayout() self.radio_button_layout = QGridLayout() # Create radio button group self.input_button_group = QButtonGroup() # List widget self.list_widget = QListWidget() self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list_widget.setDragDropMode(QAbstractItemView.DragDrop) self.list_widget.setDefaultDropAction(Qt.MoveAction) self.list_widget.setEnabled(False) self.list_widget.setSizePolicy( QSizePolicy.Maximum, QSizePolicy.Expanding) for i, key in enumerate(self._parameter.options): value = self._parameter.options[key] radio_button = QRadioButton(value.get('label')) self.radio_button_layout.addWidget(radio_button, i, 0) if value.get('type') == SINGLE_DYNAMIC: double_spin_box = QDoubleSpinBox() self.radio_button_layout.addWidget(double_spin_box, i, 1) double_spin_box.setValue(value.get('value', 0)) double_spin_box.setMinimum( value.get('constraint', {}).get('min', 0)) double_spin_box.setMaximum(value.get( 'constraint', {}).get('max', 1)) double_spin_box.setSingleStep( value.get('constraint', {}).get('step', 0.01)) step = double_spin_box.singleStep() if step > 1: precision = 0 else: precision = len(str(step).split('.')[1]) if precision > 3: precision = 3 double_spin_box.setDecimals(precision) self.spin_boxes[key] = double_spin_box # Enable spin box depends on the selected option if self._parameter.selected == key: double_spin_box.setEnabled(True) else: double_spin_box.setEnabled(False) elif value.get('type') == STATIC: static_value = value.get('value', 0) if static_value is not None: self.radio_button_layout.addWidget( QLabel(str(static_value)), i, 1) elif value.get('type') == MULTIPLE_DYNAMIC: selected_fields = value.get('value', []) if self._parameter.selected == key: self.list_widget.setEnabled(True) else: self.list_widget.setEnabled(False) self.input_button_group.addButton(radio_button, i) if self._parameter.selected == key: radio_button.setChecked(True) # Help text self.help_label = QLabel(self._parameter.help_text) self.help_label.setSizePolicy( QSizePolicy.Maximum, QSizePolicy.Expanding) self.help_label.setWordWrap(True) self.help_label.setAlignment(Qt.AlignTop) self.inner_input_layout.addLayout(self.radio_button_layout) self.inner_input_layout.addWidget(self.list_widget) # Put elements into layouts self.input_layout.addWidget(self.label) self.input_layout.addLayout(self.inner_input_layout) self.help_layout = QVBoxLayout() self.help_layout.addWidget(self.help_label) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) self.setLayout(self.main_layout) self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) # Update list widget self.update_list_widget() # Connect signal self.input_button_group.buttonClicked.connect( self.radio_buttons_clicked)