Exemplo n.º 1
0
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)
Exemplo n.º 3
0
    def __init__(self, parent, prefix = None, suffix = None, option = None, min_ = None, max_ = None,
                 step = None, tip = None, value = None, changed =None):
        super(MyDoubleSpinBox, self).__init__(parent)
    
        if prefix:
            plabel = QLabel(prefix)
        else:
            plabel = None
        if suffix:
            slabel = QLabel(suffix)
        else:
            slabel = None
        spinbox = QDoubleSpinBox(parent)
        if min_ is not None:
            spinbox.setMinimum(min_)
        if max_ is not None:
            spinbox.setMaximum(max_)
        if step is not None:
            spinbox.setSingleStep(step)
        if tip is not None:
            spinbox.setToolTip(tip)
        layout = QHBoxLayout()
        for subwidget in (plabel, spinbox, slabel):
            if subwidget is not None:
                layout.addWidget(subwidget)
        if value is not None:
            spinbox.setValue(value)
        
        if changed is not None:
            self.connect(spinbox, SIGNAL('valueChanged(double)'), changed)

        layout.addStretch(1)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        self.spin = spinbox
Exemplo n.º 4
0
 def createEditor( self, parent, option, index ):
     if index.column() == DESCRIPCION:
         combo = QComboBox( parent )
         combo.setEditable( True )
         value = index.data().toString()
         self.filtrados.append( value )
         self.proxymodel.setFilterRegExp( self.filter() )
         combo.setModel( self.proxymodel )
         combo.setModelColumn( 1 )
         combo.setCompleter( self.completer )
         return combo
     elif index.column() == BANCO:
         combo = QComboBox( parent )
         #combo.setEditable(True)
         combo.setModel( self.bancosmodel )
         combo.setModelColumn( 1 )
         #combo.setCompleter(self.completer)
         return combo
     elif index.column() == MONTO:
         doublespinbox = QDoubleSpinBox( parent )
         doublespinbox.setMinimum( -1000000 )
         doublespinbox.setMaximum( 1000000 )
         doublespinbox.setDecimals( 4 )
         doublespinbox.setAlignment( Qt.AlignHCenter )
         return doublespinbox
     elif index.column() == REFERENCIA:
         textbox = QStyledItemDelegate.createEditor( self, parent, option, index )
         textbox.setAlignment( Qt.AlignHCenter )
         return textbox
 def _getSpinbox(self, minvalue, maxvalue, step, nullable = True, value = 0):
     '''
     Get a combobox filled with the given values
     
     :param values: The values as key = value, value = description or text
     :type values: Dict
     
     :returns: A combobox
     :rtype: QWidget
     '''
     
     widget = QWidget()
     spinbox = QDoubleSpinBox()
     spinbox.setMinimum(minvalue)
     spinbox.setMaximum(maxvalue)
     spinbox.setSingleStep(step)
     spinbox.setDecimals(len(str(step).split('.')[1]) if len(str(step).split('.'))==2 else 0)
     if nullable:
         spinbox.setMinimum(minvalue - step)
         spinbox.setValue(spinbox.minimum())
         spinbox.setSpecialValueText(str(QSettings().value('qgis/nullValue', 'NULL' )))
     if value is not None:
         spinbox.setValue(value)
     layout = QHBoxLayout(widget)
     layout.addWidget(spinbox, 1);
     layout.setAlignment(Qt.AlignCenter);
     layout.setContentsMargins(5,0,5,0);
     widget.setLayout(layout);
             
     return widget
    def _getSpinbox(self, minvalue, maxvalue, step, nullable=True, value=0):
        '''
        Get a combobox filled with the given values
        
        :param values: The values as key = value, value = description or text
        :type values: Dict
        
        :returns: A combobox
        :rtype: QWidget
        '''

        widget = QWidget()
        spinbox = QDoubleSpinBox()
        spinbox.setMinimum(minvalue)
        spinbox.setMaximum(maxvalue)
        spinbox.setSingleStep(step)
        spinbox.setDecimals(
            len(str(step).split('.')[1]) if len(str(step).split('.')) ==
            2 else 0)
        if nullable:
            spinbox.setMinimum(minvalue - step)
            spinbox.setValue(spinbox.minimum())
            spinbox.setSpecialValueText(
                str(QSettings().value('qgis/nullValue', 'NULL')))
        if value is not None:
            spinbox.setValue(value)
        layout = QHBoxLayout(widget)
        layout.addWidget(spinbox, 1)
        layout.setAlignment(Qt.AlignCenter)
        layout.setContentsMargins(5, 0, 5, 0)
        widget.setLayout(layout)

        return widget
Exemplo n.º 7
0
 def create_doublespinbox(self, prefix, suffix, option, 
                    min_=None, max_=None, step=None, tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QDoubleSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[spinbox] = option
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     widget.spin = spinbox
     return widget
Exemplo n.º 8
0
    def createEditor(self, parent, option, index):
        """
        Creates the combobox inside a parent.
        :param parent: The container of the combobox
        :type parent: QWidget
        :param option: QStyleOptionViewItem class is used to describe the
        parameters used to draw an item in a view widget.
        :type option: Object
        :param index: The index where the combobox
         will be added.
        :type index: QModelIndex
        :return: The combobox
        :rtype: QComboBox
        """

        if index.column() == 0:
            str_combo = QComboBox(parent)
            str_combo.setObjectName(unicode(index.row()))
            return str_combo
        elif index.column() == 1:

            spinbox = QDoubleSpinBox(parent)
            spinbox.setObjectName(unicode(index.row()))
            spinbox.setMinimum(0.00)
            spinbox.setSuffix('%')
            spinbox.setMaximum(100.00)
            return spinbox
Exemplo n.º 9
0
class XicWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        v = QVBoxLayout()
        f = QFormLayout()

        self.mzTolSpinBox = QDoubleSpinBox(self)
        self.mzTolSpinBox.setMaximum(100)
        self.mzTolSpinBox.setMinimum(1)
        self.mzTolSpinBox.setValue(10)

        f.addRow("mz tolerance(ppm):", self.mzTolSpinBox)

        self.mzSpinBox = QDoubleSpinBox(self)
        self.mzSpinBox.setMaximum(2000.0)
        self.mzSpinBox.setMinimum(300.0)
        self.mzSpinBox.setValue(500.0)

        f.addRow("requested m/z:", self.mzSpinBox)

        v.addLayout(f)

        self.plotButton = QPushButton("Plot")

        v.addWidget(self.plotButton)
        self.setLayout(v)
Exemplo n.º 10
0
    def createEditor(self, parent, option, index):
        """
        Creates the combobox inside a parent.
        :param parent: The container of the combobox
        :type parent: QWidget
        :param option: QStyleOptionViewItem class is used to describe the
        parameters used to draw an item in a view widget.
        :type option: Object
        :param index: The index where the combobox
         will be added.
        :type index: QModelIndex
        :return: The combobox
        :rtype: QComboBox
        """

        if index.column() == 0:
            str_combo = QComboBox(parent)
            str_combo.insertItem(0, " ")
            for id, type in self.str_type_set_data().iteritems():
                str_combo.addItem(type, id)
            if self.str_type_id is not None:
                str_combo.setCurrentIndex(self.str_type_id)
            return str_combo
        elif index.column() == 1:

            spinbox = QDoubleSpinBox(parent)
            spinbox.setObjectName(unicode(index.row()))
            spinbox.setMinimum(0.00)
            spinbox.setSuffix('%')
            spinbox.setMaximum(100.00)
            return spinbox
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
 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
Exemplo n.º 13
0
 def createEditor(self, type, parent):
     if type != QVariant.Double:
         raise ValueError("This factory only creates editor for doubles")
     w = QDoubleSpinBox(parent)
     w.setDecimals(5)
     w.setMinimum(0.0001)
     w.setMaximum(10000)
     return w
 def createDoubleSpinBox(self, variable_name, variable_value, variable_type, analysis_module_variables_model):
     spinner = QDoubleSpinBox()
     spinner.setMinimumWidth(75)
     spinner.setMaximum(analysis_module_variables_model.getVariableMaximumValue(variable_name))
     spinner.setMinimum(analysis_module_variables_model.getVariableMinimumValue(variable_name))
     spinner.setSingleStep(analysis_module_variables_model.getVariableStepValue(variable_name))
     spinner.setValue(variable_value)
     spinner.valueChanged.connect(partial(self.valueChanged,variable_name, variable_type, spinner))
     return spinner;
Exemplo n.º 15
0
    def _create_widget(cls, c, parent):
        dsb = QDoubleSpinBox(parent)
        dsb.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name))

        #Set ranges
        dsb.setMinimum(float(c.minimum))
        dsb.setMaximum(float(c.maximum))

        return dsb
Exemplo n.º 16
0
 def createDoubleSpinBox(self, variable_name, variable_value, variable_type, analysis_module_variables_model):
     spinner = QDoubleSpinBox()
     spinner.setMinimumWidth(75)
     spinner.setMaximum(analysis_module_variables_model.getVariableMaximumValue(variable_name))
     spinner.setMinimum(analysis_module_variables_model.getVariableMinimumValue(variable_name))
     spinner.setSingleStep(analysis_module_variables_model.getVariableStepValue(variable_name))
     spinner.setValue(variable_value)
     spinner.valueChanged.connect(partial(self.valueChanged, variable_name, variable_type, spinner))
     return spinner;
Exemplo n.º 17
0
    def createEditor(self, parent, option, index):
        col = index.column()
        if col == 1:
            editor = QDoubleSpinBox(parent)
            editor.setSuffix('%')
        else:
            editor = QSpinBox(parent)
        editor.setMaximum(100000000)

        return editor
Exemplo n.º 18
0
    def createEditor(self, parent, option, index):
        col = index.column()
        if col == 1:
            editor = QDoubleSpinBox(parent)
            editor.setSuffix('%')
        else:
            editor = QSpinBox(parent)
        editor.setMaximum(100000000)

        return editor
Exemplo n.º 19
0
    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
Exemplo n.º 20
0
	def createWidget(self, qt_parent=None):
		"""
		Return an editor widget suitable for editing the data type.

		For example, for QDateTime return a QDateTimeEdit(parent)
		"""
		sb = QDoubleSpinBox(qt_parent)
		sb.setFrame(False)
		sb.setMinimum(-float_info.max)
		sb.setMaximum(float_info.max)
		return sb
Exemplo n.º 21
0
def extra_keywords_to_widgets(extra_keyword_definition):
    """Create widgets for extra keyword.

    :param extra_keyword_definition: An extra keyword definition.
    :type extra_keyword_definition: dict

    :return: QCheckBox and The input widget
    :rtype: (QCheckBox, QWidget)
    """
    # Check box
    check_box = QCheckBox(extra_keyword_definition['name'])
    check_box.setToolTip(extra_keyword_definition['description'])
    check_box.setChecked(True)

    # Input widget
    if extra_keyword_definition['type'] == float:
        input_widget = QDoubleSpinBox()
        input_widget.setMinimum(extra_keyword_definition['minimum'])
        input_widget.setMaximum(extra_keyword_definition['maximum'])
        input_widget.setSuffix(extra_keyword_definition['unit_string'])
    elif extra_keyword_definition['type'] == int:
        input_widget = QSpinBox()
        input_widget.setMinimum(extra_keyword_definition['minimum'])
        input_widget.setMaximum(extra_keyword_definition['maximum'])
        input_widget.setSuffix(extra_keyword_definition['unit_string'])
    elif extra_keyword_definition['type'] == unicode:
        if extra_keyword_definition.get('options'):
            input_widget = QComboBox()
            options = extra_keyword_definition['options']
            for option in options:
                input_widget.addItem(
                    option['name'],
                    option['key'],
                )
            default_option_index = input_widget.findData(
                extra_keyword_definition['default_option'])
            input_widget.setCurrentIndex(default_option_index)
        else:
            input_widget = QLineEdit()
    elif extra_keyword_definition['type'] == datetime:
        input_widget = QDateTimeEdit()
        input_widget.setCalendarPopup(True)
        input_widget.setDisplayFormat('hh:mm:ss, d MMM yyyy')
        input_widget.setDateTime(datetime.now())
    else:
        raise Exception
    input_widget.setToolTip(extra_keyword_definition['description'])

    # Signal
    # noinspection PyUnresolvedReferences
    check_box.stateChanged.connect(input_widget.setEnabled)

    return check_box, input_widget
Exemplo n.º 22
0
    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
Exemplo n.º 23
0
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
Exemplo n.º 24
0
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
Exemplo n.º 25
0
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_()
Exemplo n.º 26
0
    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
Exemplo n.º 27
0
class DoubleSpinBox(QWidget):
    def __init__(self, id, text, **kwargs):
        QWidget.__init__(self)
        self.id = id
        self.widget = QDoubleSpinBox(**kwargs)
        label = QLabel(text)
        hbox = HBoxLayout()
        hbox.addWidget(label)
        hbox.addWidget(self.widget)
        self.setLayout(hbox)
        self.widget.setMaximum(999999999)
        self.widget.setMinimum(-999999999)

    def parameterValues(self):
        return {self.id:self.widget.value()}
Exemplo n.º 28
0
    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
Exemplo n.º 29
0
    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())
Exemplo n.º 30
0
 def spinBoxFromHabName(self,habname):
     """
     If the spin box exists, return it. If not make it and return it.
     """
     #print "looking for habname: %s" % habname
     sbname = slugify( unicode(habname) ) + u"SpinBox"
     htw = self.habitatTableWidget
     try:
         sb = htw.findChild(QDoubleSpinBox,sbname)
         assert( sb!=None )
         return sb
     except AssertionError:
         #print "making SB: %s" % sbname
         newsb = QDoubleSpinBox(self.habitatTableWidget)
         newsb.setMaximum(1.0)
         newsb.setSingleStep(0.1)
         newsb.setObjectName(_fromUtf8(sbname))
         return newsb
Exemplo n.º 31
0
 def spinBoxFromHabName(self, habname):
     """
     If the spin box exists, return it. If not make it and return it.
     """
     #print "looking for habname: %s" % habname
     sbname = slugify(unicode(habname)) + u"SpinBox"
     htw = self.habitatTableWidget
     try:
         sb = htw.findChild(QDoubleSpinBox, sbname)
         assert (sb != None)
         return sb
     except AssertionError:
         #print "making SB: %s" % sbname
         newsb = QDoubleSpinBox(self.habitatTableWidget)
         newsb.setMaximum(1.0)
         newsb.setSingleStep(0.1)
         newsb.setObjectName(_fromUtf8(sbname))
         return newsb
Exemplo n.º 32
0
    def __init__(self,
                 parent,
                 prefix=None,
                 suffix=None,
                 option=None,
                 min_=None,
                 max_=None,
                 step=None,
                 tip=None,
                 value=None,
                 changed=None):
        super(MyDoubleSpinBox, self).__init__(parent)

        if prefix:
            plabel = QLabel(prefix)
        else:
            plabel = None
        if suffix:
            slabel = QLabel(suffix)
        else:
            slabel = None
        spinbox = QDoubleSpinBox(parent)
        if min_ is not None:
            spinbox.setMinimum(min_)
        if max_ is not None:
            spinbox.setMaximum(max_)
        if step is not None:
            spinbox.setSingleStep(step)
        if tip is not None:
            spinbox.setToolTip(tip)
        layout = QHBoxLayout()
        for subwidget in (plabel, spinbox, slabel):
            if subwidget is not None:
                layout.addWidget(subwidget)
        if value is not None:
            spinbox.setValue(value)

        if changed is not None:
            self.connect(spinbox, SIGNAL('valueChanged(double)'), changed)

        layout.addStretch(1)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        self.spin = spinbox
Exemplo n.º 33
0
    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
Exemplo n.º 34
0
class IntervalSpinner(QWidget):
    def __init__(self, parent, min_=1, max_=1000, step=1, round_option=True):
        QWidget.__init__(self, parent)
        layout = QVBoxLayout(self)
        hlayout = QHBoxLayout()
        self.start = QDoubleSpinBox(self)
        self.start.setMinimum(min_)
        self.start.setMaximum(max_)
        self.end = QDoubleSpinBox(self)
        self.end.setMinimum(min_)
        self.end.setMaximum(max_)
        self.end.setValue(max_)
        self.start.setSingleStep(step)
        self.end.setSingleStep(step)

        self.start.valueChanged.connect(self.on_value_start_changed)
        self.end.valueChanged.connect(self.on_value_end_changed)

        hlayout.addWidget(self.start)
        hlayout.addWidget(self.end)
        layout.addLayout(hlayout)

        if round_option:
            self.integerCheckBox = QCheckBox("Round to integer values", self)
            layout.addWidget(self.integerCheckBox)

    def on_value_start_changed(self, val):
        if self.end.value() < val:
            self.end.setValue(val)

    def on_value_end_changed(self, val):
        if self.start.value() > val:
            self.start.setValue(val)

    def getMin(self):
        return self.start.value()

    def getMax(self):
        return self.end.value()

    def getRound(self):
        return self.integerCheckBox.isChecked()
Exemplo n.º 35
0
class IntervalSpinner(QWidget):
    def __init__(self, parent, min_=1, max_=1000, step=1, round_option=True):
        QWidget.__init__(self, parent)
        layout = QVBoxLayout(self)
        hlayout = QHBoxLayout()
        self.start = QDoubleSpinBox(self)
        self.start.setMinimum(min_)
        self.start.setMaximum(max_)
        self.end = QDoubleSpinBox(self)
        self.end.setMinimum(min_)
        self.end.setMaximum(max_)
        self.end.setValue(max_)
        self.start.setSingleStep(step)
        self.end.setSingleStep(step)

        self.start.valueChanged.connect(self.on_value_start_changed)
        self.end.valueChanged.connect(self.on_value_end_changed)

        hlayout.addWidget(self.start)
        hlayout.addWidget(self.end)
        layout.addLayout(hlayout)

        if round_option:
            self.integerCheckBox = QCheckBox("Round to integer values", self)
            layout.addWidget(self.integerCheckBox)

    def on_value_start_changed(self, val):
        if self.end.value() < val:
            self.end.setValue(val)

    def on_value_end_changed(self, val):
        if self.start.value() > val:
            self.start.setValue(val)

    def getMin(self):
        return self.start.value()

    def getMax(self):
        return self.end.value()

    def getRound(self):
        return self.integerCheckBox.isChecked()
Exemplo n.º 36
0
class EkdTimePropertie(EkdPropertie):
    """
    Définition de la propriété correspondant à un conteur ou une valeur de temps
    """
    def __init__(self, prop, name, value, minimum=0, maximum=100, section=None ):
        super(EkdTimePropertie, self).__init__(prop, name, value, EkdPropertie.TIME, section)
        self.label = QLabel(name)
        self.widget = QDoubleSpinBox()
        self.widget.setValue(float(value))
        self.widget.setMaximum(maximum)
        self.widget.setMinimum(minimum)

        # Quand on change la valeur de la propriété, on met à jour EkdConfig
        self.connect(self.widget, SIGNAL("valueChanged(double)"), self.updateNum)

    def updateNum(self, val):
        self.value = val
        EkdConfig.set(self.section, self.id, self.value)
        #print "Debug:: TIMER %s | value %s | value Ekd config %s | section %s" % (self.id, self.value, EkdConfig.get(self.section, self.id), self.section)
	EkdPrint(u"Debug:: TIMER %s | value %s | value Ekd config %s | section %s" % (self.id, self.value, EkdConfig.get(self.section, self.id), self.section))
Exemplo n.º 37
0
 def createEditor(self, parent, option, index):
     node = index.internalPointer()
     if node.typeInfo == 'CODE':
         if node.valueFormat == 'percent':
             editor = QDoubleSpinBox(parent)
             editor.setSuffix('%')
         elif node.valueFormat == 'integer':
             editor = QSpinBox(parent)
         else:
             editor = QDoubleSpinBox(parent)
         editor.setMaximum(100000000)
     elif node.typeInfo == 'BAREME':
         editor = QPushButton(parent)
         editor.setText('Editer')
         value = node._value
         value.marToMoy()
         self.baremeDialog = BaremeDialog(value, self._parent)
         self.connect(editor, SIGNAL('clicked()'), self.runBaremeDialog)
         self.runBaremeDialog()
     else:
         editor = QStyledItemDelegate.createEditor(self, parent, option, index)
     return editor
Exemplo n.º 38
0
class AddNewWeight(AddNewDialog):
    def __init__(self, parent, item):
        AddNewDialog.__init__(self, parent)
        self.setText('Lisää uusi punnitus', 'Uusi punnitus')
        self.ui.lineEdit.hide()
        self.item = item
        self.priceSelector = QDoubleSpinBox(parent=self)
        self.priceSelector.setMaximum(999999)
        self.priceSelector.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.ui.horizontalLayout.addWidget(self.priceSelector)
        self.hideComboBox()
    
    def saveCheck(self):
        if self.priceSelector.value() > 0:
            self.saveNewItem()
        
    def saveNewItem(self):
        item = SqlHandler.WeightControl(animal_id = self.item.id, weight=self.priceSelector.value())
        SqlHandler.addItem(self.session, item)
        print('WeightControl saveNweItem, ', item)
        self.parent().addAskedItem(item)
        self.closeDialog()
Exemplo n.º 39
0
 def createEditor(self, parent, option, index):
     node = index.internalPointer()
     if node.typeInfo == 'CODE':
         if node.valueFormat == 'percent':
             editor = QDoubleSpinBox(parent)
             editor.setSuffix('%')
         elif node.valueFormat == 'integer':
             editor = QSpinBox(parent)
         else:
             editor = QDoubleSpinBox(parent)
         editor.setMaximum(100000000)
     elif node.typeInfo == 'BAREME':
         editor = QPushButton(parent)
         editor.setText('Editer')
         value = node._value
         value.marToMoy()
         self.baremeDialog = BaremeDialog(value, self._parent)
         self.connect(editor, SIGNAL('clicked()'), self.runBaremeDialog)
         self.runBaremeDialog()
     else:
         editor = QStyledItemDelegate.createEditor(self, parent, option,
                                                   index)
     return editor
Exemplo n.º 40
0
class AddNewWeight(AddNewDialog):
    def __init__(self, parent, item):
        AddNewDialog.__init__(self, parent)
        self.setText('Lisää uusi punnitus', 'Uusi punnitus')
        self.ui.lineEdit.hide()
        self.item = item
        self.priceSelector = QDoubleSpinBox(parent=self)
        self.priceSelector.setMaximum(999999)
        self.priceSelector.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.ui.horizontalLayout.addWidget(self.priceSelector)
        self.hideComboBox()

    def saveCheck(self):
        if self.priceSelector.value() > 0:
            self.saveNewItem()

    def saveNewItem(self):
        item = SqlHandler.WeightControl(animal_id=self.item.id,
                                        weight=self.priceSelector.value())
        SqlHandler.addItem(self.session, item)
        print('WeightControl saveNweItem, ', item)
        self.parent().addAskedItem(item)
        self.closeDialog()
Exemplo n.º 41
0
 def create_doublespinbox(self,
                          prefix,
                          suffix,
                          option,
                          min_=None,
                          max_=None,
                          step=None,
                          tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QDoubleSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[spinbox] = option
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     widget.spin = spinbox
     return widget
    def __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)
Exemplo n.º 43
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

        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 DefaultSelectParameterWidget(SelectParameterWidget):

    """Widget class for Default Select Parameter."""

    def __init__(self, parameter, parent=None):
        """Constructor

        :param parameter: A DefaultSelectParameter object.
        :type parameter: DefaultSelectParameter
        """
        super(DefaultSelectParameterWidget, self).__init__(parameter, parent)

        self.default_layout = QHBoxLayout()
        self.radio_button_layout = QHBoxLayout()
        self.radio_button_widget = QWidget()

        self.default_label = QLabel(tr('Default'))

        # Create radio button group
        self.default_input_button_group = QButtonGroup()

        # Define string enabler for radio button
        self.radio_button_enabler = self.input.itemData(0, Qt.UserRole)

        for i in range(len(self._parameter.default_labels)):
            if '%s' in self._parameter.default_labels[i]:
                label = (
                    self._parameter.default_labels[i] %
                    self._parameter.default_values[i])
            else:
                label = self._parameter.default_labels[i]

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.default_input_button_group.addButton(radio_button, i)
            if self._parameter.default_value == \
                    self._parameter.default_values[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        if self._parameter.default_values[-1]:
            self.custom_value.setValue(self._parameter.default_values[-1])
        has_min = False
        if self._parameter.minimum is not None:
            has_min = True
            self.custom_value.setMinimum(self._parameter.minimum)
        has_max = False
        if self._parameter.maximum is not None:
            has_max = True
            self.custom_value.setMaximum(self._parameter.maximum)
        if has_min and has_max:
            step = (self._parameter.maximum - self._parameter.minimum) / 100.0
            self.custom_value.setSingleStep(step)
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        # Reset the layout
        self.input_layout.setParent(None)
        self.help_layout.setParent(None)

        self.label.setParent(None)
        self.inner_input_layout.setParent(None)

        self.input_layout = QGridLayout()
        self.input_layout.setSpacing(0)

        self.input_layout.addWidget(self.label, 0, 0)
        self.input_layout.addLayout(self.inner_input_layout, 0, 1)
        self.input_layout.addWidget(self.default_label, 1, 0)
        self.input_layout.addLayout(self.radio_button_layout, 1, 1)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        # check every added combobox, it could have been toggled by
        # the existing keyword
        self.toggle_input()

        # Connect
        # noinspection PyUnresolvedReferences
        self.input.currentIndexChanged.connect(self.toggle_input)
        self.default_input_button_group.buttonClicked.connect(
            self.toggle_custom_value)

    def raise_invalid_type_exception(self):
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultSelectParameter from the current state of widget.
        """
        current_index = self.input.currentIndex()
        selected_value = self.input.itemData(current_index, Qt.UserRole)
        if hasattr(selected_value, 'toPyObject'):
            selected_value = selected_value.toPyObject()

        try:
            self._parameter.value = selected_value
        except ValueError:
            err = self.raise_invalid_type_exception()
            raise err

        radio_button_checked_id = self.default_input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.default = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif (radio_button_checked_id ==
                len(self._parameter.default_values) - 1):
            self._parameter.default_values[radio_button_checked_id] \
                = self.custom_value.value()
            self._parameter.default = self.custom_value.value()
        else:
            self._parameter.default = self._parameter.default_values[
                radio_button_checked_id]

        return self._parameter

    def set_default(self, default):
        """Set default value by item's string.

        :param default: The default.
        :type default: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            default_index = self._parameter.default_values.index(default)
            self.default_input_button_group.button(default_index).setChecked(
                True)
        except ValueError:
            last_index = len(self._parameter.default_values) - 1
            self.default_input_button_group.button(last_index).setChecked(
                True)
            self.custom_value.setValue(default)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        radio_button_checked_id = self.default_input_button_group.checkedId()
        if (radio_button_checked_id ==
                len(self._parameter.default_values) - 1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)

    def toggle_input(self):
        """Change behaviour of radio button based on input."""
        current_index = self.input.currentIndex()
        # If current input is not a radio button enabler, disable radio button.
        if self.input.itemData(current_index, Qt.UserRole) != (
                self.radio_button_enabler):
            self.disable_radio_button()
        # Otherwise, enable radio button.
        else:
            self.enable_radio_button()

    def set_selected_radio_button(self):
        """Set selected radio button to 'Do not report'."""
        dont_use_button = self.default_input_button_group.button(
            len(self._parameter.default_values) - 2)
        dont_use_button.setChecked(True)

    def disable_radio_button(self):
        """Disable radio button group and custom value input area."""
        checked = self.default_input_button_group.checkedButton()
        if checked:
            self.default_input_button_group.setExclusive(False)
            checked.setChecked(False)
            self.default_input_button_group.setExclusive(True)
        for button in self.default_input_button_group.buttons():
            button.setDisabled(True)
        self.custom_value.setDisabled(True)

    def enable_radio_button(self):
        """Enable radio button and custom value input area then set selected
        radio button to 'Do not report'.
        """
        for button in self.default_input_button_group.buttons():
            button.setEnabled(True)
        self.set_selected_radio_button()
        self.custom_value.setEnabled(True)
Exemplo n.º 45
0
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")
Exemplo n.º 46
0
class DefaultSelectParameterWidget(SelectParameterWidget):
    """Widget class for Default Select Parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        :param parameter: A DefaultSelectParameter object.
        :type parameter: DefaultSelectParameter
        """
        super(DefaultSelectParameterWidget, self).__init__(parameter, parent)

        self.default_layout = QHBoxLayout()
        self.radio_button_layout = QHBoxLayout()
        self.radio_button_widget = QWidget()

        self.default_label = QLabel(tr('Default'))

        # Create radio button group
        self.default_input_button_group = QButtonGroup()

        # Define string enabler for radio button
        self.radio_button_enabler = self.input.itemData(0, Qt.UserRole)

        for i in range(len(self._parameter.default_labels)):
            if '%s' in self._parameter.default_labels[i]:
                label = (self._parameter.default_labels[i] %
                         self._parameter.default_values[i])
            else:
                label = self._parameter.default_labels[i]

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.default_input_button_group.addButton(radio_button, i)
            if self._parameter.default_value == \
                    self._parameter.default_values[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        if self._parameter.default_values[-1]:
            self.custom_value.setValue(self._parameter.default_values[-1])
        has_min = False
        if self._parameter.minimum is not None:
            has_min = True
            self.custom_value.setMinimum(self._parameter.minimum)
        has_max = False
        if self._parameter.maximum is not None:
            has_max = True
            self.custom_value.setMaximum(self._parameter.maximum)
        if has_min and has_max:
            step = (self._parameter.maximum - self._parameter.minimum) / 100.0
            self.custom_value.setSingleStep(step)
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        # Reset the layout
        self.input_layout.setParent(None)
        self.help_layout.setParent(None)

        self.label.setParent(None)
        self.inner_input_layout.setParent(None)

        self.input_layout = QGridLayout()
        self.input_layout.setSpacing(0)

        self.input_layout.addWidget(self.label, 0, 0)
        self.input_layout.addLayout(self.inner_input_layout, 0, 1)
        self.input_layout.addWidget(self.default_label, 1, 0)
        self.input_layout.addLayout(self.radio_button_layout, 1, 1)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        # check every added combobox, it could have been toggled by
        # the existing keyword
        self.toggle_input()

        # Connect
        # noinspection PyUnresolvedReferences
        self.input.currentIndexChanged.connect(self.toggle_input)
        self.default_input_button_group.buttonClicked.connect(
            self.toggle_custom_value)

    def raise_invalid_type_exception(self):
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultSelectParameter from the current state of widget.
        """
        current_index = self.input.currentIndex()
        selected_value = self.input.itemData(current_index, Qt.UserRole)
        if hasattr(selected_value, 'toPyObject'):
            selected_value = selected_value.toPyObject()

        try:
            self._parameter.value = selected_value
        except ValueError:
            err = self.raise_invalid_type_exception()
            raise err

        radio_button_checked_id = self.default_input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.default = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif (radio_button_checked_id == len(self._parameter.default_values) -
              1):
            self._parameter.default_values[radio_button_checked_id] \
                = self.custom_value.value()
            self._parameter.default = self.custom_value.value()
        else:
            self._parameter.default = self._parameter.default_values[
                radio_button_checked_id]

        return self._parameter

    def set_default(self, default):
        """Set default value by item's string.

        :param default: The default.
        :type default: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            default_index = self._parameter.default_values.index(default)
            self.default_input_button_group.button(default_index).setChecked(
                True)
        except ValueError:
            last_index = len(self._parameter.default_values) - 1
            self.default_input_button_group.button(last_index).setChecked(True)
            self.custom_value.setValue(default)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        radio_button_checked_id = self.default_input_button_group.checkedId()
        if (radio_button_checked_id == len(self._parameter.default_values) -
                1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)

    def toggle_input(self):
        """Change behaviour of radio button based on input."""
        current_index = self.input.currentIndex()
        # If current input is not a radio button enabler, disable radio button.
        if self.input.itemData(current_index,
                               Qt.UserRole) != (self.radio_button_enabler):
            self.disable_radio_button()
        # Otherwise, enable radio button.
        else:
            self.enable_radio_button()

    def set_selected_radio_button(self):
        """Set selected radio button to 'Do not report'."""
        dont_use_button = self.default_input_button_group.button(
            len(self._parameter.default_values) - 2)
        dont_use_button.setChecked(True)

    def disable_radio_button(self):
        """Disable radio button group and custom value input area."""
        checked = self.default_input_button_group.checkedButton()
        if checked:
            self.default_input_button_group.setExclusive(False)
            checked.setChecked(False)
            self.default_input_button_group.setExclusive(True)
        for button in self.default_input_button_group.buttons():
            button.setDisabled(True)
        self.custom_value.setDisabled(True)

    def enable_radio_button(self):
        """Enable radio button and custom value input area then set selected
        radio button to 'Do not report'.
        """
        for button in self.default_input_button_group.buttons():
            button.setEnabled(True)
        self.set_selected_radio_button()
        self.custom_value.setEnabled(True)
Exemplo n.º 47
0
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()
Exemplo n.º 48
0
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A GroupSelectParameter object.
        :type parameter: GroupSelectParameter
        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Store spin box
        self.spin_boxes = {}

        # Create elements
        # Label (name)
        self.label = QLabel(self._parameter.name)

        # Layouts
        self.main_layout = QVBoxLayout()
        self.input_layout = QVBoxLayout()

        # _inner_input_layout must be filled with widget in the child class
        self.inner_input_layout = QVBoxLayout()

        self.radio_button_layout = QGridLayout()

        # Create radio button group
        self.input_button_group = QButtonGroup()

        # List widget
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list_widget.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_widget.setDefaultDropAction(Qt.MoveAction)
        self.list_widget.setEnabled(False)
        self.list_widget.setSizePolicy(QSizePolicy.Maximum,
                                       QSizePolicy.Expanding)

        for i, key in enumerate(self._parameter.options):
            value = self._parameter.options[key]
            radio_button = QRadioButton(value.get('label'))
            self.radio_button_layout.addWidget(radio_button, i, 0)
            if value.get('type') == SINGLE_DYNAMIC:
                double_spin_box = QDoubleSpinBox()
                self.radio_button_layout.addWidget(double_spin_box, i, 1)
                double_spin_box.setValue(value.get('value', 0))
                double_spin_box.setMinimum(
                    value.get('constraint', {}).get('min', 0))
                double_spin_box.setMaximum(
                    value.get('constraint', {}).get('max', 1))
                double_spin_box.setSingleStep(
                    value.get('constraint', {}).get('step', 0.01))
                step = double_spin_box.singleStep()
                if step > 1:
                    precision = 0
                else:
                    precision = len(str(step).split('.')[1])
                    if precision > 3:
                        precision = 3
                double_spin_box.setDecimals(precision)
                self.spin_boxes[key] = double_spin_box

                # Enable spin box depends on the selected option
                if self._parameter.selected == key:
                    double_spin_box.setEnabled(True)
                else:
                    double_spin_box.setEnabled(False)

            elif value.get('type') == STATIC:
                static_value = value.get('value', 0)
                if static_value is not None:
                    self.radio_button_layout.addWidget(
                        QLabel(str(static_value)), i, 1)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                selected_fields = value.get('value', [])
                if self._parameter.selected == key:
                    self.list_widget.setEnabled(True)
                else:
                    self.list_widget.setEnabled(False)

            self.input_button_group.addButton(radio_button, i)
            if self._parameter.selected == key:
                radio_button.setChecked(True)

        # Help text
        self.help_label = QLabel(self._parameter.help_text)
        self.help_label.setSizePolicy(QSizePolicy.Maximum,
                                      QSizePolicy.Expanding)
        self.help_label.setWordWrap(True)
        self.help_label.setAlignment(Qt.AlignTop)

        self.inner_input_layout.addLayout(self.radio_button_layout)
        self.inner_input_layout.addWidget(self.list_widget)

        # Put elements into layouts
        self.input_layout.addWidget(self.label)
        self.input_layout.addLayout(self.inner_input_layout)

        self.help_layout = QVBoxLayout()
        self.help_layout.addWidget(self.help_label)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        self.setLayout(self.main_layout)

        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding)

        # Update list widget
        self.update_list_widget()

        # Connect signal
        self.input_button_group.buttonClicked.connect(
            self.radio_buttons_clicked)
Exemplo n.º 49
0
    def set_widgets(self):
        """Set widgets on the Threshold tab."""
        clear_layout(self.gridLayoutThreshold)

        # Set text in the label
        layer_purpose = self.parent.step_kw_purpose.selected_purpose()
        layer_subcategory = self.parent.step_kw_subcategory.\
            selected_subcategory()
        classification = self.parent.step_kw_classification. \
            selected_classification()

        if is_raster_layer(self.parent.layer):
            statistics = self.parent.layer.dataProvider().bandStatistics(
                1, QgsRasterBandStats.All, self.parent.layer.extent(), 0)
            text = continuous_raster_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                classification['name'],
                statistics.minimumValue,
                statistics.maximumValue)
        else:
            field_name = self.parent.step_kw_field.selected_fields()
            field_index = self.parent.layer.fieldNameIndex(field_name)
            min_value_layer = self.parent.layer.minimumValue(field_index)
            max_value_layer = self.parent.layer.maximumValue(field_index)
            text = continuous_vector_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                field_name,
                classification['name'],
                min_value_layer,
                max_value_layer)
        self.lblThreshold.setText(text)

        thresholds = self.parent.get_existing_keyword('thresholds')
        selected_unit = self.parent.step_kw_unit.selected_unit()['key']

        self.classes = OrderedDict()
        classes = classification.get('classes')
        # Sort by value, put the lowest first
        classes = sorted(classes, key=lambda k: k['value'])

        for i, the_class in enumerate(classes):
            class_layout = QHBoxLayout()

            # Class label
            class_label = QLabel(the_class['name'])

            # Min label
            min_label = QLabel(tr('Min >'))

            # Min value as double spin
            min_value_input = QDoubleSpinBox()
            # TODO(IS) We can set the min and max depends on the unit, later
            min_value_input.setMinimum(0)
            min_value_input.setMaximum(999999)
            if thresholds.get(the_class['key']):
                min_value_input.setValue(thresholds[the_class['key']][0])
            else:
                default_min = the_class['numeric_default_min']
                if isinstance(default_min, dict):
                    default_min = the_class[
                        'numeric_default_min'][selected_unit]
                min_value_input.setValue(default_min)
            min_value_input.setSingleStep(0.1)

            # Max label
            max_label = QLabel(tr('Max <='))

            # Max value as double spin
            max_value_input = QDoubleSpinBox()
            # TODO(IS) We can set the min and max depends on the unit, later
            max_value_input.setMinimum(0)
            max_value_input.setMaximum(999999)
            if thresholds.get(the_class['key']):
                max_value_input.setValue(thresholds[the_class['key']][1])
            else:
                default_max = the_class['numeric_default_max']
                if isinstance(default_max, dict):
                    default_max = the_class[
                        'numeric_default_max'][selected_unit]
                max_value_input.setValue(default_max)
            max_value_input.setSingleStep(0.1)

            # Add to class_layout
            class_layout.addWidget(min_label)
            class_layout.addWidget(min_value_input)
            # class_layout.addStretch(1)
            class_layout.addWidget(max_label)
            class_layout.addWidget(max_value_input)

            # Add to grid_layout
            self.gridLayoutThreshold.addWidget(class_label, i, 0)
            self.gridLayoutThreshold.addLayout(class_layout, i, 1)

            self.classes[the_class['key']] = [min_value_input, max_value_input]

        self.gridLayoutThreshold.setSpacing(0)

        def min_max_changed(index, the_string):
            """Slot when min or max value change.

            :param index: The index of the double spin.
            :type index: int

            :param the_string: The flag to indicate the min or max value.
            :type the_string: str
            """
            if the_string == 'Max value':
                current_max_value = self.classes.values()[index][1]
                target_min_value = self.classes.values()[index + 1][0]
                if current_max_value.value() != target_min_value.value():
                    target_min_value.setValue(current_max_value.value())
            elif the_string == 'Min value':
                current_min_value = self.classes.values()[index][0]
                target_max_value = self.classes.values()[index - 1][1]
                if current_min_value.value() != target_max_value.value():
                    target_max_value.setValue(current_min_value.value())

        # Set behaviour
        for k, v in self.classes.items():
            index = self.classes.keys().index(k)
            if index < len(self.classes) - 1:
                # Max value changed
                v[1].valueChanged.connect(partial(
                    min_max_changed, index=index, the_string='Max value'))
            if index > 0:
                # Min value
                v[0].valueChanged.connect(partial(
                    min_max_changed, index=index, the_string='Min value'))
    def setup_thresholds_panel(self, classification):
        """Setup threshold panel in the right panel.

        :param classification: Classification definition.
        :type classification: dict
        """
        # Set text in the label
        layer_purpose = self.parent.step_kw_purpose.selected_purpose()
        layer_subcategory = self.parent.step_kw_subcategory.\
            selected_subcategory()

        if is_raster_layer(self.parent.layer):
            statistics = self.parent.layer.dataProvider().bandStatistics(
                1, QgsRasterBandStats.All, self.parent.layer.extent(), 0)
            description_text = continuous_raster_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                classification['name'],
                statistics.minimumValue,
                statistics.maximumValue)
        else:
            field_name = self.parent.step_kw_field.selected_fields()
            field_index = self.parent.layer.fieldNameIndex(field_name)
            min_value_layer = self.parent.layer.minimumValue(field_index)
            max_value_layer = self.parent.layer.maximumValue(field_index)
            description_text = continuous_vector_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                field_name,
                classification['name'],
                min_value_layer,
                max_value_layer)

        # Set description
        description_label = QLabel(description_text)
        description_label.setWordWrap(True)
        self.right_layout.addWidget(description_label)

        if self.thresholds:
            thresholds = self.thresholds
        else:
            thresholds = self.parent.get_existing_keyword('thresholds')
        selected_unit = self.parent.step_kw_unit.selected_unit()['key']

        self.threshold_classes = OrderedDict()
        classes = classification.get('classes')
        # Sort by value, put the lowest first
        classes = sorted(classes, key=lambda the_key: the_key['value'])

        grid_layout_thresholds = QGridLayout()

        for i, the_class in enumerate(classes):
            class_layout = QHBoxLayout()

            # Class label
            class_label = QLabel(the_class['name'])

            # Min label
            min_label = QLabel(tr('Min >'))

            # Min value as double spin
            min_value_input = QDoubleSpinBox()
            # TODO(IS) We can set the min and max depends on the unit, later
            min_value_input.setMinimum(0)
            min_value_input.setMaximum(999999)

            if thresholds.get(self.active_exposure['key']):
                exposure_thresholds = thresholds.get(
                    self.active_exposure['key'])
                if exposure_thresholds.get(classification['key']):
                    exposure_thresholds_classifications = exposure_thresholds\
                        .get(classification['key'])
                    min_value_input.setValue(
                        exposure_thresholds_classifications['classes'][
                            the_class['key']][0])
                else:
                    default_min = the_class['numeric_default_min']
                    if isinstance(default_min, dict):
                        default_min = the_class[
                            'numeric_default_min'][selected_unit]
                    min_value_input.setValue(default_min)
            else:
                default_min = the_class['numeric_default_min']
                if isinstance(default_min, dict):
                    default_min = the_class[
                        'numeric_default_min'][selected_unit]
                min_value_input.setValue(default_min)
            min_value_input.setSingleStep(0.1)

            # Max label
            max_label = QLabel(tr('Max <='))

            # Max value as double spin
            max_value_input = QDoubleSpinBox()
            # TODO(IS) We can set the min and max depends on the unit, later
            max_value_input.setMinimum(0)
            max_value_input.setMaximum(999999)
            if thresholds.get(self.active_exposure['key']):
                exposure_thresholds = thresholds.get(
                    self.active_exposure['key'])
                if exposure_thresholds.get(classification['key']):
                    exposure_thresholds_classifications = exposure_thresholds \
                        .get(classification['key'])
                    max_value_input.setValue(
                        exposure_thresholds_classifications['classes'][
                            the_class['key']][1])
                else:
                    default_max = the_class['numeric_default_max']
                    if isinstance(default_max, dict):
                        default_max = the_class[
                            'numeric_default_max'][selected_unit]
                    max_value_input.setValue(default_max)
            else:
                default_max = the_class['numeric_default_max']
                if isinstance(default_max, dict):
                    default_max = the_class[
                        'numeric_default_max'][selected_unit]
                max_value_input.setValue(default_max)
            max_value_input.setSingleStep(0.1)

            # Add to class_layout
            class_layout.addWidget(min_label)
            class_layout.addWidget(min_value_input)
            class_layout.addWidget(max_label)
            class_layout.addWidget(max_value_input)

            class_layout.setStretch(0, 1)
            class_layout.setStretch(1, 2)
            class_layout.setStretch(2, 1)
            class_layout.setStretch(3, 2)

            # Add to grid_layout
            grid_layout_thresholds.addWidget(class_label, i, 0)
            grid_layout_thresholds.addLayout(class_layout, i, 1)

            self.threshold_classes[the_class['key']] = [
                min_value_input, max_value_input]

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

        def min_max_changed(double_spin_index, mode):
            """Slot when min or max value change.

            :param double_spin_index: The index of the double spin.
            :type double_spin_index: int

            :param mode: The flag to indicate the min or max value.
            :type mode: int
            """
            if mode == MAX_VALUE_MODE:
                current_max_value = self.threshold_classes.values()[
                    double_spin_index][1]
                target_min_value = self.threshold_classes.values()[
                    double_spin_index + 1][0]
                if current_max_value.value() != target_min_value.value():
                    target_min_value.setValue(current_max_value.value())
            elif mode == MIN_VALUE_MODE:
                current_min_value = self.threshold_classes.values()[
                    double_spin_index][0]
                target_max_value = self.threshold_classes.values()[
                    double_spin_index - 1][1]
                if current_min_value.value() != target_max_value.value():
                    target_max_value.setValue(current_min_value.value())

        # Set behaviour
        for k, v in self.threshold_classes.items():
            index = self.threshold_classes.keys().index(k)
            if index < len(self.threshold_classes) - 1:
                # Max value changed
                v[1].valueChanged.connect(partial(
                    min_max_changed,
                    double_spin_index=index,
                    mode=MAX_VALUE_MODE))
            if index > 0:
                # Min value
                v[0].valueChanged.connect(partial(
                    min_max_changed,
                    double_spin_index=index,
                    mode=MIN_VALUE_MODE))

        grid_layout_thresholds.setSpacing(0)

        self.right_layout.addLayout(grid_layout_thresholds)
Exemplo n.º 51
0
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
Exemplo n.º 52
0
    def setup_thresholds_panel(self, classification):
        """Setup threshold panel in the right panel.

        :param classification: Classification definition.
        :type classification: dict
        """
        # Set text in the label
        layer_purpose = self.parent.step_kw_purpose.selected_purpose()
        layer_subcategory = self.parent.step_kw_subcategory.\
            selected_subcategory()

        if is_raster_layer(self.parent.layer):
            statistics = self.parent.layer.dataProvider().bandStatistics(
                1, QgsRasterBandStats.All, self.parent.layer.extent(), 0)
            description_text = continuous_raster_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                classification['name'],
                statistics.minimumValue,
                statistics.maximumValue)
        else:
            field_name = self.parent.step_kw_field.selected_fields()
            field_index = self.parent.layer.fieldNameIndex(field_name)
            min_value_layer = self.parent.layer.minimumValue(field_index)
            max_value_layer = self.parent.layer.maximumValue(field_index)
            description_text = continuous_vector_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                field_name,
                classification['name'],
                min_value_layer,
                max_value_layer)

        # Set description
        description_label = QLabel(description_text)
        description_label.setWordWrap(True)
        self.right_layout.addWidget(description_label)

        if self.thresholds:
            thresholds = self.thresholds
        else:
            thresholds = self.parent.get_existing_keyword('thresholds')
        selected_unit = self.parent.step_kw_unit.selected_unit()['key']

        self.threshold_classes = OrderedDict()
        classes = classification.get('classes')
        # Sort by value, put the lowest first
        classes = sorted(classes, key=lambda the_key: the_key['value'])

        grid_layout_thresholds = QGridLayout()

        for i, the_class in enumerate(classes):
            class_layout = QHBoxLayout()

            # Class label
            class_label = QLabel(the_class['name'])

            # Min label
            min_label = QLabel(tr('Min >'))

            # Min value as double spin
            min_value_input = QDoubleSpinBox()
            # TODO(IS) We can set the min and max depends on the unit, later
            min_value_input.setMinimum(0)
            min_value_input.setMaximum(999999)

            if thresholds.get(self.active_exposure['key']):
                exposure_thresholds = thresholds.get(
                    self.active_exposure['key'])
                if exposure_thresholds.get(classification['key']):
                    exposure_thresholds_classifications = exposure_thresholds\
                        .get(classification['key'])
                    min_value_input.setValue(
                        exposure_thresholds_classifications['classes'][
                            the_class['key']][0])
                else:
                    default_min = the_class['numeric_default_min']
                    if isinstance(default_min, dict):
                        default_min = the_class[
                            'numeric_default_min'][selected_unit]
                    min_value_input.setValue(default_min)
            else:
                default_min = the_class['numeric_default_min']
                if isinstance(default_min, dict):
                    default_min = the_class[
                        'numeric_default_min'][selected_unit]
                min_value_input.setValue(default_min)
            min_value_input.setSingleStep(0.1)

            # Max label
            max_label = QLabel(tr('Max <='))

            # Max value as double spin
            max_value_input = QDoubleSpinBox()
            # TODO(IS) We can set the min and max depends on the unit, later
            max_value_input.setMinimum(0)
            max_value_input.setMaximum(999999)
            if thresholds.get(self.active_exposure['key']):
                exposure_thresholds = thresholds.get(
                    self.active_exposure['key'])
                if exposure_thresholds.get(classification['key']):
                    exposure_thresholds_classifications = exposure_thresholds \
                        .get(classification['key'])
                    max_value_input.setValue(
                        exposure_thresholds_classifications['classes'][
                            the_class['key']][1])
                else:
                    default_max = the_class['numeric_default_max']
                    if isinstance(default_max, dict):
                        default_max = the_class[
                            'numeric_default_max'][selected_unit]
                    max_value_input.setValue(default_max)
            else:
                default_max = the_class['numeric_default_max']
                if isinstance(default_max, dict):
                    default_max = the_class[
                        'numeric_default_max'][selected_unit]
                max_value_input.setValue(default_max)
            max_value_input.setSingleStep(0.1)

            # Add to class_layout
            class_layout.addWidget(min_label)
            class_layout.addWidget(min_value_input)
            class_layout.addWidget(max_label)
            class_layout.addWidget(max_value_input)

            class_layout.setStretch(0, 1)
            class_layout.setStretch(1, 2)
            class_layout.setStretch(2, 1)
            class_layout.setStretch(3, 2)

            # Add to grid_layout
            grid_layout_thresholds.addWidget(class_label, i, 0)
            grid_layout_thresholds.addLayout(class_layout, i, 1)

            self.threshold_classes[the_class['key']] = [
                min_value_input, max_value_input]

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

        def min_max_changed(double_spin_index, mode):
            """Slot when min or max value change.

            :param double_spin_index: The index of the double spin.
            :type double_spin_index: int

            :param mode: The flag to indicate the min or max value.
            :type mode: int
            """
            if mode == MAX_VALUE_MODE:
                current_max_value = self.threshold_classes.values()[
                    double_spin_index][1]
                target_min_value = self.threshold_classes.values()[
                    double_spin_index + 1][0]
                if current_max_value.value() != target_min_value.value():
                    target_min_value.setValue(current_max_value.value())
            elif mode == MIN_VALUE_MODE:
                current_min_value = self.threshold_classes.values()[
                    double_spin_index][0]
                target_max_value = self.threshold_classes.values()[
                    double_spin_index - 1][1]
                if current_min_value.value() != target_max_value.value():
                    target_max_value.setValue(current_min_value.value())

        # Set behaviour
        for k, v in self.threshold_classes.items():
            index = self.threshold_classes.keys().index(k)
            if index < len(self.threshold_classes) - 1:
                # Max value changed
                v[1].valueChanged.connect(partial(
                    min_max_changed,
                    double_spin_index=index,
                    mode=MAX_VALUE_MODE))
            if index > 0:
                # Min value
                v[0].valueChanged.connect(partial(
                    min_max_changed,
                    double_spin_index=index,
                    mode=MIN_VALUE_MODE))

        grid_layout_thresholds.setSpacing(0)

        self.right_layout.addLayout(grid_layout_thresholds)
class BaseSectionWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.resize(400,80)

        self.sectionNameEdit = QLineEdit(self)
        self.sectionNameEdit.setGeometry(QRect(0,5,110,30))
        self.sectionNameEdit.setPlaceholderText("Section name")
        self.sectionNameEdit.setToolTip("Name of new section")

        self.sizeEdit = QDoubleSpinBox(self)
        self.sizeEdit.setGeometry(QRect(115,5,65,30))
        self.sizeEdit.setMaximum(100.0)
        self.sizeEdit.setToolTip("Size of section in percent")

        self.colorLabel = ColorChooser(self)
        self.colorLabel.setGeometry(QRect(185,8,25,25))

        self.displayedNameCheckBox = QCheckBox(self)
        self.displayedNameCheckBox.setGeometry(215, 5, 185, 30)
        self.displayedNameCheckBox.setText("Change displayed name")
        self.displayedNameCheckBox.setStyleSheet("font-size:11px;")

        self.displayedNameEdit = QLineEdit(self)
        self.displayedNameEdit.setGeometry(QRect(235,5,120,30))
        self.displayedNameEdit.setPlaceholderText("Displayed name")
        self.displayedNameEdit.setToolTip("Displayed name of new section")
        self.displayedNameEdit.setVisible(False)

        self.removeButton = QPushButton(self)
        self.removeButton.setGeometry(QRect(385,5,35,30))
        self.removeButton.setToolTip("Remove section")
        pixmap = QPixmap("./removeIcon.png")
        buttonIcon = QIcon(pixmap)
        self.removeButton.setIcon(buttonIcon)
        self.removeButton.setIconSize(QSize(25,25))

        self.connect(self.displayedNameCheckBox, QtCore.SIGNAL("clicked()"), self.changeDisplayedName)
        self.connect(self.removeButton, QtCore.SIGNAL("clicked()"), QtCore.SIGNAL("remove()"))
        self.connect(self.sizeEdit, QtCore.SIGNAL("valueChanged(double)"), self.changeSizeValue)

    def changeSizeValue(self):
        self.emit(QtCore.SIGNAL("sizeValueChanged(QWidget*)"), self)

    def changeDisplayedName(self):
        if self.displayedNameCheckBox.isChecked():
            self.displayedNameEdit.setVisible(True)
            self.displayedNameCheckBox.setText("")
        else:
            self.displayedNameEdit.setVisible((False))
            self.displayedNameCheckBox.setText("Change displayed name")

    def getName(self):
        return self.sectionNameEdit.text()

    def setSize(self, size):
        self.sizeEdit.setValue(size)

    def getSize(self):
        return self.sizeEdit.value()

    def getSectionData(self):
        name = self.sectionNameEdit.text()
        size = self.sizeEdit.text()
        color = self.colorLabel.getSelectedColor()
        displayedNameFlag = self.displayedNameCheckBox.isChecked()
        displayedName = self.displayedNameEdit.text()
        return [name, size, color, displayedNameFlag, displayedName]
Exemplo n.º 54
0
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
Exemplo n.º 55
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()
Exemplo n.º 56
0
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)
Exemplo n.º 57
0
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 SettingsWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.setFixedWidth(500)
        self.setFixedHeight(400)
        self.setStyleSheet("font-size:20px;")

        self.vLayout = QVBoxLayout()
        self.setLayout(self.vLayout)

        settingsLabel = QLabel(self)
        settingsLabel.setText("Default settings")
        settingsLabel.setStyleSheet("font-size:25px;")
        settingsLabel.setFixedWidth(500)
        settingsLabel.setAlignment(Qt.AlignCenter)
        self.vLayout.addWidget(settingsLabel)

        sectionColorLabel = QLabel(self)
        sectionColorLabel.setText("Section colors:")
        self.sectionColorChooser = ColorChooser()
        self.sectionColorChooser.setMaximumWidth(50)
        self.sectionSecondColorChooser = ColorChooser()
        self.sectionSecondColorChooser.setMaximumWidth(50)
        self.putInHorizontalLayout(sectionColorLabel, self.sectionColorChooser,
                                   self.sectionSecondColorChooser)

        subsectionColorLabel = QLabel(self)
        subsectionColorLabel.setText("Subsection colors: ")
        self.subsectionColorChooser = ColorChooser(self)
        self.subsectionColorChooser.setMaximumWidth(50)
        self.subsectionSecondColorChooser = ColorChooser(self)
        self.subsectionSecondColorChooser.setMaximumWidth(50)
        self.putInHorizontalLayout(subsectionColorLabel,
                                   self.subsectionColorChooser,
                                   self.subsectionSecondColorChooser)

        linacSectionSizeLabel = QLabel(self)
        linacSectionSizeLabel.setText("Linac section size: ")
        self.linacSectionSizeSpinBox = QDoubleSpinBox(self)
        self.linacSectionSizeSpinBox.setFixedWidth(100)
        self.linacSectionSizeSpinBox.setMaximum(100.0)
        self.putInHorizontalLayout(linacSectionSizeLabel,
                                   self.linacSectionSizeSpinBox)

        linacSubsectionSizeLabel = QLabel(self)
        linacSubsectionSizeLabel.setText("Linac subsection size: ")
        self.linacSubsectionSizeSpinBox = QDoubleSpinBox(self)
        self.linacSubsectionSizeSpinBox.setFixedWidth(100)
        self.linacSubsectionSizeSpinBox.setMaximum(100.0)
        self.putInHorizontalLayout(linacSubsectionSizeLabel,
                                   self.linacSubsectionSizeSpinBox)

        ringSectionSizeLabel = QLabel(self)
        ringSectionSizeLabel.setText("Ring section size: ")
        self.ringSectionSizeSpinBox = QDoubleSpinBox(self)
        self.ringSectionSizeSpinBox.setFixedWidth(100)
        self.ringSectionSizeSpinBox.setMaximum(100.0)
        self.putInHorizontalLayout(ringSectionSizeLabel,
                                   self.ringSectionSizeSpinBox)

        ringSubectionSizeLabel = QLabel(self)
        ringSubectionSizeLabel.setText("Ring subsection size: ")
        self.ringSubsectionSizeSpinBox = QDoubleSpinBox(self)
        self.ringSubsectionSizeSpinBox.setFixedWidth(100)
        self.ringSubsectionSizeSpinBox.setMaximum(100.0)
        self.putInHorizontalLayout(ringSubectionSizeLabel,
                                   self.ringSubsectionSizeSpinBox)

        centerCoordinatesLabel = QLabel(self)
        centerCoordinatesLabel.setText("Real coordinates of ring center:")
        self.centerCoordinatesEditX = QLineEdit()
        self.centerCoordinatesEditX.setPlaceholderText("X")
        self.centerCoordinatesEditX.setFixedWidth(80)
        self.centerCoordinatesEditY = QLineEdit()
        self.centerCoordinatesEditY.setPlaceholderText("Y")
        self.centerCoordinatesEditY.setFixedWidth(80)
        self.putInHorizontalLayout(centerCoordinatesLabel,
                                   self.centerCoordinatesEditX,
                                   self.centerCoordinatesEditY)

        showDeviceCaptionsLabel = QLabel(self)
        showDeviceCaptionsLabel.setText("Show device captions:")
        showDeviceCaptionsLabel.setFixedWidth(500)
        self.showDeviceCaptionsCheckBox = QCheckBox(self)
        self.putInHorizontalLayout(showDeviceCaptionsLabel,
                                   self.showDeviceCaptionsCheckBox)

        useDbParametersLabel = QLabel(self)
        useDbParametersLabel.setText("Use parameters from database")
        useDbParametersLabel.setFixedWidth(500)
        self.useDbParametersCheckBox = QCheckBox(self)
        self.putInHorizontalLayout(useDbParametersLabel,
                                   self.useDbParametersCheckBox)

        tangoHostLabel = QLabel(self)
        tangoHostLabel.setText("Tango Host")
        self.tangoHostEdit = QLineEdit(self)
        self.tangoHostEdit.setFixedHeight(25)
        self.tangoHostEdit.setText("127.0.0.1:10000")
        self.tangoHostEdit.setStyleSheet("font-size:18px;")
        self.putInHorizontalLayout(tangoHostLabel, self.tangoHostEdit)

        self.setDefaultSettings()

    def putInHorizontalLayout(self, label, edit, secondEdit=None):
        layout = QHBoxLayout()
        layout.addWidget(label, Qt.AlignLeft)
        layout.addWidget(edit, Qt.AlignRight)
        if secondEdit is not None:
            layout.addWidget(secondEdit, Qt.AlignRight)
        self.vLayout.addLayout(layout)

    def setDefaultSettings(self):
        self.linacSectionSizeSpinBox.setValue(25)
        self.linacSubsectionSizeSpinBox.setValue(50)
        self.ringSectionSizeSpinBox.setValue(25)
        self.ringSubsectionSizeSpinBox.setValue(33.33)
        self.centerCoordinatesEditX.setText("0")
        self.centerCoordinatesEditY.setText("0")
        self.showDeviceCaptionsCheckBox.setChecked(True)
        self.useDbParametersCheckBox.setChecked(True)

    def saveSettings(self):
        sectionFirstColor = str(self.sectionColorChooser.getSelectedColor())
        sectionSecondColor = str(
            self.sectionSecondColorChooser.getSelectedColor())
        subsectionColor = str(self.subsectionColorChooser.getSelectedColor())
        subsectionSecondColor = str(
            self.subsectionSecondColorChooser.getSelectedColor())
        linacSectionSize = float(self.linacSectionSizeSpinBox.value())
        linacSubsectionSize = float(self.linacSubsectionSizeSpinBox.value())
        ringSectionSize = float(self.ringSectionSizeSpinBox.value())
        ringSubsectionSize = float(self.ringSubsectionSizeSpinBox.value())
        centerCoordinateX = float(self.centerCoordinatesEditX.text())
        centerCoordinateY = float(self.centerCoordinatesEditY.text())
        deviceCaptions = bool(self.showDeviceCaptionsCheckBox.isChecked())
        parametersFromDb = bool(self.useDbParametersCheckBox.isChecked())
        tangoHost = str(self.tangoHostEdit.text())

        SettingsCloud.setParameter("sectionFirstColor", sectionFirstColor)
        SettingsCloud.setParameter("sectionSecondColor", sectionSecondColor)
        SettingsCloud.setParameter("subsectionFirstColor", subsectionColor)
        SettingsCloud.setParameter("subsectionSecondColor",
                                   subsectionSecondColor)
        SettingsCloud.setParameter("linacSectionSize", linacSectionSize)
        SettingsCloud.setParameter("linacSubsectionSize", linacSubsectionSize)
        SettingsCloud.setParameter("ringSectionSize", ringSectionSize)
        SettingsCloud.setParameter("ringSubsectionSize", ringSubsectionSize)
        SettingsCloud.setParameter("centerCoordinateX", centerCoordinateX)
        SettingsCloud.setParameter("centerCoordinateY", centerCoordinateY)
        SettingsCloud.setParameter("deviceCaptions", deviceCaptions)
        SettingsCloud.setParameter("parameterFromDb", parametersFromDb)
        TangoDeviceManager.setTangoDatabaseAddress(tangoHost)