def buildAntispam(self, layout, row, col): antispam = QGroupBox(self) antispam.setTitle(tr('Antispam')) antispam_layout = QFormLayout(antispam) antispam_enable = QCheckBox() info = QLabel(tr("This will add an <code>X-Spam-Score:</code> header " "field to all the messages and add a <code>Subject:</code> line " "beginning with *<i>SPAM</i>* and containing the original subject " "to the messages detected as spam.")) info.setWordWrap(True) antispam_layout.addRow(info) antispam_layout.addRow(tr('Activate the antispam'), antispam_enable) mark_spam_level = QDoubleSpinBox(self) mark_spam_level.setDecimals(1) antispam_layout.addRow(tr('Mark the message as spam if its score is greater than'), mark_spam_level) deny_spam_level = QDoubleSpinBox(self) deny_spam_level.setDecimals(1) antispam_layout.addRow(tr('Refuse the message if its score is greater than'), deny_spam_level) # enable/disable spam levels self.connect(antispam_enable, SIGNAL('toggled(bool)'), mark_spam_level.setEnabled) self.connect(antispam_enable, SIGNAL('toggled(bool)'), deny_spam_level.setEnabled) # update config self.connect(mark_spam_level, SIGNAL('valueChanged(double)'), self.setMarkSpamLevel) self.connect(deny_spam_level, SIGNAL('valueChanged(double)'), self.setDenySpamLevel) self.connect(antispam_enable, SIGNAL('clicked(bool)'), self.setAntispamEnabled) layout.addWidget(antispam, row, col) self.mainwindow.writeAccessNeeded(mark_spam_level, deny_spam_level) return antispam_enable, mark_spam_level, deny_spam_level
class AbstractSnappingToleranceAction(QWidgetAction): """Abstract action for Snapping Tolerance.""" snappingToleranceChanged = pyqtSignal(float) def __init__(self, parent=None): super(AbstractSnappingToleranceAction, self).__init__(parent) self._iface = None self._toleranceSpin = QDoubleSpinBox(parent) self._toleranceSpin.setDecimals(5) self._toleranceSpin.setRange(0.0, 100000000.0) self.setDefaultWidget(self._toleranceSpin) self.setText('Snapping Tolerance') self.setStatusTip('Set the snapping tolerance') self._refresh() self._toleranceSpin.valueChanged.connect(self._changed) def setInterface(self, iface): self._iface = iface self._refresh() # Private API def _changed(self, tolerance): pass def _refresh(self): pass
class FloatParameterWidget(NumericParameterWidget): """Widget class for Float parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A FloatParameter object. :type parameter: FloatParameter """ super(FloatParameterWidget, self).__init__(parameter, parent) self._input = QDoubleSpinBox() self._input.setDecimals(self._parameter.precision) self._input.setValue(self._parameter.value) self._input.setMinimum(self._parameter.minimum_allowed_value) self._input.setMaximum(self._parameter.maximum_allowed_value) self._input.setSingleStep(10**-self._parameter.precision) # is it possible to use dynamic precision ? string_min_value = '%.*f' % (self._parameter.precision, self._parameter.minimum_allowed_value) string_max_value = '%.*f' % (self._parameter.precision, self._parameter.maximum_allowed_value) tool_tip = 'Choose a number between %s and %s' % (string_min_value, string_max_value) self._input.setToolTip(tool_tip) self._input.setSizePolicy(self._spin_box_size_policy) self._inner_input_layout.addWidget(self._input) self._inner_input_layout.addWidget(self._unit_widget)
def _getSpinbox(self, minvalue, maxvalue, step, nullable = True, value = 0): ''' Get a combobox filled with the given values :param values: The values as key = value, value = description or text :type values: Dict :returns: A combobox :rtype: QWidget ''' widget = QWidget() spinbox = QDoubleSpinBox() spinbox.setMinimum(minvalue) spinbox.setMaximum(maxvalue) spinbox.setSingleStep(step) spinbox.setDecimals(len(str(step).split('.')[1]) if len(str(step).split('.'))==2 else 0) if nullable: spinbox.setMinimum(minvalue - step) spinbox.setValue(spinbox.minimum()) spinbox.setSpecialValueText(str(QSettings().value('qgis/nullValue', 'NULL' ))) if value is not None: spinbox.setValue(value) layout = QHBoxLayout(widget) layout.addWidget(spinbox, 1); layout.setAlignment(Qt.AlignCenter); layout.setContentsMargins(5,0,5,0); widget.setLayout(layout); return widget
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) self.label_ip = QLabel("IP") self.lineedit_ip = QLineEdit() layout.addRow(self.label_ip, self.lineedit_ip) self.label_port = QLabel("Port") self.spinbox_port = QSpinBox() self.spinbox_port.setMinimum(0) self.spinbox_port.setMaximum(65535) layout.addRow(self.label_port, self.spinbox_port) self.label_password = QLabel("Password") self.lineedit_password = QLineEdit() layout.addRow(self.label_password, self.lineedit_password) self.label_mount = QLabel("Mount") self.lineedit_mount = QLineEdit() layout.addRow(self.label_mount, self.lineedit_mount) # # Audio Quality # self.label_audio_quality = QLabel("Audio Quality") self.spinbox_audio_quality = QDoubleSpinBox() self.spinbox_audio_quality.setMinimum(0.0) self.spinbox_audio_quality.setMaximum(1.0) self.spinbox_audio_quality.setSingleStep(0.1) self.spinbox_audio_quality.setDecimals(1) self.spinbox_audio_quality.setValue(0.3) # Default value 0.3 # # Video Quality # self.label_video_quality = QLabel("Video Quality (kb/s)") self.spinbox_video_quality = QSpinBox() self.spinbox_video_quality.setMinimum(0) self.spinbox_video_quality.setMaximum(16777215) self.spinbox_video_quality.setValue(2400) # Default value 2400 def get_video_quality_layout(self): layout_video_quality = QHBoxLayout() layout_video_quality.addWidget(self.label_video_quality) layout_video_quality.addWidget(self.spinbox_video_quality) return layout_video_quality def get_audio_quality_layout(self): layout_audio_quality = QHBoxLayout() layout_audio_quality.addWidget(self.label_audio_quality) layout_audio_quality.addWidget(self.spinbox_audio_quality) return layout_audio_quality
class FloatParameterWidget(NumericParameterWidget): """Widget class for Float parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A FloatParameter object. :type parameter: FloatParameter """ super(FloatParameterWidget, self).__init__(parameter, parent) self._input = QDoubleSpinBox() self._input.setDecimals(self._parameter.precision) self._input.setMinimum(self._parameter.minimum_allowed_value) self._input.setMaximum(self._parameter.maximum_allowed_value) self._input.setValue(self._parameter.value) self._input.setSingleStep( 10 ** -self._parameter.precision) # is it possible to use dynamic precision ? string_min_value = '%.*f' % ( self._parameter.precision, self._parameter.minimum_allowed_value) string_max_value = '%.*f' % ( self._parameter.precision, self._parameter.maximum_allowed_value) tool_tip = 'Choose a number between %s and %s' % ( string_min_value, string_max_value) self._input.setToolTip(tool_tip) self._input.setSizePolicy(self._spin_box_size_policy) self.inner_input_layout.addWidget(self._input) self.inner_input_layout.addWidget(self._unit_widget)
class ChangeConfLevelDlg(QDialog): ''' Dialog for changing confidence level ''' def __init__(self, previous_value=DEFAULT_CONF_LEVEL, parent=None): super(ChangeConfLevelDlg, self).__init__(parent) cl_label = QLabel("Global Confidence Level:") self.conf_level_spinbox = QDoubleSpinBox() self.conf_level_spinbox.setRange(50, 99.999) self.conf_level_spinbox.setSingleStep(0.1) self.conf_level_spinbox.setSuffix(QString("%")) self.conf_level_spinbox.setValue(previous_value) self.conf_level_spinbox.setDecimals(1) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) hlayout = QHBoxLayout() hlayout.addWidget(cl_label) hlayout.addWidget(self.conf_level_spinbox) vlayout = QVBoxLayout() vlayout.addLayout(hlayout) vlayout.addWidget(buttonBox) self.setLayout(vlayout) self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()")) self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()")) self.setWindowTitle("Change Confidence Level") def get_value(self): return self.conf_level_spinbox.value()
def createEditor( self, parent, option, index ): if index.column() == DESCRIPCION: combo = QComboBox( parent ) combo.setEditable( True ) value = index.data().toString() self.filtrados.append( value ) self.proxymodel.setFilterRegExp( self.filter() ) combo.setModel( self.proxymodel ) combo.setModelColumn( 1 ) combo.setCompleter( self.completer ) return combo elif index.column() == BANCO: combo = QComboBox( parent ) #combo.setEditable(True) combo.setModel( self.bancosmodel ) combo.setModelColumn( 1 ) #combo.setCompleter(self.completer) return combo elif index.column() == MONTO: doublespinbox = QDoubleSpinBox( parent ) doublespinbox.setMinimum( -1000000 ) doublespinbox.setMaximum( 1000000 ) doublespinbox.setDecimals( 4 ) doublespinbox.setAlignment( Qt.AlignHCenter ) return doublespinbox elif index.column() == REFERENCIA: textbox = QStyledItemDelegate.createEditor( self, parent, option, index ) textbox.setAlignment( Qt.AlignHCenter ) return textbox
class ChangeConfLevelDlg(QDialog): ''' Dialog for changing confidence level ''' def __init__(self, previous_value=DEFAULT_CONF_LEVEL, parent=None): super(ChangeConfLevelDlg, self).__init__(parent) cl_label = QLabel("Global Confidence Level:") self.conf_level_spinbox = QDoubleSpinBox() self.conf_level_spinbox.setRange(50, 99.999 ) self.conf_level_spinbox.setSingleStep(0.1) self.conf_level_spinbox.setSuffix(QString("%")) self.conf_level_spinbox.setValue(previous_value) self.conf_level_spinbox.setDecimals(1) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) hlayout = QHBoxLayout() hlayout.addWidget(cl_label) hlayout.addWidget(self.conf_level_spinbox) vlayout = QVBoxLayout() vlayout.addLayout(hlayout) vlayout.addWidget(buttonBox) self.setLayout(vlayout) self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()")) self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()")) self.setWindowTitle("Change Confidence Level") def get_value(self): return self.conf_level_spinbox.value()
def _getSpinbox(self, minvalue, maxvalue, step, nullable=True, value=0): ''' Get a combobox filled with the given values :param values: The values as key = value, value = description or text :type values: Dict :returns: A combobox :rtype: QWidget ''' widget = QWidget() spinbox = QDoubleSpinBox() spinbox.setMinimum(minvalue) spinbox.setMaximum(maxvalue) spinbox.setSingleStep(step) spinbox.setDecimals( len(str(step).split('.')[1]) if len(str(step).split('.')) == 2 else 0) if nullable: spinbox.setMinimum(minvalue - step) spinbox.setValue(spinbox.minimum()) spinbox.setSpecialValueText( str(QSettings().value('qgis/nullValue', 'NULL'))) if value is not None: spinbox.setValue(value) layout = QHBoxLayout(widget) layout.addWidget(spinbox, 1) layout.setAlignment(Qt.AlignCenter) layout.setContentsMargins(5, 0, 5, 0) widget.setLayout(layout) return widget
def _create(self, base_frame): self.sliders = [] self.spinboxes = [] for i in range(len(self.dim_labels)): self.sliders.append(QSlider(QtCore.Qt.Horizontal)) self.sliders[i].setRange(0, self.n_slider_steps[i]) self.sliders[i].valueChanged.connect( partial(self._on_slide, i)) spinbox = QDoubleSpinBox() spinbox.setRange(*self.limits[i]) spinbox.setDecimals(3) spinbox.setSingleStep(0.001) self.spinboxes.append(spinbox) self.spinboxes[i].valueChanged.connect( partial(self._on_pos_edited, i)) slider_group = QGridLayout() slider_group.addWidget(QLabel("Position"), 0, 0, 1, 3, QtCore.Qt.AlignCenter) slider_group.addWidget(QLabel("Orientation (Euler angles)"), 0, 3, 1, 3, QtCore.Qt.AlignCenter) for i, slider in enumerate(self.sliders): slider_group.addWidget(QLabel(self.dim_labels[i]), 1, i) slider_group.addWidget(slider, 2, i) slider_group.addWidget(self.spinboxes[i], 3, i) slider_groupbox = QGroupBox("Transformation in frame '%s'" % base_frame) slider_groupbox.setLayout(slider_group) layout = QHBoxLayout() layout.addWidget(slider_groupbox) layout.addStretch(1) return layout
def createEditor(self, type, parent): if type != QVariant.Double: raise ValueError("This factory only creates editor for doubles") w = QDoubleSpinBox(parent) w.setDecimals(5) w.setMinimum(0.0001) w.setMaximum(10000) return w
def createDoubleSpinBox(self, variable_name, variable_value, variable_type, analysis_module_variables_model): spinner = QDoubleSpinBox() spinner.setDecimals(6) spinner.setMinimumWidth(75) spinner.setMaximum(analysis_module_variables_model.getVariableMaximumValue(variable_name)) spinner.setMinimum(analysis_module_variables_model.getVariableMinimumValue(variable_name)) spinner.setSingleStep(analysis_module_variables_model.getVariableStepValue(variable_name)) spinner.setValue(variable_value) spinner.valueChanged.connect(partial(self.valueChanged, variable_name, variable_type, spinner)) return spinner
def _set_up_opt_spin_box(self): check_box = QCheckBox() spin_box = QDoubleSpinBox() spin_box.setDecimals(5) spin_box.setSingleStep(0.01) spin_box.setMinimum(-sys.float_info.max) spin_box.setMaximum(sys.float_info.max) spin_box.setDisabled(True) check_box.toggled.connect(spin_box.setEnabled) return check_box, spin_box
class LogTool(preferences.Group): def __init__(self, page): super(LogTool, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) self.showlog = QCheckBox(toggled=self.changed) layout.addWidget(self.showlog) self.rawview = QCheckBox(toggled=self.changed) layout.addWidget(self.rawview) app.translateUI(self) def translateUI(self): self.setTitle(_("LilyPond Log")) self.fontLabel.setText(_("Font:")) self.showlog.setText(_("Show log when a job is started")) self.rawview.setText(_("Display plain log output")) self.rawview.setToolTip(_( "If checked, Frescobaldi will not shorten filenames in the log output.""")) def loadSettings(self): s = QSettings() s.beginGroup("log") font = QFont(s.value("fontfamily", "monospace")) font.setPointSizeF(float(s.value("fontsize", 9.0))) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) self.showlog.setChecked(s.value("show_on_start", True) not in (False, "false")) self.rawview.setChecked(s.value("rawview", True) not in (False, "false")) def saveSettings(self): s = QSettings() s.beginGroup("log") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value()) s.setValue("show_on_start", self.showlog.isChecked()) s.setValue("rawview", self.rawview.isChecked())
def createDoubleSpinner(self, minimum, maximum): spinner = QDoubleSpinBox() spinner.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) spinner.setMinimumWidth(105) spinner.setRange(minimum, maximum) spinner.setKeyboardTracking(False) spinner.setDecimals(8) spinner.editingFinished.connect(self.plotScaleChanged) spinner.valueChanged.connect(self.plotScaleChanged) return spinner
def _create_widget(cls, c, parent, host=None): dsb = QDoubleSpinBox(parent) dsb.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name)) # Set decimal places dsb.setDecimals(c.scale) # Set ranges dsb.setMinimum(float(c.minimum)) dsb.setMaximum(float(c.maximum)) return dsb
def createEditor( self, parent, _option, index ): if index.column() == ABONO: spinbox = QDoubleSpinBox( parent ) max = index.model().lines[index.row()].totalFac spinbox.setRange( 0.0001, max ) spinbox.setDecimals( 4 ) spinbox.setSingleStep( 1 ) spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter ) return spinbox else: None
def initUI(self): vbox = QHBoxLayout() edit = QDoubleSpinBox(self) edit.setLocale(QLocale(QLocale.English)) edit.setDecimals(2) vbox.addWidget(edit) vbox.addWidget(QLabel("10^")) expo = QSpinBox(self) expo.setMinimum(-8) expo.setMaximum(8) vbox.addWidget(expo) self.setLayout(vbox)
def widgetByType(self, valueType): if isinstance(valueType, str): valPieces = valueType.lower().split(":") typeStr = valPieces[0] rngMin = "min" rngMax = "max" if len(valPieces) == 3: rngMin = valPieces[1] if valPieces[1] != "" else "min" rngMax = valPieces[2] if valPieces[2] != "" else "max" if typeStr == "float": box = QDoubleSpinBox(self) if rngMin == "min": rngMin = -2000000000. else: rngMin = float(rngMin) if rngMax == "max": rngMax = 2000000000. else: rngMax = float(rngMax) box.setRange(rngMin, rngMax) box.setDecimals(10) return box elif typeStr == "int": box = QSpinBox(self) if rngMin == "min": rngMin = -2**31 + 1 else: rngMin = int(rngMin) if rngMax == "max": rngMax = 2**31 - 1 else: rngMax = int(rngMax) box.setRange(rngMin, rngMax) return box elif typeStr == "str": return QLineEdit(self) elif typeStr == "bool": return QCheckBox(self) elif isinstance(valueType, list): box = QComboBox(self) for item in valueType: box.addItem(item) return box
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) # # Audio Quality # self.label_audio_quality = QLabel("Audio Quality") self.spinbox_audio_quality = QDoubleSpinBox() self.spinbox_audio_quality.setMinimum(0.0) self.spinbox_audio_quality.setMaximum(1.0) self.spinbox_audio_quality.setSingleStep(0.1) self.spinbox_audio_quality.setDecimals(1) self.spinbox_audio_quality.setValue(0.3) # Default value 0.3 # # Video Quality # self.label_video_quality = QLabel("Video Quality (kb/s)") self.spinbox_video_quality = QSpinBox() self.spinbox_video_quality.setMinimum(0) self.spinbox_video_quality.setMaximum(16777215) self.spinbox_video_quality.setValue(2400) # Default value 2400 # # Misc. # self.label_matterhorn = QLabel("Matterhorn Metadata") self.label_matterhorn.setToolTip("Generates Matterhorn Metadata in XML format") self.checkbox_matterhorn = QCheckBox() layout.addRow(self.label_matterhorn, self.checkbox_matterhorn) def get_video_quality_layout(self): layout_video_quality = QHBoxLayout() layout_video_quality.addWidget(self.label_video_quality) layout_video_quality.addWidget(self.spinbox_video_quality) return layout_video_quality def get_audio_quality_layout(self): layout_audio_quality = QHBoxLayout() layout_audio_quality.addWidget(self.label_audio_quality) layout_audio_quality.addWidget(self.spinbox_audio_quality) return layout_audio_quality
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) # # Audio Quality # self.label_audio_quality = QLabel("Audio Quality") self.spinbox_audio_quality = QDoubleSpinBox() self.spinbox_audio_quality.setMinimum(0.0) self.spinbox_audio_quality.setMaximum(1.0) self.spinbox_audio_quality.setSingleStep(0.1) self.spinbox_audio_quality.setDecimals(1) self.spinbox_audio_quality.setValue(0.3) # Default value 0.3 # # Video Quality # self.label_video_quality = QLabel("Video Quality (kb/s)") self.spinbox_video_quality = QSpinBox() self.spinbox_video_quality.setMinimum(0) self.spinbox_video_quality.setMaximum(16777215) self.spinbox_video_quality.setValue(2400) # Default value 2400 # # Misc. # self.label_matterhorn = QLabel("Matterhorn Metadata") self.label_matterhorn.setToolTip( "Generates Matterhorn Metadata in XML format") self.checkbox_matterhorn = QCheckBox() layout.addRow(self.label_matterhorn, self.checkbox_matterhorn) def get_video_quality_layout(self): layout_video_quality = QHBoxLayout() layout_video_quality.addWidget(self.label_video_quality) layout_video_quality.addWidget(self.spinbox_video_quality) return layout_video_quality def get_audio_quality_layout(self): layout_audio_quality = QHBoxLayout() layout_audio_quality.addWidget(self.label_audio_quality) layout_audio_quality.addWidget(self.spinbox_audio_quality) return layout_audio_quality
def testTemperatureSubscriber(): from PyQt4.QtGui import QApplication, QDoubleSpinBox app = QApplication([]) widget = QDoubleSpinBox() widget.setDecimals(7) widget.setMinimum(0) widget.setMaximum(1000) widget.setSuffix(' K') widget.setReadOnly(True) sub = TemperatureSubscriber(widget) sub.adrTemperatureReceived.connect(widget.setValue) widget.show() sub.start() app.exec_()
def createEditor( self, parent, _option, index ): if index.column() in ( CODCUENTA, NCUENTA ): value = index.model().index( index.row(), 0 ).data().toString() self.removeFromFilter( value ) self.proxymodel.setFilterRegExp( self.filter() ) sp = SearchPanel( self.proxymodel, parent, self.showTable ) sp.setColumn( index.column() ) return sp elif index.column() == MONTO: doublespinbox = QDoubleSpinBox( parent ) doublespinbox.setMinimum( -1000000 ) doublespinbox.setMaximum( 1000000 ) doublespinbox.setDecimals( 4 ) return doublespinbox
def _create_user_value(self): layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) check_box = QCheckBox() spin_box = QDoubleSpinBox() spin_box.setDecimals(5) spin_box.setSingleStep(0.01) spin_box.setMinimum(-sys.float_info.max) spin_box.setMaximum(sys.float_info.max) spin_box.setDisabled(True) check_box.toggled.connect(spin_box.setEnabled) layout.addWidget(check_box) layout.addWidget(spin_box) return check_box, spin_box, layout
def addTableRow(self, row=None, enabled=True, f=10, A=0.1, phase=0.0, bw=5, order=8): table = self.table if row == None: row = table.rowCount() if row < 1: row = 0 table.insertRow(row) cb = QCheckBox() cb.setChecked(enabled) self.setTableCellWidget(row, 'active', cb) frequencySb = QDoubleSpinBox() frequencySb.setMinimum(1.0) frequencySb.setMaximum(self.fMax) frequencySb.setSingleStep(0.01) frequencySb.setDecimals(2) frequencySb.setValue(f) self.setTableCellWidget(row, 'f', frequencySb) amplitudeSb = AmplitudeSpinBox() amplitudeSb.setValue(A) amplitudeSb.valueChanged.connect(lambda v: self.amplitudeChanged(row, v)) self.setTableCellWidget(row, 'A', amplitudeSb) phaseSb = PhaseSpinBox() phaseSb.setValue(phase) self.setTableCellWidget(row, 'phase', phaseSb) bwSb = QDoubleSpinBox() bwSb.setMinimum(0.1) bwSb.setMaximum(1000) bwSb.setValue(bw) bwSb.setSuffix(' Hz') self.setTableCellWidget(row, 'bw', bwSb) orderSb = QSpinBox() orderSb.setMinimum(1) orderSb.setMaximum(10) orderSb.setValue(order) self.setTableCellWidget(row, 'order', orderSb) self.setTableCellWidget(row, 'X', QFloatDisplay()) self.setTableCellWidget(row, 'Y', QFloatDisplay()) self.setTableCellWidget(row, 'R', QFloatDisplay()) self.setTableCellWidget(row, 'Theta', QFloatDisplay())
def createEditor( self, parent, option, index ): if index.column() in ( CODCUENTA, NCUENTA ): model = index.model() self.proxymodel.setSourceModel( self.accounts ) current = model.data( model.index( index.row(), IDCUENTA ) ) self.proxymodel.setFilterRegExp( self.filter( model, current ) ) sp = super( AccountsSelectorDelegate, self ).createEditor( parent, option, index ) sp.setColumnHidden( IDCUENTA ) return sp elif index.column() == MONTO: doublespinbox = QDoubleSpinBox( parent ) doublespinbox.setMinimum( -100000000000 ) doublespinbox.setMaximum( 100000000000 ) doublespinbox.setDecimals( 4 ) return doublespinbox
class CharMap(preferences.Group): def __init__(self, page): super(CharMap, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) app.translateUI(self) def translateUI(self): self.setTitle(_("Special Characters")) self.fontLabel.setText(_("Font:")) def loadSettings(self): s = QSettings() s.beginGroup("charmaptool") font = self.font() family = s.value("fontfamily", "", type("")) if family: font.setFamily(family) font.setPointSizeF(s.value("fontsize", font.pointSizeF(), float)) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) def saveSettings(self): s = QSettings() s.beginGroup("charmaptool") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value())
class CharMap(preferences.Group): def __init__(self, page): super(CharMap, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) app.translateUI(self) def translateUI(self): self.setTitle(_("Special Characters")) self.fontLabel.setText(_("Font:")) def loadSettings(self): s = QSettings() s.beginGroup("charmaptool") font = self.font() family = s.value("fontfamily", "") if family: font.setFamily(family) font.setPointSizeF(float(s.value("fontsize", font.pointSizeF()))) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) def saveSettings(self): s = QSettings() s.beginGroup("charmaptool") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value())
class FontsColors(preferences.Page): def __init__(self, dialog): super(FontsColors, self).__init__(dialog) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.scheme = SchemeSelector(self) layout.addWidget(self.scheme) self.printScheme = QCheckBox() layout.addWidget(self.printScheme) hbox = QHBoxLayout() self.tree = QTreeWidget(self) self.tree.setHeaderHidden(True) self.tree.setAnimated(True) self.stack = QStackedWidget(self) hbox.addWidget(self.tree) hbox.addWidget(self.stack) layout.addLayout(hbox) hbox = QHBoxLayout() self.fontLabel = QLabel() self.fontChooser = QFontComboBox() self.fontSize = QDoubleSpinBox() self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) hbox.addWidget(self.fontLabel) hbox.addWidget(self.fontChooser, 1) hbox.addWidget(self.fontSize) layout.addLayout(hbox) # add the items to our list self.baseColorsItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStylesItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStyles = {} for name in textformats.defaultStyles: self.defaultStyles[name] = i = QTreeWidgetItem() self.defaultStylesItem.addChild(i) i.name = name self.defaultStylesItem.setExpanded(True) self.allStyles = {} for group, styles in ly.colorize.default_mapping(): i = QTreeWidgetItem() children = {} self.allStyles[group] = (i, children) self.tree.addTopLevelItem(i) i.group = group for name, base, clss in styles: j = QTreeWidgetItem() j.name = name j.base = base i.addChild(j) children[name] = j self.baseColorsWidget = BaseColors(self) self.customAttributesWidget = CustomAttributes(self) self.emptyWidget = QWidget(self) self.stack.addWidget(self.baseColorsWidget) self.stack.addWidget(self.customAttributesWidget) self.stack.addWidget(self.emptyWidget) self.tree.currentItemChanged.connect(self.currentItemChanged) self.tree.setCurrentItem(self.baseColorsItem) self.scheme.currentChanged.connect(self.currentSchemeChanged) self.scheme.changed.connect(self.changed) self.baseColorsWidget.changed.connect(self.baseColorsChanged) self.customAttributesWidget.changed.connect(self.customAttributesChanged) self.fontChooser.currentFontChanged.connect(self.fontChanged) self.fontSize.valueChanged.connect(self.fontChanged) self.printScheme.clicked.connect(self.printSchemeChanged) app.translateUI(self) def translateUI(self): self.printScheme.setText(_("Use this scheme for printing")) self.fontLabel.setText(_("Font:")) self.baseColorsItem.setText(0, _("Base Colors")) self.defaultStylesItem.setText(0, _("Default Styles")) self.defaultStyleNames = defaultStyleNames() self.allStyleNames = allStyleNames() for name in textformats.defaultStyles: self.defaultStyles[name].setText(0, self.defaultStyleNames[name]) for group, styles in ly.colorize.default_mapping(): self.allStyles[group][0].setText(0, self.allStyleNames[group][0]) for name, base, clss in styles: self.allStyles[group][1][name].setText(0, self.allStyleNames[group][1][name]) def currentItemChanged(self, item, previous): if item is self.baseColorsItem: self.stack.setCurrentWidget(self.baseColorsWidget) elif not item.parent(): self.stack.setCurrentWidget(self.emptyWidget) else: data = self.data[self.scheme.currentScheme()] w = self.customAttributesWidget self.stack.setCurrentWidget(w) toptext = None if item.parent() is self.defaultStylesItem: # default style w.setTitle(item.text(0)) w.setTristate(False) w.setTextFormat(data.defaultStyles[item.name]) else: # specific style of specific group group, name = item.parent().group, item.name w.setTitle("{0}: {1}".format(item.parent().text(0), item.text(0))) inherit = item.base if inherit: toptext = _("(Inherits: {name})").format(name=self.defaultStyleNames[inherit]) w.setTristate(bool(inherit)) w.setTextFormat(data.allStyles[group][name]) w.setTopText(toptext) def currentSchemeChanged(self): scheme = self.scheme.currentScheme() if scheme not in self.data: self.data[scheme] = textformats.TextFormatData(scheme) self.updateDisplay() if self.tree.currentItem(): self.currentItemChanged(self.tree.currentItem(), None) with qutil.signalsBlocked(self.printScheme): self.printScheme.setChecked(scheme == self._printScheme) def fontChanged(self): data = self.data[self.scheme.currentScheme()] data.font = self.fontChooser.currentFont() data.font.setPointSizeF(self.fontSize.value()) self.updateDisplay() self.changed.emit() def printSchemeChanged(self): if self.printScheme.isChecked(): self._printScheme = self.scheme.currentScheme() else: self._printScheme = None self.changed.emit() def addSchemeData(self, scheme, tfd): self.data[scheme] = tfd def currentSchemeData(self): return self.data[self.scheme.currentScheme()] def updateDisplay(self): data = self.data[self.scheme.currentScheme()] with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(data.font) self.fontSize.setValue(data.font.pointSizeF()) with qutil.signalsBlocked(self): # update base colors for name in textformats.baseColors: self.baseColorsWidget.color[name].setColor(data.baseColors[name]) # update base colors for whole treewidget p = QApplication.palette() p.setColor(QPalette.Base, data.baseColors['background']) p.setColor(QPalette.Text, data.baseColors['text']) p.setColor(QPalette.Highlight, data.baseColors['selectionbackground']) p.setColor(QPalette.HighlightedText, data.baseColors['selectiontext']) self.tree.setPalette(p) def setItemTextFormat(item, f): font = QFont(data.font) if f.hasProperty(QTextFormat.ForegroundBrush): item.setForeground(0, f.foreground().color()) else: item.setForeground(0, data.baseColors['text']) if f.hasProperty(QTextFormat.BackgroundBrush): item.setBackground(0, f.background().color()) else: item.setBackground(0, QBrush()) font.setWeight(f.fontWeight()) font.setItalic(f.fontItalic()) font.setUnderline(f.fontUnderline()) item.setFont(0, font) # update looks of default styles for name in textformats.defaultStyles: setItemTextFormat(self.defaultStyles[name], data.defaultStyles[name]) # update looks of all the specific styles for group, styles in ly.colorize.default_mapping(): children = self.allStyles[group][1] for name, inherit, clss in styles: f = QTextCharFormat(data.defaultStyles[inherit]) if inherit else QTextCharFormat() f.merge(data.allStyles[group][name]) setItemTextFormat(children[name], f) def baseColorsChanged(self, name): # keep data up to date with base colors data = self.data[self.scheme.currentScheme()] data.baseColors[name] = self.baseColorsWidget.color[name].color() self.updateDisplay() self.changed.emit() def customAttributesChanged(self): item = self.tree.currentItem() if not item or not item.parent(): return data = self.data[self.scheme.currentScheme()] if item.parent() is self.defaultStylesItem: # a default style has been changed data.defaultStyles[item.name] = self.customAttributesWidget.textFormat() else: # a specific style has been changed group, name = item.parent().group, item.name data.allStyles[group][name] = self.customAttributesWidget.textFormat() self.updateDisplay() self.changed.emit() def import_(self, filename): from . import import_export import_export.importTheme(filename, self, self.scheme) def export(self, name, filename): from . import import_export try: import_export.exportTheme(self, name, filename) except (IOError, OSError) as e: QMessageBox.critical(self, _("Error"), _( "Can't write to destination:\n\n{url}\n\n{error}").format( url=filename, error=e.strerror)) def loadSettings(self): self.data = {} # holds all data with scheme as key self._printScheme = QSettings().value("printer_scheme", "default", type("")) self.scheme.loadSettings("editor_scheme", "editor_schemes") def saveSettings(self): self.scheme.saveSettings("editor_scheme", "editor_schemes", "fontscolors") for scheme in self.scheme.schemes(): if scheme in self.data: self.data[scheme].save(scheme) if self._printScheme: QSettings().setValue("printer_scheme", self._printScheme) else: QSettings().remove("printer_scheme")
def initAppletDrawerUi(self): """ Overridden from base class (LayerViewerGui) """ op = self.topLevelOperatorView def configure_update_handlers(qt_signal, op_slot): qt_signal.connect(self.configure_operator_from_gui) op_slot.notifyDirty(self.configure_gui_from_operator) self.__cleanup_fns.append( partial(op_slot.unregisterDirty, self.configure_gui_from_operator)) def control_layout(label_text, widget): row_layout = QHBoxLayout() row_layout.addWidget(QLabel(label_text)) row_layout.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding)) row_layout.addWidget(widget) return row_layout drawer_layout = QVBoxLayout() channel_button = QPushButton() self.channel_menu = QMenu( self) # Must retain menus (in self) or else they get deleted. channel_button.setMenu(self.channel_menu) channel_button.clicked.connect(channel_button.showMenu) def populate_channel_menu(*args): if sip.isdeleted(channel_button): return self.channel_menu.clear() self.channel_actions = [] for ch in range(op.Input.meta.getTaggedShape()['c']): action = QAction("Channel {}".format(ch), self.channel_menu) action.setCheckable(True) self.channel_menu.addAction(action) self.channel_actions.append(action) configure_update_handlers(action.toggled, op.ChannelSelections) populate_channel_menu() op.Input.notifyMetaChanged(populate_channel_menu) self.__cleanup_fns.append( partial(op.Input.unregisterMetaChanged, populate_channel_menu)) channel_button.setToolTip( "Boundary channel index in the probability map") drawer_layout.addLayout(control_layout("Input Channel", channel_button)) self.channel_button = channel_button threshold_box = QDoubleSpinBox() threshold_box.setDecimals(2) threshold_box.setMinimum(0.00) threshold_box.setMaximum(1.0) threshold_box.setSingleStep(0.1) configure_update_handlers(threshold_box.valueChanged, op.Pmin) threshold_box.setToolTip("Boundary probability threshold") drawer_layout.addLayout(control_layout("Threshold", threshold_box)) self.threshold_box = threshold_box membrane_size_box = QSpinBox() membrane_size_box.setMinimum(0) membrane_size_box.setMaximum(1000000) configure_update_handlers(membrane_size_box.valueChanged, op.MinMembraneSize) membrane_size_box.setToolTip( "Size filter for boundary pieces, in pixels") drawer_layout.addLayout( control_layout("Min Boundary Size", membrane_size_box)) self.membrane_size_box = membrane_size_box seed_presmoothing_box = QDoubleSpinBox() seed_presmoothing_box.setDecimals(1) seed_presmoothing_box.setMinimum(0.0) seed_presmoothing_box.setMaximum(10.0) seed_presmoothing_box.setSingleStep(0.1) configure_update_handlers(seed_presmoothing_box.valueChanged, op.SigmaMinima) seed_presmoothing_box.setToolTip( "Smooth the distance transform map with this sigma") drawer_layout.addLayout( control_layout("Presmooth before Seeds", seed_presmoothing_box)) self.seed_presmoothing_box = seed_presmoothing_box seed_method_combo = QComboBox() seed_method_combo.addItem("Connected") seed_method_combo.addItem("Clustered") configure_update_handlers(seed_method_combo.currentIndexChanged, op.GroupSeeds) seed_method_combo.setToolTip( "Connected: combine directly adjacent pixels into seeds (more superpixels). Clustered: group pixels into seeds by distance heuristic (less superpixels)" ) drawer_layout.addLayout( control_layout("Seed Labeling", seed_method_combo)) self.seed_method_combo = seed_method_combo superpixel_size_box = QSpinBox() superpixel_size_box.setMinimum(0) superpixel_size_box.setMaximum(1000000) configure_update_handlers(superpixel_size_box.valueChanged, op.MinSegmentSize) superpixel_size_box.setToolTip("Minimal size of a superpixel") drawer_layout.addLayout( control_layout("Min Superpixel Size", superpixel_size_box)) self.superpixel_size_box = superpixel_size_box preserve_pmaps_box = QCheckBox() configure_update_handlers(preserve_pmaps_box.toggled, op.PreserveMembranePmaps) preserve_pmaps_box.setToolTip( "Preserve thin structures. Use that option when some of your foreground objects have long and thin parts" ) drawer_layout.addLayout( control_layout("Preserve Thin Structures", preserve_pmaps_box)) self.preserve_pmaps_box = preserve_pmaps_box enable_debug_box = QCheckBox() configure_update_handlers(enable_debug_box.toggled, op.EnableDebugOutputs) drawer_layout.addLayout( control_layout("Show Debug Layers", enable_debug_box)) self.enable_debug_box = enable_debug_box op.Superpixels.notifyReady(self.configure_gui_from_operator) op.Superpixels.notifyUnready(self.configure_gui_from_operator) self.__cleanup_fns.append( partial(op.Superpixels.unregisterReady, self.configure_gui_from_operator)) self.__cleanup_fns.append( partial(op.Superpixels.unregisterUnready, self.configure_gui_from_operator)) self.update_ws_button = QPushButton( "Update Watershed", clicked=self.onUpdateWatershedsButton) drawer_layout.addWidget(self.update_ws_button) drawer_layout.setSpacing(0) drawer_layout.addSpacerItem( QSpacerItem(0, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)) # Finally, the whole drawer widget drawer = QWidget(parent=self) drawer.setLayout(drawer_layout) # Save these members for later use self._drawer = drawer # Initialize everything with the operator's initial values self.configure_gui_from_operator()
class ModifyPickerPropertiesMenu(QDialog): def __init__(self, data, win_parent=None): self.win_parent = win_parent self._size = data['size'] * 100. self.out_data = data self.dim_max = data['dim_max'] QDialog.__init__(self, win_parent) self.setWindowTitle('Modify Picker Properties') self.create_widgets() self.create_layout() self.set_connections() width = 260 height = 130 self.resize(width, height) #self.show() def create_widgets(self): # Size self.size = QLabel("Percent of Screen Size:") self.size_edit = QDoubleSpinBox(self) self.size_edit.setRange(0., 10.) log_dim = log10(self.dim_max) decimals = int(ceil(abs(log_dim))) decimals = max(3, decimals) self.size_edit.setDecimals(decimals) self.size_edit.setSingleStep(10. / 5000.) self.size_edit.setValue(self._size) # closing #self.apply_button = QPushButton("Apply") #self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") def create_layout(self): grid = QGridLayout() grid.addWidget(self.size, 1, 0) grid.addWidget(self.size_edit, 1, 1) ok_cancel_box = QHBoxLayout() #ok_cancel_box.addWidget(self.apply_button) #ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addStretch() vbox.addLayout(ok_cancel_box) self.setLayout(vbox) self.layout() #def on_color(self): #pass def set_connections(self): self.size_edit.valueChanged.connect(self.on_size) if qt_version == 4: self.connect(self.size_edit, QtCore.SIGNAL('editingFinished()'), self.on_size) self.connect(self.size_edit, QtCore.SIGNAL('valueChanged()'), self.on_size) self.connect(self.size_edit, QtCore.SIGNAL('clicked()'), self.on_size) #self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) #self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) else: self.size_edit.editingFinished.connect(self.on_size) self.size_edit.valueChanged.connect(self.on_size) ## ??? clicked self.cancel_button.clicked.connect(self.on_cancel) #self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): self.out_data['close'] = True event.accept() def on_size(self): self._size = float(self.size_edit.text()) self.on_apply(force=True) @staticmethod def check_float(cell): text = cell.text() value = float(text) return value, True def on_validate(self): size_value, flag0 = self.check_float(self.size_edit) if flag0: self._size = size_value #self.out_data['min'] = min(min_value, max_value) #self.out_data['max'] = max(min_value, max_value) self.out_data['clicked_ok'] = True return True return False def on_apply(self, force=False): passed = self.on_validate() if (passed or Force) and self.win_parent is not None: self.win_parent.element_picker_size = self._size / 100. return passed def on_ok(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False self.out_data['close'] = True passed = self.on_apply() if passed: self.close() #self.destroy() def on_cancel(self): self.out_data['clicked_cancel'] = True self.out_data['close'] = True self.close()
class PlotConfigPanel(QFrame): """A panel to interact with PlotConfig instances.""" plot_marker_styles = ["", ".", ",", "o", "*", "s", "+", "x", "p", "h", "H", "D", "d"] plot_line_styles = ["", "-", "--", "-.", ":"] def __init__(self, plot_config): QFrame.__init__(self) self.plot_config = plot_config self.connect(plot_config.signal_handler, SIGNAL('plotConfigChanged(PlotConfig)'), self._fetchValues) layout = QFormLayout() layout.setRowWrapPolicy(QFormLayout.WrapLongRows) self.chk_visible = QCheckBox() layout.addRow("Visible:", self.chk_visible) self.connect(self.chk_visible, SIGNAL('stateChanged(int)'), self._setVisibleState) self.plot_linestyle = QComboBox() self.plot_linestyle.addItems(self.plot_line_styles) self.connect(self.plot_linestyle, SIGNAL("currentIndexChanged(QString)"), self._setLineStyle) layout.addRow("Line style:", self.plot_linestyle) self.plot_marker_style = QComboBox() self.plot_marker_style.addItems(self.plot_marker_styles) self.connect(self.plot_marker_style, SIGNAL("currentIndexChanged(QString)"), self._setMarker) layout.addRow("Marker style:", self.plot_marker_style) self.alpha_spinner = QDoubleSpinBox(self) self.alpha_spinner.setMinimum(0.0) self.alpha_spinner.setMaximum(1.0) self.alpha_spinner.setDecimals(3) self.alpha_spinner.setSingleStep(0.01) self.connect(self.alpha_spinner, SIGNAL('valueChanged(double)'), self._setAlpha) layout.addRow("Blend factor:", self.alpha_spinner) self.color_picker = ColorPicker(plot_config) layout.addRow("Color:", self.color_picker) self.setLayout(layout) self._fetchValues(plot_config) def _fetchValues(self, plot_config): """Fetch values from a PlotConfig and insert into the panel.""" self.plot_config = plot_config #block signals to avoid updating the incoming plot_config state = self.plot_linestyle.blockSignals(True) linestyle_index = self.plot_line_styles.index(self.plot_config.linestyle) self.plot_linestyle.setCurrentIndex(linestyle_index) self.plot_linestyle.blockSignals(state) state = self.plot_marker_style.blockSignals(True) marker_index = self.plot_marker_styles.index(self.plot_config.marker) self.plot_marker_style.setCurrentIndex(marker_index) self.plot_marker_style.blockSignals(state) state = self.alpha_spinner.blockSignals(True) self.alpha_spinner.setValue(self.plot_config.alpha) self.alpha_spinner.blockSignals(state) state = self.chk_visible.blockSignals(True) self.chk_visible.setChecked(self.plot_config.is_visible) self.chk_visible.blockSignals(state) self.color_picker.update() #------------------------------------------- # update plot config from widgets #------------------------------------------- def _setLineStyle(self, linestyle): self.plot_config.linestyle = linestyle def _setMarker(self, marker): self.plot_config.marker = marker def _setAlpha(self, alpha): self.plot_config.alpha = alpha def _setVisibleState(self, state): self.plot_config.is_visible = state == 2
def initAppletDrawerUi(self): """ Overridden from base class (LayerViewerGui) """ op = self.topLevelOperatorView def configure_update_handlers( qt_signal, op_slot ): qt_signal.connect( self.configure_operator_from_gui ) op_slot.notifyDirty( self.configure_gui_from_operator ) self.__cleanup_fns.append( partial( op_slot.unregisterDirty, self.configure_gui_from_operator ) ) def control_layout( label_text, widget ): row_layout = QHBoxLayout() row_layout.addWidget( QLabel(label_text) ) row_layout.addSpacerItem( QSpacerItem(10, 0, QSizePolicy.Expanding) ) row_layout.addWidget(widget) return row_layout drawer_layout = QVBoxLayout() channel_box = QSpinBox() def set_channel_box_range(*args): if sip.isdeleted(channel_box): return channel_box.setMinimum(0) channel_box.setMaximum( op.Input.meta.getTaggedShape()['c']-1 ) set_channel_box_range() op.Input.notifyMetaChanged( set_channel_box_range ) configure_update_handlers( channel_box.valueChanged, op.ChannelSelection ) drawer_layout.addLayout( control_layout( "Input Channel", channel_box ) ) self.channel_box = channel_box threshold_box = QDoubleSpinBox() threshold_box.setDecimals(2) threshold_box.setMinimum(0.00) threshold_box.setMaximum(1.0) threshold_box.setSingleStep(0.1) configure_update_handlers( threshold_box.valueChanged, op.Pmin ) drawer_layout.addLayout( control_layout( "Threshold", threshold_box ) ) self.threshold_box = threshold_box membrane_size_box = QSpinBox() membrane_size_box.setMinimum(0) membrane_size_box.setMaximum(1000000) configure_update_handlers( membrane_size_box.valueChanged, op.MinMembraneSize ) drawer_layout.addLayout( control_layout( "Min Membrane Size", membrane_size_box ) ) self.membrane_size_box = membrane_size_box seed_presmoothing_box = QDoubleSpinBox() seed_presmoothing_box.setDecimals(1) seed_presmoothing_box.setMinimum(0.0) seed_presmoothing_box.setMaximum(10.0) seed_presmoothing_box.setSingleStep(0.1) configure_update_handlers( seed_presmoothing_box.valueChanged, op.SigmaMinima ) drawer_layout.addLayout( control_layout( "Presmooth before seeds", seed_presmoothing_box ) ) self.seed_presmoothing_box = seed_presmoothing_box seed_method_combo = QComboBox() seed_method_combo.addItem("Connected") seed_method_combo.addItem("Clustered") configure_update_handlers( seed_method_combo.currentIndexChanged, op.GroupSeeds ) drawer_layout.addLayout( control_layout( "Seed Labeling", seed_method_combo ) ) self.seed_method_combo = seed_method_combo watershed_presmoothing_box = QDoubleSpinBox() watershed_presmoothing_box.setDecimals(1) watershed_presmoothing_box.setMinimum(0.0) watershed_presmoothing_box.setMaximum(10.0) watershed_presmoothing_box.setSingleStep(0.1) configure_update_handlers( watershed_presmoothing_box.valueChanged, op.SigmaWeights ) drawer_layout.addLayout( control_layout( "Presmooth before watershed", watershed_presmoothing_box ) ) self.watershed_presmoothing_box = watershed_presmoothing_box superpixel_size_box = QSpinBox() superpixel_size_box.setMinimum(0) superpixel_size_box.setMaximum(1000000) configure_update_handlers( superpixel_size_box.valueChanged, op.MinSegmentSize ) drawer_layout.addLayout( control_layout( "Min Superpixel Size", superpixel_size_box ) ) self.superpixel_size_box = superpixel_size_box preserve_pmaps_box = QCheckBox() configure_update_handlers( preserve_pmaps_box.toggled, op.PreserveMembranePmaps ) drawer_layout.addLayout( control_layout( "Preserve membrane probabilities", preserve_pmaps_box ) ) self.preserve_pmaps_box = preserve_pmaps_box enable_debug_box = QCheckBox() configure_update_handlers( enable_debug_box.toggled, op.EnableDebugOutputs ) drawer_layout.addLayout( control_layout( "Show Debug Layers", enable_debug_box ) ) self.enable_debug_box = enable_debug_box compute_button = QPushButton("Update Watershed", clicked=self.onUpdateWatershedsButton) drawer_layout.addWidget( compute_button ) drawer_layout.setSpacing(0) drawer_layout.addSpacerItem( QSpacerItem(0, 10, QSizePolicy.Minimum, QSizePolicy.Expanding) ) # Finally, the whole drawer widget drawer = QWidget(parent=self) drawer.setLayout(drawer_layout) # Save these members for later use self._drawer = drawer # Initialize everything with the operator's initial values self.configure_gui_from_operator()
class GUI(QWidget): def __init__(self, parent=None): global f f = open(filename, "a") f.write("Widget init.\n") f.close() QWidget.__init__(self, parent, Qt.WindowStaysOnTopHint) self.__setup_gui__(self) self._flag = False self._change = False f = open(filename, "a") f.write("End of widget init.\n") f.close() def closeEvent(self, event): reply = QMessageBox.question(self, "Confirm", "Are you sure You want to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() def __setup_gui__(self, Dialog): global f f = open(filename, "a") f.write("Setup of gui.\n") f.close() Dialog.setObjectName("Dialog") Dialog.resize(270, 145) self.setWindowTitle("Map Layer") screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) self.Render = QPushButton("Render", Dialog) self.Render.setGeometry(QRect(85, 90, 100, 25)) self.Render.setObjectName("Render") self.comboBox = QComboBox(Dialog) self.comboBox.setGeometry(QRect(100, 34, 115, 18)) self.comboBox.setEditable(False) self.comboBox.setMaxVisibleItems(11) self.comboBox.setInsertPolicy(QComboBox.InsertAtBottom) self.comboBox.setObjectName("comboBox") self.comboBox.addItems([ "Google Roadmap", "Google Terrain", "Google Satellite", "Google Hybrid", "Yahoo Roadmap", "Yahoo Satellite", "Yahoo Hybrid", "Bing Roadmap", "Bing Satellite", "Bing Hybrid", "Open Street Maps" ]) self.comboBox.setCurrentIndex(10) self.label1 = QLabel("Source:", Dialog) self.label1.setGeometry(QRect(55, 35, 35, 16)) self.label1.setObjectName("label1") self.slider = QSlider(Dialog) self.slider.setOrientation(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(12) self.slider.setValue(4) self.slider.setGeometry(QRect(110, 61, 114, 16)) self.label2 = QLabel("Quality: " + str(self.slider.value()), Dialog) self.label2.setGeometry(QRect(47, 61, 54, 16)) self.label2.setObjectName("label2") self.doubleSpinBox = QDoubleSpinBox(Dialog) self.doubleSpinBox.setGeometry(QRect(160, 5, 40, 20)) self.doubleSpinBox.setDecimals(0) self.doubleSpinBox.setObjectName("doubleSpinBox") self.doubleSpinBox.setMinimum(10.0) self.doubleSpinBox.setValue(20.0) self.doubleSpinBox.setEnabled(False) self.checkBox = QCheckBox("Auto refresh", Dialog) self.checkBox.setGeometry(QRect(50, 6, 100, 20)) self.checkBox.setLayoutDirection(Qt.RightToLeft) self.checkBox.setObjectName("checkBox") self.progressBar = QProgressBar(Dialog) self.progressBar.setGeometry(QRect(5, 130, 260, 10)) self.progressBar.setProperty("value", 0) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") self.progressBar.setVisible(False) QObject.connect(self.Render, SIGNAL("clicked()"), Dialog.__repaint__) QMetaObject.connectSlotsByName(Dialog) QObject.connect(self.slider, SIGNAL("valueChanged(int)"), self.__update_slider_label__) QObject.connect(self.comboBox, SIGNAL("activated(int)"), self.__combobox_changed__) self.timerRepaint = QTimer() QObject.connect(self.checkBox, SIGNAL("clicked()"), self.__activate_timer__) QObject.connect(self.timerRepaint, SIGNAL("timeout()"), self.__on_timer__) f = open(filename, "a") f.write("End of setup of gui.\n") f.close() def __combobox_changed__(self): self._change = True def __activate_timer__(self): self.doubleSpinBox.setEnabled(self.checkBox.isChecked()) if self.checkBox.isChecked(): self.timerRepaint.start(self.doubleSpinBox.value() * 1000) self.Render.setEnabled(False) if _progress == 0: self.__repaint__() else: self.timerRepaint.stop() self.Render.setEnabled(True) def __get_net_size__(self): global f f = open(filename, "a") f.write("Geting net size...\n") f.close() if not os.path.exists(Paths["Screenshot"]): Visum.Graphic.Screenshot(Paths["Screenshot"]) size = Image.open(Paths["Screenshot"]).size f = open(filename, "a") f.write("Read net size:" + str(size) + ".\n") f.close() return size def __on_timer__(self): global _paramGlobal self._flag = False Visum.Graphic.MaximizeNetWindow() param = _paramGlobal _paramGlobal = Visum.Graphic.GetWindow() shift = abs((param[0] - _paramGlobal[0]) / (param[2] - param[0])) zoom = abs((param[2] - param[0]) / (_paramGlobal[2] - _paramGlobal[0]) - 1) print _windowSizeGlobal if _windowSizeGlobal[2:4] != Visum.Graphic.GetMainWindowPos()[2:4]: self.__get_net_size__() self._flag = True elif shift > 0.4 or zoom > 0.2: self._flag = True if self._flag or self._change and _progress == 0: self.__repaint__() self._change = False def __update_slider_label__(self, value): self.label2.setText("Quality: " + str(value)) self._change = True def __update_progress_bar__(self): if _progress != 0: self.progressBar.setVisible(True) self.progressBar.setValue(_progress) else: self.progressBar.setVisible(False) def __rebuild_paths__(self): global Paths Paths["Images"] = [] list = os.listdir(Paths["ScriptFolder"]) imageList = [] for i in range(len(list)): if list[i][-3:] == "png": imageList.append(list[i]) for i in range(len(imageList)): try: Visum.Graphic.Backgrounds.ItemByKey(imageList[i]) Paths["Images"].append(Paths["ScriptFolder"] + "\\" + imageList[i]) except: pass def __repaint__(self): global _progress, f if len(Visum.Graphic.Backgrounds.GetAll) != len(Paths["Images"]): self.__rebuild_paths__() if _progress == 0: f = open(filename, "a") f.write("Doing repaint...\n") f.close() QWebSettings.clearMemoryCaches() timer = QTimer() timer.start(100) QObject.connect(timer, SIGNAL("timeout()"), self.__update_progress_bar__) Main(self.comboBox.currentIndex(), Visum.Graphic.GetWindow(), self.slider.value() / 4.0, self.__get_net_size__()) Visum.Graphic.Draw() self.__update_progress_bar__() _progress = 0 QTimer().singleShot(1500, self.__update_progress_bar__) f = open(filename, "a") f.write("End of doing repaint.\n") f.close()
class EditGeometryProperties(QDialog): force = True allow_update = 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 | +-------------------------+ """ QDialog.__init__(self, win_parent) self.setWindowTitle('Edit Geometry Properties') #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) # closing # self.apply_button = QPushButton("Apply") #if self._default_is_apply: #self.apply_button.setDisabled(True) # self.ok_button = QPushButton("OK") 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. """ 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.is_visible = self.checkbox_show.isChecked() 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.apply_button) # ok_cancel_box.addWidget(self.ok_button) 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.connect(arg0, QObject, arg1) if qt_version == 4: self.connect(self.opacity_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity) #self.connect(self.opacity_slider_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity) #grid.addWidget(self.opacity_slider_edit, irow, 1) # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size) # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_point_size) self.connect(self.line_width_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width) self.connect(self.point_size_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size) self.connect(self.bar_scale_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_bar_scale) else: 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.color_edit, QtCore.SIGNAL('clicked()'), self.on_color) self.connect(self.checkbox_show, QtCore.SIGNAL('clicked()'), self.on_show) self.connect(self.checkbox_hide, QtCore.SIGNAL('clicked()'), self.on_hide) #self.connect(self.check_apply, QtCore.SIGNAL('clicked()'), self.on_check_apply) # self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) # self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) else: 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): name = self.active_key obj = self.out_data[name] rgb_color_ints = obj.color msg = name col = QtGui.QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a %s color" % msg) if col.isValid(): color = col.getRgbF()[:3] obj.color = color #print('new_color =', color) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") self.on_apply(force=self.force) def on_show(self): 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): 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): 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): 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): 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): 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): 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): 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): 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): 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_check_apply(self): is_checked = self.check_apply.isChecked() self.apply_button.setDisabled(is_checked) 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.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() if (passed or force) and self.allow_update: self.win_parent.on_update_geometry_properties(self.out_data) return passed def on_cancel(self): passed = self.on_apply(force=True) if passed: self.close()
class Main(plugin.Plugin): " Main Class " def initialize(self, *args, **kwargs): " Init Main Class " super(Main, self).initialize(*args, **kwargs) self.chooser, self.process = QComboBox(), QProcess() self.chooser.addItems([' Ubuntu Unity QuickList .desktop ', ' KDE Plasma MetaData .desktop ', ' FreeDesktop Standard .desktop ']) self.chooser.currentIndexChanged.connect(self.on_index_changed) self.chooser.setToolTip('Select a target .desktop file format') # Standard FreeDesktop self.group1 = QGroupBox() self.group1.setTitle(' Standard ') self.ledVersion, self.ledCategories = QDoubleSpinBox(), QComboBox() self.ledVersion.setMinimum(0.1) self.ledVersion.setMaximum(999.9) self.ledVersion.setValue(1.0) self.ledVersion.setDecimals(1) self.ledType, self.ledName = QLineEdit('Application'), QLineEdit('App') self.ledGenericName = QLineEdit('Generic App') self.ledComment, self.ledIcon = QLineEdit('App'), QLineEdit('icon.svg') self.ledCategories.addItems(['Python Programming Language', 'Development', 'Ruby', 'C++', 'Amateur Radio', 'Communication', 'Cross Platform', 'Databases', 'Debug', 'Documentation', 'Editors', 'Education', 'Electronics', 'Email', 'Embebed Devices', 'Fonts', 'GNOME Desktop Environment', 'GNU R Statistical System', 'GObject Introspection Data', 'Games and Amusement', 'Gnustep Desktop Environtment', 'Graphics', 'Haskell Programming Language', 'Internationalization and Localization', 'Internet', 'Interpreted Computer Languages', 'KDE Software Compilation', 'Kernel and Modules', 'Libraries', 'Libraries - Development', 'Libraries - Old', 'Lisp Programming Language', 'Localization', 'Mathematics', 'Meta Packages', 'Miscelaneous - Graphical', 'Miscelaneous - Text Based', 'Mono/CLI Infraestructure', 'Multimedia', 'Networking', 'Newsgroups', 'OCaml Programming Language', 'PHP Programming Language', 'Perl Programming Language', 'Ruby Programming Language', 'Science', 'Shells', 'System Administration', 'TeX Authoring', 'Utilities', 'Version Control Systems', 'Video Software', 'Web Servers', 'Word Processing', 'Xfce Desktop Environment', 'Zope/Plone Environment']) self.ledExec, self.ledTryExec = QLineEdit('myapp'), QLineEdit('myapp') self.ledMymeType = QLineEdit('application/x-desktop') self.ledTerminal = QComboBox() self.ledTerminal.addItems(['False', 'True']) self.ledActions = QLineEdit('Next;Previous') self.ledOnlyShowIn = QLineEdit('Unity;KDE') self.ledNotShowIn = QLineEdit('Gnome2') vboxg1 = QVBoxLayout(self.group1) for each_widget in (QLabel('Version'), self.ledVersion, QLabel('Type'), self.ledType, QLabel('Name'), self.ledName, QLabel('GenericName'), self.ledGenericName, QLabel('Comment'), self.ledComment, QLabel('Icon'), self.ledIcon, QLabel('Categories'), self.ledCategories, QLabel('Exec'), self.ledExec, QLabel('TryExec'), self.ledTryExec, QLabel('MymeType'), self.ledMymeType, QLabel('Terminal'), self.ledTerminal, QLabel('Actions'), self.ledActions, QLabel('OnlyShowIn'), self.ledOnlyShowIn, QLabel('NotShowIn'), self.ledNotShowIn): vboxg1.addWidget(each_widget) # KDE Plasma self.group2 = QGroupBox() self.group2.setTitle(' KDE Plasma ') self.group2.setGraphicsEffect(QGraphicsBlurEffect(self)) self.ledEncoding, self.ledXPlasmaAPI = QComboBox(), QComboBox() self.ledEncoding.addItems(['UTF-8', 'ISO-8859-1']) self.ledServiceType = QLineEdit('Plasma/Applet') self.ledXPlasmaAPI.addItems([ 'Python', 'Javascript', 'Ruby', 'C++', 'HTML5', 'QML']) self.ledXPlasmaMainScript = QLineEdit('path/to/your/code.py') self.ledXKDEPluginInfoAuthor = QLineEdit(getuser()) self.ledXKDEPluginInfoEmail = QLineEdit(getuser() + '@gmail.com') self.ledXKDEPluginInfoName = QLineEdit('Hello-World') self.ledXKDEPluginInfoVersion = QLineEdit('1.0') self.ledXKDEPluginInfoWebsite = QLineEdit('http:plasma.kde.org') self.ledXKDEPluginInfoCategory = QComboBox() self.ledXKDEPluginInfoCategory.addItems(['Application Launchers', 'Accessibility', 'Astronomy', 'Date and Time', 'Development Tools', 'Education', 'Environment', 'Examples', 'File System', 'Fun and Games', 'Graphics', 'Language', 'Mapping', 'Multimedia', 'Online Services', 'System Information', 'Utilities', 'Windows and Tasks', 'Miscelaneous']) self.ledXKDEPluginInfoDepends = QLineEdit() self.ledXKDEPluginInfoLicense = QLineEdit('GPL') self.ledXKDEPluginInfoEnabledByDefault = QComboBox() self.ledXKDEPluginInfoEnabledByDefault.addItems(['True', 'False']) vboxg2 = QVBoxLayout(self.group2) for each_widget in ( QLabel('Encoding'), self.ledEncoding, QLabel('ServiceType'), self.ledServiceType, QLabel('X-Plasma-API'), self.ledXPlasmaAPI, QLabel('X-Plasma-MainScript'), self.ledXPlasmaMainScript, QLabel('X-KDE-PluginInfo-Author'), self.ledXKDEPluginInfoAuthor, QLabel('X-KDE-PluginInfo-Email'), self.ledXKDEPluginInfoEmail, QLabel('X-KDE-PluginInfo-Name'), self.ledXKDEPluginInfoName, QLabel('X-KDE-PluginInfo-Version'), self.ledXKDEPluginInfoVersion, QLabel('X-KDE-PluginInfo-Website'), self.ledXKDEPluginInfoWebsite, QLabel('X-KDE-PluginInfo-Category'), self.ledXKDEPluginInfoCategory, QLabel('X-KDE-PluginInfo-Depends'), self.ledXKDEPluginInfoDepends, QLabel('X-KDE-PluginInfo-License'), self.ledXKDEPluginInfoLicense, QLabel('X-KDE-PluginInfo-EnabledByDefault'), self.ledXKDEPluginInfoEnabledByDefault): vboxg2.addWidget(each_widget) # Ubuntu Unity self.ledXAyatanaDesktopShortcuts = QLineEdit('Next;Previous') self.checkbox1 = QCheckBox('Open .desktop file when done') self.checkbox2 = QCheckBox('Make .desktop file Executable') [a.setChecked(True) for a in (self.checkbox1, self.checkbox2)] self.button = QPushButton(' Make .Desktop File ! ') self.button.setMinimumSize(100, 50) self.button.clicked.connect(self.writeFile) glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) self.button.setGraphicsEffect(glow) glow.setEnabled(True) class TransientWidget(QWidget): ' persistant widget thingy ' def __init__(self, widget_list): ' init sub class ' super(TransientWidget, self).__init__() vbox = QVBoxLayout(self) for each_widget in widget_list: vbox.addWidget(each_widget) tw = TransientWidget((self.chooser, self.group1, self.group2, QLabel('X-Ayatana-Desktop-Shortcuts'), self.ledXAyatanaDesktopShortcuts, QLabel(''), self.checkbox1, self.checkbox2, self.button)) self.dock, self.scrollable = QDockWidget(), QScrollArea() self.scrollable.setWidgetResizable(True) self.scrollable.setWidget(tw) self.dock.setWindowTitle(__doc__) self.dock.setStyleSheet('QDockWidget::title{text-align: center;}') self.dock.setWidget(self.scrollable) ExplorerContainer().addTab(self.dock, "DotDesktop") QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__, ''.join((__doc__, __version__, __license__, 'by', __author__)))) def writeFile(self): ' write the .desktop file to disk ' UNITY = ''.join(a for a in iter(( 'OnlyShowIn=', str(self.ledOnlyShowIn.text()), linesep, 'NotShowIn=', str(self.ledNotShowIn.text()), linesep, 'X-Ayatana-Desktop-Shortcuts=', str(self.ledXAyatanaDesktopShortcuts.text()), linesep))) PLASMA = ''.join(a for a in iter(( 'OnlyShowIn=', str(self.ledOnlyShowIn.text()), linesep, 'NotShowIn=', str(self.ledNotShowIn.text()), linesep, 'Encoding=', str(self.ledEncoding.currentText()), linesep, 'ServiceTypes=', str(self.ledServiceType.text()), linesep, 'X-Plasma-API=', str(self.ledXPlasmaAPI.currentText()), linesep, 'X-Plasma-MainScript=', str(self.ledXPlasmaMainScript.text()), linesep, 'X-KDE-PluginInfo-Author=', str(self.ledXKDEPluginInfoAuthor.text()), linesep, 'X-KDE-PluginInfo-Email=', str(self.ledXKDEPluginInfoEmail.text()), linesep, 'X-KDE-PluginInfo-Name=', str(self.ledXKDEPluginInfoName.text()), linesep, 'X-KDE-PluginInfo-Version=', str(self.ledXKDEPluginInfoVersion.text()), linesep, 'X-KDE-PluginInfo-Website=', str(self.ledXKDEPluginInfoWebsite.text()), linesep, 'X-KDE-PluginInfo-Category=', str(self.ledXKDEPluginInfoCategory.currentText()), linesep, 'X-KDE-PluginInfo-Depends=', str(self.ledXKDEPluginInfoDepends.text()), linesep, 'X-KDE-PluginInfo-License=', str(self.ledXKDEPluginInfoLicense.text()), linesep, 'X-KDE-PluginInfo-EnabledByDefault=', str(self.ledXKDEPluginInfoEnabledByDefault.currentText()), linesep))) BASE = ''.join(a for a in iter(( '[Desktop Entry]', linesep, 'Version=', str(self.ledVersion.value()), linesep, 'Type=', str(self.ledType.text()), linesep, 'Name=', str(self.ledName.text()), linesep, 'Comment=', str(self.ledComment.text()), linesep, 'TryExec=', str(self.ledTryExec.text()), linesep, 'Exec=', str(self.ledExec.text()), linesep, 'Icon=', str(self.ledIcon.text()), linesep, 'MimeType=', str(self.ledMymeType.text()), linesep, 'Actions=', str(self.ledActions.text()), linesep, 'Terminal=', str(self.ledTerminal.currentText()), linesep))) ACTIONS * len(str(self.ledActions.text()).lower().strip().split(';')) fnm = str(QFileDialog.getSaveFileName(self.dock, '', '', "(*.desktop)")) with open(fnm, 'w') as f: if self.chooser.currentIndex() is 0 and fnm is not '': f.write(''.join(a for a in iter((BASE, UNITY, ACTIONS)))) elif self.chooser.currentIndex() is 1 and fnm is not '': f.write(''.join(a for a in iter((BASE, PLASMA)))) elif fnm is not '': f.write(BASE) if self.checkbox2.isChecked() and fnm is not '': try: chmod(fnm, 0775) # Py2 except: chmod(fnm, 0o775) # Py3 if self.checkbox1.isChecked() and fnm is not '': self.process.start('ninja-ide ' + fnm) if not self.process.waitForStarted(): print((" ERROR: FAIL: {} failed!".format(fnm))) return def on_index_changed(self): ' enable disable the qgroupbox if needed ' if self.chooser.currentIndex() is 1: self.group2.graphicsEffect().setEnabled(False) self.group2.setEnabled(True) else: self.group2.graphicsEffect().setEnabled(True) self.group2.setEnabled(False) if self.chooser.currentIndex() is 0: self.ledXAyatanaDesktopShortcuts.setEnabled(True) else: self.ledXAyatanaDesktopShortcuts.setEnabled(False)
class StyleChooser(QWidget): def __init__(self, area_supported=False): QWidget.__init__(self) self._style = PlotStyle("StyleChooser Internal Style") self._styles = STYLES if area_supported else STYLES_LINE_ONLY self.setMinimumWidth(140) self.setMaximumHeight(25) layout = QHBoxLayout() layout.setMargin(0) layout.setSpacing(2) self.line_chooser = QComboBox() self.line_chooser.setToolTip("Select line style.") for style in self._styles: self.line_chooser.addItem(*style) self.marker_chooser = QComboBox() self.marker_chooser.setToolTip("Select marker style.") for marker in MARKERS: self.marker_chooser.addItem(*marker) self.thickness_spinner = QDoubleSpinBox() self.thickness_spinner.setToolTip("Line thickness") self.thickness_spinner.setMinimum(0.1) self.thickness_spinner.setDecimals(1) self.thickness_spinner.setSingleStep(0.1) self.size_spinner = QDoubleSpinBox() self.size_spinner.setToolTip("Marker Size") self.size_spinner.setMinimum(0.1) self.size_spinner.setDecimals(1) self.size_spinner.setSingleStep(0.1) layout.addWidget(self.line_chooser) layout.addWidget(self.thickness_spinner) layout.addWidget(self.marker_chooser) layout.addWidget(self.size_spinner) self.setLayout(layout) self.line_chooser.currentIndexChanged.connect(self._updateStyle) self.marker_chooser.currentIndexChanged.connect(self._updateStyle) self.thickness_spinner.valueChanged.connect(self._updateStyle) self.size_spinner.valueChanged.connect(self._updateStyle) self._updateLineStyleAndMarker(self._style.line_style, self._style.marker, self._style.width, self._style.size) self._layout = layout def getItemSizes(self): line_style_combo_width = self._layout.itemAt(0).sizeHint().width() thickness_spinner_width = self._layout.itemAt(1).sizeHint().width() marker_combo_width = self._layout.itemAt(2).sizeHint().width() size_spinner_width = self._layout.itemAt(3).sizeHint().width() return line_style_combo_width, thickness_spinner_width, marker_combo_width, size_spinner_width def _findLineStyleIndex(self, line_style): for index, style in enumerate(self._styles): if style[1] == line_style: return index elif style[1] is None and line_style == "": return index return -1 def _findMarkerStyleIndex(self, marker): for index, style in enumerate(MARKERS): if style[1] == marker: return index elif style[1] is None and marker == "": return index return -1 def _updateLineStyleAndMarker(self, line_style, marker, thickness, size): self.line_chooser.setCurrentIndex(self._findLineStyleIndex(line_style)) self.marker_chooser.setCurrentIndex(self._findMarkerStyleIndex(marker)) self.thickness_spinner.setValue(thickness) self.size_spinner.setValue(size) def _updateStyle(self): self.marker_chooser.setEnabled(self.line_chooser.currentText() != "Area") line_style = self.line_chooser.itemData(self.line_chooser.currentIndex()) marker_style = self.marker_chooser.itemData(self.marker_chooser.currentIndex()) thickness = float(self.thickness_spinner.value()) size = float(self.size_spinner.value()) self._style.line_style = str(line_style.toString()) self._style.marker = str(marker_style.toString()) self._style.width = thickness self._style.size = size def setStyle(self, style): """ @type style: PlotStyle """ self._style.copyStyleFrom(style) self._updateLineStyleAndMarker(style.line_style, style.marker, style.width, style.size) def getStyle(self): """ @rtype: PlotStyle """ style = PlotStyle("Generated Style from StyleChooser") style.copyStyleFrom(self._style) return style def createLabelLayout(self, layout=None): if layout is None: layout = QHBoxLayout() titles = ["Line Style", "Width", "Marker Style", "Size"] sizes = self.getItemSizes() for title, size in zip(titles, sizes): label = QLabel(title) label.setFixedWidth(size) layout.addWidget(label) return layout
class GeoLocationWidget(QWidget): """GeoLocationWidget(QWidget) Provides a custom geographical location widget. """ __pyqtSignals__ = ("latitudeChanged(double)", "longitudeChanged(double)", "elevationChanged(double)") def __init__(self, parent = None): super().__init__(parent) latitudeLabel = QLabel(self.tr("Latitude:")) self.latitudeSpinBox = QDoubleSpinBox() self.latitudeSpinBox.setRange(-90.0, 90.0) self.latitudeSpinBox.setDecimals(5) self.latitudeSpinBox.setSuffix(" degrees") self.latitudeSpinBox.setToolTip("How far north or sourth you are from the equator. Must be between -90 and 90.") longitudeLabel = QLabel(self.tr("Longitude:")) self.longitudeSpinBox = QDoubleSpinBox() self.longitudeSpinBox.setRange(-180.0, 180.0) self.longitudeSpinBox.setDecimals(5) self.longitudeSpinBox.setSuffix(" degrees") self.longitudeSpinBox.setToolTip("How far west or east you are from the meridian. Must be between -180 and 180.") elevationLabel = QLabel(self.tr("Elevation")) self.elevationSpinBox = QDoubleSpinBox() self.elevationSpinBox.setRange(-418.0, 8850.0) self.elevationSpinBox.setDecimals(5) self.elevationSpinBox.setSuffix(" m") self.elevationSpinBox.setToolTip("The distance from sea level in meters. Must be between -418 and 8850.") self.connect(self.latitudeSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("latitudeChanged(double)")) self.connect(self.longitudeSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("longitudeChanged(double)")) self.connect(self.elevationSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("elevationChanged(double)")) layout = QGridLayout(self) layout.addWidget(latitudeLabel, 0, 0) layout.addWidget(self.latitudeSpinBox, 1, 0) layout.addWidget(longitudeLabel, 0, 1) layout.addWidget(self.longitudeSpinBox, 1, 1) layout.addWidget(elevationLabel, 0, 2) layout.addWidget(self.elevationSpinBox, 1, 2) # The latitude property is implemented with the latitude() and setLatitude() # methods, and contains the latitude of the user. def latitude(self): return self.latitudeSpinBox.value() @pyqtSignature("setLatitude(double)") def setLatitude(self, latitude): if latitude != self.latitudeSpinBox.value(): self.latitudeSpinBox.setValue(latitude) self.emit(SIGNAL("latitudeChanged(double)"), latitude) latitude = pyqtProperty("double", latitude, setLatitude) # The longitude property is implemented with the longitude() and setlongitude() # methods, and contains the longitude of the user. def longitude(self): return self.longitudeSpinBox.value() @pyqtSignature("setLongitude(double)") def setLongitude(self, longitude): if longitude != self.longitudeSpinBox.value(): self.longitudeSpinBox.setValue(longitude) self.emit(SIGNAL("longitudeChanged(double)"), longitude) longitude = pyqtProperty("double", longitude, setLongitude) def elevation(self): return self.elevationSpinBox.value() @pyqtSignature("setElevation(double)") def setElevation(self, elevation): if elevation != self.elevationSpinBox.value(): self.elevationSpinBox.setValue(elevation) self.emit(SIGNAL("elevationChanged(double)"), elevation) elevation = pyqtProperty("double", elevation, setElevation)
def __init__(self, parameter, parent=None): """Constructor. :param parameter: A GroupSelectParameter object. :type parameter: GroupSelectParameter """ QWidget.__init__(self, parent) self._parameter = parameter # Store spin box self.spin_boxes = {} # Create elements # Label (name) self.label = QLabel(self._parameter.name) # Layouts self.main_layout = QVBoxLayout() self.input_layout = QVBoxLayout() # _inner_input_layout must be filled with widget in the child class self.inner_input_layout = QVBoxLayout() self.radio_button_layout = QGridLayout() # Create radio button group self.input_button_group = QButtonGroup() # List widget self.list_widget = QListWidget() self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list_widget.setDragDropMode(QAbstractItemView.DragDrop) self.list_widget.setDefaultDropAction(Qt.MoveAction) self.list_widget.setEnabled(False) self.list_widget.setSizePolicy( QSizePolicy.Maximum, QSizePolicy.Expanding) for i, key in enumerate(self._parameter.options): value = self._parameter.options[key] radio_button = QRadioButton(value.get('label')) self.radio_button_layout.addWidget(radio_button, i, 0) if value.get('type') == SINGLE_DYNAMIC: double_spin_box = QDoubleSpinBox() self.radio_button_layout.addWidget(double_spin_box, i, 1) double_spin_box.setValue(value.get('value', 0)) double_spin_box.setMinimum( value.get('constraint', {}).get('min', 0)) double_spin_box.setMaximum(value.get( 'constraint', {}).get('max', 1)) double_spin_box.setSingleStep( value.get('constraint', {}).get('step', 0.01)) step = double_spin_box.singleStep() if step > 1: precision = 0 else: precision = len(str(step).split('.')[1]) if precision > 3: precision = 3 double_spin_box.setDecimals(precision) self.spin_boxes[key] = double_spin_box # Enable spin box depends on the selected option if self._parameter.selected == key: double_spin_box.setEnabled(True) else: double_spin_box.setEnabled(False) elif value.get('type') == STATIC: static_value = value.get('value', 0) if static_value is not None: self.radio_button_layout.addWidget( QLabel(str(static_value)), i, 1) elif value.get('type') == MULTIPLE_DYNAMIC: selected_fields = value.get('value', []) if self._parameter.selected == key: self.list_widget.setEnabled(True) else: self.list_widget.setEnabled(False) self.input_button_group.addButton(radio_button, i) if self._parameter.selected == key: radio_button.setChecked(True) # Help text self.help_label = QLabel(self._parameter.help_text) self.help_label.setSizePolicy( QSizePolicy.Maximum, QSizePolicy.Expanding) self.help_label.setWordWrap(True) self.help_label.setAlignment(Qt.AlignTop) self.inner_input_layout.addLayout(self.radio_button_layout) self.inner_input_layout.addWidget(self.list_widget) # Put elements into layouts self.input_layout.addWidget(self.label) self.input_layout.addLayout(self.inner_input_layout) self.help_layout = QVBoxLayout() self.help_layout.addWidget(self.help_label) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) self.setLayout(self.main_layout) self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) # Update list widget self.update_list_widget() # Connect signal self.input_button_group.buttonClicked.connect( self.radio_buttons_clicked)
class AnalogConfigLayout(QFormLayout): rangeChanged = pyqtSignal() def __init__(self, showSampleRateSb=False, settings=None, parent=None): super(AnalogConfigLayout, self).__init__(parent) self.deviceCombo = QComboBox() self.deviceCombo.setObjectName('deviceCombo') self.addRow('&Device', self.deviceCombo) self.channelCombo = QComboBox() self.channelCombo.setObjectName('channelCombo') self.addRow('&Channel', self.channelCombo) self.rangeCombo = QComboBox() self.rangeCombo.setObjectName('rangeCombo') self.addRow('&Range', self.rangeCombo) if showSampleRateSb: self.sampleRateSb = QDoubleSpinBox() self.sampleRateSb.setSuffix(' kHz') self.sampleRateSb.setMinimum(0.001) self.sampleRateSb.setDecimals(3) self.sampleRateSb.setValue(1) self.sampleRateSb.setObjectName('sampleRateSb') self.addRow('&Sample rate', self.sampleRateSb) else: self.sampleRateSb = None self._ranges = [] self.deviceCombo.currentIndexChanged.connect(self.deviceChanged) self.populateDevices() self.rangeCombo.currentIndexChanged.connect(self.rangeChanged) self.deviceCombo.setContextMenuPolicy(Qt.CustomContextMenu) self.deviceCombo.customContextMenuRequested.connect(self.contextMenu) def contextMenu(self, point): globalPos = self.deviceCombo.mapToGlobal(point) menu = QMenu() refreshAction = QAction("&Refresh", menu) menu.addAction(refreshAction) selected = menu.exec_(globalPos) if selected == refreshAction: self.populateDevices() def populateDevices(self): self.deviceCombo.clear() system = daq.System() devices = system.findDevices() for dev in devices: self.deviceCombo.addItem(dev) def deviceChanged(self): self.channelCombo.clear() for channel in self.channels(): self.channelCombo.addItem(channel) self.rangeCombo.clear() self._ranges = self.ranges() for r in self._ranges: self.rangeCombo.addItem('%+.2f -> %+.2f V' % (r.min, r.max)) if self.sampleRateSb is not None: fmax = self.maxSampleRate() self.sampleRateSb.setMaximum(1E-3 * fmax) def maxSampleRate(self): raise NotImplementedError def device(self): t = self.deviceCombo.currentText() if len(t): return str(t) else: return None def channel(self): return str(self.channelCombo.currentText()) def voltageRange(self): i = self.rangeCombo.currentIndex() return None if i < 0 else self._ranges[i] def restoreSettings(self, s=None): if s is None: s = QSettings() try: device = s.value('device', '', type=str) i = self.deviceCombo.findText(device) self.deviceCombo.setCurrentIndex(i) except: pass channel = s.value('channel', '', type=str) i = self.channelCombo.findText(channel) self.channelCombo.setCurrentIndex(i) voltageRange = s.value('range', '', type=str) i = self.rangeCombo.findText(voltageRange) self.rangeCombo.setCurrentIndex(i) def saveSettings(self, s=None): if s is None: s = QSettings() s.setValue('device', self.device()) s.setValue('channel', self.channel()) s.setValue('range', self.rangeCombo.currentText())
class 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()
class IntersectDistanceDialog(QDialog): """ Dialog class to choose the circle radius """ def __init__(self, mapPoint): """ Constructor :param mapPoint: map point intersection """ QDialog.__init__(self) self.__mapPoint = mapPoint self.setWindowTitle(QCoreApplication.translate("VDLTools", "Choose radius")) self.resize(275, 177) self.__gridLayout = QGridLayout() self.__label = QLabel(QCoreApplication.translate("VDLTools", "Radius")) self.__gridLayout.addWidget(self.__label, 2, 1, 1, 1) self.__observation = QDoubleSpinBox() self.__observation.setDecimals(4) self.__observation.setMaximum(999999.99) self.__observation.setSingleStep(1.0) self.__gridLayout.addWidget(self.__observation, 2, 2, 1, 1) self.__label_3 = QLabel("m") self.__gridLayout.addWidget(self.__label_3, 2, 3, 1, 1) self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__gridLayout.addWidget(self.__okButton, 5, 1) self.__gridLayout.addWidget(self.__cancelButton, 5, 2) self.__label_5 = QLabel("y") self.__gridLayout.addWidget(self.__label_5, 1, 1, 1, 1) self.__label_6 = QLabel("x") self.__gridLayout.addWidget(self.__label_6, 0, 1, 1, 1) self.__x = QLineEdit("x") self.__x.setText(str(self.__mapPoint.x())) self.__x.setEnabled(False) self.__gridLayout.addWidget(self.__x, 0, 2, 1, 2) self.__y = QLineEdit("y") self.__y.setText(str(self.__mapPoint.y())) self.__y.setEnabled(False) self.__gridLayout.addWidget(self.__y, 1, 2, 1, 2) self.setLayout(self.__gridLayout) def observation(self): """ To get the circle radius edit widget :return: circle radius edit widget """ return self.__observation def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def mapPoint(self): """ To get the map point intersection :return: map point intersection """ return self.__mapPoint
class MainWindow(QWidget): # set up signals resetClicked = pyqtSignal() inputChanged = pyqtSignal() input_one = None def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # -------------------------------------------------------- # main window self.setObjectName("Multiply") self.resize(400, 300) # label self.label = QLabel(self) self.label.setGeometry(QRect(20, 10, 250, 50)) self.label.setText("Multiply two numbers!") # self.label.show() # input frame self.input_frame = QFrame(self) self.input_frame.setGeometry(QRect(20, 60, 350, 130)) self.input_frame.setFrameShape(QFrame.StyledPanel) self.input_frame.setFrameShadow(QFrame.Raised) # set the layout of the frame self.verticalLayout = QVBoxLayout(self.input_frame) self.verticalLayout.setObjectName("verticalLayout") # first input self.input_one = QDoubleSpinBox(self.input_frame) self.input_one.setObjectName("input_one") self.input_one.setDecimals(4) self.input_one.setSingleStep(0.01) self.verticalLayout.addWidget(self.input_one) # second input self.input_two = QDoubleSpinBox(self.input_frame) self.input_two.setObjectName("input_two") self.input_two.setDecimals(4) self.input_two.setSingleStep(0.01) self.verticalLayout.addWidget(self.input_two) # LCD result self.result_lcd = QLCDNumber(self) self.result_lcd.setObjectName("result_lcd") self.result_lcd.setGeometry(QRect(20, 200, 350, 80)) self.result_lcd.setDigitCount(10) self.result_lcd.setSmallDecimalPoint(True) # Reset Button self.reset_button = QPushButton(self) self.reset_button.setGeometry(QRect(270, 10, 100, 30)) self.reset_button.setObjectName("reset_button") self.reset_button.setText("Reset") # -------------------------------------------------------- # connect slots self.reset_button.clicked.connect(self.onResetClick) self.input_one.valueChanged.connect(self.onInputChanged) self.input_two.valueChanged.connect(self.onInputChanged) # define slots def onResetClick(self): self.resetClicked.emit() def onInputChanged(self): self.inputChanged.emit() def setResult(self, value): self.result_lcd.display(value)
class AnimationWindow(PyDialog): """ +-------------------+ | Animation | +-------------------------+ | icase ______ | | scale ______ Default | | time ______ Default | | | | nframes ______ Default | | resolu. ______ Default | | Dir ______ Browse | | iFrame ______ | | | | Animations: | | o Scale, Phase, Time | # TODO: add time | | | x delete images | | x repeat | # TODO: change to an integer | x make gif | | | | Step, RunAll | | Close | +-------------------------+ TODO: add key-frame support """ def __init__(self, data, win_parent=None): PyDialog.__init__(self, data, win_parent) self.set_font_size(data['font_size']) self.istep = 0 self._animate_type = 'time' self._updated_animation = False self._icase = data['icase'] self._default_name = data['name'] self._default_time = data['time'] self._default_fps = data['frames/sec'] self._default_resolution = data['resolution'] self._scale = data['scale'] self._default_scale = data['default_scale'] self._default_is_scale = data['is_scale'] self._phase = data['phase'] self._default_phase = data['default_phase'] self._default_dirname = data['dirname'] self._default_gif_name = os.path.join(self._default_dirname, data['name'] + '.gif') self.animation_types = [ 'Animate Scale', ] #'Animate Phase', #'Animate Time', #'Animate Frequency Sweep' #] self.setWindowTitle('Animate Model') self.create_widgets() self.create_layout() self.set_connections() self.is_gui = False if hasattr(self.win_parent, '_updated_legend'): self.win_parent.is_animate_open = True self.is_gui = True def create_widgets(self): """creates the menu objects""" icase_max = 1000 # TODO: update 1000 self.icase = QLabel("iCase:") self.icase_edit = QSpinBox(self) self.icase_edit.setRange(1, icase_max) self.icase_edit.setSingleStep(1) self.icase_edit.setValue(self._icase) self.icase_edit.setToolTip( 'Case Number for the Scale/Phase Animation Type.\n' 'Defaults to the result you had shown when you clicked "Create Animation".\n' 'iCase can be seen by clicking "Apply" on a result.') self.scale = QLabel("Scale:") self.scale_edit = QLineEdit(str(self._scale)) self.scale_button = QPushButton("Default") self.scale_edit.setToolTip('Scale factor of the "deflection"') self.scale_button.setToolTip('Sets the scale factor of the gif to %s' % self._scale) self.time = QLabel("Total Time (sec):") self.time_edit = QDoubleSpinBox(self) self.time_edit.setValue(self._default_time) self.time_edit.setRange(0.1, 10.0) self.time_edit.setDecimals(2) self.time_edit.setSingleStep(0.1) self.time_button = QPushButton("Default") self.time_edit.setToolTip("Total time of the gif") self.time_button.setToolTip('Sets the total time of the gif to %.2f' % self._default_time) self.fps = QLabel("Frames/Second:") self.fps_edit = QSpinBox(self) self.fps_edit.setRange(1, 60) self.fps_edit.setSingleStep(1) self.fps_edit.setValue(self._default_fps) self.fps_button = QPushButton("Default") self.fps_edit.setToolTip( "A higher FPS is smoother, but may not play well for large gifs") self.fps_button.setToolTip('Sets the FPS to %s' % self._default_fps) self.resolution = QLabel("Resolution Scale:") self.resolution_edit = QSpinBox(self) self.resolution_edit.setRange(1, 5) self.resolution_edit.setSingleStep(1) self.resolution_edit.setValue(self._default_resolution) self.resolution_button = QPushButton("Default") self.resolution_edit.setToolTip( 'Scales the window resolution by an integer factor') self.resolution_button.setToolTip('Sets the resolution to %s' % self._default_resolution) #----------------- # Time plot self.icase_start = QLabel("iCase Start:") self.icase_start_edit = QSpinBox(self) self.icase_start_edit.setRange(0, icase_max) self.icase_start_edit.setSingleStep(1) self.icase_start_edit.setValue(self._icase) self.icase_start_button = QPushButton("Default") self.icase_end = QLabel("iCase End:") self.icase_end_edit = QSpinBox(self) self.icase_end_edit.setRange(0, icase_max) self.icase_end_edit.setSingleStep(1) self.icase_end_edit.setValue(self._icase) self.icase_end_button = QPushButton("Default") self.icase_delta = QLabel("iCase Delta:") self.icase_delta_edit = QSpinBox(self) self.icase_delta_edit.setRange(1, icase_max) self.icase_delta_edit.setSingleStep(1) self.icase_delta_edit.setValue(1) self.icase_delta_button = QPushButton("Default") self.min_value = QLabel("Min Value:") self.min_value_edit = QLineEdit(str(0.)) #self.min_value_edit.setRange(1, 1000) #self.min_value_edit.setSingleStep(1) #self.min_value_edit.setValue(1) self.min_value_button = QPushButton("Default") self.max_value = QLabel("Max Value:") self.max_value_edit = QLineEdit(str(1.)) #self.min_value_edit.setRange(1, 1000) # TODO: update 1000 #self.min_value_edit.setSingleStep(1) #self.min_value_edit.setValue(1) self.max_value_button = QPushButton("Default") self.icase_start_edit.setToolTip('The first frame of the animation') self.icase_end_edit.setToolTip( 'The last frame of the animation\n' 'Assumes icase_start + nframes * icase_delta = icase_end') self.icase_delta_edit.setToolTip( 'The frame step size (to skip non-consecutive results).\n' 'Frame skipping can be used to:\n' " - skip across results that you don't want to plot\n" ' - adjust the FPS') self.min_value_edit.setToolTip( 'Min value of the legend (not supported)') self.max_value_edit.setToolTip( 'Max value of the legend (not supported)') #'time' : 0., #'default_time' : 0, #'icase_start' : 10, #'icase_delta' : 3, #'min_value' : 0., #'max_value' : 1000., self.browse_folder = QLabel('Output Directory:') self.browse_folder_edit = QLineEdit(str(self._default_dirname)) self.browse_folder_button = QPushButton('Browse') self.browse_folder_edit.setToolTip( 'Location to save the png/gif files') self.gif = QLabel("Gif Filename:") self.gif_edit = QLineEdit(str(self._default_name + '.gif')) self.gif_button = QPushButton('Default') self.gif_edit.setToolTip('Name of the gif') self.gif_button.setToolTip('Sets the name of the gif to %s.gif' % self._default_name) # scale / phase self.animate_scale_radio = QRadioButton("Animate Scale") self.animate_phase_radio = QRadioButton("Animate Phase") self.animate_time_radio = QRadioButton("Animate Time") self.animate_freq_sweeep_radio = QRadioButton( "Animate Frequency Sweep") self.animate_scale_radio.setToolTip( 'Animates the scale factor based on the "Animation Type"') self.animate_time_radio.setToolTip('Animates the time/load/mode step') self.animate_scale_radio.setChecked(self._default_is_scale) self.animate_phase_radio.setChecked(not self._default_is_scale) self.animate_time_radio.setChecked(False) msg = 'Scale : Animates the scale factor based on the "Animation Profile"\n' if self._default_phase is None: self.animate_phase_radio.setDisabled(True) self.animate_phase_radio.setToolTip('Animates the phase angle ' '(only for complex results)') msg += 'Phase : Animates the phase angle (only for complex results)\n' else: self.animate_phase_radio.setToolTip("Animates the phase angle") msg += 'Phase : Animates the phase angle\n' msg += ( 'Time : Animates the time/load/mode step\n' 'Freq Sweep : Animates a complex result across a range of frequencies ' '(not supported)\n') self.animate_freq_sweeep_radio.setDisabled(True) self.animate_freq_sweeep_radio.setToolTip( 'Animates a complex result across a range of frequencies (not supported)' ) self.animation_type = QLabel("Animation Type:") animation_type = OrderedDict() #scale_msg = 'Scale\n' #phase_msg = 'Phase\n' #time_msg = 'Time\n' #animation_types = [ #('Animate Scale', scale_msg), #('Animate Phase', phase_msg), #('Animate Time', time_msg), ##'Animate Frequency Sweep' #] if self._phase is not None: self.animation_types.append('Animate Phase') self.animation_types.append('Animate Time') self.animation_profile = QLabel("Animation Profile:") self.animation_profile_edit = QComboBox() for animation_profile in ANIMATION_PROFILES: self.animation_profile_edit.addItem(animation_profile) self.animation_profile_edit.setToolTip('The profile for a scaled GIF') self.animation_type_edit = QComboBox() # TODO: add a tooltip for each item for animation_type in self.animation_types: self.animation_type_edit.addItem(animation_type) #self.animation_type_edit.setToolTip('The profile for a scaled GIF') self.animation_type_edit.setToolTip(msg) self.csv_profile = QLabel("CSV profile:") self.csv_profile_edit = QLineEdit() self.csv_profile_browse_button = QPushButton('Browse') self.csv_profile_edit.setToolTip( 'The path to the CSV file of (Scale1, Scale2, Scale3, ...)') widget = QWidget(self) horizontal_vertical_group = QButtonGroup(widget) horizontal_vertical_group.addButton(self.animate_scale_radio) horizontal_vertical_group.addButton(self.animate_phase_radio) horizontal_vertical_group.addButton(self.animate_time_radio) horizontal_vertical_group.addButton(self.animate_freq_sweeep_radio) # one / two sided self.onesided_radio = QRadioButton("One Sided") self.onesided_radio.setToolTip( "A one sided gif doesn't return to the starting point (e.g., 0 to 360 degrees)" ) self.twosided_radio = QRadioButton("Two Sided") self.twosided_radio.setToolTip( 'A two sided gif returns to the starting point (e.g., 0 to 10 to 0)' ) if self._default_phase is None: self.onesided_radio.setChecked(False) self.twosided_radio.setChecked(True) else: self.onesided_radio.setChecked(True) self.twosided_radio.setChecked(False) widget = QWidget(self) horizontal_vertical_group = QButtonGroup(widget) horizontal_vertical_group.addButton(self.onesided_radio) horizontal_vertical_group.addButton(self.twosided_radio) # animate in gui self.animate_in_gui_checkbox = QCheckBox("Animate In GUI?") self.animate_in_gui_checkbox.setChecked(True) # make images self.make_images_checkbox = QCheckBox("Make images?") self.make_images_checkbox.setChecked(True) # make images self.overwrite_images_checkbox = QCheckBox("Overwrite images?") self.overwrite_images_checkbox.setChecked(True) # delete images when finished self.delete_images_checkbox = QCheckBox("Delete images when finished?") self.delete_images_checkbox.setChecked(True) # endless loop self.repeat_checkbox = QCheckBox("Repeat?") self.repeat_checkbox.setChecked(True) self.repeat_checkbox.setToolTip( "Repeating creates an infinitely looping gif") # endless loop self.make_gif_checkbox = QCheckBox("Make Gif?") if IS_IMAGEIO: self.make_gif_checkbox.setChecked(True) else: self.make_gif_checkbox.setChecked(False) self.make_gif_checkbox.setEnabled(False) self.make_gif_checkbox.setToolTip( 'imageio is not available; install it') # bottom buttons self.step_button = QPushButton("Step") self.stop_button = QPushButton("Stop") self.run_button = QPushButton("Run All") #self.apply_button = QPushButton("Apply") #self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") #self.set_grid_time(enabled=False) #self.set_grid_scale(enabled=self._default_is_scale) if self._default_phase: self.on_animate_phase(force=True) else: self.on_animate_scale(force=True) def set_connections(self): """creates button actions""" self.scale_button.clicked.connect(self.on_default_scale) self.time_button.clicked.connect(self.on_default_time) self.fps_button.clicked.connect(self.on_default_fps) self.resolution_button.clicked.connect(self.on_default_resolution) self.browse_folder_button.clicked.connect(self.on_browse_folder) self.csv_profile_browse_button.clicked.connect(self.on_browse_csv) self.gif_button.clicked.connect(self.on_default_name) self.step_button.clicked.connect(self.on_step) self.stop_button.clicked.connect(self.on_stop) self.run_button.clicked.connect(self.on_run) #self.animate_scale_radio.clicked.connect(self.on_animate_scale) #self.animate_phase_radio.clicked.connect(self.on_animate_phase) #self.animate_time_radio.clicked.connect(self.on_animate_time) self.animation_type_edit.currentIndexChanged.connect(self.on_animate) #self.animate_freq_sweeep_radio #self.apply_button.clicked.connect(self.on_apply) #self.ok_button.clicked.connect(self.on_ok) self.cancel_button.clicked.connect(self.on_cancel) self.animate_in_gui_checkbox.clicked.connect(self.on_animate_in_gui) self.animate_in_gui_checkbox.setChecked(True) self.on_animate_in_gui() def on_animate_in_gui(self): animate_in_gui = self.animate_in_gui_checkbox.isChecked() enable = not animate_in_gui self.make_images_checkbox.setEnabled(enable) self.delete_images_checkbox.setEnabled(enable) self.make_gif_checkbox.setEnabled(enable) self.repeat_checkbox.setEnabled(enable) self.resolution_button.setEnabled(enable) self.resolution_edit.setEnabled(enable) self.gif_edit.setEnabled(enable) self.gif_button.setEnabled(enable) self.browse_folder_button.setEnabled(enable) self.browse_folder_edit.setEnabled(enable) self.step_button.setEnabled(enable) def on_animate(self, value): """ animate pulldown Parameters ---------- value : int index in animation_types """ #animation_types = ['Animate Scale', 'Animate Phase', 'Animate Time', #'Animate Frequency Sweep'] animation_type = self.animation_types[value] if animation_type == 'Animate Scale': self.on_animate_scale() elif animation_type == 'Animate Phase': self.on_animate_phase() elif animation_type == 'Animate Time': self.on_animate_time() else: raise NotImplementedError('value = ', value) def on_animate_time(self, force=False): """enables the secondary input""" #print('on_animate_time') if self._animate_type == 'scale' or force: self.set_grid_scale(False, 'time') self.set_grid_time(True, 'time') self._animate_type = 'time' def on_animate_scale(self, force=False): """enables the secondary input""" #print('on_animate_scale') self.set_grid_scale(True, 'scale') if self._animate_type == 'time' or force: self.set_grid_time(False, 'scale') self._animate_type = 'scale' def on_animate_phase(self, force=False): """enables the secondary input""" #print('on_animate_phase') if self._animate_type == 'scale' or force: self.set_grid_scale(False, 'phase') if self._animate_type == 'time' or force: self.set_grid_time(False, 'phase') self._animate_type = 'phase' def set_grid_scale(self, enabled=True, word=''): """enables/disables the secondary input""" #print('%s-set_grid_scale; enabled = %r' % (word, enabled)) self.animation_profile.setEnabled(enabled) self.animation_profile_edit.setEnabled(enabled) # TODO: doesn't work... #self.csv_profile.setEnabled(enabled) #self.csv_profile_edit.setEnabled(enabled) #self.csv_profile_button.setEnabled(enabled) def set_grid_time(self, enabled=True, word=''): """enables/disables the secondary input""" #print('%s-set_grid_time; enabled = %r' % (word, enabled)) self.icase_start.setEnabled(enabled) self.icase_start_edit.setEnabled(enabled) self.icase_start_button.setEnabled(enabled) self.icase_end.setEnabled(enabled) self.icase_end_edit.setEnabled(enabled) self.icase_end_button.setEnabled(enabled) self.icase_delta.setEnabled(enabled) self.icase_delta_edit.setEnabled(enabled) self.icase_delta_button.setEnabled(enabled) self.min_value.setEnabled(enabled) self.min_value_edit.setEnabled(enabled) self.min_value_button.setEnabled(enabled) self.max_value.setEnabled(enabled) self.max_value_edit.setEnabled(enabled) self.max_value_button.setEnabled(enabled) self.icase.setEnabled(not enabled) self.icase_edit.setEnabled(not enabled) self.fps.setEnabled(not enabled) self.fps_edit.setEnabled(not enabled) self.fps_button.setEnabled(not enabled) def on_browse_folder(self): """opens a folder dialog""" dirname = open_directory_dialog(self, 'Select a Directory') if not dirname: return self.browse_folder_edit.setText(dirname) def on_browse_csv(self): """opens a file dialog""" default_filename = '' file_types = 'Delimited Text (*.txt; *.dat; *.csv)' dirname = open_file_dialog(self, 'Select a CSV File', default_filename, file_types) if not dirname: return self.csv_profile_browse_button.setText(dirname) def on_default_name(self): """sets the default gif name""" self.gif_edit.setText(self._default_name + '.gif') def on_default_scale(self): """sets the default displacement scale factor""" self.scale_edit.setText(str(self._default_scale)) self.scale_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_time(self): """sets the default gif time""" self.time_edit.setValue(self._default_time) def on_default_fps(self): """sets the default FPS""" self.fps_edit.setValue(self._default_fps) def on_default_resolution(self): """sets the default image resolution scale factor""" self.resolution_edit.setValue(self._default_resolution) def create_layout(self): """displays the menu objects""" grid = QGridLayout() grid.addWidget(self.icase, 0, 0) grid.addWidget(self.icase_edit, 0, 1) grid.addWidget(self.scale, 1, 0) grid.addWidget(self.scale_edit, 1, 1) grid.addWidget(self.scale_button, 1, 2) grid.addWidget(self.time, 2, 0) grid.addWidget(self.time_edit, 2, 1) grid.addWidget(self.time_button, 2, 2) # spacer spacer = QLabel('') grid.addWidget(self.fps, 3, 0) grid.addWidget(self.fps_edit, 3, 1) grid.addWidget(self.fps_button, 3, 2) grid.addWidget(self.resolution, 4, 0) grid.addWidget(self.resolution_edit, 4, 1) grid.addWidget(self.resolution_button, 4, 2) grid.addWidget(self.browse_folder, 5, 0) grid.addWidget(self.browse_folder_edit, 5, 1) grid.addWidget(self.browse_folder_button, 5, 2) grid.addWidget(self.gif, 6, 0) grid.addWidget(self.gif_edit, 6, 1) grid.addWidget(self.gif_button, 6, 2) grid.addWidget(self.animation_type, 7, 0) grid.addWidget(self.animation_type_edit, 7, 1) grid.addWidget(spacer, 8, 0) #---------- #Time grid_time = QGridLayout() grid_time.addWidget(self.icase_start, 0, 0) grid_time.addWidget(self.icase_start_edit, 0, 1) #grid_time.addWidget(self.icase_start_button, 0, 2) grid_time.addWidget(self.icase_end, 1, 0) grid_time.addWidget(self.icase_end_edit, 1, 1) #grid_time.addWidget(self.icase_end_button, 1, 2) grid_time.addWidget(self.icase_delta, 2, 0) grid_time.addWidget(self.icase_delta_edit, 2, 1) #grid_time.addWidget(self.icase_delta_button, 2, 2) #grid_time.addWidget(self.min_value, 3, 0) #grid_time.addWidget(self.min_value_edit, 3, 1) #grid_time.addWidget(self.min_value_button, 3, 2) #grid_time.addWidget(self.max_value, 4, 0) #grid_time.addWidget(self.max_value_edit, 4, 1) #grid_time.addWidget(self.max_value_button, 4, 2) grid_time.addWidget(spacer, 5, 0) #-------------- grid_scale = QGridLayout() grid_scale.addWidget(self.animation_profile, 0, 0) grid_scale.addWidget(self.animation_profile_edit, 0, 1) #grid_scale.addWidget(self.csv_profile, 1, 0) #grid_scale.addWidget(self.csv_profile_edit, 1, 1) #grid_scale.addWidget(self.csv_profile_browse_button, 1, 2) self.csv_profile = QLabel("CSV profile:") self.csv_profile_edit = QLineEdit() self.csv_profile_button = QPushButton('Browse') #box_time = QVBoxLayout() # TODO: It's super annoying that the animate time box doesn't # line up with the previous box box_scale = QGroupBox('Animate Scale') box_scale.setLayout(grid_scale) box_time = QGroupBox('Animate Time') box_time.setLayout(grid_time) #---------- grid2 = QGridLayout() #grid2.addWidget(self.animate_scale_radio, 8, 0) #grid2.addWidget(self.animate_phase_radio, 8, 1) #grid2.addWidget(self.animate_time_radio, 8, 2) #grid2.addWidget(self.animate_freq_sweeep_radio, 8, 3) grid2.addWidget(self.animate_in_gui_checkbox, 10, 0) grid2.addWidget(self.make_images_checkbox, 11, 0) #grid2.addWidget(self.overwrite_images_checkbox, 11, 0) grid2.addWidget(self.delete_images_checkbox, 11, 1) grid2.addWidget(self.make_gif_checkbox, 11, 2) grid2.addWidget(self.repeat_checkbox, 12, 0) grid2.addWidget(spacer, 13, 0) grid_hbox = QHBoxLayout() grid_hbox.addWidget(spacer) grid_hbox.addLayout(grid2) grid_hbox.addWidget(spacer) # bottom buttons step_run_box = QHBoxLayout() step_run_box.addWidget(self.step_button) step_run_box.addWidget(self.stop_button) step_run_box.addWidget(self.run_button) ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addWidget(box_scale) vbox.addWidget(box_time) #vbox.addLayout(checkboxes) vbox.addLayout(grid_hbox) vbox.addStretch() vbox.addLayout(step_run_box) vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def on_step(self): """click the Step button""" passed, validate_out = self.on_validate() if passed: try: self._make_gif(validate_out, istep=self.istep) self.istep += 1 except IndexError: self._make_gif(validate_out, istep=0) self.istep += 1 def on_stop(self): passed, validate_out = self.on_validate() if passed: self._make_gif(validate_out, stop_animation=True) def on_run(self): """click the Run button""" self.istep = 0 passed, validate_out = self.on_validate() if passed: self._make_gif(validate_out, istep=None) return passed def _make_gif(self, validate_out, istep=None, stop_animation=False): """interface for making the gif""" icase, scale, time, fps, animate_in_gui, magnify, output_dir, gifbase = validate_out gif_filename = None if not stop_animation and not animate_in_gui: if gifbase.lower().endswith('.gif'): gifbase = gifbase[:-4] gif_filename = os.path.join(output_dir, gifbase + '.gif') animate_scale = self.animate_scale_radio.isChecked() animate_phase = self.animate_phase_radio.isChecked() animate_time = self.animate_time_radio.isChecked() animate_scale = False animate_phase = False animate_time = False if self._animate_type == 'scale': animate_scale = True elif self._animate_type == 'phase': animate_phase = True elif self._animate_type == 'time': animate_time = True else: raise NotImplementedError(self._animate_type) make_images = self.make_images_checkbox.isChecked() delete_images = self.delete_images_checkbox.isChecked() make_gif = self.make_gif_checkbox.isChecked() key = str(self.animation_profile_edit.currentText()) #profile = ANIMATION_PROFILES[key] #ANIMATION_PROFILES['0 to Scale'] = [0., 1.] #ANIMATION_PROFILES['0 to Scale to 0'] = [0., 1., 0.] if key == '0 to Scale': onesided = True else: onesided = False icase_start = self.icase_start_edit.value() icase_end = self.icase_end_edit.value() icase_delta = self.icase_delta_edit.value() #onesided = self.onesided_radio.isChecked() bool_repeat = self.repeat_checkbox.isChecked( ) # TODO: change this to an integer if bool_repeat: nrepeat = 0 else: nrepeat = 1 #self.out_data['is_shown'] = self.show_radio.isChecked() #icase = self._icase if self.is_gui: self.win_parent.win_parent.make_gif( gif_filename, scale, istep=istep, animate_scale=animate_scale, animate_phase=animate_phase, animate_time=animate_time, icase=icase, icase_start=icase_start, icase_end=icase_end, icase_delta=icase_delta, time=time, onesided=onesided, nrepeat=nrepeat, fps=fps, magnify=magnify, make_images=make_images, delete_images=delete_images, make_gif=make_gif, stop_animation=stop_animation, animate_in_gui=animate_in_gui, ) self.out_data['clicked_ok'] = True self.out_data['close'] = True def on_validate(self): """checks to see if the input is valid""" icase, flag0 = self.check_int(self.icase_edit) scale, flag1 = self.check_float(self.scale_edit) time, flag2 = self.check_float(self.time_edit) fps, flag3 = self.check_float(self.fps_edit) animate_in_gui = self.animate_in_gui_checkbox.isChecked() if animate_in_gui: passed = all([flag0, flag1, flag2, flag3]) return passed, (icase, scale, time, fps, animate_in_gui, None, None, None) magnify, flag4 = self.check_int(self.resolution_edit) output_dir, flag5 = self.check_path(self.browse_folder_edit) gifbase, flag6 = self.check_name(self.gif_edit) passed = all([flag0, flag1, flag2, flag3, flag4, flag5, flag6]) return passed, (icase, scale, time, fps, animate_in_gui, magnify, output_dir, gifbase) @staticmethod def check_name(cell): """verifies that the data is string-able""" cell_value = cell.text() try: text = str(cell_value).strip() except UnicodeEncodeError: cell.setStyleSheet("QLineEdit{background: red;}") return None, False if len(text): cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False def check_path(self, cell): """verifies that the path exists""" text, passed = self.check_name(cell) if not passed: return None, False if os.path.exists(text): cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False #def on_ok(self): #"""click the OK button""" #passed = self.on_apply() #if passed: #self.win_parent._animation_window_shown = False #self.close() ##self.destroy() def on_cancel(self): """click the Cancel button""" self.on_stop() self.out_data['close'] = True self.close()
class GeoLocationWidget(QWidget): """GeoLocationWidget(QWidget) Provides a custom geographical location widget. """ __pyqtSignals__ = ("latitudeChanged(double)", "longitudeChanged(double)", "elevationChanged(double)") def __init__(self, parent=None): super().__init__(parent) latitudeLabel = QLabel(self.tr("Latitude:")) self.latitudeSpinBox = QDoubleSpinBox() self.latitudeSpinBox.setRange(-90.0, 90.0) self.latitudeSpinBox.setDecimals(5) self.latitudeSpinBox.setSuffix(" degrees") self.latitudeSpinBox.setToolTip( "How far north or sourth you are from the equator. Must be between -90 and 90." ) longitudeLabel = QLabel(self.tr("Longitude:")) self.longitudeSpinBox = QDoubleSpinBox() self.longitudeSpinBox.setRange(-180.0, 180.0) self.longitudeSpinBox.setDecimals(5) self.longitudeSpinBox.setSuffix(" degrees") self.longitudeSpinBox.setToolTip( "How far west or east you are from the meridian. Must be between -180 and 180." ) elevationLabel = QLabel(self.tr("Elevation")) self.elevationSpinBox = QDoubleSpinBox() self.elevationSpinBox.setRange(-418.0, 8850.0) self.elevationSpinBox.setDecimals(5) self.elevationSpinBox.setSuffix(" m") self.elevationSpinBox.setToolTip( "The distance from sea level in meters. Must be between -418 and 8850." ) self.connect(self.latitudeSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("latitudeChanged(double)")) self.connect(self.longitudeSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("longitudeChanged(double)")) self.connect(self.elevationSpinBox, SIGNAL("valueChanged(double)"), self, SIGNAL("elevationChanged(double)")) layout = QGridLayout(self) layout.addWidget(latitudeLabel, 0, 0) layout.addWidget(self.latitudeSpinBox, 1, 0) layout.addWidget(longitudeLabel, 0, 1) layout.addWidget(self.longitudeSpinBox, 1, 1) layout.addWidget(elevationLabel, 0, 2) layout.addWidget(self.elevationSpinBox, 1, 2) # The latitude property is implemented with the latitude() and setLatitude() # methods, and contains the latitude of the user. def latitude(self): return self.latitudeSpinBox.value() @pyqtSignature("setLatitude(double)") def setLatitude(self, latitude): if latitude != self.latitudeSpinBox.value(): self.latitudeSpinBox.setValue(latitude) self.emit(SIGNAL("latitudeChanged(double)"), latitude) latitude = pyqtProperty("double", latitude, setLatitude) # The longitude property is implemented with the longitude() and setlongitude() # methods, and contains the longitude of the user. def longitude(self): return self.longitudeSpinBox.value() @pyqtSignature("setLongitude(double)") def setLongitude(self, longitude): if longitude != self.longitudeSpinBox.value(): self.longitudeSpinBox.setValue(longitude) self.emit(SIGNAL("longitudeChanged(double)"), longitude) longitude = pyqtProperty("double", longitude, setLongitude) def elevation(self): return self.elevationSpinBox.value() @pyqtSignature("setElevation(double)") def setElevation(self, elevation): if elevation != self.elevationSpinBox.value(): self.elevationSpinBox.setValue(elevation) self.emit(SIGNAL("elevationChanged(double)"), elevation) elevation = pyqtProperty("double", elevation, setElevation)
def __init__(self, parameter, parent=None): """Constructor. :param parameter: A GroupSelectParameter object. :type parameter: GroupSelectParameter """ QWidget.__init__(self, parent) self._parameter = parameter # Store spin box self.spin_boxes = {} # Create elements # Label (name) self.label = QLabel(self._parameter.name) # Layouts self.main_layout = QVBoxLayout() self.input_layout = QVBoxLayout() # _inner_input_layout must be filled with widget in the child class self.inner_input_layout = QVBoxLayout() self.radio_button_layout = QGridLayout() # Create radio button group self.input_button_group = QButtonGroup() # List widget self.list_widget = QListWidget() self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list_widget.setDragDropMode(QAbstractItemView.DragDrop) self.list_widget.setDefaultDropAction(Qt.MoveAction) self.list_widget.setEnabled(False) self.list_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) for i, key in enumerate(self._parameter.options): value = self._parameter.options[key] radio_button = QRadioButton(value.get('label')) self.radio_button_layout.addWidget(radio_button, i, 0) if value.get('type') == SINGLE_DYNAMIC: double_spin_box = QDoubleSpinBox() self.radio_button_layout.addWidget(double_spin_box, i, 1) double_spin_box.setValue(value.get('value', 0)) double_spin_box.setMinimum( value.get('constraint', {}).get('min', 0)) double_spin_box.setMaximum( value.get('constraint', {}).get('max', 1)) double_spin_box.setSingleStep( value.get('constraint', {}).get('step', 0.01)) step = double_spin_box.singleStep() if step > 1: precision = 0 else: precision = len(str(step).split('.')[1]) if precision > 3: precision = 3 double_spin_box.setDecimals(precision) self.spin_boxes[key] = double_spin_box # Enable spin box depends on the selected option if self._parameter.selected == key: double_spin_box.setEnabled(True) else: double_spin_box.setEnabled(False) elif value.get('type') == STATIC: static_value = value.get('value', 0) if static_value is not None: self.radio_button_layout.addWidget( QLabel(str(static_value)), i, 1) elif value.get('type') == MULTIPLE_DYNAMIC: selected_fields = value.get('value', []) if self._parameter.selected == key: self.list_widget.setEnabled(True) else: self.list_widget.setEnabled(False) self.input_button_group.addButton(radio_button, i) if self._parameter.selected == key: radio_button.setChecked(True) # Help text self.help_label = QLabel(self._parameter.help_text) self.help_label.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) self.help_label.setWordWrap(True) self.help_label.setAlignment(Qt.AlignTop) self.inner_input_layout.addLayout(self.radio_button_layout) self.inner_input_layout.addWidget(self.list_widget) # Put elements into layouts self.input_layout.addWidget(self.label) self.input_layout.addLayout(self.inner_input_layout) self.help_layout = QVBoxLayout() self.help_layout.addWidget(self.help_label) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) self.setLayout(self.main_layout) self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding) # Update list widget self.update_list_widget() # Connect signal self.input_button_group.buttonClicked.connect( self.radio_buttons_clicked)
class ModifyLabelPropertiesMenu(QDialog): def __init__(self, data, win_parent=None): self.win_parent = win_parent float_color = data['color'] assert len(float_color) == 3, float_color assert isinstance(float_color[0], float), float_color self.float_color = float_color self.int_color = [int(colori * 255) for colori in float_color] assert isinstance(self.float_color[0], float), self.float_color assert isinstance(self.int_color[0], int), self.int_color self._size = data['size'] self.out_data = data self.dim_max = data['dim_max'] QDialog.__init__(self, win_parent) self.setWindowTitle('Modify Label Properties') self.create_widgets() self.create_layout() self.set_connections() width = 260 height = 130 self.resize(width, height) #self.show() def create_widgets(self): # Min self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) qcolor = QtGui.QColor() qcolor.setRgb(*self.int_color) palette = QtGui.QPalette(self.color_edit.palette()) palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue')) self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(self.int_color) + #"border:1px solid rgb(255, 170, 255); " "}") # Size self.size = QLabel("Size:") self.size_edit = QDoubleSpinBox(self) self.size_edit.setRange(0.0, self.dim_max) log_dim = log10(self.dim_max) decimals = int(ceil(abs(log_dim))) decimals = max(6, decimals) self.size_edit.setDecimals(decimals) #self.size_edit.setSingleStep(self.dim_max / 100.) self.size_edit.setSingleStep(self.dim_max / 1000.) self.size_edit.setValue(self._size) # closing #self.apply_button = QPushButton("Apply") #self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") def create_layout(self): grid = QGridLayout() grid.addWidget(self.color, 0, 0) grid.addWidget(self.color_edit, 0, 1) #grid.addWidget(self.min_button, 0, 2) grid.addWidget(self.size, 1, 0) grid.addWidget(self.size_edit, 1, 1) ok_cancel_box = QHBoxLayout() #ok_cancel_box.addWidget(self.apply_button) #ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addStretch() vbox.addLayout(ok_cancel_box) self.setLayout(vbox) self.layout() def on_color(self): rgb_color_ints = self.int_color col = QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a label color") if col.isValid(): float_color = col.getRgbF()[:3] # floats self.int_color = [int(colori * 255) for colori in float_color] self.float_color = float_color assert isinstance(self.float_color[0], float), self.float_color assert isinstance(self.int_color[0], int), self.int_color self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(self.int_color) + #"border:1px solid rgb(255, 170, 255); " "}") self.on_apply(force=True) #def on_color(self): #pass def set_connections(self): self.size_edit.valueChanged.connect(self.on_size) if qt_version == 4: self.connect(self.size_edit, QtCore.SIGNAL('editingFinished()'), self.on_size) self.connect(self.size_edit, QtCore.SIGNAL('valueChanged()'), self.on_size) self.connect(self.size_edit, QtCore.SIGNAL('clicked()'), self.on_size) self.connect(self.color_edit, QtCore.SIGNAL('clicked()'), self.on_color) #self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) #self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) else: self.size_edit.editingFinished.connect(self.on_size) self.size_edit.valueChanged.connect(self.on_size) #self.size_edit.clicked self.color_edit.clicked.connect(self.on_color) 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.out_data['close'] = True event.accept() def on_size(self): self._size = float(self.size_edit.text()) self.on_apply(force=True) #self.min_edit.setText(str(self._default_min)) #self.min_edit.setStyleSheet("QLineEdit{background: white;}") @staticmethod def check_float(cell): text = cell.text() value = float(text) return value, True #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 on_validate(self): size_value, flag0 = self.check_float(self.size_edit) assert isinstance(self.float_color[0], float), self.float_color assert isinstance(self.int_color[0], int), self.int_color if flag0: self._size = size_value #self.out_data['min'] = min(min_value, max_value) #self.out_data['max'] = max(min_value, max_value) self.out_data['clicked_ok'] = True return True return False def on_apply(self, force=False): passed = self.on_validate() if (passed or Force) and self.win_parent is not None: self.win_parent.set_labelsize_color(self._size, self.float_color) return passed def on_ok(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False self.out_data['close'] = True passed = self.on_apply() if passed: self.close() #self.destroy() def on_cancel(self): self.out_data['clicked_cancel'] = True self.out_data['close'] = True self.close()
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 LogTool(preferences.Group): def __init__(self, page): super(LogTool, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) self.showlog = QCheckBox(toggled=self.changed) layout.addWidget(self.showlog) self.rawview = QCheckBox(toggled=self.changed) layout.addWidget(self.rawview) self.hideauto = QCheckBox(toggled=self.changed) layout.addWidget(self.hideauto) app.translateUI(self) def translateUI(self): self.setTitle(_("LilyPond Log")) self.fontLabel.setText(_("Font:")) self.showlog.setText(_("Show log when a job is started")) self.rawview.setText(_("Display plain log output")) self.rawview.setToolTip( _("If checked, Frescobaldi will not shorten filenames in the log output." "")) self.hideauto.setText(_("Hide automatic engraving jobs")) self.hideauto.setToolTip( _("If checked, Frescobaldi will not show the log for automatically\n" "started engraving jobs (LilyPond->Auto-engrave).")) def loadSettings(self): s = QSettings() s.beginGroup("log") font = QFont(s.value("fontfamily", "monospace", type(""))) font.setPointSizeF(s.value("fontsize", 9.0, float)) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) self.showlog.setChecked(s.value("show_on_start", True, bool)) self.rawview.setChecked(s.value("rawview", True, bool)) self.hideauto.setChecked(s.value("hide_auto_engrave", False, bool)) def saveSettings(self): s = QSettings() s.beginGroup("log") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value()) s.setValue("show_on_start", self.showlog.isChecked()) s.setValue("rawview", self.rawview.isChecked()) s.setValue("hide_auto_engrave", self.hideauto.isChecked())
class CADOptionsToolbar_Arc(CADOptionsToolbar): def __init__(self, layer): super(CADOptionsToolbar_Arc, self).__init__() self.settings = QSettings() self.arc_featurePitch = self.settings.value("/CADDigitize/arc/pitch", 2, type=float) self.arc_featureAngle = self.settings.value("/CADDigitize/arc/angle", 1, type=int) self.arc_method = self.settings.value("/CADDigitize/arc/method", "pitch", type=str) self.arc_angleDirection = self.settings.value( "/CADDigitize/arc/direction", "ClockWise", type=str) if layer.geometryType() == 2: self.arc_polygonCreation = self.settings.value( "/CADDigitize/arc/polygon", "pie") self.ArcPolygonCombo = QComboBox(self.optionsToolBar) self.ArcPolygonCombo.addItems([ tr(u"Pie segment"), tr(u"Chord")]) self.ArcPolygonComboAction = self.optionsToolBar.addWidget( self.ArcPolygonCombo) if self.arc_polygonCreation == "pie": self.ArcPolygonCombo.setCurrentIndex(0) else: self.ArcPolygonCombo.setCurrentIndex(1) self.ArcPolygonCombo.currentIndexChanged["int"].connect( self.polygonArc) self.ArcAngleDirectionCombo = QComboBox(self.optionsToolBar) self.ArcAngleDirectionCombo.addItems([ tr(u"ClockWise"), tr(u"CounterClockWise")]) self.ArcAngleDirectionComboAction = self.optionsToolBar.addWidget( self.ArcAngleDirectionCombo) self.ArcFeatureCombo = QComboBox(self.optionsToolBar) self.ArcFeatureCombo.addItems([ tr(u"Pitch"), tr(u"Angle")]) self.ArcFeatureComboAction = self.optionsToolBar.addWidget( self.ArcFeatureCombo) self.ArcPitchSpin = QDoubleSpinBox(self.optionsToolBar) self.ArcPitchSpin.setMinimum(1) self.ArcPitchSpin.setMaximum(1000) self.ArcPitchSpin.setDecimals(1) self.ArcPitchSpin.setValue(self.arc_featurePitch) self.ArcPitchSpinAction = self.optionsToolBar.addWidget( self.ArcPitchSpin) self.ArcPitchSpin.setToolTip(tr(u"Pitch")) self.ArcPitchSpinAction.setEnabled(True) self.ArcAngleSpin = QDoubleSpinBox(self.optionsToolBar) self.ArcAngleSpin.setMinimum(1) self.ArcAngleSpin.setMaximum(3600) self.ArcAngleSpin.setDecimals(0) self.ArcAngleSpin.setValue(self.arc_featureAngle) self.ArcAngleSpinAction = self.optionsToolBar.addWidget( self.ArcAngleSpin) self.ArcAngleSpin.setToolTip(tr(u"Angle")) self.ArcAngleSpinAction.setEnabled(True) if self.arc_method == "pitch": self.ArcPitchSpin.setEnabled(True) self.ArcAngleSpin.setEnabled(False) self.ArcFeatureCombo.setCurrentIndex(0) else: self.ArcPitchSpin.setEnabled(False) self.ArcAngleSpin.setEnabled(True) self.ArcFeatureCombo.setCurrentIndex(1) if self.arc_angleDirection == "ClockWise": self.ArcAngleDirectionCombo.setCurrentIndex(0) else: self.ArcAngleDirectionCombo.setCurrentIndex(1) self.ArcPitchSpin.valueChanged["double"].connect( self.pitchSettings) self.ArcAngleSpin.valueChanged["double"].connect( self.angleSettings) self.ArcFeatureCombo.currentIndexChanged["int"].connect( self.featureArc) self.ArcAngleDirectionCombo.currentIndexChanged["int"].connect( self.angleDirectionArc) def polygonArc(self): if self.ArcPolygonCombo.currentIndex() == 0: self.settings.setValue("/CADDigitize/arc/polygon", "pie") else: self.settings.setValue("/CADDigitize/arc/polygon", "chord") def angleDirectionArc(self): if self.ArcAngleDirectionCombo.currentIndex() == 0: self.settings.setValue("/CADDigitize/arc/direction", "ClockWise") else: self.settings.setValue("/CADDigitize/arc/direction", "CounterClockWise") def angleSettings(self): self.arc_featureAngle = self.ArcAngleSpin.value() self.settings.setValue("/CADDigitize/arc/angle", self.arc_featureAngle) def pitchSettings(self): self.arc_featurePitch = self.ArcPitchSpin.value() self.settings.setValue("/CADDigitize/arc/pitch", self.arc_featurePitch) def featureArc(self): if self.ArcFeatureCombo.currentIndex() == 0: self.ArcPitchSpin.setEnabled(True) self.ArcAngleSpin.setEnabled(False) self.settings.setValue("/CADDigitize/arc/method", "pitch") else: self.ArcPitchSpin.setEnabled(False) self.ArcAngleSpin.setEnabled(True) self.settings.setValue("/CADDigitize/arc/method", "angle")
class Barometer(PluginBase): def __init__(self, *args): PluginBase.__init__(self, BrickletBarometer, *args) self.barometer = self.device self.has_calibrate = self.firmware_version == (1, 0, 0) self.has_averaging = self.firmware_version >= (2, 0, 2) self.moving_average_pressure = 25 self.average_pressure = 10 self.average_temperature = 10 self.cbe_air_pressure = CallbackEmulator(self.barometer.get_air_pressure, self.cb_air_pressure, self.increase_error_count) self.cbe_altitude = CallbackEmulator(self.barometer.get_altitude, self.cb_altitude, self.increase_error_count) self.chip_temperature_label = ChipTemperatureLabel() self.current_air_pressure = None # float, mbar self.current_altitude = None # float, m self.clear_graphs_button = QPushButton('Clear Graphs') plots = [('Air Pressure', Qt.red, lambda: self.current_air_pressure, '{:.3f} mbar (QFE)'.format)] self.air_pressure_plot_widget = PlotWidget('Air Pressure [mbar]', plots, self.clear_graphs_button) plots = [('Altitude', Qt.darkGreen, lambda: self.current_altitude, lambda value: '{:.2f} m ({:.2f} ft)'.format(value, value / 0.3048))] self.altitude_plot_widget = PlotWidget('Altitude [m]', plots, self.clear_graphs_button) if self.has_calibrate: self.calibrate_button = QPushButton('Calibrate Altitude') self.calibrate_button.clicked.connect(self.calibrate_clicked) else: self.reference_label = QLabel('Reference Air Pressure [mbar]:') self.reference_box = QDoubleSpinBox() self.reference_box.setMinimum(10) self.reference_box.setMaximum(1200) self.reference_box.setDecimals(3) self.reference_box.setValue(1013.25) self.reference_box.editingFinished.connect(self.reference_box_finished) self.use_current_button = QPushButton('Use Current') self.use_current_button.clicked.connect(self.use_current_clicked) if self.has_averaging: self.avg_pressure_box = QSpinBox() self.avg_pressure_box.setMinimum(0) self.avg_pressure_box.setMaximum(10) self.avg_pressure_box.setSingleStep(1) self.avg_pressure_box.setValue(10) self.avg_pressure_box.editingFinished.connect(self.avg_pressure_box_finished) self.avg_temperature_box = QSpinBox() self.avg_temperature_box.setMinimum(0) self.avg_temperature_box.setMaximum(255) self.avg_temperature_box.setSingleStep(1) self.avg_temperature_box.setValue(10) self.avg_temperature_box.editingFinished.connect(self.avg_temperature_box_finished) self.avg_moving_pressure_box = QSpinBox() self.avg_moving_pressure_box.setMinimum(0) self.avg_moving_pressure_box.setMaximum(25) self.avg_moving_pressure_box.setSingleStep(1) self.avg_moving_pressure_box.setValue(25) self.avg_moving_pressure_box.editingFinished.connect(self.avg_moving_pressure_box_finished) layout_h1 = QHBoxLayout() layout_h1.addWidget(self.air_pressure_plot_widget) layout_h1.addWidget(self.altitude_plot_widget) layout = QVBoxLayout(self) layout.addLayout(layout_h1) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout.addWidget(line) if self.has_calibrate: layout_h2 = QHBoxLayout() layout_h2.addWidget(self.chip_temperature_label) layout_h2.addStretch() layout_h2.addWidget(self.calibrate_button) layout_h2.addWidget(self.clear_graphs_button) else: layout_h2 = QHBoxLayout() layout_h2.addWidget(self.reference_label) layout_h2.addWidget(self.reference_box) layout_h2.addWidget(self.use_current_button) layout_h2.addStretch() layout_h2.addWidget(self.chip_temperature_label) layout_h2.addStretch() layout_h2.addWidget(self.clear_graphs_button) layout.addLayout(layout_h2) if self.has_averaging: layout_h3 = QHBoxLayout() layout_h3.addWidget(QLabel('Air Pressure Moving Average Length:')) layout_h3.addWidget(self.avg_moving_pressure_box) layout_h3.addStretch() layout_h3.addWidget(QLabel('Air Pressure Average Length:')) layout_h3.addWidget(self.avg_pressure_box) layout_h3.addStretch() layout_h3.addWidget(QLabel('Temperate Average Length:')) layout_h3.addWidget(self.avg_temperature_box) layout.addLayout(layout_h3) self.chip_temp_timer = QTimer() self.chip_temp_timer.timeout.connect(self.update_chip_temp) self.chip_temp_timer.setInterval(100) def start(self): async_call(self.barometer.get_air_pressure, None, self.cb_air_pressure, self.increase_error_count) async_call(self.barometer.get_altitude, None, self.cb_altitude, self.increase_error_count) self.cbe_air_pressure.set_period(100) self.cbe_altitude.set_period(100) if self.has_averaging: async_call(self.barometer.get_averaging, None, self.get_averaging_async, self.increase_error_count) if not self.has_calibrate: async_call(self.barometer.get_reference_air_pressure, None, self.get_reference_air_pressure_async, self.increase_error_count) self.air_pressure_plot_widget.stop = False self.altitude_plot_widget.stop = False self.update_chip_temp() self.chip_temp_timer.start() def stop(self): self.cbe_air_pressure.set_period(0) self.cbe_altitude.set_period(0) self.air_pressure_plot_widget.stop = True self.altitude_plot_widget.stop = True self.chip_temp_timer.stop() def destroy(self): pass def get_url_part(self): return 'barometer' @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletBarometer.DEVICE_IDENTIFIER def get_averaging_async(self, avg): moving_average_pressure, average_pressure, average_temperature = avg self.moving_average_pressure = moving_average_pressure self.average_pressure = average_pressure self.average_temperature = average_temperature self.avg_moving_pressure_box.setValue(moving_average_pressure) self.avg_pressure_box.setValue(average_pressure) self.avg_temperature_box.setValue(average_temperature) def avg_pressure_box_finished(self): self.average_pressure = self.avg_pressure_box.value() self.save_new_averaging() def avg_temperature_box_finished(self): self.average_temperature = self.avg_temperature_box.value() self.save_new_averaging() def avg_moving_pressure_box_finished(self): self.moving_average_pressure = self.avg_moving_pressure_box.value() self.save_new_averaging() def save_new_averaging(self): self.barometer.set_averaging(self.moving_average_pressure, self.average_pressure, self.average_temperature) def calibrate_clicked(self): try: # Call set_reference_air_pressure that has the same function ID as # calibrate_altitude the extra parameter will just be ignored self.barometer.set_reference_air_pressure(0) except ip_connection.Error: pass def get_reference_air_pressure_async(self, reference): self.reference_box.setValue(reference / 1000.0) def use_current_clicked(self): self.barometer.set_reference_air_pressure(0) async_call(self.barometer.get_reference_air_pressure, None, self.get_reference_air_pressure_async, self.increase_error_count) def reference_box_finished(self): self.barometer.set_reference_air_pressure(self.reference_box.value() * 1000.0) def update_chip_temp_async(self, temp): self.chip_temperature_label.setText('{:.2f}'.format(temp / 100.0)) def update_chip_temp(self): async_call(self.barometer.get_chip_temperature, None, self.update_chip_temp_async, self.increase_error_count) def cb_air_pressure(self, air_pressure): self.current_air_pressure = air_pressure / 1000.0 def cb_altitude(self, altitude): self.current_altitude = altitude / 100.0
def initAppletDrawerUi(self): """ Overridden from base class (LayerViewerGui) """ op = self.topLevelOperatorView def configure_update_handlers(qt_signal, op_slot): qt_signal.connect(self.configure_operator_from_gui) op_slot.notifyDirty(self.configure_gui_from_operator) self.__cleanup_fns.append( partial(op_slot.unregisterDirty, self.configure_gui_from_operator)) def control_layout(label_text, widget): row_layout = QHBoxLayout() row_layout.addWidget(QLabel(label_text)) row_layout.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding)) row_layout.addWidget(widget) return row_layout drawer_layout = QVBoxLayout() channel_box = QSpinBox() def set_channel_box_range(*args): if sip.isdeleted(channel_box): return channel_box.setMinimum(0) channel_box.setMaximum(op.Input.meta.getTaggedShape()['c'] - 1) set_channel_box_range() op.Input.notifyMetaChanged(set_channel_box_range) configure_update_handlers(channel_box.valueChanged, op.ChannelSelection) drawer_layout.addLayout(control_layout("Input Channel", channel_box)) self.channel_box = channel_box threshold_box = QDoubleSpinBox() threshold_box.setDecimals(2) threshold_box.setMinimum(0.00) threshold_box.setMaximum(1.0) threshold_box.setSingleStep(0.1) configure_update_handlers(threshold_box.valueChanged, op.Pmin) drawer_layout.addLayout(control_layout("Threshold", threshold_box)) self.threshold_box = threshold_box membrane_size_box = QSpinBox() membrane_size_box.setMinimum(0) membrane_size_box.setMaximum(1000000) configure_update_handlers(membrane_size_box.valueChanged, op.MinMembraneSize) drawer_layout.addLayout( control_layout("Min Membrane Size", membrane_size_box)) self.membrane_size_box = membrane_size_box seed_presmoothing_box = QDoubleSpinBox() seed_presmoothing_box.setDecimals(1) seed_presmoothing_box.setMinimum(0.0) seed_presmoothing_box.setMaximum(10.0) seed_presmoothing_box.setSingleStep(0.1) configure_update_handlers(seed_presmoothing_box.valueChanged, op.SigmaMinima) drawer_layout.addLayout( control_layout("Presmooth before seeds", seed_presmoothing_box)) self.seed_presmoothing_box = seed_presmoothing_box seed_method_combo = QComboBox() seed_method_combo.addItem("Connected") seed_method_combo.addItem("Clustered") configure_update_handlers(seed_method_combo.currentIndexChanged, op.GroupSeeds) drawer_layout.addLayout( control_layout("Seed Labeling", seed_method_combo)) self.seed_method_combo = seed_method_combo watershed_presmoothing_box = QDoubleSpinBox() watershed_presmoothing_box.setDecimals(1) watershed_presmoothing_box.setMinimum(0.0) watershed_presmoothing_box.setMaximum(10.0) watershed_presmoothing_box.setSingleStep(0.1) configure_update_handlers(watershed_presmoothing_box.valueChanged, op.SigmaWeights) drawer_layout.addLayout( control_layout("Presmooth before watershed", watershed_presmoothing_box)) self.watershed_presmoothing_box = watershed_presmoothing_box superpixel_size_box = QSpinBox() superpixel_size_box.setMinimum(0) superpixel_size_box.setMaximum(1000000) configure_update_handlers(superpixel_size_box.valueChanged, op.MinSegmentSize) drawer_layout.addLayout( control_layout("Min Superpixel Size", superpixel_size_box)) self.superpixel_size_box = superpixel_size_box enable_debug_box = QCheckBox() configure_update_handlers(enable_debug_box.toggled, op.EnableDebugOutputs) drawer_layout.addLayout( control_layout("Show Debug Layers", enable_debug_box)) self.enable_debug_box = enable_debug_box compute_button = QPushButton("Update Watershed", clicked=self.onUpdateWatershedsButton) drawer_layout.addWidget(compute_button) drawer_layout.setSpacing(0) drawer_layout.addSpacerItem( QSpacerItem(0, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)) # Finally, the whole drawer widget drawer = QWidget(parent=self) drawer.setLayout(drawer_layout) # Save these members for later use self._drawer = drawer # Initialize everything with the operator's initial values self.configure_gui_from_operator()
class OffsetWidget(QWidget): """This widet displays the elements for editing the offset. This widget deals with the logic of when the new offset should be taken into account internally. When it determines that the new offset should be used, it emits the 'new_offset' signal. Parameters ---------- parent : ? Attributes ---------- offset_entry : QDoubleSpinBox The numerical element where the user can enter the offset. The units are determined by the currently displayed channel. Methods ------- toggle_preview Determine how the new_offset signal should be emitted and connect the proper element to the emit_new_offset method. emit_new_offset Wrapper function for connecting one of the widget's element's signals to the new_offset signal. Signals ------- new_offset Indicates that a new offset has been entered and is ready to be used in calculations. """ # Define a new signal called 'new_offset' new_offset = pyqtSignal() def __init__(self, parent=None): super(OffsetWidget, self).__init__(parent) # Create the numerical entry spinbox and its label offset_label = QLabel("Offset") self.offset_entry = QDoubleSpinBox(self) self.offset_entry.setDecimals(10) self.offset_entry.setRange(-1000000,1000000) # Create the preview checkbox and its label preview_chkbx_lbl = QLabel("preview") self.preview_chkbx = QCheckBox() # Create the 'Show' and 'Save' push buttons self.show_btn = QPushButton("Show") self.save_btn = QPushButton("Save") # The save feature is planned for later, so the button is disabled for # now self.save_btn.setEnabled(False) # Create the layout for the checkbox/button strip at the bottom of the # widget's layout: # | checkbox | checkbox label | show button | save button | btn_layout = QHBoxLayout() btn_layout.addWidget(self.preview_chkbx) btn_layout.addWidget(preview_chkbx_lbl) btn_layout.addWidget(self.show_btn) btn_layout.addWidget(self.save_btn) # Create the main layout of the widget: # | spinbox label | # | spinbox | # | checkbox/button layout | layout = QVBoxLayout() layout.addWidget(offset_label) layout.addWidget(self.offset_entry) layout.addLayout(btn_layout) # Set the layout self.setLayout(layout) # Connect the checkbox's 'stateChanged' signal to the toggle_preview # method self.preview_chkbx.stateChanged.connect(self.toggle_preview) # Connect the show button's 'clicked' signal to the emit_new_offset # method. # By default the checkbox is not selected, thus the default is that the # show button is how the user indicates that there is a new offset. self.show_btn.clicked.connect(self.emit_new_offset) def toggle_preview(self): """Toggle previewing offset changes automatically. This function checks the state of the preview checkbox and establishes the Offset_Widget's method of emitting the new_offset signal. """ # Connect and disconnect the spinbox's and show button's signals to the # widget's new_offset signal. if self.preview_chkbx.isChecked(): # Preview is selected: # show button is disconnected from new_offset # spinbox is connected to new_offset self.show_btn.clicked.disconnect(self.emit_new_offset) self.offset_entry.editingFinished.connect(self.emit_new_offset) elif not self.preview_chkbx.isChecked(): # Preview is not selected: # spinbox is disconnected from new_offset # show button is connected to new_offset self.offset_entry.editingFinished.disconnect(self.emit_new_offset) self.show_btn.clicked.connect(self.emit_new_offset) # Enable or disable the show button depending on checkbox's state self.show_btn.setEnabled(not self.preview_chkbx.isChecked()) def emit_new_offset(self): """Emit the 'new_offset' signal. The function just provides an easy way to connect other signals to emitting the widget's new_offset signal. """ self.new_offset.emit()