def createEditor( self, parent, option, index ): if index.column() == CANTIDAD: spinbox = QSpinBox( parent ) spinbox.setRange( 0, index.model().lines[index.row()].maxquantity ) spinbox.setSingleStep( 1 ) return spinbox else: QStyledItemDelegate.createEditor( self, parent, option, index )
def createEditor(self, parent, option, index): if index.column() == CANTIDAD: spinbox = QSpinBox(parent) spinbox.setRange(0, 1000) spinbox.setSingleStep(1) return spinbox elif index.column() == DENOMINACION: model = index.model() self.proxymodel.setSourceModel(self.denominationsmodel) current = model.index(index.row(), IDDENOMINACION).data().toInt()[0] self.proxymodel.setFilterRegExp(self.filter(model, current)) sp = super(ArqueoDelegate, self).createEditor(parent, option, index) sp.setColumnHidden(0) sp.setColumnHidden(2) sp.setColumnHidden(3) return sp else: return super(ArqueoDelegate, self).createEditor(parent, option, index)
def createEditor( self, parent, option, index ): if index.column() == CANTIDAD: max_items = index.model().lines[index.row()].existencia if max_items < 1 : return None spinbox = QSpinBox( parent ) spinbox.setRange( 0, max_items ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter ) return spinbox elif index.column() == DESCRIPCION : if self.articles.rowCount() > 0: self.proxymodel.setSourceModel( self.articles ) model = index.model() current = model.index( index.row(), IDARTICULOEX ).data() self.proxymodel.setFilterRegExp( self.filter( model , current ) ) sp = super( FacturaDelegate, self ).createEditor( parent, option, index ) #sp.setColumnHidden( IDBODEGAEX ) #sp.setColumnHidden( IDARTICULOEX ) return sp elif index.column() == TOTALPROD: return None elif index.column() == PRECIO: spinbox = QDoubleSpinBox( parent ) spinbox.setRange( 0.0001, 10000 ) spinbox.setDecimals( 4 ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter ) return spinbox else: super( FacturaDelegate, self ).createEditor( parent, option, index )
def __init__(self, parent, prefix = None, suffix = None, option = None, min_ = None, max_ = None, step = None, tip = None, value = None, changed =None): super(MySpinBox, self).__init__(parent) if prefix: plabel = QLabel(prefix) else: plabel = None if suffix: slabel = QLabel(suffix) else: slabel = None spinbox = QSpinBox(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(int)'), changed) layout.addStretch(1) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.spin = spinbox
def create_spinbox(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 = QSpinBox() 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): if index.column() == TEU: spinbox = QSpinBox(parent) spinbox.setRange(0, 200000) spinbox.setSingleStep(1000) spinbox.setAlignment(Qt.AlignRight|Qt.AlignVCenter) return spinbox elif index.column() == OWNER: combobox = QComboBox(parent) combobox.addItems(sorted(index.model().owners)) combobox.setEditable(True) return combobox elif index.column() == COUNTRY: combobox = QComboBox(parent) combobox.addItems(sorted(index.model().countries)) combobox.setEditable(True) return combobox elif index.column() == NAME: editor = QLineEdit(parent) editor.returnPressed.connect(self.commitAndCloseEditor) return editor elif index.column() == DESCRIPTION: editor = richtextlineedit.RichTextLineEdit(parent) editor.returnPressed.connect(self.commitAndCloseEditor) return editor else: return QStyledItemDelegate.createEditor(self, parent, option, index)
def createEditor(self, parent, option, index): if index.column() == TEU: spinbox = QSpinBox(parent) spinbox.setRange(0, 200000) spinbox.setSingleStep(1000) spinbox.setAlignment(Qt.AlignRight|Qt.AlignVCenter) return spinbox elif index.column() == OWNER: combobox = QComboBox(parent) combobox.addItems(sorted(index.model().owners)) combobox.setEditable(True) return combobox elif index.column() == COUNTRY: combobox = QComboBox(parent) combobox.addItems(sorted(index.model().countries)) combobox.setEditable(True) return combobox elif index.column() == NAME: editor = QLineEdit(parent) self.connect(editor, SIGNAL("returnPressed()"), self.commitAndCloseEditor) return editor elif index.column() == DESCRIPTION: editor = richtextlineedit.RichTextLineEdit(parent) self.connect(editor, SIGNAL("returnPressed()"), self.commitAndCloseEditor) return editor else: return QStyledItemDelegate.createEditor(self, parent, option, index)
def addSpinBox(self, attribute_name, title, tool_tip=None, min_value=1, max_value=10, single_step=1): sb = QSpinBox() self[attribute_name] = sb sb.setMaximumHeight(25) sb_layout = QHBoxLayout() sb_layout.addWidget(sb) sb_layout.addStretch() self.addRow(title, sb_layout) if tool_tip is not None: sb.setToolTip(tool_tip) sb.setMinimum(min_value) sb.setMaximum(max_value) sb.setSingleStep(single_step) def getter(self): return self[attribute_name].value() def setter(self, value): self[attribute_name].setValue(value) self.updateProperty(attribute_name, getter, setter) return sb
def create_spinbox(self, prefix, suffix, option, default=NoDefault, 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 = QSpinBox() 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, default) 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) return widget
def _populateFormCB(self, config): cfg = json.loads(config) cfg = Helpers.makeDictKeysInt(cfg) if 'Inputsignals' not in cfg: pass else: signalsin = cfg['Inputsignals'] it = {} for k, item in signalsin.iteritems(): it[item['name']] = k self.addComboBox('InputSignal', 'input signal', it) self.addLineEdit('Duration', 'Duration of one run in milliseconds') self.settings['Duration'].setText(str(100)) spin = QSpinBox() spin.setRange(2**8, 2**16) spin.setSingleStep(2**8) spin.setValue(2**11) self.addSetting('Samples', 'Number of bytes to be read.', spin) sampling = QLabel() sampling.setText(str(2**11 / 100.0) + ' kS/s') self.addSetting('Sampling', 'Resulting sampling rate', sampling) self.addCheckBox('Loop', 'Run infinitely') self.settings['Loop'].setChecked(True) spin.valueChanged.connect(self.spinValueChangedCB) self.settings['Duration'].textChanged.connect( self.durationValueChangedCB)
def createEditor(self, parent, option, index): if index.column() == CANTIDAD: max_items = index.model().lines[index.row()].existencia if max_items < 1: return None spinbox = QSpinBox(parent) spinbox.setRange(1, max_items) spinbox.setSingleStep(1) spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter) return spinbox elif index.column() == DESCRIPCION: if self.articles.rowCount() > 0: self.proxymodel.setSourceModel(self.articles) model = index.model() current = model.index(index.row(), IDARTICULOEX).data() self.proxymodel.setFilterRegExp(self.filter(model, current)) sp = super(FacturaDelegate, self).createEditor(parent, option, index) # sp.setColumnHidden( IDBODEGAEX ) # sp.setColumnHidden( IDARTICULOEX ) return sp elif index.column() == TOTALPROD: return None elif index.column() == PRECIO: spinbox = QDoubleSpinBox(parent) spinbox.setRange(0.0001, 10000) spinbox.setDecimals(4) spinbox.setSingleStep(1) spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter) return spinbox else: super(FacturaDelegate, self).createEditor(parent, option, index)
def createEditor( self, parent, option, index ): """ Aca se crean los widgets para edición """ if index.column() == CANTIDAD: spinbox = QSpinBox( parent ) spinbox.setRange( 1, 1000 ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter ) return spinbox elif index.column() == DESCRIPCION : # if index.data() != "": # self.prods.items.append( [ index.model().data( index.model().index( index.row(), 0 ) ) , index.data().toString()] ) self.proxymodel.setSourceModel( self.prods ) model = index.model() current = model.index( index.row(), IDARTICULO ).data() self.proxymodel.setFilterRegExp( self.filter( model, current ) ) sp = super( EntradaCompraDelegate, self ).createEditor( parent, option, index ) return sp elif index.column() == TOTALPROD: return None elif index.column() in ( PRECIO, PRECIOD ): spinbox = QDoubleSpinBox( parent ) spinbox.setRange( 0, 10000 ) spinbox.setDecimals( 4 ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter ) return spinbox else: return super( EntradaCompraDelegate, self ).createEditor( parent, option, index )
def createEditor( self, parent, option, index ): if index.column() == CANTIDAD: spinbox = QSpinBox( parent ) spinbox.setRange( 1, 1000 ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter ) return spinbox elif index .column() == COSTOUNIT: spinbox = QDoubleSpinBox( parent ) spinbox.setRange( 0.0001, 100000 ) spinbox.setDecimals( 4 ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter ) return spinbox elif index.column() in ( IDARTICULO, ARTICULO ): self.proxymodel.setSourceModel( self.prods ) current = index.model().data( index.model().index( index.row(), IDARTICULO ) ) self.proxymodel.setFilterRegExp( self.filter( index.model(), current ) ) sp = super( LiquidacionDelegate, self ).createEditor( parent, option, index ) sp.setColumnHidden( IDARTICULO ) sp.setMinimumWidth( 600 ) return sp else: super( LiquidacionDelegate, self ).createEditor( parent, option, index )
def int_widget(self, start_val, min_val=-100, max_val=100, step=1): """ Returns an int widget with the given values. """ box = QSpinBox() box.setRange(min_val, max_val) box.setValue(start_val) box.setSingleStep(step) return box
def createEditor(self, parent, option, index): if index.column() == NUMAJUSTE: spinbox = QSpinBox(parent) spinbox.setRange(-1000, 1000) spinbox.setSingleStep(1) return spinbox else: QStyledItemDelegate.createEditor(self, parent, option, index)
class ProjectData(QWidget): def __init__(self, parent): super(ProjectData, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0) self.name = QLineEdit() if not len(self._parent.project.name): self.name.setText(file_manager.get_basename( self._parent.project.path)) else: self.name.setText(self._parent.project.name) grid.addWidget(self.name, 0, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0) self.txtPath = QLineEdit() self.txtPath.setReadOnly(True) self.txtPath.setText(self._parent.project.path) grid.addWidget(self.txtPath, 1, 1) grid.addWidget(QLabel(translations.TR_PROJECT_TYPE), 2, 0) self.txtType = QLineEdit() completer = QCompleter(sorted(settings.PROJECT_TYPES)) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.txtType.setCompleter(completer) self.txtType.setText(self._parent.project.project_type) grid.addWidget(self.txtType, 2, 1) grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0) self.description = QPlainTextEdit() self.description.setPlainText(self._parent.project.description) grid.addWidget(self.description, 3, 1) grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0) self.url = QLineEdit() self.url.setText(self._parent.project.url) self.url.setPlaceholderText('https://www.{}.com'.format(getuser())) grid.addWidget(self.url, 4, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0) self.cboLicense = QComboBox() self.cboLicense.addItems(LICENCES) self.cboLicense.setCurrentIndex(12) index = self.cboLicense.findText(self._parent.project.license) self.cboLicense.setCurrentIndex(index) grid.addWidget(self.cboLicense, 5, 1) self.txtExtensions = QLineEdit() self.txtExtensions.setText(', '.join(self._parent.project.extensions)) grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0) grid.addWidget(self.txtExtensions, 6, 1) grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0) self.spinIndentation = QSpinBox() self.spinIndentation.setValue(self._parent.project.indentation) self.spinIndentation.setRange(2, 10) self.spinIndentation.setValue(4) self.spinIndentation.setSingleStep(2) grid.addWidget(self.spinIndentation, 7, 1) self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS) self.checkUseTabs.setChecked(self._parent.project.use_tabs) grid.addWidget(self.checkUseTabs, 7, 2)
class ProjectData(QWidget): def __init__(self, parent): super(ProjectData, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0) self.name = QLineEdit() if not len(self._parent.project.name): self.name.setText( file_manager.get_basename(self._parent.project.path)) else: self.name.setText(self._parent.project.name) grid.addWidget(self.name, 0, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0) self.txtPath = QLineEdit() self.txtPath.setReadOnly(True) self.txtPath.setText(self._parent.project.path) grid.addWidget(self.txtPath, 1, 1) grid.addWidget(QLabel(translations.TR_PROJECT_TYPE), 2, 0) self.txtType = QLineEdit() completer = QCompleter(sorted(settings.PROJECT_TYPES)) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.txtType.setCompleter(completer) self.txtType.setText(self._parent.project.project_type) grid.addWidget(self.txtType, 2, 1) grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0) self.description = QPlainTextEdit() self.description.setPlainText(self._parent.project.description) grid.addWidget(self.description, 3, 1) grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0) self.url = QLineEdit() self.url.setText(self._parent.project.url) self.url.setPlaceholderText('https://www.{}.com'.format(getuser())) grid.addWidget(self.url, 4, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0) self.cboLicense = QComboBox() self.cboLicense.addItems(LICENCES) self.cboLicense.setCurrentIndex(12) index = self.cboLicense.findText(self._parent.project.license) self.cboLicense.setCurrentIndex(index) grid.addWidget(self.cboLicense, 5, 1) self.txtExtensions = QLineEdit() self.txtExtensions.setText(', '.join(self._parent.project.extensions)) grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0) grid.addWidget(self.txtExtensions, 6, 1) grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0) self.spinIndentation = QSpinBox() self.spinIndentation.setValue(self._parent.project.indentation) self.spinIndentation.setRange(2, 10) self.spinIndentation.setValue(4) self.spinIndentation.setSingleStep(2) grid.addWidget(self.spinIndentation, 7, 1) self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS) self.checkUseTabs.setChecked(self._parent.project.use_tabs) grid.addWidget(self.checkUseTabs, 7, 2)
def createSpinBox(self, variable_name, variable_value, variable_type, analysis_module_variables_model): spinner = QSpinBox() 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)) if variable_value is not None: spinner.setValue(variable_value) spinner.valueChanged.connect(partial(self.valueChanged, variable_name, variable_type, spinner)) return spinner
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.label_amount = QLabel('Amount') self.spin_amount = QDoubleSpinBox() self.spin_amount.setRange(0, 10000000000) self.spin_amount.setPrefix('Rp. ') self.spin_amount.setSingleStep(100000) self.label_rate = QLabel('Rate') self.spin_rate = QDoubleSpinBox() self.spin_rate.setSuffix(' %') self.spin_rate.setSingleStep(0.1) self.spin_rate.setRange(0, 100) self.label_year = QLabel('Years') self.spin_year = QSpinBox() self.spin_year.setSuffix(' year') self.spin_year.setSingleStep(1) self.spin_year.setRange(0, 1000) self.spin_year.setValue(1) self.label_total_ = QLabel('Total') self.label_total = QLabel('Rp. 0.00') grid = QGridLayout() grid.addWidget(self.label_amount, 0, 0) grid.addWidget(self.spin_amount, 0, 1) grid.addWidget(self.label_rate, 1, 0) grid.addWidget(self.spin_rate, 1, 1) grid.addWidget(self.label_year, 2, 0) grid.addWidget(self.spin_year, 2, 1) grid.addWidget(self.label_total_, 3, 0) grid.addWidget(self.label_total, 3, 1) self.setLayout(grid) self.connect(self.spin_amount, SIGNAL('valueChanged(double)'), self.update_ui) self.connect(self.spin_rate, SIGNAL('valueChanged(double)'), self.update_ui) self.connect(self.spin_year, SIGNAL('valueChanged(int)'), self.update_ui) self.setWindowTitle('Interest') def update_ui(self): amount = self.spin_amount.value() rate = self.spin_rate.value() year = self.spin_year.value() total = amount * (1 + rate / 100.0)**year self.label_total.setText('Rp. %.2f' % total)
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.label_amount = QLabel('Amount') self.spin_amount = QDoubleSpinBox() self.spin_amount.setRange(0, 10000000000) self.spin_amount.setPrefix('Rp. ') self.spin_amount.setSingleStep(100000) self.label_rate = QLabel('Rate') self.spin_rate = QDoubleSpinBox() self.spin_rate.setSuffix(' %') self.spin_rate.setSingleStep(0.1) self.spin_rate.setRange(0, 100) self.label_year = QLabel('Years') self.spin_year = QSpinBox() self.spin_year.setSuffix(' year') self.spin_year.setSingleStep(1) self.spin_year.setRange(0, 1000) self.spin_year.setValue(1) self.label_total_ = QLabel('Total') self.label_total = QLabel('Rp. 0.00') grid = QGridLayout() grid.addWidget(self.label_amount, 0, 0) grid.addWidget(self.spin_amount, 0, 1) grid.addWidget(self.label_rate, 1, 0) grid.addWidget(self.spin_rate, 1, 1) grid.addWidget(self.label_year, 2, 0) grid.addWidget(self.spin_year, 2, 1) grid.addWidget(self.label_total_, 3, 0) grid.addWidget(self.label_total, 3, 1) self.setLayout(grid) self.connect(self.spin_amount, SIGNAL('valueChanged(double)'), self.update_ui) self.connect(self.spin_rate, SIGNAL('valueChanged(double)'), self.update_ui) self.connect(self.spin_year, SIGNAL('valueChanged(int)'), self.update_ui) self.setWindowTitle('Interest') def update_ui(self): amount = self.spin_amount.value() rate = self.spin_rate.value() year = self.spin_year.value() total = amount * (1 + rate / 100.0) ** year self.label_total.setText('Rp. %.2f' % total)
def createEditor( self, parent, option, index ): if index.column() == CANTIDAD: spinbox = QSpinBox( parent ) spinbox.setRange( -500, 500 ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignLeft | Qt.AlignVCenter ) return spinbox elif index.column() in ( DESCRIPCION, IDARTICULO ): current = index.model().data( index.model().index( index.row(), IDARTICULO ) ) self.proxymodel.setFilterRegExp( self.filter( index.model(), current ) ) sp = super( KardexOtherDelegate, self ).createEditor( parent, option, index ) sp.setColumnHidden( IDARTICULO ) sp.setColumnHidden( COSTO ) return sp else: super( KardexOtherDelegate, self ).createEditor( parent, option, index )
def addSpinBox(self, name): sb = QSpinBox(self) sb.setEnabled(True) sb.setMinimumSize(QSize(60, 20)) sb.setMaximumSize(QSize(60, 20)) sb.setWrapping(False) sb.setFrame(True) sb.setButtonSymbols(QSpinBox.NoButtons) sb.setAccelerated(True) sb.setCorrectionMode(QSpinBox.CorrectToPreviousValue) sb.setKeyboardTracking(True) sb.setMinimum(0) sb.setMaximum(99999999) sb.setSingleStep(1000) sb.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) sb.setProperty("value", 0) sb.setObjectName(name) return sb
def addSpinBox(self, name): sb = QSpinBox(self) sb.setEnabled(True) sb.setMinimumSize(QSize(60, 20)) sb.setMaximumSize(QSize(60, 20)) sb.setWrapping(False) sb.setFrame(True) sb.setButtonSymbols(QSpinBox.NoButtons) sb.setAccelerated(True) sb.setCorrectionMode(QSpinBox.CorrectToPreviousValue) sb.setKeyboardTracking(True) sb.setMinimum(0) sb.setMaximum(99999999) sb.setSingleStep(1000) sb.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) sb.setProperty("value", 0) sb.setObjectName(name) return sb
def __init__(self, parent, prefix=None, suffix=None, option=None, min_=None, max_=None, step=None, tip=None, value=None, changed=None): super(MySpinBox, self).__init__(parent) if prefix: plabel = QLabel(prefix) else: plabel = None if suffix: slabel = QLabel(suffix) else: slabel = None spinbox = QSpinBox(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(int)'), changed) layout.addStretch(1) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.spin = spinbox
def createEditor(self, parent, option, index): model = index.model() if model.isColumn("name", index): textedit = QLineEdit(parent) return textedit elif model.isColumn("rating", index): spinbox = QSpinBox(parent) spinbox.setRange(0, 200) spinbox.setSingleStep(1) spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter) return spinbox elif model.isColumn("adjust", index): spinbox = QSpinBox(parent) spinbox.setRange(-10, 10) spinbox.setSingleStep(1) spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter) return spinbox else: return QItemDelegate.createEditor(self, parent, option, index)
class CADOptionsToolbar_Ellipse(CADOptionsToolbar): def __init__(self): super(CADOptionsToolbar_Ellipse, self).__init__() self.settings = QSettings() self.spinBox = QSpinBox(self.optionsToolBar) self.spinBox.setMinimum(3) self.spinBox.setMaximum(3600) segvalue = self.settings.value("/CADDigitize/ellipse/segments", 36, type=int) if not segvalue: self.settings.setValue("/CADDigitize/ellipse/segments", 36) self.spinBox.setValue(segvalue) self.spinBox.setSingleStep(1) self.spinBoxAction = self.optionsToolBar.addWidget(self.spinBox) self.spinBox.setToolTip(tr(u"Number of points")) self.spinBoxAction.setEnabled(True) self.spinBox.valueChanged["int"].connect(self.segmentsettingsEllipse) def segmentsettingsEllipse(self): self.settings.setValue("/CADDigitize/ellipse/segments", self.spinBox.value())
class CADOptionsToolbar_RPolygon(CADOptionsToolbar): def __init__(self): super(CADOptionsToolbar_RPolygon, self).__init__() self.settings = QSettings() self.spinBox = QSpinBox(self.optionsToolBar) self.spinBox.setMinimum(3) self.spinBox.setMaximum(3600) segvalue = self.settings.value("/CADDigitize/rpolygon/nbedges", 5, type=int) if not segvalue: self.settings.setValue("/CADDigitize/rpolygon/nbedges", 5) self.spinBox.setValue(segvalue) self.spinBox.setSingleStep(1) self.spinBoxAction = self.optionsToolBar.addWidget(self.spinBox) self.spinBox.setToolTip(tr(u"Number of edges")) self.spinBoxAction.setEnabled(True) self.spinBox.valueChanged["int"].connect(self.edgesSettingsRPolygon) def edgesSettingsRPolygon(self): self.settings.setValue("/CADDigitize/rpolygon/nbedges", self.spinBox.value())
class IntervalWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout(self) layout.setContentsMargins(0,0,0,0) self.spinbox = QSpinBox(self) self.combo = QComboBox(self) sp = self.spinbox.sizePolicy() sp.setHorizontalStretch(1) self.spinbox.setSizePolicy(sp) self.spinbox.setRange(0, (1 << 31) - 1) self.spinbox.setSingleStep(1) self.combo.addItem('Seconds') self.combo.addItem('Milliseconds') layout.addWidget(self.spinbox) layout.addWidget(self.combo) def set_interval(self, interval): if ('%.03f' % interval).endswith('.000'): self.spinbox.setValue(int(interval)) self.combo.setCurrentIndex(0) else: self.spinbox.setValue(round(interval * 1000.0)) self.combo.setCurrentIndex(1) def get_interval(self): if self.combo.currentIndex() == 0: return self.spinbox.value() else: return self.spinbox.value() / 1000.0
class IndustrialDualAnalogInV2(COMCUPluginBase): def __init__(self, *args): COMCUPluginBase.__init__(self, BrickletIndustrialDualAnalogInV2, *args) self.analog_in = self.device self.cbe_voltage0 = CallbackEmulator(functools.partial(self.analog_in.get_voltage, 0), functools.partial(self.cb_voltage, 0), self.increase_error_count) self.cbe_voltage1 = CallbackEmulator(functools.partial(self.analog_in.get_voltage, 1), functools.partial(self.cb_voltage, 1), self.increase_error_count) self.calibration = None self.sample_rate_label = QLabel('Sample Rate:') self.sample_rate_combo = QComboBox() self.sample_rate_combo.addItem('976 Hz') self.sample_rate_combo.addItem('488 Hz') self.sample_rate_combo.addItem('244 Hz') self.sample_rate_combo.addItem('122 Hz') self.sample_rate_combo.addItem('61 Hz') self.sample_rate_combo.addItem('4 Hz') self.sample_rate_combo.addItem('2 Hz') self.sample_rate_combo.addItem('1 Hz') self.current_voltage = [None, None] # float, V self.calibration_button = QPushButton('Calibration...') self.sample_rate_combo.currentIndexChanged.connect(self.sample_rate_combo_index_changed) self.calibration_button.clicked.connect(self.calibration_button_clicked) plots = [('Channel 0', Qt.red, lambda: self.current_voltage[0], format_voltage), ('Channel 1', Qt.blue, lambda: self.current_voltage[1], format_voltage)] self.plot_widget = PlotWidget('Voltage [V]', plots) # Define lines line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) line1 = QFrame() line1.setFrameShape(QFrame.HLine) line1.setFrameShadow(QFrame.Sunken) line2 = QFrame() line2.setFrameShape(QFrame.HLine) line2.setFrameShadow(QFrame.Sunken) # Define channel LED status config widgets self.led_config_ch0_label = QLabel('Channel 0') self.led_config_ch1_label = QLabel('Channel 1') self.led_config_label = QLabel('LED Config:') self.led_status_config_label = QLabel('LED Status Config:') self.led_status_config_ch0_min_label = QLabel('Min:') self.led_status_config_ch0_max_label = QLabel('Max:') self.led_status_config_ch1_min_label = QLabel('Min:') self.led_status_config_ch1_max_label = QLabel('Max:') self.led_config_ch0_combo = QComboBox() self.led_config_ch0_combo.addItem('Off') self.led_config_ch0_combo.addItem('On') self.led_config_ch0_combo.addItem('Show Heartbeat') self.led_config_ch0_combo.addItem('Show Channel Status') self.led_config_ch0_combo.currentIndexChanged.connect(self.led_config_ch0_combo_changed) self.led_config_ch1_combo = QComboBox() self.led_config_ch1_combo.addItem('Off') self.led_config_ch1_combo.addItem('On') self.led_config_ch1_combo.addItem('Show Heartbeat') self.led_config_ch1_combo.addItem('Show Channel Status') self.led_config_ch1_combo.currentIndexChanged.connect(self.led_config_ch1_combo_changed) self.led_status_config_ch0_combo = QComboBox() self.led_status_config_ch0_combo.addItem('Threshold') self.led_status_config_ch0_combo.addItem('Intensity') self.led_status_config_ch0_combo.currentIndexChanged.connect(self.led_status_config_ch0_combo_changed) self.led_status_config_ch1_combo = QComboBox() self.led_status_config_ch1_combo.addItem('Threshold') self.led_status_config_ch1_combo.addItem('Intensity') self.led_status_config_ch1_combo.currentIndexChanged.connect(self.led_status_config_ch1_combo_changed) self.led_status_config_ch0_min_sbox = QSpinBox() self.led_status_config_ch0_min_sbox.setMinimum(-35000) self.led_status_config_ch0_min_sbox.setMaximum(35000) self.led_status_config_ch0_min_sbox.setValue(0) self.led_status_config_ch0_min_sbox.setSingleStep(1) self.led_status_config_ch0_min_sbox.setSuffix(' mV') self.led_status_config_ch0_min_sbox.valueChanged.connect(self.led_status_config_ch0_min_sbox_changed) self.led_status_config_ch0_max_sbox = QSpinBox() self.led_status_config_ch0_max_sbox.setMinimum(-35000) self.led_status_config_ch0_max_sbox.setMaximum(35000) self.led_status_config_ch0_max_sbox.setValue(0) self.led_status_config_ch0_max_sbox.setSingleStep(1) self.led_status_config_ch0_max_sbox.setSuffix(' mV') self.led_status_config_ch0_max_sbox.valueChanged.connect(self.led_status_config_ch0_max_sbox_changed) self.led_status_config_ch1_min_sbox = QSpinBox() self.led_status_config_ch1_min_sbox.setMinimum(-35000) self.led_status_config_ch1_min_sbox.setMaximum(35000) self.led_status_config_ch1_min_sbox.setValue(0) self.led_status_config_ch1_min_sbox.setSingleStep(1) self.led_status_config_ch1_min_sbox.setSuffix(' mV') self.led_status_config_ch1_min_sbox.valueChanged.connect(self.led_status_config_ch1_min_sbox_changed) self.led_status_config_ch1_max_sbox = QSpinBox() self.led_status_config_ch1_max_sbox.setMinimum(-35000) self.led_status_config_ch1_max_sbox.setMaximum(35000) self.led_status_config_ch1_max_sbox.setValue(0) self.led_status_config_ch1_max_sbox.setSingleStep(1) self.led_status_config_ch1_max_sbox.setSuffix(' mV') self.led_status_config_ch1_max_sbox.valueChanged.connect(self.led_status_config_ch1_max_sbox_changed) # Define size policies h_sp = QSizePolicy() h_sp.setHorizontalPolicy(QSizePolicy.Expanding) # Set size policies self.sample_rate_combo.setSizePolicy(h_sp) self.led_config_ch0_combo.setSizePolicy(h_sp) self.led_config_ch1_combo.setSizePolicy(h_sp) self.led_status_config_ch0_combo.setSizePolicy(h_sp) self.led_status_config_ch1_combo.setSizePolicy(h_sp) self.led_status_config_ch0_min_sbox.setSizePolicy(h_sp) self.led_status_config_ch0_max_sbox.setSizePolicy(h_sp) self.led_status_config_ch1_min_sbox.setSizePolicy(h_sp) self.led_status_config_ch1_max_sbox.setSizePolicy(h_sp) # Define layouts hlayout = QHBoxLayout() vlayout = QVBoxLayout() glayout = QGridLayout() layout = QVBoxLayout(self) hlayout_ch0_min_max = QHBoxLayout() hlayout_ch1_min_max = QHBoxLayout() # Populate layouts vlayout.addWidget(self.calibration_button) hlayout.addWidget(self.sample_rate_label) hlayout.addWidget(self.sample_rate_combo) vlayout.addLayout(hlayout) vlayout.addWidget(line1) hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_min_label) hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_min_sbox) hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_max_label) hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_max_sbox) hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_min_label) hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_min_sbox) hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_max_label) hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_max_sbox) glayout.addWidget(self.led_config_ch0_label, 0, 1, 1, 1) # R, C, RS, CS glayout.addWidget(self.led_config_ch1_label, 0, 2, 1, 1) glayout.addWidget(line2, 1, 0, 1, 3) glayout.addWidget(self.led_config_label, 2, 0, 1, 1) glayout.addWidget(self.led_config_ch0_combo, 2, 1, 1, 1) glayout.addWidget(self.led_config_ch1_combo, 2, 2, 1, 1) glayout.addWidget(self.led_status_config_label, 3, 0, 1, 1) glayout.addWidget(self.led_status_config_ch0_combo, 3, 1, 1, 1) glayout.addWidget(self.led_status_config_ch1_combo, 3, 2, 1, 1) glayout.addLayout(hlayout_ch0_min_max, 4, 1, 1, 1) glayout.addLayout(hlayout_ch1_min_max, 4, 2, 1, 1) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(vlayout) layout.addLayout(glayout) self.ui_group_ch_status_ch0 = [self.led_status_config_ch0_combo, self.led_status_config_ch0_min_sbox, self.led_status_config_ch0_max_sbox] self.ui_group_ch_status_ch1 = [self.led_status_config_ch1_combo, self.led_status_config_ch1_min_sbox, self.led_status_config_ch1_max_sbox] def start(self): async_call(self.analog_in.get_voltage, 0, lambda x: self.cb_voltage(0, x), self.increase_error_count) async_call(self.analog_in.get_voltage, 1, lambda x: self.cb_voltage(1, x), self.increase_error_count) async_call(self.analog_in.get_sample_rate, None, self.get_sample_rate_async, self.increase_error_count) async_call(self.analog_in.get_channel_led_config, CH_0, lambda config: self.get_channel_led_config_async(CH_0, config), self.increase_error_count) async_call(self.analog_in.get_channel_led_status_config, CH_0, lambda config: self.get_channel_led_status_config_async(CH_0, config), self.increase_error_count) async_call(self.analog_in.get_channel_led_config, CH_1, lambda config: self.get_channel_led_config_async(CH_1, config), self.increase_error_count) async_call(self.analog_in.get_channel_led_status_config, CH_1, lambda config: self.get_channel_led_status_config_async(CH_1, config), self.increase_error_count) self.cbe_voltage0.set_period(100) self.cbe_voltage1.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_voltage0.set_period(0) self.cbe_voltage1.set_period(0) self.plot_widget.stop = True def destroy(self): if self.calibration != None: self.calibration.close() @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletIndustrialDualAnalogInV2.DEVICE_IDENTIFIER def calibration_button_clicked(self): if self.calibration == None: self.calibration = Calibration(self) self.calibration_button.setEnabled(False) self.calibration.show() def sample_rate_combo_index_changed(self, index): async_call(self.analog_in.set_sample_rate, index, None, self.increase_error_count) def led_config_ch0_combo_changed(self, index): if index != self.analog_in.CHANNEL_LED_CONFIG_SHOW_CHANNEL_STATUS: for e in self.ui_group_ch_status_ch0: e.setEnabled(False) else: for e in self.ui_group_ch_status_ch0: e.setEnabled(True) self.analog_in.set_channel_led_config(CH_0, index) def led_config_ch1_combo_changed(self, index): if index != self.analog_in.CHANNEL_LED_CONFIG_SHOW_CHANNEL_STATUS: for e in self.ui_group_ch_status_ch1: e.setEnabled(False) else: for e in self.ui_group_ch_status_ch1: e.setEnabled(True) self.analog_in.set_channel_led_config(CH_1, index) def led_status_config_ch0_combo_changed(self, index): self.analog_in.set_channel_led_status_config(CH_0, self.led_status_config_ch0_min_sbox.value(), self.led_status_config_ch0_max_sbox.value(), index) def led_status_config_ch1_combo_changed(self, index): self.analog_in.set_channel_led_status_config(CH_1, self.led_status_config_ch1_min_sbox.value(), self.led_status_config_ch1_max_sbox.value(), index) def led_status_config_ch0_min_sbox_changed(self, value): QObject.sender(self).blockSignals(True) self.analog_in.set_channel_led_status_config(CH_0, self.led_status_config_ch0_min_sbox.value(), self.led_status_config_ch0_max_sbox.value(), self.led_status_config_ch0_combo.currentIndex()) QObject.sender(self).blockSignals(False) def led_status_config_ch0_max_sbox_changed(self, value): QObject.sender(self).blockSignals(True) self.analog_in.set_channel_led_status_config(CH_0, self.led_status_config_ch0_min_sbox.value(), self.led_status_config_ch0_max_sbox.value(), self.led_status_config_ch0_combo.currentIndex()) QObject.sender(self).blockSignals(False) def led_status_config_ch1_min_sbox_changed(self, value): QObject.sender(self).blockSignals(True) self.analog_in.set_channel_led_status_config(CH_1, self.led_status_config_ch1_min_sbox.value(), self.led_status_config_ch1_max_sbox.value(), self.led_status_config_ch1_combo.currentIndex()) QObject.sender(self).blockSignals(False) def led_status_config_ch1_max_sbox_changed(self, value): QObject.sender(self).blockSignals(True) self.analog_in.set_channel_led_status_config(CH_1, self.led_status_config_ch1_min_sbox.value(), self.led_status_config_ch1_max_sbox.value(), self.led_status_config_ch1_combo.currentIndex()) QObject.sender(self).blockSignals(False) def get_voltage_value0(self): return self.voltage_value[0] def get_voltage_value1(self): return self.voltage_value[1] def get_sample_rate_async(self, rate): self.sample_rate_combo.blockSignals(True) self.sample_rate_combo.setCurrentIndex(rate) self.sample_rate_combo.blockSignals(False) def get_channel_led_config_async(self, channel, config): self.led_config_ch0_combo.blockSignals(True) self.led_config_ch1_combo.blockSignals(True) if channel == CH_0: self.led_config_ch0_combo.setCurrentIndex(config) elif channel == CH_1: self.led_config_ch1_combo.setCurrentIndex(config) self.led_config_ch0_combo.blockSignals(False) self.led_config_ch1_combo.blockSignals(False) def get_channel_led_status_config_async(self, channel, config): self.led_status_config_ch0_combo.blockSignals(True) self.led_status_config_ch1_combo.blockSignals(True) if channel == CH_0: self.led_status_config_ch0_combo.setCurrentIndex(config.config) self.led_status_config_ch0_max_sbox.setValue(config.max) self.led_status_config_ch0_min_sbox.setValue(config.min) elif channel == CH_1: self.led_status_config_ch1_combo.setCurrentIndex(config.config) self.led_status_config_ch1_max_sbox.setValue(config.max) self.led_status_config_ch1_min_sbox.setValue(config.min) self.led_status_config_ch0_combo.blockSignals(False) self.led_status_config_ch1_combo.blockSignals(False) def cb_voltage(self, sensor, voltage): self.current_voltage[sensor] = voltage / 1000.0
class BrowserMatPlotFrame(QtGui.QWidget): "定义画图的页面" def __init__(self, parent = None): QtGui.QWidget.__init__(self) self.parent = parent self.status_bar = parent.status_bar #State self.draw_node_labels_tf = True self.draw_axis_units_tf = False self.draw_grid_tf = False self.g = None #PATH used in drawing STEP hierarchy, co-occurence, context self.step_path = parent.step_path #MPL figure self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.fig.subplots_adjust(left=0,right=1,top=1,bottom=0) #QT canvas self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.canvas.mpl_connect('pick_event', self.on_pick) #used when selectingpyth canvas objects self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.axes = self.fig.add_subplot(111) #self.axes.hold(False) #clear the axes every time plot() is called self.mpl_toolbar = NavigationToolbar(self.canvas, self) #GUI controls self.mode_combo = QComboBox() self.mode_combo.addItems(["Graph Test", "Graph Test Numpy", "STEP Hierarchy", "STEP Co-occurence", "STEP Context"]) self.mode_combo.setMinimumWidth(200) self.draw_button = QPushButton("&Draw/Refresh") self.connect(self.draw_button, QtCore.SIGNAL('clicked()'), self.on_draw) self.node_size = QSpinBox(self) self.node_size.setSingleStep(5) self.node_size.setMaximum(100) self.node_size.setValue(25) self.node_size_label = QLabel('Node Size (%):') # connection set in on_draw() method #Horizontal layout hbox = QtGui.QHBoxLayout() #Adding matplotlib widgets for w in [self.mode_combo, 's', self.node_size_label, self.node_size, self.draw_button]: if w == 's': hbox.addStretch() else: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) #Vertical layout. Adding all other widgets, and hbox layout. vbox = QtGui.QVBoxLayout() vbox.addWidget(self.mpl_toolbar) vbox.addWidget(self.canvas) vbox.addLayout(hbox) self.setLayout(vbox) self.canvas.setFocus(True) def draw_axis_units(self): fw = self.fig.get_figwidth() fh = self.fig.get_figheight() l_margin = .4 / fw #.4in b_margin = .3 / fh #.3in if self.draw_axis_units_tf == True: self.fig.subplots_adjust(left=l_margin,right=1,top=1,bottom=b_margin) else: self.fig.subplots_adjust(left=0,right=1,top=1,bottom=0) self.canvas.draw() def draw_grid(self): if self.draw_grid_tf == False: self.draw_grid_tf = True else: self.draw_grid_tf = False self.axes.grid(self.draw_grid_tf) self.canvas.draw() def on_draw(self): draw_mode = self.mode_combo.currentText() self.axes.clear() if self.g != None: if hasattr(self.g, 'destruct'): self.g.destruct() if draw_mode == "Graph Test": self.g = GraphTest(self) elif draw_mode == "Graph Test Numpy": self.g = GraphTestNumPy(self) elif draw_mode == "STEP Hierarchy": self.g = GraphHierarchy(self) elif draw_mode == "STEP Co-occurence": self.g = GraphCoOccurrence(self) elif draw_mode == "STEP Context": self.g = GraphCoOccurrence(self) self.connect(self.node_size, QtCore.SIGNAL('valueChanged(int)'), self.g.set_node_mult) self.axes.grid(self.draw_grid_tf) self.canvas.draw() def on_pick(self, args): print "in matplotframe: ", args def resizeEvent(self, ev): self.draw_axis_units() def set_step_path(self, path): self.step_path = path self.parent.set_step_path(path) def toggle_axis_units(self): if self.draw_axis_units_tf == False: self.draw_axis_units_tf = True else: self.draw_axis_units_tf = False self.draw_axis_units() def toggle_node_labels(self): if self.draw_node_labels_tf == False: self.draw_node_labels_tf = True else: self.draw_node_labels_tf = False if self.g != None: self.g.redraw()
class EditGeometryProperties(PyDialog): force = True def __init__(self, data, win_parent=None): """ +------------------+ | Edit Actor Props | +------------------+------+ | Name1 | | Name2 | | Name3 | | Name4 | | | | Active_Name main | | Color box | | Line_Width 2 | | Point_Size 2 | | Bar_Scale 2 | | Opacity 0.5 | | Show/Hide | | | | Apply OK Cancel | +-------------------------+ """ PyDialog.__init__(self, data, win_parent) self.set_font_size(data['font_size']) del self.out_data['font_size'] self.setWindowTitle('Edit Geometry Properties') self.allow_update = True #default #self.win_parent = win_parent #self.out_data = data self.keys = sorted(data.keys()) self.keys = data.keys() keys = self.keys nrows = len(keys) self.active_key = 'main' #keys[0] items = keys header_labels = ['Groups'] table_model = Model(items, header_labels, self) view = CustomQTableView(self) #Call your custom QTableView here view.setModel(table_model) if qt_version == 4: view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.table = view actor_obj = data[self.active_key] name = actor_obj.name line_width = actor_obj.line_width point_size = actor_obj.point_size bar_scale = actor_obj.bar_scale opacity = actor_obj.opacity color = actor_obj.color show = actor_obj.is_visible self.representation = actor_obj.representation # table header = self.table.horizontalHeader() header.setStretchLastSection(True) self._default_is_apply = False self.name = QLabel("Name:") self.name_edit = QLineEdit(str(name)) self.name_edit.setDisabled(True) self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) color = self.out_data[self.active_key].color qcolor = QtGui.QColor() qcolor.setRgb(*color) #print('color =%s' % str(color)) palette = QtGui.QPalette( self.color_edit.palette()) # make a copy of the palette #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \ #qcolor) palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue')) # ButtonText self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color) + #"border:1px solid rgb(255, 170, 255); " "}") self.use_slider = True self.is_opacity_edit_active = False self.is_opacity_edit_slider_active = False self.is_line_width_edit_active = False self.is_line_width_edit_slider_active = False self.is_point_size_edit_active = False self.is_point_size_edit_slider_active = False self.is_bar_scale_edit_active = False self.is_bar_scale_edit_slider_active = False self.opacity = QLabel("Opacity:") self.opacity_edit = QDoubleSpinBox(self) self.opacity_edit.setRange(0.1, 1.0) self.opacity_edit.setDecimals(1) self.opacity_edit.setSingleStep(0.1) self.opacity_edit.setValue(opacity) if self.use_slider: self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal) self.opacity_slider_edit.setRange(1, 10) self.opacity_slider_edit.setValue(opacity * 10) self.opacity_slider_edit.setTickInterval(1) self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow) self.line_width = QLabel("Line Width:") self.line_width_edit = QSpinBox(self) self.line_width_edit.setRange(1, 15) self.line_width_edit.setSingleStep(1) self.line_width_edit.setValue(line_width) if self.use_slider: self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal) self.line_width_slider_edit.setRange(1, 15) self.line_width_slider_edit.setValue(line_width) self.line_width_slider_edit.setTickInterval(1) self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation in ['point', 'surface']: self.line_width.setEnabled(False) self.line_width_edit.setEnabled(False) self.line_width_slider_edit.setEnabled(False) self.point_size = QLabel("Point Size:") self.point_size_edit = QSpinBox(self) self.point_size_edit.setRange(1, 15) self.point_size_edit.setSingleStep(1) self.point_size_edit.setValue(point_size) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) if self.use_slider: self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal) self.point_size_slider_edit.setRange(1, 15) self.point_size_slider_edit.setValue(point_size) self.point_size_slider_edit.setTickInterval(1) self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow) self.point_size_slider_edit.setVisible(False) if self.representation in ['wire', 'surface']: self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) self.bar_scale = QLabel("Bar Scale:") self.bar_scale_edit = QDoubleSpinBox(self) #self.bar_scale_edit.setRange(0.01, 1.0) # was 0.1 #self.bar_scale_edit.setRange(0.05, 5.0) self.bar_scale_edit.setDecimals(1) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) self.bar_scale_edit.setSingleStep(0.1) self.bar_scale_edit.setValue(bar_scale) #if self.use_slider: #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal) #self.bar_scale_slider_edit.setRange(1, 100) # 1/0.05 = 100/5.0 #self.bar_scale_slider_edit.setValue(opacity * 0.05) #self.bar_scale_slider_edit.setTickInterval(10) #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation != 'bar': self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setEnabled(False) # show/hide self.checkbox_show = QCheckBox("Show") self.checkbox_hide = QCheckBox("Hide") self.checkbox_show.setChecked(show) self.checkbox_hide.setChecked(not show) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) self.cancel_button = QPushButton("Close") self.create_layout() self.set_connections() def on_update_geometry_properties_window(self, data): """Not Implemented""" return #new_keys = sorted(data.keys()) #if self.active_key in new_keys: #i = new_keys.index(self.active_key) #else: #i = 0 #self.table.update_data(new_keys) #self.out_data = data #self.update_active_key(i) def update_active_key(self, index): """ Parameters ---------- index : PyQt4.QtCore.QModelIndex the index of the list Internal Parameters ------------------- name : str the name of obj obj : CoordProperties, AltGeometry the storage object for things like line_width, point_size, etc. """ if qt_version == 4: name = str(index.data().toString()) else: name = str(index.data()) print('name = %r' % name) #i = self.keys.index(self.active_key) self.active_key = name self.name_edit.setText(name) obj = self.out_data[name] if isinstance(obj, CoordProperties): opacity = 1.0 representation = 'coord' is_visible = obj.is_visible elif isinstance(obj, AltGeometry): line_width = obj.line_width point_size = obj.point_size bar_scale = obj.bar_scale opacity = obj.opacity representation = obj.representation is_visible = obj.is_visible self.color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") self.allow_update = False self.force = False self.line_width_edit.setValue(line_width) self.point_size_edit.setValue(point_size) self.bar_scale_edit.setValue(bar_scale) self.force = True self.allow_update = True else: raise NotImplementedError(obj) allowed_representations = [ 'main', 'surface', 'coord', 'toggle', 'wire', 'point', 'bar' ] if self.representation != representation: self.representation = representation if representation not in allowed_representations: msg = 'name=%r; representation=%r is invalid\nrepresentations=%r' % ( name, representation, allowed_representations) if self.representation == 'coord': self.color.setVisible(False) self.color_edit.setVisible(False) self.line_width.setVisible(False) self.line_width_edit.setVisible(False) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) self.opacity.setVisible(False) self.opacity_edit.setVisible(False) if self.use_slider: self.opacity_slider_edit.setVisible(False) self.point_size_slider_edit.setVisible(False) self.line_width_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setVisible(True) self.color_edit.setVisible(True) self.line_width.setVisible(True) self.line_width_edit.setVisible(True) self.point_size.setVisible(True) self.point_size_edit.setVisible(True) self.bar_scale.setVisible(True) #self.bar_scale_edit.setVisible(True) self.opacity.setVisible(True) self.opacity_edit.setVisible(True) if self.use_slider: self.opacity_slider_edit.setVisible(True) self.line_width_slider_edit.setVisible(True) self.point_size_slider_edit.setVisible(True) #self.bar_scale_slider_edit.setVisible(True) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) self.line_width.setEnabled(True) self.line_width_edit.setEnabled(True) self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) show_points = False show_line_width = True show_bar_scale = False if self.use_slider: self.line_width_slider_edit.setEnabled(True) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setEnabled(True) self.color_edit.setEnabled(True) show_points = False if self.representation in ['point', 'wire+point']: show_points = True show_line_width = False if self.representation in ['wire', 'wire+point', 'bar']: show_line_width = True if representation == 'bar': show_bar_scale = True else: show_bar_scale = False #self.bar_scale_button.setVisible(show_bar_scale) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) #if self.use_slider: #self.bar_scale_slider_edit.setEnabled(False) self.point_size.setEnabled(show_points) self.point_size_edit.setEnabled(show_points) self.point_size.setVisible(show_points) self.point_size_edit.setVisible(show_points) self.line_width.setEnabled(show_line_width) self.line_width_edit.setEnabled(show_line_width) self.bar_scale.setEnabled(show_bar_scale) self.bar_scale_edit.setEnabled(show_bar_scale) self.bar_scale.setVisible(show_bar_scale) self.bar_scale_edit.setVisible(show_bar_scale) if self.use_slider: self.point_size_slider_edit.setEnabled(show_points) self.point_size_slider_edit.setVisible(show_points) self.line_width_slider_edit.setEnabled(show_line_width) #if self.representation in ['wire', 'surface']: self.opacity_edit.setValue(opacity) #if self.use_slider: #self.opacity_slider_edit.setValue(opacity*10) self.checkbox_show.setChecked(is_visible) self.checkbox_hide.setChecked(not is_visible) passed = self.on_validate() #self.on_apply(force=True) # TODO: was turned on...do I want this??? #self.allow_update = True #def on_name_select(self): #print('on_name_select') #return def create_layout(self): ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.cancel_button) grid = QGridLayout() irow = 0 grid.addWidget(self.name, irow, 0) grid.addWidget(self.name_edit, irow, 1) irow += 1 grid.addWidget(self.color, irow, 0) grid.addWidget(self.color_edit, irow, 1) irow += 1 grid.addWidget(self.opacity, irow, 0) if self.use_slider: grid.addWidget(self.opacity_edit, irow, 2) grid.addWidget(self.opacity_slider_edit, irow, 1) else: grid.addWidget(self.opacity_edit, irow, 1) irow += 1 grid.addWidget(self.line_width, irow, 0) if self.use_slider: grid.addWidget(self.line_width_edit, irow, 2) grid.addWidget(self.line_width_slider_edit, irow, 1) else: grid.addWidget(self.line_width_edit, irow, 1) irow += 1 grid.addWidget(self.point_size, irow, 0) if self.use_slider: grid.addWidget(self.point_size_edit, irow, 2) grid.addWidget(self.point_size_slider_edit, irow, 1) else: grid.addWidget(self.point_size_edit, irow, 1) irow += 1 grid.addWidget(self.bar_scale, irow, 0) if self.use_slider and 0: grid.addWidget(self.bar_scale_edit, irow, 2) grid.addWidget(self.bar_scale_slider_edit, irow, 1) else: grid.addWidget(self.bar_scale_edit, irow, 1) irow += 1 checkboxs = QButtonGroup(self) checkboxs.addButton(self.checkbox_show) checkboxs.addButton(self.checkbox_hide) vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addLayout(grid) if 0: vbox.addWidget(self.checkbox_show) vbox.addWidget(self.checkbox_hide) else: vbox1 = QVBoxLayout() vbox1.addWidget(self.checkbox_show) vbox1.addWidget(self.checkbox_hide) vbox.addLayout(vbox1) vbox.addStretch() #vbox.addWidget(self.check_apply) vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def set_connections(self): self.opacity_edit.valueChanged.connect(self.on_opacity) self.line_width_edit.valueChanged.connect(self.on_line_width) self.point_size_edit.valueChanged.connect(self.on_point_size) self.bar_scale_edit.valueChanged.connect(self.on_bar_scale) if self.use_slider: self.opacity_slider_edit.valueChanged.connect( self.on_opacity_slider) self.line_width_slider_edit.valueChanged.connect( self.on_line_width_slider) self.point_size_slider_edit.valueChanged.connect( self.on_point_size_slider) #self.bar_scale_slider_edit.valueChanged.connect(self.on_bar_scale_slider) # self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity) # self.connect(self.line_width, QtCore.SIGNAL('clicked()'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size) if qt_version == 4: self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) self.color_edit.clicked.connect(self.on_color) self.checkbox_show.clicked.connect(self.on_show) self.checkbox_hide.clicked.connect(self.on_hide) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): self.on_cancel() def on_color(self): """called when the user clicks on the color box""" name = self.active_key obj = self.out_data[name] rgb_color_ints = obj.color msg = name col = QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a %s color" % msg) if col.isValid(): color_float = col.getRgbF()[:3] obj.color = color_float color_int = [int(colori * 255) for colori in color_float] self.color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color_int) + #"border:1px solid rgb(255, 170, 255); " "}") self.on_apply(force=self.force) #print(self.allow_update) def on_show(self): """shows the actor""" name = self.active_key is_checked = self.checkbox_show.isChecked() self.out_data[name].is_visible = is_checked self.on_apply(force=self.force) def on_hide(self): """hides the actor""" name = self.active_key is_checked = self.checkbox_hide.isChecked() self.out_data[name].is_visible = not is_checked self.on_apply(force=self.force) def on_line_width(self): """increases/decreases the wireframe (for solid bodies) or the bar thickness""" self.is_line_width_edit_active = True name = self.active_key line_width = self.line_width_edit.value() self.out_data[name].line_width = line_width if not self.is_line_width_edit_slider_active: if self.use_slider: self.line_width_slider_edit.setValue(line_width) self.is_line_width_edit_active = False self.on_apply(force=self.force) self.is_line_width_edit_active = False def on_line_width_slider(self): """increases/decreases the wireframe (for solid bodies) or the bar thickness""" self.is_line_width_edit_slider_active = True #name = self.active_key line_width = self.line_width_slider_edit.value() if not self.is_line_width_edit_active: self.line_width_edit.setValue(line_width) self.is_line_width_edit_slider_active = False def on_point_size(self): """increases/decreases the point size""" self.is_point_size_edit_active = True name = self.active_key point_size = self.point_size_edit.value() self.out_data[name].point_size = point_size if not self.is_point_size_edit_slider_active: if self.use_slider: self.point_size_slider_edit.setValue(point_size) self.is_point_size_edit_active = False self.on_apply(force=self.force) self.is_point_size_edit_active = False def on_point_size_slider(self): """increases/decreases the point size""" self.is_point_size_edit_slider_active = True name = self.active_key point_size = self.point_size_slider_edit.value() if not self.is_point_size_edit_active: self.point_size_edit.setValue(point_size) self.is_point_size_edit_slider_active = False def on_bar_scale(self): """ Vectors start at some xyz coordinate and can increase in length. Increases/decreases the length scale factor. """ self.is_bar_scale_edit_active = True name = self.active_key float_bar_scale = self.bar_scale_edit.value() self.out_data[name].bar_scale = float_bar_scale if not self.is_bar_scale_edit_slider_active: int_bar_scale = int(round(float_bar_scale * 20, 0)) #if self.use_slider: #self.bar_scale_slider_edit.setValue(int_bar_scale) self.is_bar_scale_edit_active = False self.on_apply(force=self.force) self.is_bar_scale_edit_active = False def on_bar_scale_slider(self): """ Vectors start at some xyz coordinate and can increase in length. Increases/decreases the length scale factor. """ self.is_bar_scale_edit_slider_active = True name = self.active_key int_bar_scale = self.bar_scale_slider_edit.value() if not self.is_bar_scale_edit_active: float_bar_scale = int_bar_scale / 20. self.bar_scale_edit.setValue(float_bar_scale) self.is_bar_scale_edit_slider_active = False def on_opacity(self): """ opacity = 1.0 (solid/opaque) opacity = 0.0 (invisible) """ self.is_opacity_edit_active = True name = self.active_key float_opacity = self.opacity_edit.value() self.out_data[name].opacity = float_opacity if not self.is_opacity_edit_slider_active: int_opacity = int(round(float_opacity * 10, 0)) if self.use_slider: self.opacity_slider_edit.setValue(int_opacity) self.is_opacity_edit_active = False self.on_apply(force=self.force) self.is_opacity_edit_active = False def on_opacity_slider(self): """ opacity = 1.0 (solid/opaque) opacity = 0.0 (invisible) """ self.is_opacity_edit_slider_active = True name = self.active_key int_opacity = self.opacity_slider_edit.value() if not self.is_opacity_edit_active: float_opacity = int_opacity / 10. self.opacity_edit.setValue(float_opacity) self.is_opacity_edit_slider_active = False #def on_axis(self, text): ##print(self.combo_axis.itemText()) #self._axis = str(text) #self.plane.setText('Point on %s? Plane:' % self._axis) #self.point_a.setText('Point on %s Axis:' % self._axis) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) #def on_plane(self, text): #self._plane = str(text) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) #def _on_float(self, field): #try: #eval_float_from_string(field.text()) #field.setStyleSheet("QLineEdit{background: white;}") #except ValueError: #field.setStyleSheet("QLineEdit{background: red;}") #def on_default_name(self): #self.name_edit.setText(str(self._default_name)) #self.name_edit.setStyleSheet("QLineEdit{background: white;}") #def check_float(self, cell): #text = cell.text() #try: #value = eval_float_from_string(text) #cell.setStyleSheet("QLineEdit{background: white;}") #return value, True #except ValueError: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False #def check_name(self, cell): #text = str(cell.text()).strip() #if len(text): #cell.setStyleSheet("QLineEdit{background: white;}") #return text, True #else: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False def on_validate(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False old_obj = self.out_data[self.active_key] old_obj.line_width = self.line_width_edit.value() old_obj.point_size = self.point_size_edit.value() old_obj.bar_scale = self.bar_scale_edit.value() old_obj.opacity = self.opacity_edit.value() #old_obj.color = self.color_edit old_obj.is_visible = self.checkbox_show.isChecked() return True #name_value, flag0 = self.check_name(self.name_edit) #ox_value, flag1 = self.check_float(self.transparency_edit) #if flag0 and flag1: #self.out_data['clicked_ok'] = True #return True #return False def on_apply(self, force=False): passed = self.on_validate() #print("passed=%s force=%s allow=%s" % (passed, force, self.allow_update)) if (passed or force) and self.allow_update and hasattr( self.win_parent, 'on_update_geometry_properties'): #print('obj = %s' % self.out_data[self.active_key]) self.win_parent.on_update_geometry_properties(self.out_data, name=self.active_key) return passed def on_cancel(self): passed = self.on_apply(force=True) if passed: self.close()
def add_device_to_tree(self, device): # check if device is already added if len(device['uid']) > 0: for row in range(self.model_devices.rowCount()): existing_name = self.model_devices.item(row, 0).text() exisitng_uid = self.tree_devices.indexWidget( self.model_devices.item(row, 1).index()).text() if device['name'] == existing_name and device[ 'uid'] == exisitng_uid: EventLogger.info( 'Ignoring duplicate device "{0}" with UID "{1}"'. format(device['name'], device['uid'])) return # add device name_item = QStandardItem(device['name']) uid_item = QStandardItem('') self.model_devices.appendRow([name_item, uid_item]) edit_uid = QLineEdit() edit_uid.setPlaceholderText('Enter UID') edit_uid.setValidator( QRegExpValidator(QRegExp( '^[{0}]{{1,6}}$'.format(BASE58)))) # FIXME: use stricter logic edit_uid.setText(device['uid']) self.tree_devices.setIndexWidget(uid_item.index(), edit_uid) value_specs = device_specs[device['name']]['values'] parent_item = QStandardItem('Values') name_item.appendRow([parent_item, QStandardItem('')]) self.tree_devices.expand(parent_item.index()) # add values for value_spec in value_specs: value_name_item = QStandardItem(value_spec['name']) value_interval_item = QStandardItem('') parent_item.appendRow([value_name_item, value_interval_item]) spinbox_interval = QSpinBox() spinbox_interval.setRange(0, (1 << 31) - 1) spinbox_interval.setSingleStep(1) spinbox_interval.setValue( device['values'][value_spec['name']]['interval']) spinbox_interval.setSuffix(' seconds') self.tree_devices.setIndexWidget(value_interval_item.index(), spinbox_interval) if value_spec['subvalues'] != None: for subvalue_name in value_spec['subvalues']: subvalue_name_item = QStandardItem(subvalue_name) subvalue_check_item = QStandardItem('') value_name_item.appendRow( [subvalue_name_item, subvalue_check_item]) check_subvalue = QCheckBox() check_subvalue.setChecked(device['values'][ value_spec['name']]['subvalues'][subvalue_name]) self.tree_devices.setIndexWidget( subvalue_check_item.index(), check_subvalue) self.tree_devices.expand(name_item.index()) # add options option_specs = device_specs[device['name']]['options'] if option_specs != None: parent_item = QStandardItem('Options') name_item.appendRow([parent_item, QStandardItem('')]) for option_spec in option_specs: option_name_item = QStandardItem(option_spec['name']) option_widget_item = QStandardItem('') parent_item.appendRow([option_name_item, option_widget_item]) if option_spec['type'] == 'choice': widget_option_value = QComboBox() for option_value_spec in option_spec['values']: widget_option_value.addItem( option_value_spec[0].decode('utf-8'), option_value_spec[1]) widget_option_value.setCurrentIndex( widget_option_value.findText(device['options'][ option_spec['name']]['value'].decode('utf-8'))) elif option_spec['type'] == 'int': widget_option_value = QSpinBox() widget_option_value.setRange(option_spec['minimum'], option_spec['maximum']) widget_option_value.setSuffix(option_spec['suffix']) widget_option_value.setValue( device['options'][option_spec['name']]['value']) elif option_spec['type'] == 'bool': widget_option_value = QCheckBox() widget_option_value.setChecked( device['options'][option_spec['name']]['value']) self.tree_devices.setIndexWidget(option_widget_item.index(), widget_option_value)
class AnalogOut(PluginBase): def __init__ (self, ipcon, uid): PluginBase.__init__(self, ipcon, uid) self.ao = bricklet_analog_out.AnalogOut(self.uid) self.ipcon.add_device(self.ao) self.version = '.'.join(map(str, self.ao.get_version()[1])) self.voltage_label = QLabel('Output Voltage (mV): ') self.voltage_box = QSpinBox() self.voltage_box.setMinimum(0) self.voltage_box.setMaximum(5000) self.voltage_box.setSingleStep(1) self.mode_label = QLabel('Mode: ') self.mode_combo = QComboBox() self.mode_combo.addItem("Normal Mode") self.mode_combo.addItem("1k Ohm resistor to ground") self.mode_combo.addItem("100k Ohm resistor to ground") self.mode_combo.addItem("500k Ohm resistor to ground") layout_h1 = QHBoxLayout() layout_h1.addStretch() layout_h1.addWidget(self.voltage_label) layout_h1.addWidget(self.voltage_box) layout_h1.addStretch() layout_h2 = QHBoxLayout() layout_h2.addStretch() layout_h2.addWidget(self.mode_label) layout_h2.addWidget(self.mode_combo) layout_h2.addStretch() layout = QVBoxLayout(self) layout.addLayout(layout_h2) layout.addLayout(layout_h1) layout.addStretch() self.voltage_box.editingFinished.connect(self.voltage_finished) self.mode_combo.activated.connect(self.mode_changed) def start(self): try: voltage = self.ao.get_voltage() mode = self.ao.get_mode() self.voltage_box.setValue(voltage) self.mode_combo.setCurrentIndex(mode) except ip_connection.Error: return def stop(self): pass @staticmethod def has_name(name): return 'Analog Out Bricklet' in name def voltage_finished(self): value = self.voltage_box.value() try: self.ao.set_voltage(value) except ip_connection.Error: return self.mode_combo.setCurrentIndex(0) def mode_changed(self, mode): try: self.ao.set_mode(mode) except ip_connection.Error: return self.voltage_box.setValue(0)
def initGui(): def setData(): buttonPath.setText(self.data["path"]) radioVisual.setChecked(self.data["isVisual"]) radioAnalytic.setChecked(not self.data["isVisual"]) chkBoxSquare.setChecked(self.data["isSquare"]) d1 = self.data["date1"] d2 = self.data["date2"] date1.setDate(d1) date2.setDate(d2) date1.setMaximumDate(d2.addDays(-1)) date2.setMinimumDate(d1.addDays(+1)) spinDay.setValue(d1.daysTo(d2)) def connect(): buttonOK.clicked.connect(self.onOK) buttonPath.clicked.connect(self.onPath) date1.dateChanged.connect(self.onDateChanged1) date2.dateChanged.connect(self.onDateChanged2) spinDay.valueChanged.connect(self.onValueChanged) windowTitle = "Setting download images Planet Labs" self.setWindowTitle(windowTitle) self.setWindowIcon(icon) grpImage = QGroupBox("Images", self) radioVisual = QRadioButton("Visual", grpImage) radioVisual.setObjectName("rbVisual") radioAnalytic = QRadioButton("Analytic", grpImage) chkBoxSquare = QCheckBox("Square thumbnail", grpImage) chkBoxSquare.setObjectName("cbBoxSquare") buttonPath = QPushButton(self.titleSelectDirectory, grpImage) buttonPath.setObjectName("pbPath") layoutRadioButtons = QHBoxLayout() for item in (radioVisual, radioAnalytic): layoutRadioButtons.addWidget(item) layoutImage = QVBoxLayout(grpImage) layoutImage.addLayout(layoutRadioButtons) layoutImage.addWidget(chkBoxSquare) layoutImage.addWidget(buttonPath) grpDateSearch = QGroupBox("Dates for search", self) date1 = QDateEdit(grpDateSearch) date1.setObjectName("deDate1") date2 = QDateEdit(grpDateSearch) date2.setObjectName("deDate2") for item in [date1, date2]: item.setCalendarPopup(True) format = item.displayFormat().replace("yy", "yyyy") item.setDisplayFormat(format) spinDay = QSpinBox(grpDateSearch) spinDay.setObjectName("sbDay") spinDay.setSingleStep(1) spinDay.setSuffix(" Days") spinDay.setRange(1, 1000 * 360) layoutDate = QHBoxLayout(grpDateSearch) layoutDate.addWidget(QLabel("From", grpDateSearch)) layoutDate.addWidget(date1) layoutDate.addWidget(QLabel("To", grpDateSearch)) layoutDate.addWidget(date2) layoutDate.addWidget(spinDay) buttonOK = QPushButton("OK", self) layout = QVBoxLayout(self) layout.addWidget(grpImage) layout.addWidget(grpDateSearch) layout.addWidget(buttonOK) self.resize(5 * len(windowTitle) + 200, 30) if not self.data is None: setData() else: radioVisual.setChecked(True) radioAnalytic.setChecked(False) chkBoxSquare.setChecked(False) d2 = QDate.currentDate() d1 = d2.addMonths(-1) date1.setDate(d1) date2.setDate(d2) date1.setMaximumDate(d2.addDays(-1)) date2.setMinimumDate(d1.addDays(+1)) spinDay.setValue(d1.daysTo(d2)) connect()
def make_spinbox(low, high, value, step=1): spin_box = QSpinBox() spin_box.setRange(low, high) spin_box.setValue(value) spin_box.setSingleStep(step) return spin_box
class Pressure(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletPressure, *args) self.p = self.device self.cbe_pressure = CallbackEmulator(self.p.get_pressure, self.cb_pressure, self.increase_error_count) self.current_pressure = None # float, kPa plots = [('Pressure', Qt.red, lambda: self.current_pressure, '{:.3f} kPa'.format)] self.plot_widget = PlotWidget('Pressure [kPa]', plots) self.combo_sensor = QComboBox() self.combo_sensor.addItem('MPX5500') self.combo_sensor.addItem('MPXV5004') self.combo_sensor.addItem('MPX4115A') self.combo_sensor.currentIndexChanged.connect( self.combo_sensor_changed) self.spin_average = QSpinBox() self.spin_average.setMinimum(1) self.spin_average.setMaximum(50) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) hlayout = QHBoxLayout() hlayout.addWidget(QLabel('Sensor Type:')) hlayout.addWidget(self.combo_sensor) hlayout.addStretch() hlayout.addWidget(QLabel('Moving Average Length:')) hlayout.addWidget(self.spin_average) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout) def get_sensor_type_async(self, sensor): self.combo_sensor.setCurrentIndex(sensor) def get_moving_average_async(self, average): self.spin_average.setValue(average) def start(self): async_call(self.p.get_sensor_type, None, self.get_sensor_type_async, self.increase_error_count) async_call(self.p.get_moving_average, None, self.get_moving_average_async, self.increase_error_count) async_call(self.p.get_pressure, None, self.cb_pressure, self.increase_error_count) self.cbe_pressure.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_pressure.set_period(0) self.plot_widget.stop = True def destroy(self): pass @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletPressure.DEVICE_IDENTIFIER def cb_pressure(self, pressure): self.current_pressure = pressure / 1000.0 def combo_sensor_changed(self): self.p.set_sensor_type(self.combo_sensor.currentIndex()) def spin_average_finished(self): self.p.set_moving_average(self.spin_average.value())
class AnalogIn(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletAnalogIn, *args) self.ai = self.device self.cbe_voltage = CallbackEmulator(self.ai.get_voltage, self.cb_voltage, self.increase_error_count) self.voltage_label = VoltageLabel('Voltage: ') self.current_value = None plot_list = [['', Qt.red, self.get_current_value]] self.plot_widget = PlotWidget('Voltage [mV]', plot_list) layout_h2 = QHBoxLayout() layout_h2.addStretch() layout_h2.addWidget(self.voltage_label) layout_h2.addStretch() layout = QVBoxLayout(self) layout.addLayout(layout_h2) layout.addWidget(self.plot_widget) if self.firmware_version >= (2, 0, 1): self.combo_range = QComboBox() self.combo_range.addItem('Automatic', BrickletAnalogIn.RANGE_AUTOMATIC) if self.firmware_version >= (2, 0, 3): self.combo_range.addItem('0V - 3.30V', BrickletAnalogIn.RANGE_UP_TO_3V) self.combo_range.addItem('0V - 6.05V', BrickletAnalogIn.RANGE_UP_TO_6V) self.combo_range.addItem('0V - 10.32V', BrickletAnalogIn.RANGE_UP_TO_10V) self.combo_range.addItem('0V - 36.30V', BrickletAnalogIn.RANGE_UP_TO_36V) self.combo_range.addItem('0V - 45.00V', BrickletAnalogIn.RANGE_UP_TO_45V) self.combo_range.currentIndexChanged.connect(self.range_changed) layout_h1 = QHBoxLayout() layout_h1.addStretch() layout_h1.addWidget(QLabel('Range:')) layout_h1.addWidget(self.combo_range) if self.firmware_version >= (2, 0, 3): self.spin_average = QSpinBox() self.spin_average.setMinimum(0) self.spin_average.setMaximum(255) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) layout_h1.addStretch() layout_h1.addWidget(QLabel('Average Length:')) layout_h1.addWidget(self.spin_average) layout_h1.addStretch() layout.addLayout(layout_h1) def get_range_async(self, range_): self.combo_range.setCurrentIndex(self.combo_range.findData(range_)) def get_averaging_async(self, average): self.spin_average.setValue(average) def start(self): if self.firmware_version >= (2, 0, 1): async_call(self.ai.get_range, None, self.get_range_async, self.increase_error_count) if self.firmware_version >= (2, 0, 3): async_call(self.ai.get_averaging, None, self.get_averaging_async, self.increase_error_count) async_call(self.ai.get_voltage, None, self.cb_voltage, self.increase_error_count) self.cbe_voltage.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_voltage.set_period(0) self.plot_widget.stop = True def destroy(self): pass def get_url_part(self): return 'analog_in' @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletAnalogIn.DEVICE_IDENTIFIER def get_current_value(self): return self.current_value def cb_voltage(self, voltage): self.current_value = voltage self.voltage_label.setText(str(voltage/1000.0)) def range_changed(self, index): if index >= 0 and self.firmware_version >= (2, 0, 1): range_ = self.combo_range.itemData(index) async_call(self.ai.set_range, range_, None, self.increase_error_count) def spin_average_finished(self): self.ai.set_averaging(self.spin_average.value())
class EditorConfiguration(QWidget): """EditorConfiguration widget class""" def __init__(self, parent): super(EditorConfiguration, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) # groups group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_INDENT) group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_MARGIN) group3 = QGroupBox(translations.TR_LINT_DIRTY_TEXT) group4 = QGroupBox(translations.TR_PEP8_DIRTY_TEXT) group5 = QGroupBox(translations.TR_HIGHLIGHTER_EXTRAS) group6 = QGroupBox(translations.TR_TYPING_ASSISTANCE) group7 = QGroupBox(translations.TR_DISPLAY) # groups container container_widget_with_all_preferences = QWidget() formFeatures = QGridLayout(container_widget_with_all_preferences) # Indentation hboxg1 = QHBoxLayout(group1) hboxg1.setContentsMargins(5, 15, 5, 5) self._spin, self._checkUseTabs = QSpinBox(), QComboBox() self._spin.setRange(1, 10) self._spin.setValue(settings.INDENT) hboxg1.addWidget(self._spin) self._checkUseTabs.addItems([ translations.TR_PREFERENCES_EDITOR_CONFIG_SPACES.capitalize(), translations.TR_PREFERENCES_EDITOR_CONFIG_TABS.capitalize() ]) self._checkUseTabs.setCurrentIndex(int(settings.USE_TABS)) hboxg1.addWidget(self._checkUseTabs) formFeatures.addWidget(group1, 0, 0) # Margin Line hboxg2 = QHBoxLayout(group2) hboxg2.setContentsMargins(5, 15, 5, 5) self._checkShowMargin = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MARGIN_LINE) self._checkShowMargin.setChecked(settings.SHOW_MARGIN_LINE) hboxg2.addWidget(self._checkShowMargin) self._spinMargin = QSpinBox() self._spinMargin.setRange(50, 100) self._spinMargin.setSingleStep(2) self._spinMargin.setValue(settings.MARGIN_LINE) hboxg2.addWidget(self._spinMargin) hboxg2.addWidget(QLabel(translations.TR_CHARACTERS)) formFeatures.addWidget(group2, 0, 1) # Display Errors vboxDisplay = QVBoxLayout(group7) vboxDisplay.setContentsMargins(5, 15, 5, 5) self._checkHighlightLine = QComboBox() self._checkHighlightLine.addItems([ translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_BACKGROUND, translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_UNDERLINE ]) self._checkHighlightLine.setCurrentIndex( int(settings.UNDERLINE_NOT_BACKGROUND)) hboxDisplay1 = QHBoxLayout() hboxDisplay1.addWidget(QLabel(translations.TR_DISPLAY_ERRORS)) hboxDisplay1.addWidget(self._checkHighlightLine) hboxDisplay2 = QHBoxLayout() self._checkDisplayLineNumbers = QCheckBox( translations.TR_DISPLAY_LINE_NUMBERS) self._checkDisplayLineNumbers.setChecked(settings.SHOW_LINE_NUMBERS) hboxDisplay2.addWidget(self._checkDisplayLineNumbers) vboxDisplay.addLayout(hboxDisplay1) vboxDisplay.addLayout(hboxDisplay2) formFeatures.addWidget(group7, 1, 0, 1, 0) # Find Lint Errors (highlighter) vboxg3 = QVBoxLayout(group3) self._checkErrors = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS) self._checkErrors.setChecked(settings.FIND_ERRORS) self.connect(self._checkErrors, SIGNAL("stateChanged(int)"), self._disable_show_errors) self._showErrorsOnLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS) self._showErrorsOnLine.setChecked(settings.ERRORS_HIGHLIGHT_LINE) self.connect(self._showErrorsOnLine, SIGNAL("stateChanged(int)"), self._enable_errors_inline) vboxg3.addWidget(self._checkErrors) vboxg3.addWidget(self._showErrorsOnLine) vboxg3.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding)) formFeatures.addWidget(group3, 2, 0) # Find PEP8 Errors (highlighter) vboxg4 = QHBoxLayout(group4) vboxg4.setContentsMargins(5, 15, 5, 5) vvbox = QVBoxLayout() self._checkStyle = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8) self._checkStyle.setChecked(settings.CHECK_STYLE) self.connect(self._checkStyle, SIGNAL("stateChanged(int)"), self._disable_check_style) vvbox.addWidget(self._checkStyle) self._checkStyleOnLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8) self._checkStyleOnLine.setChecked(settings.CHECK_HIGHLIGHT_LINE) self.connect(self._checkStyleOnLine, SIGNAL("stateChanged(int)"), self._enable_check_inline) vvbox.addWidget(self._checkStyleOnLine) vvbox.addItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) vboxg4.addLayout(vvbox) # Container for tree widget and buttons widget = QWidget() hhbox = QHBoxLayout(widget) hhbox.setContentsMargins(0, 0, 0, 0) # Tree Widget with custom item delegate # always adds uppercase text self._listIgnoreViolations = QTreeWidget() self._listIgnoreViolations.setObjectName("ignore_pep8") self._listIgnoreViolations.setItemDelegate(ui_tools.CustomDelegate()) self._listIgnoreViolations.setMaximumHeight(80) self._listIgnoreViolations.setHeaderLabel( translations.TR_PREFERENCES_EDITOR_CONFIG_IGNORE_PEP8) for ic in settings.IGNORE_PEP8_LIST: self._listIgnoreViolations.addTopLevelItem(QTreeWidgetItem([ic])) hhbox.addWidget(self._listIgnoreViolations) box = QVBoxLayout() box.setContentsMargins(0, 0, 0, 0) btn_add = QPushButton(QIcon(":img/add_small"), '') btn_add.setMaximumSize(26, 24) btn_add.clicked.connect(self._add_code_pep8) box.addWidget(btn_add) btn_remove = QPushButton(QIcon(":img/delete_small"), '') btn_remove.setMaximumSize(26, 24) btn_remove.clicked.connect(self._remove_code_pep8) box.addWidget(btn_remove) box.addItem(QSpacerItem(0, 0, QSizePolicy.Fixed, QSizePolicy.Expanding)) hhbox.addLayout(box) vboxg4.addWidget(widget) formFeatures.addWidget(group4) # Show Python3 Migration, DocStrings and Spaces (highlighter) vboxg5 = QVBoxLayout(group5) vboxg5.setContentsMargins(5, 15, 5, 5) self._showMigrationTips = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MIGRATION) self._showMigrationTips.setChecked(settings.SHOW_MIGRATION_TIPS) vboxg5.addWidget(self._showMigrationTips) self._checkForDocstrings = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_CHECK_FOR_DOCSTRINGS) self._checkForDocstrings.setChecked(settings.CHECK_FOR_DOCSTRINGS) vboxg5.addWidget(self._checkForDocstrings) self._checkShowSpaces = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES) self._checkShowSpaces.setChecked(settings.SHOW_TABS_AND_SPACES) vboxg5.addWidget(self._checkShowSpaces) self._checkIndentationGuide = QCheckBox( translations.TR_SHOW_INDENTATION_GUIDE) self._checkIndentationGuide.setChecked(settings.SHOW_INDENTATION_GUIDE) vboxg5.addWidget(self._checkIndentationGuide) formFeatures.addWidget(group5, 3, 0) # End of line, Stop Scrolling At Last Line, Trailing space, Word wrap vboxg6 = QVBoxLayout(group6) vboxg6.setContentsMargins(5, 15, 5, 5) self._checkEndOfLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE) self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE) vboxg6.addWidget(self._checkEndOfLine) self._checkEndAtLastLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_END_AT_LAST_LINE) self._checkEndAtLastLine.setChecked(settings.END_AT_LAST_LINE) vboxg6.addWidget(self._checkEndAtLastLine) self._checkTrailing = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING) self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES) vboxg6.addWidget(self._checkTrailing) self._allowWordWrap = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP) self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP) vboxg6.addWidget(self._allowWordWrap) formFeatures.addWidget(group6, 3, 1) # pack all the groups vbox.addWidget(container_widget_with_all_preferences) vbox.addItem( QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding)) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def _add_code_pep8(self): item = QTreeWidgetItem() item.setFlags(item.flags() | Qt.ItemIsEditable) self._listIgnoreViolations.addTopLevelItem(item) self._listIgnoreViolations.setCurrentItem(item) self._listIgnoreViolations.editItem(item, 0) def _remove_code_pep8(self): index = self._listIgnoreViolations.indexOfTopLevelItem( self._listIgnoreViolations.currentItem()) self._listIgnoreViolations.takeTopLevelItem(index) def _enable_check_inline(self, val): """Method that takes a value to enable the inline style checking""" if val == Qt.Checked: self._checkStyle.setChecked(True) def _enable_errors_inline(self, val): """Method that takes a value to enable the inline errors checking""" if val == Qt.Checked: self._checkErrors.setChecked(True) def _disable_check_style(self, val): """Method that takes a value to disable the inline style checking""" if val == Qt.Unchecked: self._checkStyleOnLine.setChecked(False) def _disable_show_errors(self, val): """Method that takes a value to disable the inline errors checking""" if val == Qt.Unchecked: self._showErrorsOnLine.setChecked(False) def save(self): """Method to save settings""" qsettings = IDE.ninja_settings() settings.USE_TABS = bool(self._checkUseTabs.currentIndex()) qsettings.setValue('preferences/editor/useTabs', settings.USE_TABS) margin_line = self._spinMargin.value() settings.MARGIN_LINE = margin_line settings.pycodestylemod_update_margin_line_length(margin_line) qsettings.setValue('preferences/editor/marginLine', margin_line) settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked() qsettings.setValue('preferences/editor/showMarginLine', settings.SHOW_MARGIN_LINE) settings.INDENT = self._spin.value() qsettings.setValue('preferences/editor/indent', settings.INDENT) endOfLine = self._checkEndOfLine.isChecked() settings.USE_PLATFORM_END_OF_LINE = endOfLine qsettings.setValue('preferences/editor/platformEndOfLine', endOfLine) settings.UNDERLINE_NOT_BACKGROUND = \ bool(self._checkHighlightLine.currentIndex()) qsettings.setValue('preferences/editor/errorsUnderlineBackground', settings.UNDERLINE_NOT_BACKGROUND) settings.FIND_ERRORS = self._checkErrors.isChecked() qsettings.setValue('preferences/editor/errors', settings.FIND_ERRORS) settings.ERRORS_HIGHLIGHT_LINE = self._showErrorsOnLine.isChecked() qsettings.setValue('preferences/editor/errorsInLine', settings.ERRORS_HIGHLIGHT_LINE) settings.CHECK_STYLE = self._checkStyle.isChecked() qsettings.setValue('preferences/editor/checkStyle', settings.CHECK_STYLE) settings.SHOW_MIGRATION_TIPS = self._showMigrationTips.isChecked() qsettings.setValue('preferences/editor/showMigrationTips', settings.SHOW_MIGRATION_TIPS) settings.CHECK_HIGHLIGHT_LINE = self._checkStyleOnLine.isChecked() qsettings.setValue('preferences/editor/checkStyleInline', settings.CHECK_HIGHLIGHT_LINE) settings.END_AT_LAST_LINE = self._checkEndAtLastLine.isChecked() qsettings.setValue('preferences/editor/endAtLastLine', settings.END_AT_LAST_LINE) settings.REMOVE_TRAILING_SPACES = self._checkTrailing.isChecked() qsettings.setValue('preferences/editor/removeTrailingSpaces', settings.REMOVE_TRAILING_SPACES) settings.ALLOW_WORD_WRAP = self._allowWordWrap.isChecked() qsettings.setValue('preferences/editor/allowWordWrap', settings.ALLOW_WORD_WRAP) settings.SHOW_TABS_AND_SPACES = self._checkShowSpaces.isChecked() qsettings.setValue('preferences/editor/showTabsAndSpaces', settings.SHOW_TABS_AND_SPACES) settings.SHOW_INDENTATION_GUIDE = ( self._checkIndentationGuide.isChecked()) qsettings.setValue('preferences/editor/showIndentationGuide', settings.SHOW_INDENTATION_GUIDE) settings.CHECK_FOR_DOCSTRINGS = self._checkForDocstrings.isChecked() qsettings.setValue('preferences/editor/checkForDocstrings', settings.CHECK_FOR_DOCSTRINGS) settings.SHOW_LINE_NUMBERS = self._checkDisplayLineNumbers.isChecked() qsettings.setValue('preferences/editor/showLineNumbers', settings.SHOW_LINE_NUMBERS) current_ignores = set(settings.IGNORE_PEP8_LIST) new_ignore_codes = [] # Get pep8 from tree widget for index in range(self._listIgnoreViolations.topLevelItemCount()): ignore_code = self._listIgnoreViolations.topLevelItem(index).text( 0) if ignore_code: new_ignore_codes.append(ignore_code.strip()) # pep8 list that will be removed to_remove = [x for x in current_ignores if x not in new_ignore_codes] # Update list settings.IGNORE_PEP8_LIST = new_ignore_codes qsettings.setValue('preferences/editor/defaultIgnorePep8', settings.IGNORE_PEP8_LIST) # Add for ignore_code in settings.IGNORE_PEP8_LIST: settings.pycodestylemod_add_ignore(ignore_code) # Remove for ignore_code in to_remove: settings.pycodestylemod_remove_ignore(ignore_code) if settings.USE_TABS: settings.pycodestylemod_add_ignore("W191") else: settings.pycodestylemod_remove_ignore("W191")
class ACCurrent(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletACCurrent, *args) self.acc = self.device self.cbe_current = CallbackEmulator(self.acc.get_current, self.cb_current, self.increase_error_count) self.current_current = None # float, A plots = [('Current', Qt.red, lambda: self.current_current, format_current)] self.plot_widget = PlotWidget('Current [A]', plots) self.label_average = QLabel('Moving Average Length:') self.spin_average = QSpinBox() self.spin_average.setMinimum(1) self.spin_average.setMaximum(50) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) self.label_range = QLabel('Current Range:') self.combo_range = QComboBox() self.combo_range.addItem("0") # TODO: Adjust ranges self.combo_range.addItem("1") self.combo_range.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addWidget(self.label_average) hlayout.addWidget(self.spin_average) hlayout.addStretch() hlayout.addWidget(self.label_range) hlayout.addWidget(self.combo_range) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout) def get_configuration_async(self, conf): self.combo_range.setCurrentIndex(conf) def get_moving_average_async(self, average): self.spin_average.setValue(average) def new_config(self, value): try: self.acc.set_configuration(value) except: pass def start(self): async_call(self.acc.get_configuration, None, self.get_configuration_async, self.increase_error_count) async_call(self.acc.get_moving_average, None, self.get_moving_average_async, self.increase_error_count) async_call(self.acc.get_current, None, self.cb_current, self.increase_error_count) self.cbe_current.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_current.set_period(0) self.plot_widget.stop = True def destroy(self): pass @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletACCurrent.DEVICE_IDENTIFIER def cb_current(self, current): self.current_current = current / 1000.0 def spin_average_finished(self): self.acc.set_moving_average(self.spin_average.value())
class MikidownCfgDialog(QDialog): def __init__(self, parent=None): super(MikidownCfgDialog, self).__init__(parent) #tab = QWidget() #tab2 = QWidget() self.setWindowTitle(self.tr("Settings - mikidown")) self.recentNotesCount = QSpinBox() recent_notes_n = Mikibook.settings.value('recentNotesNumber', type=int, defaultValue=20) self.recentNotesCount.setValue(recent_notes_n) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.hltCfg = MikidownHighlightCfgWidget(parent=self) self.tabWidth = QSpinBox(self) self.tabWidth.setRange(2, 8) self.tabWidth.setSingleStep(2) self.iconTheme = QLineEdit(self) self.iconTheme.setText( Mikibook.settings.value('iconTheme', QIcon.themeName())) self.editorFont = QFontButton(parent=self) fontval = QFont() fontfam = Mikibook.settings.value('editorFont', defaultValue=None) fontsize = Mikibook.settings.value('editorFontSize', type=int, defaultValue=12) if fontfam is not None: fontval.setFamily(fontfam) fontval.setPointSize(fontsize) self.headerScalesFont = QCheckBox(self) if Mikibook.settings.value('headerScaleFont', type=bool, defaultValue=True): self.headerScalesFont.setCheckState(Qt.Checked) else: self.headerScalesFont.setCheckState(Qt.Unchecked) self.editorFont.font = fontval self.tabWidth.setValue( Mikibook.settings.value('tabWidth', type=int, defaultValue=4)) self.tabToSpaces = QCheckBox(self) if Mikibook.settings.value('tabInsertsSpaces', type=bool, defaultValue=True): self.tabToSpaces.setCheckState(Qt.Checked) else: self.tabToSpaces.setCheckState(Qt.Unchecked) layout = QGridLayout(self) layout.addWidget(QLabel(self.tr("# of recently viewed notes to keep")), 0, 0, 1, 1) layout.addWidget(self.recentNotesCount, 0, 1, 1, 1) layout.addWidget(QLabel(self.tr("Editor font")), 1, 0, 1, 1) layout.addWidget(self.editorFont, 1, 1, 1, 1) layout.addWidget(QLabel(self.tr("Header rank scales editor font?")), 2, 0, 1, 1) layout.addWidget(self.headerScalesFont, 2, 1, 1, 1) qs = QScrollArea(self) qs.setWidget(self.hltCfg) layout.addWidget(QLabel(self.tr("Tabs expand to spaces?")), 3, 0, 1, 1) layout.addWidget(self.tabToSpaces, 3, 1, 1, 1) layout.addWidget(QLabel(self.tr("Tab width")), 4, 0, 1, 1) layout.addWidget(self.tabWidth, 4, 1, 1, 1) layout.addWidget(QLabel(self.tr("Icon Theme")), 5, 0, 1, 1) layout.addWidget(self.iconTheme, 5, 1, 1, 1) layout.addWidget(qs, 6, 0, 1, 2) layout.addWidget(self.buttonBox, 7, 0, 1, 2) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def accept(self): Mikibook.settings.setValue('recentNotesNumber', self.recentNotesCount.value()) Mikibook.settings.setValue('editorFont', self.editorFont.font.family()) Mikibook.settings.setValue('editorFontSize', self.editorFont.font.pointSize()) if self.headerScalesFont.isChecked(): Mikibook.settings.setValue('headerScaleFont', True) else: Mikibook.settings.setValue('headerScaleFont', False) Mikibook.settings.setValue('tabWidth', self.tabWidth.value()) Mikibook.settings.setValue('iconTheme', self.iconTheme.text()) if self.tabToSpaces.isChecked(): Mikibook.settings.setValue('tabInsertsSpaces', True) else: Mikibook.settings.setValue('tabInsertsSpaces', False) Mikibook.setHighlighterColors(self.hltCfg.configToList()) QIcon.setThemeName(self.iconTheme.text()) #then make mikidown use these settings NOW self.parent().loadHighlighter() QDialog.accept(self)
class LaserRangeFinder(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletLaserRangeFinder, *args) self.lrf = self.device self.cbe_distance = CallbackEmulator(self.lrf.get_distance, self.cb_distance, self.increase_error_count) self.cbe_velocity = CallbackEmulator(self.lrf.get_velocity, self.cb_velocity, self.increase_error_count) self.current_distance = None # int, cm self.current_velocity = None # float, m/s plots_distance = [('Distance', Qt.red, lambda: self.current_distance, format_distance)] plots_velocity = [('Velocity', Qt.red, lambda: self.current_velocity, '{:.2f} m/s'.format)] self.plot_widget_distance = PlotWidget('Distance [cm]', plots_distance) self.plot_widget_velocity = PlotWidget('Velocity [m/s]', plots_velocity) self.mode_label = QLabel('Mode:') self.mode_combo = QComboBox() self.mode_combo.addItem("Distance: 1cm resolution, 40m max") self.mode_combo.addItem("Velocity: 0.10 m/s resolution, 12.70m/s max") self.mode_combo.addItem("Velocity: 0.25 m/s resolution, 31.75m/s max") self.mode_combo.addItem("Velocity: 0.50 m/s resolution, 63.50m/s max") self.mode_combo.addItem("Velocity: 1.00 m/s resolution, 127.00m/s max") self.mode_combo.currentIndexChanged.connect(self.mode_changed) self.mode_combo.hide() self.label_average_distance = QLabel('Moving Average for Distance:') self.spin_average_distance = QSpinBox() self.spin_average_distance.setMinimum(0) self.spin_average_distance.setMaximum(50) self.spin_average_distance.setSingleStep(1) self.spin_average_distance.setValue(10) self.spin_average_distance.editingFinished.connect( self.spin_average_finished) self.label_average_velocity = QLabel('Moving Average for Velocity:') self.spin_average_velocity = QSpinBox() self.spin_average_velocity.setMinimum(0) self.spin_average_velocity.setMaximum(50) self.spin_average_velocity.setSingleStep(1) self.spin_average_velocity.setValue(10) self.spin_average_velocity.editingFinished.connect( self.spin_average_finished) self.enable_laser = QCheckBox("Enable Laser") self.enable_laser.stateChanged.connect(self.enable_laser_changed) self.label_acquisition_count = QLabel('Acquisition Count:') self.spin_acquisition_count = QSpinBox() self.spin_acquisition_count.setMinimum(1) self.spin_acquisition_count.setMaximum(255) self.spin_acquisition_count.setSingleStep(1) self.spin_acquisition_count.setValue(128) self.enable_qick_termination = QCheckBox("Quick Termination") self.label_threshold = QLabel('Threshold:') self.threshold = QCheckBox("Automatic Threshold") self.spin_threshold = QSpinBox() self.spin_threshold.setMinimum(1) self.spin_threshold.setMaximum(255) self.spin_threshold.setSingleStep(1) self.spin_threshold.setValue(1) self.label_frequency = QLabel('Frequency [Hz]:') self.frequency = QCheckBox( "Automatic Frequency (Disable for Velocity)") self.spin_frequency = QSpinBox() self.spin_frequency.setMinimum(10) self.spin_frequency.setMaximum(500) self.spin_frequency.setSingleStep(1) self.spin_frequency.setValue(10) self.spin_acquisition_count.editingFinished.connect( self.configuration_changed) self.enable_qick_termination.stateChanged.connect( self.configuration_changed) self.spin_threshold.editingFinished.connect(self.configuration_changed) self.threshold.stateChanged.connect(self.configuration_changed) self.spin_frequency.editingFinished.connect(self.configuration_changed) self.frequency.stateChanged.connect(self.configuration_changed) layout_h1 = QHBoxLayout() layout_h1.addWidget(self.plot_widget_distance) layout_h1.addWidget(self.plot_widget_velocity) layout_h2 = QHBoxLayout() layout_h2.addWidget(self.mode_label) layout_h2.addWidget(self.mode_combo) layout_h2.addWidget(self.label_average_distance) layout_h2.addWidget(self.spin_average_distance) layout_h2.addWidget(self.label_average_velocity) layout_h2.addWidget(self.spin_average_velocity) layout_h2.addStretch() layout_h2.addWidget(self.enable_laser) layout_h3 = QHBoxLayout() layout_h3.addWidget(self.label_frequency) layout_h3.addWidget(self.spin_frequency) layout_h3.addWidget(self.frequency) layout_h3.addStretch() layout_h3.addWidget(self.enable_qick_termination) layout_h4 = QHBoxLayout() layout_h4.addWidget(self.label_threshold) layout_h4.addWidget(self.spin_threshold) layout_h4.addWidget(self.threshold) layout_h4.addStretch() layout_h4.addWidget(self.label_acquisition_count) layout_h4.addWidget(self.spin_acquisition_count) self.widgets_distance = [ self.plot_widget_distance, self.spin_average_distance, self.label_average_distance ] self.widgets_velocity = [ self.plot_widget_velocity, self.spin_average_velocity, self.label_average_velocity ] for w in self.widgets_distance: w.hide() for w in self.widgets_velocity: w.hide() line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addLayout(layout_h1) layout.addWidget(line) layout.addLayout(layout_h2) layout.addLayout(layout_h3) layout.addLayout(layout_h4) self.has_sensor_hardware_version_api = self.firmware_version >= (2, 0, 3) self.has_configuration_api = self.firmware_version >= (2, 0, 3) def start(self): if self.has_sensor_hardware_version_api: async_call(self.lrf.get_sensor_hardware_version, None, self.get_sensor_hardware_version_async, self.increase_error_count) else: self.get_sensor_hardware_version_async(1) if self.has_configuration_api: async_call(self.lrf.get_configuration, None, self.get_configuration_async, self.increase_error_count) async_call(self.lrf.get_mode, None, self.get_mode_async, self.increase_error_count) async_call(self.lrf.is_laser_enabled, None, self.is_laser_enabled_async, self.increase_error_count) async_call(self.lrf.get_moving_average, None, self.get_moving_average_async, self.increase_error_count) async_call(self.lrf.get_distance, None, self.cb_distance, self.increase_error_count) async_call(self.lrf.get_velocity, None, self.cb_velocity, self.increase_error_count) self.cbe_distance.set_period(25) self.cbe_velocity.set_period(25) self.plot_widget_distance.stop = False self.plot_widget_velocity.stop = False def stop(self): self.cbe_distance.set_period(0) self.cbe_velocity.set_period(0) self.plot_widget_distance.stop = True self.plot_widget_velocity.stop = True def destroy(self): pass @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletLaserRangeFinder.DEVICE_IDENTIFIER def is_laser_enabled_async(self, enabled): if enabled: self.enable_laser.setChecked(True) else: self.enable_laser.setChecked(False) def enable_laser_changed(self, state): if state == Qt.Checked: self.lrf.enable_laser() else: self.lrf.disable_laser() def mode_changed(self, value): if value < 0 or value > 4: return self.lrf.set_mode(value) if value == 0: for w in self.widgets_velocity: w.hide() for w in self.widgets_distance: w.show() else: for w in self.widgets_distance: w.hide() for w in self.widgets_velocity: w.show() def cb_distance(self, distance): self.current_distance = distance def cb_velocity(self, velocity): self.current_velocity = velocity / 100.0 def configuration_changed(self): acquisition_count = self.spin_acquisition_count.value() enable_quick_termination = self.enable_qick_termination.isChecked() if self.threshold.isChecked(): threshold = 0 else: threshold = self.spin_threshold.value() if self.frequency.isChecked(): frequency = 0 for w in self.widgets_velocity: w.hide() else: frequency = self.spin_frequency.value() for w in self.widgets_velocity: w.show() self.spin_threshold.setDisabled(threshold == 0) self.spin_frequency.setDisabled(frequency == 0) self.lrf.set_configuration(acquisition_count, enable_quick_termination, threshold, frequency) def get_configuration_async(self, conf): self.spin_acquisition_count.blockSignals(True) self.spin_acquisition_count.setValue(conf.acquisition_count) self.spin_acquisition_count.blockSignals(False) self.enable_qick_termination.blockSignals(True) self.enable_qick_termination.setChecked(conf.enable_quick_termination) self.enable_qick_termination.blockSignals(False) self.spin_threshold.blockSignals(True) self.spin_threshold.setValue(conf.threshold_value) self.spin_threshold.setDisabled(conf.threshold_value == 0) self.spin_threshold.blockSignals(False) self.spin_frequency.blockSignals(True) self.spin_frequency.setValue(conf.measurement_frequency) self.spin_frequency.setDisabled(conf.measurement_frequency == 0) self.spin_frequency.blockSignals(False) self.threshold.blockSignals(True) self.threshold.setChecked(conf.threshold_value == 0) self.threshold.blockSignals(False) self.frequency.blockSignals(True) self.frequency.setChecked(conf.measurement_frequency == 0) self.frequency.blockSignals(False) self.configuration_changed() def get_sensor_hardware_version_async(self, value): if value == 1: self.mode_combo.show() self.mode_label.show() self.label_acquisition_count.hide() self.spin_acquisition_count.hide() self.enable_qick_termination.hide() self.label_threshold.hide() self.spin_threshold.hide() self.threshold.hide() self.label_frequency.hide() self.spin_frequency.hide() self.frequency.hide() else: self.mode_combo.hide() self.mode_label.hide() self.label_acquisition_count.show() self.spin_acquisition_count.show() self.enable_qick_termination.show() self.label_threshold.show() self.spin_threshold.show() self.threshold.show() self.label_frequency.show() self.spin_frequency.show() self.frequency.show() for w in self.widgets_distance: w.show() for w in self.widgets_velocity: w.show() def get_mode_async(self, value): self.mode_combo.setCurrentIndex(value) self.mode_changed(value) def get_moving_average_async(self, avg): self.spin_average_distance.setValue(avg.distance_average_length) self.spin_average_velocity.setValue(avg.velocity_average_length) def spin_average_finished(self): self.lrf.set_moving_average(self.spin_average_distance.value(), self.spin_average_velocity.value())
class AnalogOut(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletAnalogOut, *args) self.ao = self.device self.voltage_label = QLabel('Output Voltage [mV]:') self.voltage_box = QSpinBox() self.voltage_box.setMinimum(0) self.voltage_box.setMaximum(5000) self.voltage_box.setSingleStep(1) self.mode_label = QLabel('Mode:') self.mode_combo = QComboBox() self.mode_combo.addItem("Normal") self.mode_combo.addItem("1 kOhm Resistor to GND") self.mode_combo.addItem("100 kOhm resistor to GND") self.mode_combo.addItem("500 kOhm resistor to GND") layout_h1 = QHBoxLayout() layout_h1.addStretch() layout_h1.addWidget(self.voltage_label) layout_h1.addWidget(self.voltage_box) layout_h1.addStretch() layout_h2 = QHBoxLayout() layout_h2.addStretch() layout_h2.addWidget(self.mode_label) layout_h2.addWidget(self.mode_combo) layout_h2.addStretch() layout = QVBoxLayout(self) layout.addLayout(layout_h2) layout.addLayout(layout_h1) layout.addStretch() self.voltage_box.editingFinished.connect(self.voltage_finished) self.mode_combo.currentIndexChanged.connect(self.mode_changed) def start(self): async_call(self.ao.get_voltage, None, self.voltage_box.setValue, self.increase_error_count) async_call(self.ao.get_mode, None, self.mode_combo.setCurrentIndex, self.increase_error_count) def stop(self): pass def destroy(self): pass @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletAnalogOut.DEVICE_IDENTIFIER def voltage_finished(self): value = self.voltage_box.value() try: self.ao.set_voltage(value) except ip_connection.Error: return self.mode_combo.setCurrentIndex(0) def mode_changed(self, mode): try: self.ao.set_mode(mode) except ip_connection.Error: return self.voltage_box.setValue(0)
class AnalogInV2(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletAnalogInV2, *args) self.ai = self.device self.cbe_voltage = CallbackEmulator(self.ai.get_voltage, self.cb_voltage, self.increase_error_count) self.current_voltage = None # float, V plots = [('Voltage', Qt.red, lambda: self.current_voltage, format_voltage)] self.plot_widget = PlotWidget('Voltage [V]', plots) self.spin_average = QSpinBox() self.spin_average.setMinimum(1) self.spin_average.setMaximum(50) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) layout_h1 = QHBoxLayout() layout_h1.addWidget(QLabel('Moving Average Length:')) layout_h1.addWidget(self.spin_average) layout_h1.addStretch() line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(layout_h1) def get_moving_average_async(self, average): self.spin_average.setValue(average) def start(self): async_call(self.ai.get_moving_average, None, self.get_moving_average_async, self.increase_error_count) async_call(self.ai.get_voltage, None, self.cb_voltage, self.increase_error_count) self.cbe_voltage.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_voltage.set_period(0) self.plot_widget.stop = True def destroy(self): pass @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletAnalogInV2.DEVICE_IDENTIFIER def cb_voltage(self, voltage): self.current_voltage = voltage / 1000.0 def spin_average_finished(self): self.ai.set_moving_average(self.spin_average.value())
class AnalogOutV2(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletAnalogOutV2, *args) self.ao = self.device self.input_voltage_label = VoltageLabel() self.output_voltage_label = QLabel('Output Voltage [mV]: ') self.output_voltage_box = QSpinBox() self.output_voltage_box.setMinimum(0) self.output_voltage_box.setMaximum(12000) self.output_voltage_box.setSingleStep(1) layout_h1 = QHBoxLayout() layout_h1.addStretch() layout_h1.addWidget(self.output_voltage_label) layout_h1.addWidget(self.output_voltage_box) layout_h1.addStretch() layout_h2 = QHBoxLayout() layout_h2.addStretch() layout_h2.addWidget(self.input_voltage_label) layout_h2.addStretch() layout = QVBoxLayout(self) layout.addLayout(layout_h2) layout.addLayout(layout_h1) layout.addStretch() self.output_voltage_box.editingFinished.connect(self.voltage_finished) self.cbe_input_voltage = CallbackEmulator(self.ao.get_input_voltage, self.cb_get_input_voltage, self.increase_error_count) def start(self): async_call(self.ao.get_output_voltage, None, self.cb_get_output_voltage, self.increase_error_count) async_call(self.ao.get_input_voltage, None, self.cb_get_input_voltage, self.increase_error_count) self.cbe_input_voltage.set_period(1000) def stop(self): self.cbe_input_voltage.set_period(0) def destroy(self): pass def get_url_part(self): return 'analog_out_v2' @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletAnalogOutV2.DEVICE_IDENTIFIER def cb_get_output_voltage(self, voltage): self.output_voltage_box.setValue(voltage) def cb_get_input_voltage(self, voltage): self.input_voltage_label.setText(voltage) def voltage_finished(self): value = self.output_voltage_box.value() try: self.ao.set_output_voltage(value) except ip_connection.Error: return
class Barometer(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletBarometer, *args) self.barometer = self.device has_calibrate = self.firmware_version == (1, 0, 0) has_averaging = self.firmware_version >= (2, 0, 1) 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.air_pressure_label = AirPressureLabel() self.altitude_label = AltitudeLabel() self.chip_temperature_label = ChipTemperatureLabel() if has_calibrate: self.chip_temperature_label.setAlignment(Qt.AlignCenter) self.current_air_pressure = None self.current_altitude = None plot_list = [['', Qt.red, self.get_current_air_pressure]] self.air_pressure_plot_widget = PlotWidget('Air Pressure [mbar]', plot_list) plot_list = [['', Qt.darkGreen, self.get_current_altitude]] self.altitude_plot_widget = PlotWidget('Altitude [m]', plot_list) if has_calibrate: self.calibrate_button = QPushButton('Calibrate Altitude') self.calibrate_button.clicked.connect(self.calibrate_clicked) else: self.get_reference_button = QPushButton('Get') self.get_reference_button.clicked.connect(self.get_reference_clicked) self.set_reference_button = QPushButton('Set') self.set_reference_button.clicked.connect(self.set_reference_clicked) self.reference_label = QLabel('Reference Air Pressure [mbar]:') self.reference_edit = QLineEdit() self.get_reference_clicked() if 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_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_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_pressure_box.editingFinished.connect(self.avg_pressure_box_finished) self.avg_temperature_box.editingFinished.connect(self.avg_temperature_box_finished) self.avg_moving_pressure_box.editingFinished.connect(self.avg_moving_pressure_box_finished) layout_h1 = QHBoxLayout() layout_h1.addStretch() layout_h1.addWidget(self.air_pressure_label) layout_h1.addStretch() layout_v1 = QVBoxLayout() layout_v1.addLayout(layout_h1) layout_v1.addWidget(self.air_pressure_plot_widget) layout_h2 = QHBoxLayout() layout_h2.addStretch() layout_h2.addWidget(self.altitude_label) layout_h2.addStretch() layout_v2 = QVBoxLayout() layout_v2.addLayout(layout_h2) layout_v2.addWidget(self.altitude_plot_widget) if has_calibrate: layout_h3 = QHBoxLayout() layout_h3.addWidget(self.chip_temperature_label) layout_h3.addWidget(self.calibrate_button) else: layout_h3 = QHBoxLayout() layout_h3.addWidget(self.reference_label) layout_h3.addWidget(self.reference_edit) layout_h3.addWidget(self.get_reference_button) layout_h3.addWidget(self.set_reference_button) layout_v3 = QVBoxLayout() layout_v3.addWidget(self.chip_temperature_label) layout_v3.addLayout(layout_h3) if has_averaging: line1 = QFrame() line1.setFrameShape(QFrame.VLine) line1.setFrameShadow(QFrame.Sunken) line2 = QFrame() line2.setFrameShape(QFrame.VLine) line2.setFrameShadow(QFrame.Sunken) layout_h4 = QHBoxLayout() layout_h4.addWidget(QLabel('Air Pressure Moving Average Length:')) layout_h4.addWidget(self.avg_moving_pressure_box) layout_h4.addWidget(line1) layout_h4.addWidget(QLabel('Air Pressure Average Length:')) layout_h4.addWidget(self.avg_pressure_box) layout_h4.addWidget(line2) layout_h4.addWidget(QLabel('Temperate Average Length:')) layout_h4.addWidget(self.avg_temperature_box) layout_h1 = QHBoxLayout() layout_h1.addLayout(layout_v1) layout_h1.addLayout(layout_v2) layout = QVBoxLayout(self) layout.addLayout(layout_h1) if has_calibrate: layout.addLayout(layout_h3) else: layout.addLayout(layout_v3) if has_averaging: lineh = QFrame() lineh.setFrameShape(QFrame.HLine) lineh.setFrameShadow(QFrame.Sunken) layout.addWidget(lineh) layout.addLayout(layout_h4) 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) async_call(self.barometer.get_averaging, None, self.cb_averaging, 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 cb_averaging(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_clicked_async(self, reference): r = str(reference/1000.0) self.reference_edit.setText(r) def get_reference_clicked(self): async_call(self.barometer.get_reference_air_pressure, None, self.get_reference_clicked_async, self.increase_error_count) def set_reference_clicked(self): try: r = round(float(self.reference_edit.text())*1000) except: self.reference_edit.setText('Invalid input') return try: self.barometer.set_reference_air_pressure(r) except ip_connection.Error: self.reference_edit.setText('Error while setting reference air pressure') return def get_current_air_pressure(self): return self.current_air_pressure def get_current_altitude(self): return self.current_altitude def update_chip_temp_async(self, temp): t = temp/100.0 self.chip_temperature_label.setText('%.2f' % t) 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 self.air_pressure_label.setText('%.3f' % self.current_air_pressure) def cb_altitude(self, altitude): self.current_altitude = altitude/100.0 self.altitude_label.setText('%.2f' % self.current_altitude, '%.2f' % (self.current_altitude/0.3048))
class Window(QWidget): def __init__(self): super(Window, self).__init__() grid_layout = QGridLayout() self.setLayout(grid_layout) self.setWindowTitle('Parameters') self.fps_label = QLabel('FPS') self.fps_spinbox = QSpinBox() self.fps_spinbox.setRange(1, 1000) self.fps_spinbox.setSingleStep(1) self.fps_spinbox.setValue(globals.FPS) self.force_label = QLabel('Key force') self.force_spinbox = QSpinBox() self.force_spinbox.setRange(1, 1000) self.force_spinbox.setSingleStep(1) self.force_spinbox.setValue(globals.KEY_FORCE) self.friction_label = QLabel('Friction') self.friction_spinbox = QSpinBox() self.friction_spinbox.setRange(1, 1000) self.friction_spinbox.setSingleStep(1) self.friction_spinbox.setValue(globals.FRICTION) self.shape_type_label = QLabel('New shape type') self.shape_type_combobox = QComboBox() self.shape_type_combobox.addItem('Polygon') self.shape_type_combobox.addItem('Circle') self.shape_type_combobox.setCurrentIndex(0) self.shape_radius_label = QLabel('New shape radius') self.shape_radius_spinbox = QSpinBox() self.shape_radius_spinbox.setRange(1, 500) self.shape_radius_spinbox.setSingleStep(1) self.shape_radius_spinbox.setValue(globals.NEW_SHAPE_RADIUS) self.shape_mass_label = QLabel('New shape mass') self.shape_mass_spinbox = QSpinBox() self.shape_mass_spinbox.setRange(1, 500) self.shape_mass_spinbox.setSingleStep(1) self.shape_mass_spinbox.setValue(globals.NEW_SHAPE_MASS) self.shape_degree_label = QLabel('New shape degree') self.shape_degree_spinbox = QSpinBox() self.shape_degree_spinbox.setRange(1, 500) self.shape_degree_spinbox.setSingleStep(1) self.shape_degree_spinbox.setValue(globals.NEW_SHAPE_DEGREE) self.confirm_button = QPushButton('Confirm') QObject.connect(self.confirm_button, SIGNAL('clicked()'), self.change_parameters) grid_layout.addWidget(self.fps_label, 0, 0) grid_layout.addWidget(self.fps_spinbox, 0, 1) grid_layout.addWidget(self.force_label, 0, 2) grid_layout.addWidget(self.force_spinbox, 0, 3) grid_layout.addWidget(self.friction_label, 0, 4) grid_layout.addWidget(self.friction_spinbox, 0, 5) grid_layout.addWidget(self.shape_type_label, 1, 0) grid_layout.addWidget(self.shape_type_combobox, 1, 1) grid_layout.addWidget(self.shape_radius_label, 1, 2) grid_layout.addWidget(self.shape_radius_spinbox, 1, 3) grid_layout.addWidget(self.shape_mass_label, 2, 0) grid_layout.addWidget(self.shape_mass_spinbox, 2, 1) grid_layout.addWidget(self.shape_degree_label, 2, 2) grid_layout.addWidget(self.shape_degree_spinbox, 2, 3) grid_layout.addWidget(self.confirm_button, 2, 4, 1, 2) def change_parameters(self): globals.FPS = self.fps_spinbox.value() globals.KEY_FORCE = self.force_spinbox.value() globals.NEW_SHAPE_TYPE = ( globals.ShapeType.POLYGON if self.shape_type_combobox.currentIndex() == 0 else globals.ShapeType.CIRCLE) globals.NEW_SHAPE_RADIUS = self.shape_radius_spinbox.value() globals.NEW_SHAPE_MASS = self.shape_mass_spinbox.value() globals.NEW_SHAPE_DEGREE = self.shape_degree_spinbox.value()
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 Img2GifWidget(QDialog): AppName = u"GIF生成工具" def __init__(self, parent=None): super(Img2GifWidget, self).__init__(parent) self.setWindowTitle(Img2GifWidget.AppName) self.listWidget = QListWidget() self.listWidget.setMinimumSize(400, 300) self.btnAdd = QPushButton("&Add") self.btnUp = QPushButton("&Up") self.btnDown = QPushButton("&Down") self.btnDel = QPushButton("&Delete") self.btnClear = QPushButton("&Clear") topLeftLay = QVBoxLayout() topLeftLay.addWidget(self.btnAdd) topLeftLay.addWidget(self.btnUp) topLeftLay.addWidget(self.btnDown) topLeftLay.addWidget(self.btnDel) topLeftLay.addWidget(self.btnClear) topLeftLay.addStretch() topLay = QHBoxLayout() topLay.addWidget(self.listWidget) topLay.addLayout(topLeftLay) label = QLabel(u"Gif文件路径:") self.txtGifPath = QLineEdit() self.btnBrowser = QPushButton('...') midLay = QHBoxLayout() midLay.addWidget(label) midLay.addWidget(self.txtGifPath) midLay.addWidget(self.btnBrowser) timeLabel = QLabel(u"时间间隔:") self.spbTime = QDoubleSpinBox() self.spbTime.setRange(0.001, 10) self.spbTime.setSingleStep(0.001) self.spbTime.setValue(1) self.spbTime.setSuffix('s') loopLabel = QLabel(u"循环:") self.spbLoop = QDoubleSpinBox() self.spbLoop = QSpinBox() self.spbLoop.setRange(0, 1000) self.spbLoop.setSingleStep(1) self.spbLoop.setValue(0) self.spbLoop.setToolTip(u"0次循环表示永久循环") self.spbLoop.setSuffix(u"次") self.btnBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bottomLay = QHBoxLayout() bottomLay.addWidget(timeLabel) bottomLay.addWidget(self.spbTime) bottomLay.addWidget(loopLabel) bottomLay.addWidget(self.spbLoop) bottomLay.addStretch() bottomLay.addWidget(self.btnBox) mainLay = QVBoxLayout() mainLay.addLayout(topLay) mainLay.addLayout(midLay) mainLay.addLayout(bottomLay) self.setLayout(mainLay) self.btnAdd.clicked.connect(self.itemAdd) self.btnUp.clicked.connect(self.itemUp) self.btnDown.clicked.connect(self.itemDown) self.btnDel.clicked.connect(self.itemDel) self.btnClear.clicked.connect(self.listWidget.clear) self.btnBrowser.clicked.connect(self.setGifPath) self.btnBox.rejected.connect(self.close) self.btnBox.accepted.connect(self.makeGif) self.txtGifPath.returnPressed.connect(self.updateGifPath) def itemAdd(self): fileNames = QFileDialog.getOpenFileNames(None, u"{0} -- {1}".format(qApp.applicationName(), Img2GifWidget.AppName), '.', u'所有文件(*.*);;BMP文件(*.bmp);;PNG文件(*.png);;JPG文件(*.jpg *.jpeg)') for fn in fileNames: f = QFileInfo(fn) if unicode(f.suffix().toLower()) in ['jpg', 'png', 'bmp', 'jpeg']: self.listWidget.addItem(fn) def itemUp(self): row = self.listWidget.currentRow() if row <= 0: return item = self.listWidget.currentItem() self.listWidget.takeItem(row) self.listWidget.insertItem(row - 1, item) self.listWidget.setCurrentRow(row - 1) def itemDown(self): rows = self.listWidget.count() row = self.listWidget.currentRow() if (row < 0) or (row == rows - 1): return item = self.listWidget.currentItem() self.listWidget.takeItem(row) self.listWidget.insertItem(row + 1, item) self.listWidget.setCurrentRow(row + 1) def itemDel(self): row = self.listWidget.currentRow() if row >= 0: self.listWidget.takeItem(row) def setGifPath(self): filename = QFileDialog.getSaveFileName(self, u"{0} -- {1}".format(qApp.applicationName(), Img2GifWidget.AppName), ".", "Gif(*.gif)") self.txtGifPath.setText(filename) def updateGifPath(self): fileName = self.txtGifPath.text() f = QFileInfo(fileName) if f.dir().exists and not f.baseName().isEmpty() and not f.suffix().isEmpty(): self.txtGifPath.setText(fileName) return True else: QMessageBox.warning(self, u"{0} -- warning".format(Img2GifWidget.AppName), u"要生成的GIF存储路径{0}不是有效的GIF文件".format(unicode(fileName))) return False def makeGif(self): imgs = [unicode(self.listWidget.item(i).text()) for i in range(self.listWidget.count())] if len(imgs) <= 1: QMessageBox.warning(self, u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName), u"GIF动画文件必须要给定大于一张图片。") return if not self.updateGifPath(): return durations = self.spbTime.value() loops = self.spbLoop.value() ok, msg = img2gif.images2gif(imgs, self.txtGifPath.text(), durations=durations, loops=loops) if ok: QMessageBox.about(self, u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName), u"Succeed!\n{0}".format(msg)) qApp.processEvents() else: QMessageBox.about(u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName), u"sorry! Failed to generate the {0}".format(unicode(self.txtGifPath)))
class LoadCell(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletLoadCell, *args) self.lc = self.device self.cbe_weight = CallbackEmulator(self.lc.get_weight, self.cb_weight, self.increase_error_count) self.gain = 0 # 128x self.current_weight = None # int, g self.calibration = None plots = [('Weight', Qt.red, lambda: self.current_weight, format_weight) ] self.plot_widget = PlotWidget('Weight [g]', plots) self.button_calibration = QPushButton("Calibration...") self.button_calibration.clicked.connect( self.button_calibration_clicked) self.button_tare = QPushButton("Tare") self.button_tare.clicked.connect(self.button_tare_clicked) self.enable_led = QCheckBox("Enable LED") self.enable_led.stateChanged.connect(self.enable_led_changed) self.spin_average = QSpinBox() self.spin_average.setMinimum(0) self.spin_average.setMaximum(40) self.spin_average.setSingleStep(1) self.spin_average.setValue(5) self.spin_average.editingFinished.connect(self.spin_average_finished) self.label_average = QLabel('Moving Average Length:') self.rate_label = QLabel('Rate:') self.rate_combo = QComboBox() self.rate_combo.addItem("10 Hz") self.rate_combo.addItem("80 Hz") self.rate_combo.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addWidget(self.label_average) hlayout.addWidget(self.spin_average) hlayout.addWidget(self.rate_label) hlayout.addWidget(self.rate_combo) hlayout.addStretch() hlayout.addWidget(self.button_calibration) hlayout.addWidget(self.button_tare) hlayout.addWidget(self.enable_led) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout) def start(self): async_call(self.lc.is_led_on, None, self.is_led_on_async, self.increase_error_count) async_call(self.lc.get_configuration, None, self.get_configuration_async, self.increase_error_count) async_call(self.lc.get_moving_average, None, self.get_moving_average_async, self.increase_error_count) async_call(self.lc.get_weight, None, self.cb_weight, self.increase_error_count) self.cbe_weight.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_weight.set_period(0) self.plot_widget.stop = True def destroy(self): if self.calibration: self.calibration.close() @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletLoadCell.DEVICE_IDENTIFIER def get_moving_average_async(self, avg): self.spin_average.setValue(avg) def get_configuration_async(self, conf): self.gain = conf.gain self.rate_combo.setCurrentIndex(conf.rate) def is_led_on_async(self, value): if value: self.enable_led.setChecked(True) else: self.enable_led.setChecked(False) def button_calibration_clicked(self): if self.calibration is None: self.calibration = Calibration(self) self.button_calibration.setEnabled(False) self.calibration.show() def button_tare_clicked(self): self.lc.tare() def enable_led_changed(self, state): if state == Qt.Checked: self.lc.led_on() else: self.lc.led_off() def new_config(self, value): rate = self.rate_combo.currentIndex() self.lc.set_configuration(rate, self.gain) def spin_average_finished(self): self.lc.set_moving_average(self.spin_average.value()) def cb_weight(self, weight): self.current_weight = weight
class AnalogOut(PluginBase): def __init__(self, ipcon, uid, version): PluginBase.__init__(self, ipcon, uid, "Analog Out Bricklet", version) self.ao = BrickletAnalogOut(uid, ipcon) self.voltage_label = QLabel("Output Voltage (mV): ") self.voltage_box = QSpinBox() self.voltage_box.setMinimum(0) self.voltage_box.setMaximum(5000) self.voltage_box.setSingleStep(1) self.mode_label = QLabel("Mode: ") self.mode_combo = QComboBox() self.mode_combo.addItem("Normal Mode") self.mode_combo.addItem("1k Ohm resistor to ground") self.mode_combo.addItem("100k Ohm resistor to ground") self.mode_combo.addItem("500k Ohm resistor to ground") layout_h1 = QHBoxLayout() layout_h1.addStretch() layout_h1.addWidget(self.voltage_label) layout_h1.addWidget(self.voltage_box) layout_h1.addStretch() layout_h2 = QHBoxLayout() layout_h2.addStretch() layout_h2.addWidget(self.mode_label) layout_h2.addWidget(self.mode_combo) layout_h2.addStretch() layout = QVBoxLayout(self) layout.addLayout(layout_h2) layout.addLayout(layout_h1) layout.addStretch() self.voltage_box.editingFinished.connect(self.voltage_finished) self.mode_combo.activated.connect(self.mode_changed) def start(self): async_call(self.ao.get_voltage, None, self.voltage_box.setValue, self.increase_error_count) async_call(self.ao.get_mode, None, self.mode_combo.setCurrentIndex, self.increase_error_count) def stop(self): pass def get_url_part(self): return "analog_out" @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletAnalogOut.DEVICE_IDENTIFIER def voltage_finished(self): value = self.voltage_box.value() try: self.ao.set_voltage(value) except ip_connection.Error: return self.mode_combo.setCurrentIndex(0) def mode_changed(self, mode): try: self.ao.set_mode(mode) except ip_connection.Error: return self.voltage_box.setValue(0)
class EditorConfiguration(QWidget): """EditorConfiguration widget class""" def __init__(self, parent): super(EditorConfiguration, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) # groups group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_INDENT) group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_MARGIN) group3 = QGroupBox(translations.TR_LINT_DIRTY_TEXT) group4 = QGroupBox(translations.TR_PEP8_DIRTY_TEXT) group5 = QGroupBox(translations.TR_HIGHLIGHTER_EXTRAS) group6 = QGroupBox(translations.TR_TYPING_ASSISTANCE) group7 = QGroupBox(translations.TR_DISPLAY_ERRORS) # groups container container_widget_with_all_preferences = QWidget() formFeatures = QGridLayout(container_widget_with_all_preferences) # Indentation hboxg1 = QHBoxLayout(group1) hboxg1.setContentsMargins(5, 15, 5, 5) self._spin, self._checkUseTabs = QSpinBox(), QComboBox() self._spin.setRange(1, 10) self._spin.setValue(settings.INDENT) hboxg1.addWidget(self._spin) self._checkUseTabs.addItems([ translations.TR_PREFERENCES_EDITOR_CONFIG_SPACES.capitalize(), translations.TR_PREFERENCES_EDITOR_CONFIG_TABS.capitalize()]) self._checkUseTabs.setCurrentIndex(int(settings.USE_TABS)) hboxg1.addWidget(self._checkUseTabs) formFeatures.addWidget(group1, 0, 0) # Margin Line hboxg2 = QHBoxLayout(group2) hboxg2.setContentsMargins(5, 15, 5, 5) self._checkShowMargin = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MARGIN_LINE) self._checkShowMargin.setChecked(settings.SHOW_MARGIN_LINE) hboxg2.addWidget(self._checkShowMargin) self._spinMargin = QSpinBox() self._spinMargin.setRange(50, 100) self._spinMargin.setSingleStep(2) self._spinMargin.setValue(settings.MARGIN_LINE) hboxg2.addWidget(self._spinMargin) hboxg2.addWidget(QLabel(translations.TR_CHARACTERS)) formFeatures.addWidget(group2, 0, 1) # Display Errors hboxDisplay = QHBoxLayout(group7) hboxDisplay.setContentsMargins(5, 15, 5, 5) self._checkHighlightLine = QComboBox() self._checkHighlightLine.addItems([ translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_BACKGROUND, translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_UNDERLINE]) self._checkHighlightLine.setCurrentIndex( int(settings.UNDERLINE_NOT_BACKGROUND)) hboxDisplay.addWidget(self._checkHighlightLine) formFeatures.addWidget(group7, 1, 0, 1, 0) # Find Lint Errors (highlighter) vboxg3 = QVBoxLayout(group3) self._checkErrors = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS) self._checkErrors.setChecked(settings.FIND_ERRORS) self.connect(self._checkErrors, SIGNAL("stateChanged(int)"), self._disable_show_errors) self._showErrorsOnLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS) self._showErrorsOnLine.setChecked(settings.ERRORS_HIGHLIGHT_LINE) self.connect(self._showErrorsOnLine, SIGNAL("stateChanged(int)"), self._enable_errors_inline) vboxg3.addWidget(self._checkErrors) vboxg3.addWidget(self._showErrorsOnLine) formFeatures.addWidget(group3, 2, 0) # Find PEP8 Errors (highlighter) vboxg4 = QVBoxLayout(group4) vboxg4.setContentsMargins(5, 15, 5, 5) self._checkStyle = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8) self._checkStyle.setChecked(settings.CHECK_STYLE) self.connect(self._checkStyle, SIGNAL("stateChanged(int)"), self._disable_check_style) vboxg4.addWidget(self._checkStyle) self._checkStyleOnLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8) self._checkStyleOnLine.setChecked(settings.CHECK_HIGHLIGHT_LINE) self.connect(self._checkStyleOnLine, SIGNAL("stateChanged(int)"), self._enable_check_inline) vboxg4.addWidget(self._checkStyleOnLine) formFeatures.addWidget(group4, 2, 1) # Show Python3 Migration, DocStrings and Spaces (highlighter) vboxg5 = QVBoxLayout(group5) vboxg5.setContentsMargins(5, 15, 5, 5) self._showMigrationTips = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MIGRATION) self._showMigrationTips.setChecked(settings.SHOW_MIGRATION_TIPS) vboxg5.addWidget(self._showMigrationTips) self._checkForDocstrings = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_CHECK_FOR_DOCSTRINGS) self._checkForDocstrings.setChecked(settings.CHECK_FOR_DOCSTRINGS) vboxg5.addWidget(self._checkForDocstrings) self._checkShowSpaces = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES) self._checkShowSpaces.setChecked(settings.SHOW_TABS_AND_SPACES) vboxg5.addWidget(self._checkShowSpaces) self._checkIndentationGuide = QCheckBox( translations.TR_SHOW_INDENTATION_GUIDE) self._checkIndentationGuide.setChecked(settings.SHOW_INDENTATION_GUIDE) vboxg5.addWidget(self._checkIndentationGuide) formFeatures.addWidget(group5, 3, 0) # End of line, Center On Scroll, Trailing space, Word wrap vboxg6 = QVBoxLayout(group6) vboxg6.setContentsMargins(5, 15, 5, 5) self._checkEndOfLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE) self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE) vboxg6.addWidget(self._checkEndOfLine) self._checkCenterScroll = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_CENTER_SCROLL) self._checkCenterScroll.setChecked(settings.CENTER_ON_SCROLL) vboxg6.addWidget(self._checkCenterScroll) self._checkTrailing = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING) self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES) vboxg6.addWidget(self._checkTrailing) self._allowWordWrap = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP) self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP) vboxg6.addWidget(self._allowWordWrap) formFeatures.addWidget(group6, 3, 1) # pack all the groups vbox.addWidget(container_widget_with_all_preferences) vbox.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding)) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def _enable_check_inline(self, val): """Method that takes a value to enable the inline style checking""" if val == Qt.Checked: self._checkStyle.setChecked(True) def _enable_errors_inline(self, val): """Method that takes a value to enable the inline errors checking""" if val == Qt.Checked: self._checkErrors.setChecked(True) def _disable_check_style(self, val): """Method that takes a value to disable the inline style checking""" if val == Qt.Unchecked: self._checkStyleOnLine.setChecked(False) def _disable_show_errors(self, val): """Method that takes a value to disable the inline errors checking""" if val == Qt.Unchecked: self._showErrorsOnLine.setChecked(False) def save(self): """Method to save settings""" qsettings = IDE.ninja_settings() settings.USE_TABS = bool(self._checkUseTabs.currentIndex()) qsettings.setValue('preferences/editor/useTabs', settings.USE_TABS) margin_line = self._spinMargin.value() settings.MARGIN_LINE = margin_line settings.pep8mod_update_margin_line_length(margin_line) qsettings.setValue('preferences/editor/marginLine', margin_line) settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked() qsettings.setValue('preferences/editor/showMarginLine', settings.SHOW_MARGIN_LINE) settings.INDENT = self._spin.value() qsettings.setValue('preferences/editor/indent', settings.INDENT) endOfLine = self._checkEndOfLine.isChecked() settings.USE_PLATFORM_END_OF_LINE = endOfLine qsettings.setValue('preferences/editor/platformEndOfLine', endOfLine) settings.UNDERLINE_NOT_BACKGROUND = \ bool(self._checkHighlightLine.currentIndex()) qsettings.setValue('preferences/editor/errorsUnderlineBackground', settings.UNDERLINE_NOT_BACKGROUND) settings.FIND_ERRORS = self._checkErrors.isChecked() qsettings.setValue('preferences/editor/errors', settings.FIND_ERRORS) settings.ERRORS_HIGHLIGHT_LINE = self._showErrorsOnLine.isChecked() qsettings.setValue('preferences/editor/errorsInLine', settings.ERRORS_HIGHLIGHT_LINE) settings.CHECK_STYLE = self._checkStyle.isChecked() qsettings.setValue('preferences/editor/checkStyle', settings.CHECK_STYLE) settings.SHOW_MIGRATION_TIPS = self._showMigrationTips.isChecked() qsettings.setValue('preferences/editor/showMigrationTips', settings.SHOW_MIGRATION_TIPS) settings.CHECK_HIGHLIGHT_LINE = self._checkStyleOnLine.isChecked() qsettings.setValue('preferences/editor/checkStyleInline', settings.CHECK_HIGHLIGHT_LINE) settings.CENTER_ON_SCROLL = self._checkCenterScroll.isChecked() qsettings.setValue('preferences/editor/centerOnScroll', settings.CENTER_ON_SCROLL) settings.REMOVE_TRAILING_SPACES = self._checkTrailing.isChecked() qsettings.setValue('preferences/editor/removeTrailingSpaces', settings.REMOVE_TRAILING_SPACES) settings.ALLOW_WORD_WRAP = self._allowWordWrap.isChecked() qsettings.setValue('preferences/editor/allowWordWrap', settings.ALLOW_WORD_WRAP) settings.SHOW_TABS_AND_SPACES = self._checkShowSpaces.isChecked() qsettings.setValue('preferences/editor/showTabsAndSpaces', settings.SHOW_TABS_AND_SPACES) settings.SHOW_INDENTATION_GUIDE = ( self._checkIndentationGuide.isChecked()) qsettings.setValue('preferences/editor/showIndentationGuide', settings.SHOW_INDENTATION_GUIDE) settings.CHECK_FOR_DOCSTRINGS = self._checkForDocstrings.isChecked() qsettings.setValue('preferences/editor/checkForDocstrings', settings.CHECK_FOR_DOCSTRINGS) if settings.USE_TABS: settings.pep8mod_add_ignore("W191") else: settings.pep8mod_remove_ignore("W191") settings.pep8mod_refresh_checks()
class Browser(preferences.Group): def __init__(self, page): super(Browser, self).__init__(page) layout = QGridLayout() self.setLayout(layout) self.languagesLabel = QLabel() self.languages = QComboBox(currentIndexChanged=self.changed) layout.addWidget(self.languagesLabel, 0, 0) layout.addWidget(self.languages, 0, 1) items = ['', ''] items.extend(language_names.languageName(l, l) for l in lilydoc.translations) self.languages.addItems(items) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QSpinBox(valueChanged=self.changed) self.fontSize.setRange(6, 32) self.fontSize.setSingleStep(1) layout.addWidget(self.fontLabel, 1, 0) layout.addWidget(self.fontChooser, 1, 1) layout.addWidget(self.fontSize, 1, 2) app.translateUI(self) def translateUI(self): self.setTitle(_("Documentation Browser")) self.languagesLabel.setText(_("Preferred Language:")) self.languages.setItemText(0, _("Default")) self.languages.setItemText(1, _("English (untranslated)")) self.fontLabel.setText(_("Font:")) def loadSettings(self): s = QSettings() s.beginGroup("documentation") lang = s.value("language", "default", type("")) if lang in lilydoc.translations: i = lilydoc.translations.index(lang) + 2 elif lang == "C": i = 1 else: i = 0 self.languages.setCurrentIndex(i) font = self.font() family = s.value("fontfamily", "", type("")) if family: font.setFamily(family) size = s.value("fontsize", 16, int) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(size) def saveSettings(self): s = QSettings() s.beginGroup("documentation") langs = ['default', 'C'] + lilydoc.translations s.setValue("language", langs[self.languages.currentIndex()]) s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value())
class LoadCell(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletLoadCell, *args) self.lc = self.device self.cbe_weight = CallbackEmulator(self.lc.get_weight, self.cb_weight, self.increase_error_count) self.gain = 0 # 128x self.current_weight = None # int, g self.calibration = None plots = [('Weight', Qt.red, lambda: self.current_weight, format_weight)] self.plot_widget = PlotWidget('Weight [g]', plots) self.button_calibration = QPushButton("Calibration...") self.button_calibration.clicked.connect(self.button_calibration_clicked) self.button_tare = QPushButton("Tare") self.button_tare.clicked.connect(self.button_tare_clicked) self.enable_led = QCheckBox("Enable LED") self.enable_led.stateChanged.connect(self.enable_led_changed) self.spin_average = QSpinBox() self.spin_average.setMinimum(0) self.spin_average.setMaximum(40) self.spin_average.setSingleStep(1) self.spin_average.setValue(5) self.spin_average.editingFinished.connect(self.spin_average_finished) self.label_average = QLabel('Moving Average Length:') self.rate_label = QLabel('Rate: ') self.rate_combo = QComboBox() self.rate_combo.addItem("10 Hz") self.rate_combo.addItem("80 Hz") self.rate_combo.currentIndexChanged.connect(self.new_config) hlayout = QHBoxLayout() hlayout.addWidget(self.label_average) hlayout.addWidget(self.spin_average) hlayout.addWidget(self.rate_label) hlayout.addWidget(self.rate_combo) hlayout.addStretch() hlayout.addWidget(self.button_calibration) hlayout.addWidget(self.button_tare) hlayout.addWidget(self.enable_led) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(line) layout.addLayout(hlayout) def start(self): async_call(self.lc.is_led_on, None, self.is_led_on_async, self.increase_error_count) async_call(self.lc.get_configuration, None, self.get_configuration_async, self.increase_error_count) async_call(self.lc.get_moving_average, None, self.get_moving_average_async, self.increase_error_count) async_call(self.lc.get_weight, None, self.cb_weight, self.increase_error_count) self.cbe_weight.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_weight.set_period(0) self.plot_widget.stop = True def destroy(self): if self.calibration: self.calibration.close() def get_url_part(self): return 'load_cell' @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletLoadCell.DEVICE_IDENTIFIER def get_moving_average_async(self, avg): self.spin_average.setValue(avg) def get_configuration_async(self, conf): self.gain = conf.gain self.rate_combo.setCurrentIndex(conf.rate) def is_led_on_async(self, value): if value: self.enable_led.setChecked(True) else: self.enable_led.setChecked(False) def button_calibration_clicked(self): if self.calibration is None: self.calibration = Calibration(self) self.button_calibration.setEnabled(False) self.calibration.show() def button_tare_clicked(self): self.lc.tare() def enable_led_changed(self, state): if state == Qt.Checked: self.lc.led_on() else: self.lc.led_off() def new_config(self, value): rate = self.rate_combo.currentIndex() self.lc.set_configuration(rate, self.gain) def spin_average_finished(self): self.lc.set_moving_average(self.spin_average.value()) def cb_weight(self, weight): self.current_weight = weight
class ACCurrent(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletACCurrent, *args) self.acc = self.device self.cbe_current = CallbackEmulator(self.acc.get_current, self.cb_current, self.increase_error_count) self.current_label = CurrentLabel('Current: ') self.current_value = None plot_list = [['', Qt.red, self.get_current_value]] self.plot_widget = PlotWidget('Current [A]', plot_list) layout_h2 = QHBoxLayout() layout_h2.addStretch() layout_h2.addWidget(self.current_label) layout_h2.addStretch() layout = QVBoxLayout(self) layout.addLayout(layout_h2) layout.addWidget(self.plot_widget) self.label_average = QLabel('Length of moving average:') self.spin_average = QSpinBox() self.spin_average.setMinimum(1) self.spin_average.setMaximum(50) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) self.label_range = QLabel('Current Range: ') self.combo_range = QComboBox() self.combo_range.addItem("0") # TODO: Adjust ranges self.combo_range.addItem("1") self.combo_range.currentIndexChanged.connect(self.new_config) layout_h1 = QHBoxLayout() layout_h1.addStretch() layout_h1.addWidget(self.label_average) layout_h1.addWidget(self.spin_average) layout_h1.addStretch() layout_h1.addWidget(self.label_range) layout_h1.addWidget(self.combo_range) layout_h1.addStretch() layout.addLayout(layout_h1) def get_configuration_async(self, conf): self.combo_range.setCurrentIndex(conf) def get_moving_average_async(self, average): self.spin_average.setValue(average) def new_config(self, value): try: self.acc.set_configuration(value) except: pass def start(self): async_call(self.acc.get_configuration, None, self.get_configuration_async, self.increase_error_count) async_call(self.acc.get_moving_average, None, self.get_moving_average_async, self.increase_error_count) async_call(self.acc.get_current, None, self.cb_current, self.increase_error_count) self.cbe_current.set_period(100) self.plot_widget.stop = False def stop(self): self.cbe_current.set_period(0) self.plot_widget.stop = True def destroy(self): pass def get_url_part(self): return 'ac_current' @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletACCurrent.DEVICE_IDENTIFIER def get_current_value(self): return self.current_value def cb_current(self, current): c = round(current/1000.0, 2) self.current_value = c self.current_label.setText('%6.02f' % c) def spin_average_finished(self): self.acc.set_moving_average(self.spin_average.value())