Exemplo n.º 1
0
    def __init__(self, parent, prefix = None, suffix = None, option = None, min_ = None, max_ = None,
                 step = None, tip = None, value = None, changed =None):
        super(MySpinBox, self).__init__(parent)
    
        if prefix:
            plabel = QLabel(prefix)
        else:
            plabel = None
        if suffix:
            slabel = QLabel(suffix)
        else:
            slabel = None
        spinbox = QSpinBox(parent)
        if min_ is not None:
            spinbox.setMinimum(min_)
        if max_ is not None:
            spinbox.setMaximum(max_)
        if step is not None:
            spinbox.setSingleStep(step)
        if tip is not None:
            spinbox.setToolTip(tip)
        layout = QHBoxLayout()
        for subwidget in (plabel, spinbox, slabel):
            if subwidget is not None:
                layout.addWidget(subwidget)
        if value is not None:
            spinbox.setValue(value)
        
        if changed is not None:
            self.connect(spinbox, SIGNAL('valueChanged(int)'), changed)

        layout.addStretch(1)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        self.spin = spinbox
Exemplo n.º 2
0
    def createTimeStepRow(self):
        history_length_spinner = QSpinBox()
        addHelpToWidget(history_length_spinner, "config/init/history_length")
        history_length_spinner.setMinimum(0)
        history_length_spinner.setMaximum(getHistoryLength())

        initial = QToolButton()
        initial.setText("Initial")
        addHelpToWidget(initial, "config/init/history_length")

        def setToMin():
            history_length_spinner.setValue(0)

        initial.clicked.connect(setToMin)

        end_of_time = QToolButton()
        end_of_time.setText("End of time")
        addHelpToWidget(end_of_time, "config/init/history_length")

        def setToMax():
            history_length_spinner.setValue(getHistoryLength())

        end_of_time.clicked.connect(setToMax)

        row = createRow(QLabel("Timestep:"), history_length_spinner, initial, end_of_time)

        return row, history_length_spinner
Exemplo n.º 3
0
class DataConfigurationWidget(ConfigurationWidget):
    def __init__(self):
        ConfigurationWidget.__init__(self)

        self.keyIndex = QSpinBox()
        self.keyIndex.setMinimum(0)

        self.addRow("index:", self.keyIndex)

        self.setIndexBounds(0)

        self.connect(self.keyIndex, SIGNAL("valueChanged(int)"), self.applyConfiguration)

    def setIndexBounds(self, i):
        self.keyIndex.setMaximum(i)

    def getIndex(self):
        return self.keyIndex.value()

    def setParameter(self, parameter):
        self.parameter = parameter
        self.applyConfiguration(False)

    def applyConfiguration(self, emit=True):
        user_data = {"state": self.getState(), "data_index": self.getIndex()}
        self.parameter.setUserData(user_data)
        self.emitConfigurationChanged(emit)
Exemplo n.º 4
0
class Option(QWidget):
   
    def __init__(self):
        QWidget.__init__(self)
        self.resize(168, 86)
        self.name = "Progress"
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setMargin(0)
        self.label_2 = QLabel(self)
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.spinBox = QSpinBox(self)
        self.spinBox.setMinimum(60)
        self.spinBox.setMaximum(600)
        self.gridLayout.addWidget(self.spinBox, 0, 2, 1, 1)
        self.spinBox_2 = QSpinBox(self)
        self.spinBox_2.setMinimum(120)
        self.spinBox_2.setMaximum(600)
        self.spinBox_2.setProperty("value", 600)
        self.gridLayout.addWidget(self.spinBox_2, 1, 2, 1, 1)
        self.label = QLabel(self)

        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)

        self.label_2.setText(u"Max Süre(dk):")
        self.label.setText(u"Min. Süre(dk):")
Exemplo n.º 5
0
    def addSpinBox(self,
                   attribute_name,
                   title,
                   tool_tip=None,
                   min_value=1,
                   max_value=10,
                   single_step=1):
        sb = QSpinBox()
        self[attribute_name] = sb
        sb.setMaximumHeight(25)
        sb_layout = QHBoxLayout()
        sb_layout.addWidget(sb)
        sb_layout.addStretch()
        self.addRow(title, sb_layout)

        if tool_tip is not None:
            sb.setToolTip(tool_tip)

        sb.setMinimum(min_value)
        sb.setMaximum(max_value)
        sb.setSingleStep(single_step)

        def getter(self):
            return self[attribute_name].value()

        def setter(self, value):
            self[attribute_name].setValue(value)

        self.updateProperty(attribute_name, getter, setter)
        return sb
Exemplo n.º 6
0
class ProjectData(QWidget):

    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(self.tr("Name:")), 0, 0)
        self.name = QLineEdit()
        if self._parent._item.name == '':
            self.name.setText(file_manager.get_basename(
                self._parent._item.path))
        else:
            self.name.setText(self._parent._item.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(self.tr("Project Type:")), 1, 0)
        self.txtType = QLineEdit()
        completer = QCompleter(sorted(settings.PROJECT_TYPES))
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.txtType.setCompleter(completer)
        self.txtType.setText(self._parent._item.projectType)
        grid.addWidget(self.txtType, 1, 1)
        grid.addWidget(QLabel(self.tr("Description:")), 2, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent._item.description)
        grid.addWidget(self.description, 2, 1)
        grid.addWidget(QLabel(self.tr("URL:")), 3, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent._item.url)
        grid.addWidget(self.url, 3, 1)
        grid.addWidget(QLabel(self.tr("Licence:")), 4, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        index = self.cboLicense.findText(self._parent._item.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 4, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent._item.extensions))
        grid.addWidget(QLabel(self.tr("Supported Extensions:")), 5, 0)
        grid.addWidget(self.txtExtensions, 5, 1)

        grid.addWidget(QLabel(self.tr("Indentation: ")), 6, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent._item.indentation)
        self.spinIndentation.setMinimum(1)
        grid.addWidget(self.spinIndentation, 6, 1)
        self.checkUseTabs = QCheckBox(self.tr("Use Tabs."))
        self.checkUseTabs.setChecked(self._parent._item.useTabs)
        grid.addWidget(self.checkUseTabs, 6, 2)
Exemplo n.º 7
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
Exemplo n.º 8
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)
Exemplo n.º 9
0
 def create_spinbox(self, prefix, suffix, option, default=NoDefault,
                    min_=None, max_=None, step=None, tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[spinbox] = (option, default)
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
Exemplo n.º 10
0
class AddWordsDialog(QDialog):
    """
    Dialog that allows the user to insert the number of words he wants to add.
    """
    def __init__(self, parent = None):
        super(AddWordsDialog, self).__init__(parent)

        label = QLabel("How many words do you want to add?")
        self.spinBox = QSpinBox()
        self.spinBox.setMinimum(1)
        self.spinBox.setMaximum(50)
        label.setBuddy(self.spinBox)
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        HLayout = QHBoxLayout()
        HLayout.addWidget(label)
        HLayout.addWidget(self.spinBox)
        HLayout2 = QHBoxLayout()
        HLayout2.addWidget(buttonBox)
        VLayout = QVBoxLayout()
        VLayout.addLayout(HLayout)
        VLayout.addLayout(HLayout2)

        self.setLayout(VLayout)
        self.spinBox.setFocus()
        self.setWindowTitle("Add Words")

        self.connect(buttonBox, SIGNAL("accepted()"),
                    self.accept)
        self.connect(buttonBox, SIGNAL("rejected()"),
                    self.reject)
Exemplo n.º 11
0
    def createTimeStepRow(self):
        history_length_spinner = QSpinBox()
        addHelpToWidget(history_length_spinner, "config/init/history_length")
        history_length_spinner.setMinimum(0)
        history_length_spinner.setMaximum(getHistoryLength())

        initial = QToolButton()
        initial.setText("Initial")
        addHelpToWidget(initial, "config/init/history_length")

        def setToMin():
            history_length_spinner.setValue(0)

        initial.clicked.connect(setToMin)

        end_of_time = QToolButton()
        end_of_time.setText("End of time")
        addHelpToWidget(end_of_time, "config/init/history_length")

        def setToMax():
            history_length_spinner.setValue(getHistoryLength())

        end_of_time.clicked.connect(setToMax)

        row = createRow(QLabel("Timestep:"), history_length_spinner, initial,
                        end_of_time)

        return row, history_length_spinner
Exemplo n.º 12
0
    def createEditor(self, parent, option, index):

        editor = QSpinBox(parent)
        editor.setMinimum(0)
        editor.setMaximum(100)

        return editor
Exemplo n.º 13
0
 def create_spinbox(self, prefix, suffix, option, 
                    min_=None, max_=None, step=None, tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[spinbox] = option
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     widget.spin = spinbox
     return widget
class IntegerParameterWidget(NumericParameterWidget):
    """Widget class for Integer parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A IntegerParameter object.
        :type parameter: IntegerParameter

        """
        super(IntegerParameterWidget, self).__init__(parameter, parent)

        self._input = QSpinBox()
        self._input.setValue(self._parameter.value)
        self._input.setMinimum(self._parameter.minimum_allowed_value)
        self._input.setMaximum(self._parameter.maximum_allowed_value)
        tool_tip = 'Choose a number between %d and %d' % (
            self._parameter.minimum_allowed_value,
            self._parameter.maximum_allowed_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.º 15
0
class IntegerParameterWidget(NumericParameterWidget):
    """Widget class for Integer parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A IntegerParameter object.
        :type parameter: IntegerParameter

        """
        super(IntegerParameterWidget, self).__init__(parameter, parent)

        self._input = QSpinBox()
        self._input.setValue(self._parameter.value)
        self._input.setMinimum(self._parameter.minimum_allowed_value)
        self._input.setMaximum(self._parameter.maximum_allowed_value)
        tool_tip = 'Choose a number between %d and %d' % (
            self._parameter.minimum_allowed_value,
            self._parameter.maximum_allowed_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.º 16
0
class AddressAndMaskInput(QWidget):
    def __init__(self, ip_version=4, parent=None):
        QWidget.__init__(self, parent)

        self.address = QLineEdit()
        self.prefix = QSpinBox()
        self.prefix.setMinimum(0)

        self.setVersion(ip_version)
        layout = QHBoxLayout(self)

        layout.addWidget(self.address)
        layout.addWidget(QLabel("<h2>/</h2>"))
        layout.addWidget(self.prefix)

    def setVersion(self, ip_version):
        if ip_version == 4:
            self.ip_regex = IPV4_REGEXP
            mask_size = 31
        else:
            self.ip_regex = IPV6_REGEXP
            mask_size = 127

        validator = QRegExpValidator(self.ip_regex, self.address)
        self.address.setValidator(validator)
        self.prefix.setMaximum(mask_size)

    def showValid(self, valid):
        if valid:
            style = u''
        else:
            style = u'background: #b52323;'

        for widget in (self.prefix, self.address):
            widget.setStyleSheet(style)
Exemplo n.º 17
0
    def __init__(self,parent,attached=False):
      cp=QLineEdit(parent)
      tel=QLineEdit(parent)
      tipo=QSpinBox(parent)
      tipo.setMaximum(2)
      tipo.setMinimum(0)
      tipo.setButtonSymbols(2)
      #cp.setInputMask("#####")
      tel.setInputMask("(###)-###-##-##")
      cp.setAlignment(QtCore.Qt.AlignCenter)
      tipo.setAlignment(QtCore.Qt.AlignCenter)
      tel.setAlignment(QtCore.Qt.AlignCenter)
      Admin1.__init__(self,parent,'clientes',
      [['id','Id:','str',None,False],
      ['nombre','Nombre:','str',None,True],
      ['rfc','RFC:','str',None,True],
      ['direccion','Direccion:','str',None,True],
      ['poblacion','Poblacion:','str',None,True],
      ['estado','Estado:','str',None,True],
      ['tel','Telefono:','str',tel,True],
      ['correo','E-mail:','str',cp,True],
      ['tipo','Tipo:','hide',0,True],
      ['credito','Limite de credito:','double',None,True]],
      info="",logo=":/modulos/images/png/elegant/clientes.png",ide=-1,ancla=True,cond=" WHERE tipo=0 order by nombre"
      )
      self.ui=parent
      self.ui.connect(self.ui.tClientes, QtCore.SIGNAL("clicked()"), self.iniciar)
      self.ui.connect(self.ui.verClientes, QtCore.SIGNAL("triggered()"), self.iniciar)

      self.anclar(attached)
	
    def __init__(self, advanced_option=False):
        SimulationConfigPanel.__init__(self, IteratedEnsembleSmoother(),
                                       advanced_option)

        layout = QFormLayout()

        case_selector = CaseSelector()
        layout.addRow("Current case:", case_selector)

        run_path_label = QLabel("<b>%s</b>" % getRunPath())
        addHelpToWidget(run_path_label, "config/simulation/runpath")
        layout.addRow("Runpath:", run_path_label)

        number_of_realizations_label = QLabel("<b>%d</b>" %
                                              getRealizationCount())
        addHelpToWidget(number_of_realizations_label,
                        "config/ensemble/num_realizations")
        layout.addRow(QLabel("Number of realizations:"),
                      number_of_realizations_label)

        # The num_iterations_spinner does not track any external changes (will that ever happen?)
        num_iterations_spinner = QSpinBox()
        num_iterations_spinner.setMinimum(1)
        num_iterations_spinner.setMaximum(100)
        num_iterations_spinner.setValue(getNumberOfIterations())
        addHelpToWidget(num_iterations_spinner,
                        "config/simulation/number_of_iterations")
        num_iterations_spinner.valueChanged[int].connect(setNumberOfIterations)

        layout.addRow("Number of iterations:", num_iterations_spinner)

        self._iterated_target_case_format_model = TargetCaseModel(
            format_mode=True)
        self._iterated_target_case_format_field = StringBox(
            self._iterated_target_case_format_model,
            "config/simulation/iterated_target_case_format")
        self._iterated_target_case_format_field.setValidator(
            ProperNameFormatArgument())
        layout.addRow("Target case format:",
                      self._iterated_target_case_format_field)

        self._analysis_module_selector = AnalysisModuleSelector(
            iterable=True, help_link="config/analysis/analysis_module")
        layout.addRow("Analysis Module:", self._analysis_module_selector)

        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(
            self._active_realizations_model,
            "config/simulation/active_realizations")
        self._active_realizations_field.setValidator(
            RangeStringArgument(getRealizationCount()))
        layout.addRow("Active realizations", self._active_realizations_field)

        self._iterated_target_case_format_field.getValidationSupport(
        ).validationChanged.connect(self.simulationConfigurationChanged)
        self._active_realizations_field.getValidationSupport(
        ).validationChanged.connect(self.simulationConfigurationChanged)

        self.setLayout(layout)
Exemplo n.º 19
0
class FloatColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget):
    def __init__(self, parent, hex_widget, column):
        QWidget.__init__(self, parent)
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        self.hexWidget = hex_widget
        self.column = column

        self.cmbBinaryFormat = QComboBox(self)
        self.cmbBinaryFormat.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        for fmt in (valuecodecs.FloatCodec.FormatFloat, valuecodecs.FloatCodec.FormatDouble):
            self.cmbBinaryFormat.addItem(valuecodecs.FloatCodec.formatName(fmt), fmt)
            if column is not None and column.valuecodec.binaryFormat == fmt:
                self.cmbBinaryFormat.setCurrentIndex(self.cmbBinaryFormat.count() - 1)

        self.spnPrecision = QSpinBox(self)
        self.spnPrecision.setMinimum(0)
        self.spnPrecision.setMaximum(12)
        if column is not None:
            self.spnPrecision.setValue(column.formatter.precision)
        else:
            self.spnPrecision.setValue(6)

        self.spnColumnsOnRow = QSpinBox(self)
        self.spnColumnsOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.spnColumnsOnRow.setMinimum(1)
        self.spnColumnsOnRow.setMaximum(32)
        if column is not None:
            self.spnColumnsOnRow.setValue(column.columnsOnRow)
        else:
            self.spnColumnsOnRow.setValue(4)

        self.setLayout(QFormLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addRow(utils.tr('Binary format:'), self.cmbBinaryFormat)
        self.layout().addRow(utils.tr('Digits after point:'), self.spnPrecision)
        self.layout().addRow(utils.tr('Columns on row:'), self.spnColumnsOnRow)

    @property
    def _valueCodec(self):
        c = valuecodecs.FloatCodec()
        c.binaryFormat = self.cmbBinaryFormat.itemData(self.cmbBinaryFormat.currentIndex())
        return c

    @property
    def _formatter(self):
        f = formatters.FloatFormatter()
        f.precision = self.spnPrecision.value()
        return f

    def createColumnModel(self, hex_widget):
        return FloatColumnModel(hex_widget.document, self._valueCodec, self._formatter, self.spnColumnsOnRow.value())

    def saveToColumn(self, column):
        column.valuecodec = self._valueCodec
        column.formatter = self._formatter
        column.columnsOnRow = self.spnColumnsOnRow.value()
        column.reset()
Exemplo n.º 20
0
 def createSpinBox(self, variable_name, variable_value, variable_type, analysis_module_variables_model):
     spinner = QSpinBox()
     spinner.setMinimumWidth(75)
     spinner.setMaximum(analysis_module_variables_model.getVariableMaximumValue(variable_name))
     spinner.setMinimum(analysis_module_variables_model.getVariableMinimumValue(variable_name))
     spinner.setSingleStep(analysis_module_variables_model.getVariableStepValue(variable_name))
     if variable_value is not None:
         spinner.setValue(variable_value)
     spinner.valueChanged.connect(partial(self.valueChanged, variable_name, variable_type, spinner))
     return spinner
 def createSpinBox(self, variable_name, variable_value, variable_type, analysis_module_variables_model):
     spinner = QSpinBox()
     spinner.setMinimumWidth(75)
     spinner.setMaximum(analysis_module_variables_model.getVariableMaximumValue(variable_name))
     spinner.setMinimum(analysis_module_variables_model.getVariableMinimumValue(variable_name))
     spinner.setSingleStep(analysis_module_variables_model.getVariableStepValue(variable_name))
     if variable_value is not None:
         spinner.setValue(variable_value)
     spinner.valueChanged.connect(partial(self.valueChanged, variable_name, variable_type, spinner))
     return spinner
Exemplo n.º 22
0
class AutoNumbering(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        def hbox(*widgets):
            box = QHBoxLayout()
            [box.addWidget(z) for z in widgets]
            box.addStretch()
            return box

        vbox = QVBoxLayout()

        startlabel = QLabel(translate('Autonumbering Wizard', "&Start: "))
        self._start = QSpinBox()
        startlabel.setBuddy(self._start)
        self._start.setValue(1)
        self._start.setMaximum(65536)

        vbox.addLayout(hbox(startlabel, self._start))

        label = QLabel(
            translate('Autonumbering Wizard',
                      'Max length after padding with zeroes: '))
        self._padlength = QSpinBox()
        label.setBuddy(self._padlength)
        self._padlength.setValue(1)
        self._padlength.setMaximum(65535)
        self._padlength.setMinimum(1)
        vbox.addLayout(hbox(label, self._padlength))

        self._restart_numbering = QCheckBox(
            translate('Autonumbering Wizard',
                      "&Restart numbering at each directory."))

        vbox.addWidget(self._restart_numbering)
        vbox.addStretch()

        self.setLayout(vbox)

    def setArguments(self, *args):
        minimum = sanitize(int, args[0], 0)
        restart = sanitize(bool, args[1], True)
        padding = sanitize(int, args[2], 1)

        self._start.setValue(minimum)
        self._restart_numbering.setChecked(restart)
        self._padlength.setValue(padding)

    def arguments(self):
        x = [
            self._start.value(),
            self._restart_numbering.isChecked(),
            self._padlength.value()
        ]
        return x
Exemplo n.º 23
0
    def _create_widget(cls, c, parent, host=None):
        sb = QSpinBox(parent)
        sb.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name))

        # Set ranges
        c_min = sb.valueFromText(str(c.minimum))
        c_max = sb.valueFromText(str(c.maximum))
        sb.setMinimum(c.minimum)
        sb.setMaximum(c.maximum)

        return sb
Exemplo n.º 24
0
class ConfigWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QFormLayout()
        self.setLayout(layout)

        self.inputLabel = QLabel("Video Input")
        self.inputLayout = QHBoxLayout()
        self.inputCombobox = QComboBox()
        self.inputSettingsToolButton = QToolButton()
        self.inputSettingsToolButton.setText("Settings")
        configIcon = QIcon.fromTheme("preferences-other")
        self.inputSettingsToolButton.setIcon(configIcon)
        self.inputSettingsToolButton.setSizePolicy(QSizePolicy.Maximum,
                                                   QSizePolicy.Maximum)
        self.inputSettingsToolButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.inputSettingsStack = QStackedWidget()
        blankWidget = QWidget()
        self.inputSettingsStack.addWidget(blankWidget)
        self.inputSettingsStack.addWidget(self.inputSettingsToolButton)
        self.inputLayout.addWidget(self.inputCombobox)
        self.inputLayout.addWidget(self.inputSettingsStack)
        layout.addRow(self.inputLabel, self.inputLayout)

        self.videocolourLabel = QLabel(self.tr("Colour Format"))
        self.videocolourComboBox = QComboBox()
        self.videocolourComboBox.addItem("video/x-raw-rgb")
        self.videocolourComboBox.addItem("video/x-raw-yuv")
        self.videocolourComboBox.setSizePolicy(QSizePolicy.Minimum,
                                               QSizePolicy.Maximum)
        layout.addRow(self.videocolourLabel, self.videocolourComboBox)

        self.framerateLabel = QLabel("Framerate")
        self.framerateLayout = QHBoxLayout()
        self.framerateSlider = QSlider()
        self.framerateSlider.setOrientation(Qt.Horizontal)
        self.framerateSlider.setMinimum(1)
        self.framerateSlider.setMaximum(60)
        self.framerateSpinBox = QSpinBox()
        self.framerateSpinBox.setMinimum(1)
        self.framerateSpinBox.setMaximum(60)
        self.framerateLayout.addWidget(self.framerateSlider)
        self.framerateLayout.addWidget(self.framerateSpinBox)
        layout.addRow(self.framerateLabel, self.framerateLayout)

        self.videoscaleLabel = QLabel("Video Scale")
        self.videoscaleComboBox = QComboBox()
        for scale in resmap:
            self.videoscaleComboBox.addItem(scale)
        self.videoscaleComboBox.setSizePolicy(QSizePolicy.Minimum,
                                              QSizePolicy.Maximum)
        layout.addRow(self.videoscaleLabel, self.videoscaleComboBox)
Exemplo n.º 25
0
    def initUI(self):

        vbox = QHBoxLayout()
        edit = QDoubleSpinBox(self)
        edit.setLocale(QLocale(QLocale.English))
        edit.setDecimals(2)
        vbox.addWidget(edit)
        vbox.addWidget(QLabel("10^"))
        expo = QSpinBox(self)
        expo.setMinimum(-8)
        expo.setMaximum(8)
        vbox.addWidget(expo)
        self.setLayout(vbox)
Exemplo n.º 26
0
class ConfigWidget(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QFormLayout()
        self.setLayout(layout)

        self.inputLabel = QLabel("Video Input")
        self.inputLayout = QHBoxLayout()
        self.inputCombobox = QComboBox()
        self.inputSettingsToolButton = QToolButton()
        self.inputSettingsToolButton.setText("Settings")
        configIcon = QIcon.fromTheme("preferences-other")
        self.inputSettingsToolButton.setIcon(configIcon)
        self.inputSettingsToolButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.inputSettingsToolButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.inputSettingsStack = QStackedWidget()
        blankWidget = QWidget()
        self.inputSettingsStack.addWidget(blankWidget)
        self.inputSettingsStack.addWidget(self.inputSettingsToolButton)
        self.inputLayout.addWidget(self.inputCombobox)
        self.inputLayout.addWidget(self.inputSettingsStack)
        layout.addRow(self.inputLabel, self.inputLayout)

        self.videocolourLabel = QLabel(self.tr("Colour Format"))
        self.videocolourComboBox = QComboBox()
        self.videocolourComboBox.addItem("video/x-raw-rgb")
        self.videocolourComboBox.addItem("video/x-raw-yuv")
        self.videocolourComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        layout.addRow(self.videocolourLabel, self.videocolourComboBox)

        self.framerateLabel = QLabel("Framerate")
        self.framerateLayout = QHBoxLayout()
        self.framerateSlider = QSlider()
        self.framerateSlider.setOrientation(Qt.Horizontal)
        self.framerateSlider.setMinimum(1)
        self.framerateSlider.setMaximum(60)
        self.framerateSpinBox = QSpinBox()
        self.framerateSpinBox.setMinimum(1)
        self.framerateSpinBox.setMaximum(60)
        self.framerateLayout.addWidget(self.framerateSlider)
        self.framerateLayout.addWidget(self.framerateSpinBox)
        layout.addRow(self.framerateLabel, self.framerateLayout)

        self.videoscaleLabel = QLabel("Video Scale")
        self.videoscaleComboBox = QComboBox()
        for scale in resmap:
            self.videoscaleComboBox.addItem(scale)
        self.videoscaleComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        layout.addRow(self.videoscaleLabel, self.videoscaleComboBox)
Exemplo n.º 27
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.º 28
0
    def __init__(self, attr_name, attr_val, parent=None):
        super(Attribute, self).__init__(parent)

        # The label with the attribute's name
        label = QLabel(attr_name)

        # Now create the editing element, initialized with the attribute's
        # value.
        # First, if the value is an integer, use a spinbox
        if type(attr_val) is int:
            value = QSpinBox()
            value.setMaximum(1E9)
            value.setValue(attr_val)
        # Second, if the value is a float, use a doublespinbox, with some
        # customizations for certain attributes.
        elif type(attr_val) is float:
            # We want to display the sensitivities in useful units, which should
            # simulate scientific notation. The attribute value is the
            # sensitivity's index in the SENSVECTOR.
            if "Sens" in attr_name:
                value = QSpinBox()
                value.setMaximum(1E10)
                value.setMinimum(1)
                attr_val = SENSVECTOR[int(attr_val)]
                # Figure out which units to use
                for ex in [(1E-3, 'mV'), (1E-6, 'uV'), (1E-9, 'nV')]:
                    if attr_val / ex[0] > 1 and attr_val / ex[0] < 1000:
                        value.setValue(attr_val / ex[0])
                        value.setSuffix(' {units}'.format(units=ex[1]))
            # If the value is a float, but not a sensitivity, just use a normal
            # doublespinbox
            else:
                value = QDoubleSpinBox()
                value.setMaximum(1E9)
                value.setMinimum(-1E9)
                value.setValue(attr_val)
        # Third, if the value is a datetime, dispaly it in a datetimeedit
        # element.
        elif type(attr_val) is datetime:
            value = QDateTimeEdit()
            value.setDateTime(attr_val)
        # Finally, for everything else just display it in a lineedit element.
        else:
            value = QLineEdit()
            value.setText(str(attr_val))

        layout = QHBoxLayout()
        layout.addWidget(label)
        layout.addWidget(value)

        self.setLayout(layout)
Exemplo n.º 29
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.º 30
0
class AutoNumbering(QWidget):
    def __init__(self, parent = None):
        QWidget.__init__(self, parent)

        def hbox(*widgets):
            box = QHBoxLayout()
            [box.addWidget(z) for z in widgets]
            box.addStretch()
            return box

        vbox = QVBoxLayout()

        startlabel = QLabel(translate('Autonumbering Wizard', "&Start: "))
        self._start = QSpinBox()
        startlabel.setBuddy(self._start)
        self._start.setValue(1)
        self._start.setMaximum(65536)

        vbox.addLayout(hbox(startlabel, self._start))

        label = QLabel(translate('Autonumbering Wizard', 'Max length after padding with zeroes: '))
        self._padlength = QSpinBox()
        label.setBuddy(self._padlength)
        self._padlength.setValue(1)
        self._padlength.setMaximum(65535)
        self._padlength.setMinimum(1)
        vbox.addLayout(hbox(label, self._padlength))

        self._restart_numbering = QCheckBox(translate('Autonumbering Wizard', "&Restart numbering at each directory."))

        vbox.addWidget(self._restart_numbering)
        vbox.addStretch()

        self.setLayout(vbox)

    def setArguments(self, *args):
        minimum = sanitize(int, args[0], 0)
        restart = sanitize(bool, args[1], True)
        padding = sanitize(int, args[2], 1)

        self._start.setValue(minimum)
        self._restart_numbering.setChecked(restart)
        self._padlength.setValue(padding)

    def arguments(self):
        x = [
            self._start.value(),
            self._restart_numbering.isChecked(),
            self._padlength.value()]
        return x
Exemplo n.º 31
0
class IntegerSpinner(HelpedWidget):
    """A spinner widget for integers. The data structure expected and sent to the getter and setter is an integer."""
    def __init__(self, model, spinner_label="Integer Number", help_link=""):
        HelpedWidget.__init__(self, spinner_label, help_link)

        assert isinstance(model, SpinnerModelMixin)
        self.model = model
        model.observable().attach(
            SpinnerModelMixin.SPINNER_VALUE_CHANGED_EVENT,
            self.getValueFromModel)
        model.observable().attach(SpinnerModelMixin.RANGE_VALUE_CHANGED_EVENT,
                                  self.getRangeFromModel)

        self.spinner = QSpinBox(self)
        self.addWidget(self.spinner)

        self.info_label = QLabel()
        self.info_label.setHidden(True)
        self.addWidget(self.info_label)

        self.addStretch()

        # self.connect(self.spinner, SIGNAL('editingFinished()'), self.updateModel)
        self.__initialized = False
        self.connect(self.spinner, SIGNAL('valueChanged(int)'),
                     self.updateModel)

        self.getRangeFromModel()
        self.getValueFromModel()

    def updateModel(self):
        """Called whenever the contents of the spinner changes."""
        if self.__initialized:
            self.model.setSpinnerValue(self.spinner.value())

    def getRangeFromModel(self):
        self.spinner.setMinimum(self.model.getMinValue())
        self.spinner.setMaximum(self.model.getMaxValue())

    def getValueFromModel(self):
        """Retrieves data from the model and inserts it into the spinner"""
        if not self.__initialized:
            self.__initialized = True
        self.spinner.setValue(self.model.getSpinnerValue())

    def setInfo(self, info):
        self.info_label.setText(info)
        self.info_label.setHidden(False)
Exemplo n.º 32
0
    def _initInsertPositionTableWithExtents(self, axes, mx):
        positionTbl = self.positionWidget

        tblHeaders = ["insert at", "max"]

        positionTbl.setColumnCount(len(tblHeaders))
        positionTbl.setHorizontalHeaderLabels(tblHeaders)
        positionTbl.resizeColumnsToContents()

        tagged_insert = collections.OrderedDict(zip(axes, self.imageOffsets))
        tagged_max = collections.OrderedDict(zip(axes, mx))
        self._tagged_insert = tagged_insert

        positionTbl.setRowCount(len(tagged_insert))
        positionTbl.setVerticalHeaderLabels(tagged_insert.keys())

        self._insert_position_boxes.clear()

        for row, (axis_key, extent) in enumerate(tagged_max.items()):
            # Init min/max spinboxes
            default_insert = tagged_insert[axis_key] or 0
            default_max = tagged_max[axis_key] or extent

            insertBox = QSpinBox(self)
            maxBox = QLabel(str(default_max), self)

            insertBox.setValue(0)
            insertBox.setMinimum(0)
            insertBox.setMaximum(extent)
            insertBox.setEnabled( tagged_insert[axis_key] is not None )
            if insertBox.isEnabled():
                insertBox.setValue( default_insert )

            # TODO: maxBox shouldn't be in tab list (but it still is)
            maxBox.setTextInteractionFlags(Qt.NoTextInteraction)
            maxBox.setFocusPolicy(Qt.NoFocus)
            maxBox.setEnabled(False)

            insertBox.valueChanged.connect( self._updatePosition )

            positionTbl.setCellWidget( row, 0, insertBox )
            positionTbl.setCellWidget( row, 1, maxBox )

            self._insert_position_boxes[axis_key] = (insertBox, maxBox)

        positionTbl.resizeColumnsToContents()
Exemplo n.º 33
0
    def _initInsertPositionTableWithExtents(self, axes, mx):
        positionTbl = self.positionWidget

        tblHeaders = ["insert at", "max"]

        positionTbl.setColumnCount(len(tblHeaders))
        positionTbl.setHorizontalHeaderLabels(tblHeaders)
        positionTbl.resizeColumnsToContents()

        tagged_insert = collections.OrderedDict(zip(axes, self.imageOffsets))
        tagged_max = collections.OrderedDict(zip(axes, mx))
        self._tagged_insert = tagged_insert

        positionTbl.setRowCount(len(tagged_insert))
        positionTbl.setVerticalHeaderLabels(tagged_insert.keys())

        self._insert_position_boxes.clear()

        for row, (axis_key, extent) in enumerate(tagged_max.items()):
            # Init min/max spinboxes
            default_insert = tagged_insert[axis_key] or 0
            default_max = tagged_max[axis_key] or extent

            insertBox = QSpinBox(self)
            maxBox = QLabel(str(default_max), self)

            insertBox.setValue(0)
            insertBox.setMinimum(0)
            insertBox.setMaximum(extent)
            insertBox.setEnabled(tagged_insert[axis_key] is not None)
            if insertBox.isEnabled():
                insertBox.setValue(default_insert)

            # TODO: maxBox shouldn't be in tab list (but it still is)
            maxBox.setTextInteractionFlags(Qt.NoTextInteraction)
            maxBox.setFocusPolicy(Qt.NoFocus)
            maxBox.setEnabled(False)

            insertBox.valueChanged.connect(self._updatePosition)

            positionTbl.setCellWidget(row, 0, insertBox)
            positionTbl.setCellWidget(row, 1, maxBox)

            self._insert_position_boxes[axis_key] = (insertBox, maxBox)

        positionTbl.resizeColumnsToContents()
Exemplo n.º 34
0
    def _initLabelMappingTableWithExtents(self):
        mappingTbl = self.mappingWidget
        max_labels, read_labels_info = self._labelInfo
        labels, label_counts = read_labels_info
        label_mapping = self.labelMapping

        mappings = zip(labels, [label_mapping[i] for i in labels],
                       label_counts)

        tblHeaders = ["map", "to", "px count"]
        mappingTbl.setColumnCount(len(tblHeaders))
        mappingTbl.setHorizontalHeaderLabels(tblHeaders)
        mappingTbl.resizeColumnsToContents()

        mappingTbl.setRowCount(len(labels))
        mappingTbl.setVerticalHeaderLabels(map(lambda x: str(x), labels))

        self._insert_mapping_boxes.clear()

        for row, (label_from, label_to, px_cnt) in enumerate(mappings):
            enabledBox = QCheckBox(self)
            mapToBox = QSpinBox(self)
            pxCountBox = QLabel(str(px_cnt), self)

            enabledBox.setChecked(label_to > 0)

            mapToBox.setMinimum(1 if label_to else 0)
            mapToBox.setMaximum(max_labels if label_to else 0)
            mapToBox.setValue(label_to)
            mapToBox.setEnabled(label_to > 0)

            enabledBox.stateChanged.connect(self._updateMappingEnabled)
            mapToBox.valueChanged.connect(self._updateMapping)

            # TODO: pxCountBox shouldn't be in tab list (but it still is)
            pxCountBox.setTextInteractionFlags(Qt.NoTextInteraction)
            pxCountBox.setFocusPolicy(Qt.NoFocus)
            pxCountBox.setEnabled(False)

            mappingTbl.setCellWidget(row, 0, enabledBox)
            mappingTbl.setCellWidget(row, 1, mapToBox)
            mappingTbl.setCellWidget(row, 2, pxCountBox)

            self._insert_mapping_boxes[label_from] = (enabledBox, mapToBox)

        mappingTbl.resizeColumnsToContents()
    def __init__(self, advanced_option=False):
        SimulationConfigPanel.__init__(self, IteratedEnsembleSmoother(), advanced_option)

        layout = QFormLayout()

        case_selector = CaseSelector()
        layout.addRow("Current case:", case_selector)

        run_path_label = QLabel("<b>%s</b>" % getRunPath())
        addHelpToWidget(run_path_label, "config/simulation/runpath")
        layout.addRow("Runpath:", run_path_label)

        number_of_realizations_label = QLabel("<b>%d</b>" % getRealizationCount())
        addHelpToWidget(number_of_realizations_label, "config/ensemble/num_realizations")
        layout.addRow(QLabel("Number of realizations:"), number_of_realizations_label)

        # The num_iterations_spinner does not track any external changes (will that ever happen?)
        num_iterations_spinner = QSpinBox()
        num_iterations_spinner.setMinimum(1)
        num_iterations_spinner.setMaximum(100)
        num_iterations_spinner.setValue(getNumberOfIterations())
        addHelpToWidget(num_iterations_spinner, "config/simulation/number_of_iterations")
        num_iterations_spinner.valueChanged[int].connect(setNumberOfIterations)

        layout.addRow("Number of iterations:", num_iterations_spinner)

        self._iterated_target_case_format_model = TargetCaseModel(format_mode=True)
        self._iterated_target_case_format_field = StringBox(self._iterated_target_case_format_model, "config/simulation/iterated_target_case_format")
        self._iterated_target_case_format_field.setValidator(ProperNameFormatArgument())
        layout.addRow("Target case format:", self._iterated_target_case_format_field)


        self._analysis_module_selector = AnalysisModuleSelector(iterable=True, help_link="config/analysis/analysis_module")
        layout.addRow("Analysis Module:", self._analysis_module_selector)

        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(self._active_realizations_model, "config/simulation/active_realizations")
        self._active_realizations_field.setValidator(RangeStringArgument(getRealizationCount()))
        layout.addRow("Active realizations", self._active_realizations_field)


        self._iterated_target_case_format_field.getValidationSupport().validationChanged.connect(self.simulationConfigurationChanged)
        self._active_realizations_field.getValidationSupport().validationChanged.connect(self.simulationConfigurationChanged)

        self.setLayout(layout)
Exemplo n.º 36
0
class IntegerSpinner(HelpedWidget):
    """A spinner widget for integers. The data structure expected and sent to the getter and setter is an integer."""

    def __init__(self, model, spinner_label="Integer Number", help_link=""):
        HelpedWidget.__init__(self, spinner_label, help_link)

        assert isinstance(model, SpinnerModelMixin)
        self.model = model
        model.observable().attach(SpinnerModelMixin.SPINNER_VALUE_CHANGED_EVENT, self.getValueFromModel)
        model.observable().attach(SpinnerModelMixin.RANGE_VALUE_CHANGED_EVENT, self.getRangeFromModel)

        self.spinner = QSpinBox(self)
        self.addWidget(self.spinner)

        self.info_label = QLabel()
        self.info_label.setHidden(True)
        self.addWidget(self.info_label)

        self.addStretch()

        # self.connect(self.spinner, SIGNAL('editingFinished()'), self.updateModel)
        self.__initialized = False
        self.connect(self.spinner, SIGNAL("valueChanged(int)"), self.updateModel)

        self.getRangeFromModel()
        self.getValueFromModel()

    def updateModel(self):
        """Called whenever the contents of the spinner changes."""
        if self.__initialized:
            self.model.setSpinnerValue(self.spinner.value())

    def getRangeFromModel(self):
        self.spinner.setMinimum(self.model.getMinValue())
        self.spinner.setMaximum(self.model.getMaxValue())

    def getValueFromModel(self):
        """Retrieves data from the model and inserts it into the spinner"""
        if not self.__initialized:
            self.__initialized = True
        self.spinner.setValue(self.model.getSpinnerValue())

    def setInfo(self, info):
        self.info_label.setText(info)
        self.info_label.setHidden(False)
Exemplo n.º 37
0
    def _initLabelMappingTableWithExtents(self):
        mappingTbl = self.mappingWidget
        max_labels, read_labels_info = self._labelInfo
        labels, label_counts = read_labels_info
        label_mapping = self.labelMapping

        mappings = zip(labels, [label_mapping[i] for i in labels], label_counts)

        tblHeaders = ["map", "to", "px count"]
        mappingTbl.setColumnCount(len(tblHeaders))
        mappingTbl.setHorizontalHeaderLabels(tblHeaders)
        mappingTbl.resizeColumnsToContents()

        mappingTbl.setRowCount( len(labels) )
        mappingTbl.setVerticalHeaderLabels( map(lambda x: str(x), labels) )

        self._insert_mapping_boxes.clear()

        for row, (label_from, label_to, px_cnt) in enumerate(mappings):
            enabledBox = QCheckBox(self)
            mapToBox = QSpinBox(self)
            pxCountBox = QLabel(str(px_cnt), self)

            enabledBox.setChecked(label_to > 0)

            mapToBox.setMinimum(1 if label_to else 0)
            mapToBox.setMaximum(max_labels if label_to else 0)
            mapToBox.setValue(label_to)
            mapToBox.setEnabled(label_to > 0)

            enabledBox.stateChanged.connect( self._updateMappingEnabled )
            mapToBox.valueChanged.connect( self._updateMapping )

            # TODO: pxCountBox shouldn't be in tab list (but it still is)
            pxCountBox.setTextInteractionFlags(Qt.NoTextInteraction)
            pxCountBox.setFocusPolicy(Qt.NoFocus)
            pxCountBox.setEnabled(False)

            mappingTbl.setCellWidget( row, 0, enabledBox )
            mappingTbl.setCellWidget( row, 1, mapToBox )
            mappingTbl.setCellWidget( row, 2, pxCountBox )

            self._insert_mapping_boxes[label_from] = (enabledBox, mapToBox)

        mappingTbl.resizeColumnsToContents()
Exemplo n.º 38
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.º 39
0
 def addSpinBox(self, name):
     sb = QSpinBox(self)
     sb.setEnabled(True)
     sb.setMinimumSize(QSize(60, 20))
     sb.setMaximumSize(QSize(60, 20))
     sb.setWrapping(False)
     sb.setFrame(True)
     sb.setButtonSymbols(QSpinBox.NoButtons)
     sb.setAccelerated(True)
     sb.setCorrectionMode(QSpinBox.CorrectToPreviousValue)
     sb.setKeyboardTracking(True)
     sb.setMinimum(0)
     sb.setMaximum(99999999)
     sb.setSingleStep(1000)
     sb.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
     sb.setProperty("value", 0)
     sb.setObjectName(name)
     return sb
Exemplo n.º 40
0
 def addSpinBox(self, name):
     sb = QSpinBox(self)
     sb.setEnabled(True)
     sb.setMinimumSize(QSize(60, 20))
     sb.setMaximumSize(QSize(60, 20))
     sb.setWrapping(False)
     sb.setFrame(True)
     sb.setButtonSymbols(QSpinBox.NoButtons)
     sb.setAccelerated(True)
     sb.setCorrectionMode(QSpinBox.CorrectToPreviousValue)
     sb.setKeyboardTracking(True)
     sb.setMinimum(0)
     sb.setMaximum(99999999)
     sb.setSingleStep(1000)
     sb.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
     sb.setProperty("value", 0)
     sb.setObjectName(name)
     return sb
Exemplo n.º 41
0
class EkdNumPropertie(EkdPropertie):
    """
    Définition de la propriété correspondant à un conteur ou une valeur numérique
    """
    def __init__(self, prop, name, value, minimum=0, maximum=100, section=None ):
        super(EkdNumPropertie, self).__init__(prop, name, value, EkdPropertie.NUM, section)
        self.label = QLabel(name)
        self.widget = QSpinBox()
        self.widget.setValue(int(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(int)"), self.updateNum)

    def updateNum(self, val):
        self.value = val
        EkdConfig.set(self.section, self.id, self.value)
Exemplo n.º 42
0
    def __init__(self,
                 parent,
                 prefix=None,
                 suffix=None,
                 option=None,
                 min_=None,
                 max_=None,
                 step=None,
                 tip=None,
                 value=None,
                 changed=None):
        super(MySpinBox, self).__init__(parent)

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

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

        layout.addStretch(1)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        self.spin = spinbox
Exemplo n.º 43
0
class CharColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget):
    def __init__(self, parent, hex_widget, column):
        QWidget.__init__(self, parent)
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        self.hexWidget = hex_widget
        self.columnModel = column

        self.setLayout(QFormLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)

        self.cmbEncoding = QComboBox(self)
        self.cmbEncoding.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addRow(utils.tr('Encoding:'), self.cmbEncoding)
        for encoding in sorted(encodings.encodings.keys()):
            self.cmbEncoding.addItem(encoding)
            if column is not None and column.codec.name.lower() == encoding.lower():
                self.cmbEncoding.setCurrentIndex(self.cmbEncoding.count() - 1)
        if column is None:
            self.cmbEncoding.setCurrentIndex(self.cmbEncoding.findText('Windows-1251'))

        self.spnBytesOnRow = QSpinBox(self)
        self.spnBytesOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.spnBytesOnRow.setMinimum(1)
        self.spnBytesOnRow.setMaximum(32)
        self.layout().addRow(utils.tr('Bytes on row:'), self.spnBytesOnRow)
        if column is not None:
            self.spnBytesOnRow.setValue(column.bytesOnRow)
        else:
            self.spnBytesOnRow.setValue(16)

    def createColumnModel(self, hex_widget):
        model = CharColumnModel(self.hexWidget.document, encodings.getCodec(self.cmbEncoding.currentText()),
                                self.hexWidget.font(), self.spnBytesOnRow.value())
        return model

    def saveToColumn(self, column):
        column.codec = encodings.getCodec(self.cmbEncoding.currentText())
        column._bytesOnRow = self.spnBytesOnRow.value()
        column.reset()
Exemplo n.º 44
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        
        Layout = QVBoxLayout(self)
        
        self.editor = BoxEditor(self)
        QObject.connect(self.editor, SIGNAL('valueChanged'),
                        self.slotBoxEditor)
        Layout.addWidget(self.editor)

        ControlLayout = QHBoxLayout()
        Layout.addLayout(ControlLayout)

        for i in ('x', 'y', 'w', 'h'):
            name = i+'SpinBox'
            s = QSpinBox(self)
            s.setMaximum(5000)
            s.setMinimum(-5000)
            QObject.connect(s, SIGNAL('valueChanged(int)'),
                            self.slotSpinBox)
            setattr(self, name, s)
            ControlLayout.addWidget(s)
Exemplo n.º 45
0
    def multisig_choice(self):
        vbox = QVBoxLayout()
        self.set_layout(vbox)
        vbox.addWidget(QLabel(_("Multi Signature Wallet")))

        cw = CosignWidget(2, 2)
        vbox.addWidget(cw, 1)
        vbox.addWidget(QLabel(_("Please choose the number of signatures needed to unlock funds in your wallet") + ':'))

        m_edit = QSpinBox()
        n_edit = QSpinBox()
        m_edit.setValue(2)
        n_edit.setValue(2)
        n_edit.setMinimum(2)
        n_edit.setMaximum(15)
        m_edit.setMinimum(1)
        m_edit.setMaximum(2)
        n_edit.valueChanged.connect(m_edit.setMaximum)

        n_edit.valueChanged.connect(cw.set_n)
        m_edit.valueChanged.connect(cw.set_m)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(_('Require')))
        hbox.addWidget(m_edit)
        hbox.addWidget(QLabel(_('of')))
        hbox.addWidget(n_edit)
        hbox.addWidget(QLabel(_('signatures')))
        hbox.addStretch(1)

        vbox.addLayout(hbox)
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next'))))
        if not self.exec_():
            return
        m = int(m_edit.value())
        n = int(n_edit.value())
        wallet_type = '%dof%d' % (m, n)
        return wallet_type
Exemplo n.º 46
0
 def __init__(self, parent, attached=False):
     cp = QLineEdit(parent)
     tel = QLineEdit(parent)
     tipo = QSpinBox(parent)
     tipo.setMaximum(2)
     tipo.setMinimum(0)
     tipo.setButtonSymbols(2)
     cp.setInputMask("#####")
     tel.setInputMask("(###)-###-##-##")
     cp.setAlignment(QtCore.Qt.AlignCenter)
     tipo.setAlignment(QtCore.Qt.AlignCenter)
     tel.setAlignment(QtCore.Qt.AlignCenter)
     Admin1.__init__(
         self,
         parent,
         "clientes,proveedores",
         [
             ["id", "Id:", "str", None, False],
             ["nombre", "Nombre:", "str", None, True],
             ["rfc", "RFC:", "str", None, True],
             ["direccion", "Direccion:", "str", None, True],
             ["poblacion", "Poblacion:", "str", None, True],
             ["estado", "Estado:", "str", None, True],
             ["tel", "Telefono:", "str", tel, True],
             ["correo", "E-Mail:", "str", None, True],
             ["tipo", "Tipo:", "hide", 1, True],
             ["credito", "Limite de credito:", "double", None, True],
         ],
         info="",
         logo=":/modulos/images/png/elegant/proveedores.png",
         ide=-1,
         ancla=True,
         cond=" WHERE tipo=1 ",
     )
     self.ui = parent
     self.ui.connect(self.ui.actionProveedores, QtCore.SIGNAL("triggered()"), self.iniciar)
     self.ui.connect(self.ui.tProveedores, QtCore.SIGNAL("clicked()"), self.iniciar)
     self.anclar(attached)
Exemplo n.º 47
0
 def __init__(self, parent, attached=False):
     # ip=QLineEdit(parent)
     tipo = QSpinBox(parent)
     tipo.setMaximum(2)
     tipo.setMinimum(0)
     tipo.setButtonSymbols(2)
     # ip.setInputMask("000.000.000.000")
     tipo.setAlignment(QtCore.Qt.AlignCenter)
     # ip.setAlignment(QtCore.Qt.AlignRight)
     info = "Las ventas son distribuidas en cajas, asi que debe existir una caja por menos."
     icono = ":/actions/images/actions/color_18/monitor.png"
     Admin1.__init__(
         self,
         parent,
         "cajas",
         [
             ["num_caja", "Id:", "str", None, False],
             ["nombre", "Nombre:", "str", None, True],
             ["maquina", "Direccion IP (Opcional):", "str", None, True],
             ["saldo_inicial", "Saldo inicial:", "double", None, True],
             ["estado", "Ultima apertura :", "date", None, True],
             ["efectivo", "Efectivo:", "double", None, True],
         ],
         info,
         icono,
         -1,
         True,
     )
     self.ui = parent
     action = self.ui.menuObjetos.addAction(QIcon(icono), "Cajas")
     action.setIconVisibleInMenu(True)
     # self.ui.menuObjetos.addAction()
     self.ui.connect(action, QtCore.SIGNAL("triggered()"), self.iniciar)
     self.ui.connect(parent.tCajas, QtCore.SIGNAL("clicked()"), self.iniciar)
     # self.iniciar()
     # self.ui.stack.addWidget(self)
     # self.num=self.ui.stack.count()-1
     self.anclar(attached)
Exemplo n.º 48
0
class ConnectionDialog(QDialog):
    def __init__(self, parent):
        super(ConnectionDialog, self).__init__(parent)
        layout = QVBoxLayout(self)
        formLayout = QFormLayout()
        self.filePath = QLineEdit("/home/vertrex/dump/registry/system")
        formLayout.addRow(QLabel("server registry file path :"), self.filePath)
        self.ipAddress = QLineEdit("127.0.0.1")
        formLayout.addRow(QLabel("server ip address :"), self.ipAddress)
        self.port = QSpinBox()
        self.port.setMinimum(1)
        self.port.setMaximum(65536)
        self.port.setValue(0xdff)
        formLayout.addRow(QLabel("port :"), self.port)
        configurationGroupBox = QGroupBox("Configuration")
        configurationGroupBox.setLayout(formLayout)
        layout.addWidget(configurationGroupBox)

        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        layout.addWidget(self.buttons)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
Exemplo n.º 49
0
class CADOptionsToolbar_Ellipse(CADOptionsToolbar):
    def __init__(self):
        super(CADOptionsToolbar_Ellipse, self).__init__()
        self.settings = QSettings()

        self.spinBox = QSpinBox(self.optionsToolBar)
        self.spinBox.setMinimum(3)
        self.spinBox.setMaximum(3600)
        segvalue = self.settings.value("/CADDigitize/ellipse/segments",
                                       36,
                                       type=int)
        if not segvalue:
            self.settings.setValue("/CADDigitize/ellipse/segments", 36)
        self.spinBox.setValue(segvalue)
        self.spinBox.setSingleStep(1)
        self.spinBoxAction = self.optionsToolBar.addWidget(self.spinBox)
        self.spinBox.setToolTip(tr(u"Number of points"))
        self.spinBoxAction.setEnabled(True)

        self.spinBox.valueChanged["int"].connect(self.segmentsettingsEllipse)

    def segmentsettingsEllipse(self):
        self.settings.setValue("/CADDigitize/ellipse/segments",
                               self.spinBox.value())
Exemplo n.º 50
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)
Exemplo n.º 51
0
class Option(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.resize(168, 86)
        self.name = "Progress"
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setMargin(0)
        self.label_2 = QLabel(self)
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.spinBox = QSpinBox(self)
        self.spinBox.setMinimum(60)
        self.spinBox.setMaximum(600)
        self.gridLayout.addWidget(self.spinBox, 0, 2, 1, 1)
        self.spinBox_2 = QSpinBox(self)
        self.spinBox_2.setMinimum(120)
        self.spinBox_2.setMaximum(600)
        self.spinBox_2.setProperty("value", 600)
        self.gridLayout.addWidget(self.spinBox_2, 1, 2, 1, 1)
        self.label = QLabel(self)

        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)

        self.label_2.setText(u"Max Süre(dk):")
        self.label.setText(u"Min. Süre(dk):")
Exemplo n.º 52
0
class ObjectWidget(QWidget):
    """
    Widget for editing OBJECT parameters
    """
    signal_object_changed = pyqtSignal(name='objectChanged')

    def __init__(self, parent=None):
        super(ObjectWidget, self).__init__(parent)

        l_nbr_steps = QLabel("Nbr Steps ")
        self.nbr_steps = QSpinBox()
        self.nbr_steps.setMinimum(3)
        self.nbr_steps.setMaximum(100)
        self.nbr_steps.setValue(6)
        self.nbr_steps.valueChanged.connect(self.update_param)

        l_cmap = QLabel("Cmap ")
        self.cmap = sorted(get_colormaps().keys())
        self.combo = QComboBox(self)
        self.combo.addItems(self.cmap)
        self.combo.currentIndexChanged.connect(self.update_param)

        gbox = QGridLayout()
        gbox.addWidget(l_cmap, 0, 0)
        gbox.addWidget(self.combo, 0, 1)
        gbox.addWidget(l_nbr_steps, 1, 0)
        gbox.addWidget(self.nbr_steps, 1, 1)

        vbox = QVBoxLayout()
        vbox.addLayout(gbox)
        vbox.addStretch(1.0)

        self.setLayout(vbox)

    def update_param(self, option):
        self.signal_object_changed.emit()
Exemplo n.º 53
0
class CADOptionsToolbar_RPolygon(CADOptionsToolbar):
    def __init__(self):
        super(CADOptionsToolbar_RPolygon, self).__init__()
        self.settings = QSettings()

        self.spinBox = QSpinBox(self.optionsToolBar)
        self.spinBox.setMinimum(3)
        self.spinBox.setMaximum(3600)
        segvalue = self.settings.value("/CADDigitize/rpolygon/nbedges",
                                       5,
                                       type=int)
        if not segvalue:
            self.settings.setValue("/CADDigitize/rpolygon/nbedges", 5)
        self.spinBox.setValue(segvalue)
        self.spinBox.setSingleStep(1)
        self.spinBoxAction = self.optionsToolBar.addWidget(self.spinBox)
        self.spinBox.setToolTip(tr(u"Number of edges"))
        self.spinBoxAction.setEnabled(True)

        self.spinBox.valueChanged["int"].connect(self.edgesSettingsRPolygon)

    def edgesSettingsRPolygon(self):
        self.settings.setValue("/CADDigitize/rpolygon/nbedges",
                               self.spinBox.value())
Exemplo n.º 54
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.º 55
0
class Pressure(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletPressure, *args)

        self.p = self.device

        self.cbe_pressure = CallbackEmulator(self.p.get_pressure,
                                             self.cb_pressure,
                                             self.increase_error_count)

        self.current_pressure = None  # float, kPa

        plots = [('Pressure', Qt.red, lambda: self.current_pressure,
                  '{:.3f} kPa'.format)]
        self.plot_widget = PlotWidget('Pressure [kPa]', plots)

        self.combo_sensor = QComboBox()
        self.combo_sensor.addItem('MPX5500')
        self.combo_sensor.addItem('MPXV5004')
        self.combo_sensor.addItem('MPX4115A')
        self.combo_sensor.currentIndexChanged.connect(
            self.combo_sensor_changed)

        self.spin_average = QSpinBox()
        self.spin_average.setMinimum(1)
        self.spin_average.setMaximum(50)
        self.spin_average.setSingleStep(1)
        self.spin_average.setValue(50)
        self.spin_average.editingFinished.connect(self.spin_average_finished)

        hlayout = QHBoxLayout()
        hlayout.addWidget(QLabel('Sensor Type:'))
        hlayout.addWidget(self.combo_sensor)
        hlayout.addStretch()
        hlayout.addWidget(QLabel('Moving Average Length:'))
        hlayout.addWidget(self.spin_average)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(hlayout)

    def get_sensor_type_async(self, sensor):
        self.combo_sensor.setCurrentIndex(sensor)

    def get_moving_average_async(self, average):
        self.spin_average.setValue(average)

    def start(self):
        async_call(self.p.get_sensor_type, None, self.get_sensor_type_async,
                   self.increase_error_count)
        async_call(self.p.get_moving_average, None,
                   self.get_moving_average_async, self.increase_error_count)
        async_call(self.p.get_pressure, None, self.cb_pressure,
                   self.increase_error_count)
        self.cbe_pressure.set_period(100)

        self.plot_widget.stop = False

    def stop(self):
        self.cbe_pressure.set_period(0)

        self.plot_widget.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletPressure.DEVICE_IDENTIFIER

    def cb_pressure(self, pressure):
        self.current_pressure = pressure / 1000.0

    def combo_sensor_changed(self):
        self.p.set_sensor_type(self.combo_sensor.currentIndex())

    def spin_average_finished(self):
        self.p.set_moving_average(self.spin_average.value())
Exemplo n.º 56
0
class previewDlg(QMainWindow):
    '''
    classdocs
    '''
    def __init__(self, parent, comp, basePMCheck, model):
        '''
        Constructor
        '''

        QMainWindow.__init__(self, parent)

        self.basePMCheck = basePMCheck
        #         self.ui = Ui_Previewself.grbPageProperty()
        #         self.ui.setupUi(self)
        self.resize(1000, 700)
        self.setWindowTitle("Preview Dialog")
        self.view = QgsComposerView(self)
        viewLayout = QGridLayout()
        viewLayout.setSpacing(0)
        viewLayout.setMargin(0)
        mHorizontalRuler = QgsComposerRuler(QgsComposerRuler.Horizontal)
        mVerticalRuler = QgsComposerRuler(QgsComposerRuler.Vertical)
        mRulerLayoutFix = QWidget()
        mRulerLayoutFix.setAttribute(Qt.WA_NoMousePropagation)
        mRulerLayoutFix.setBackgroundRole(QPalette.Window)
        mRulerLayoutFix.setFixedSize(mVerticalRuler.rulerSize(),
                                     mHorizontalRuler.rulerSize())
        viewLayout.addWidget(mRulerLayoutFix, 0, 0)
        viewLayout.addWidget(mHorizontalRuler, 0, 1)
        viewLayout.addWidget(mVerticalRuler, 1, 0)

        self.view.setContentsMargins(0, 0, 0, 0)
        self.view.setHorizontalRuler(mHorizontalRuler)
        self.view.setVerticalRuler(mVerticalRuler)
        viewLayout.addWidget(self.view, 1, 1)

        #         self.scene = comp

        self.view.setZoomLevel(1.0)
        self.view.setComposition(comp)
        self.scene = self.view.composition()
        layout = QVBoxLayout()
        hLayout = QHBoxLayout()
        hLayout.addLayout(viewLayout)

        self.mapItem = self.scene.getComposerMapById(0)

        self.view.scale(2.8, 2.8)
        self.view.setPreviewModeEnabled(True)

        self.toolBarAction = self.addToolBar("composer action")
        self.actionMapRefresh = QAction(self)
        self.actionMapRefresh.setObjectName("actionMapRefresh")
        icon3 = QIcon("Resource/Refresh.png")
        self.actionMapRefresh.setIcon(icon3)
        self.actionMapRefresh.setToolTip("Refresh")
        # self.textItemAction.setCheckable(True)
        self.connect(self.actionMapRefresh, SIGNAL("triggered()"),
                     self.actionMapRefresh_triggered)
        self.toolBarAction.addAction(self.actionMapRefresh)

        # # self.templeteCreateAction = QAction(self)
        # # self.templeteCreateAction.setObjectName("createTempleteAction")
        # # icon4 = QIcon("Resource\\templetepointer.png")
        # # self.templeteCreateAction.setIcon(icon4)
        # # self.templeteCreateAction.setToolTip("Create Templete")
        # # self.templeteCreateAction.setCheckable(True)
        # # self.connect(self.templeteCreateAction, SIGNAL("triggered()"), self.createTempleteAction)
        # # self.toolBar.addAction(self.templeteCreateAction)
        # layout.insertWidget(0, self.toolBar)

        #         self.scene.selectedItemChanged.connect(self.selectedItemDisplay)
        self.view.selectedItemChanged.connect(self.selectedItemDisplay)

        self.view.cursorPosChanged.connect(self.cursorPosChangedEvent)
        #         self.connect(self.view, SIGNAL("selectedItemChanged(QgsComposerItem)"),self, SLOT("selectedItemDisplay(QgsComposerItem)"))
        #         self.scene.composerLabelAdded.connect(self.composerLabelAddedEvent)
        self.view.itemRemoved.connect(self.deleteItem)
        # self.connect( self.view, SIGNAL( "actionFinished()" ), self.setSelectionTool)

        #listen out for position updates from the QgsComposerView
        self.propertyWidget = QWidget(self)
        hLayout.addWidget(self.propertyWidget)
        self.propertyWidget.setObjectName("propertyWidget")
        self.propertyWidget.resize(222, 302)
        self.vLayout_3 = QVBoxLayout(self.propertyWidget)
        self.vLayout_3.setObjectName("vLayout_3")
        self.groupBox = QGroupBox(self.propertyWidget)
        self.groupBox.setObjectName("groupBox")
        self.horizontalLayout_2 = QHBoxLayout(self.groupBox)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.frame = QFrame(self.groupBox)
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName("frame")
        self.verticalLayout = QVBoxLayout(self.frame)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label = QLabel(self.frame)
        self.label.setObjectName("label")
        self.verticalLayout.addWidget(self.label)
        self.labelText = QPlainTextEdit(self.frame)
        self.labelText.setObjectName("labelText")
        self.verticalLayout.addWidget(self.labelText)
        self.btnLabelFont = QPushButton(self.frame)
        self.btnLabelFont.setObjectName("btnLabelFont")
        self.verticalLayout.addWidget(self.btnLabelFont)
        self.btnLabelColor = QPushButton(self.frame)
        self.btnLabelColor.setObjectName("btnLabelColor")
        self.verticalLayout.addWidget(self.btnLabelColor)
        self.frame_2 = QFrame(self.frame)
        self.frame_2.setFrameShape(QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QFrame.Raised)
        self.frame_2.setObjectName("frame_2")
        self.horizontalLayout = QHBoxLayout(self.frame_2)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_2 = QLabel(self.frame_2)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.spinLabelRotation = QSpinBox(self.frame_2)
        self.spinLabelRotation.setObjectName("spinLabelRotation")
        self.spinLabelRotation.setMinimum(-360)
        self.spinLabelRotation.setMaximum(360)
        self.horizontalLayout.addWidget(self.spinLabelRotation)
        self.verticalLayout.addWidget(self.frame_2)
        self.chbBackgroundEnable = QCheckBox(self.frame)
        self.chbBackgroundEnable.setChecked(True)
        self.chbBackgroundEnable.setObjectName("chbBackgroundEnable")
        self.verticalLayout.addWidget(self.chbBackgroundEnable)
        self.horizontalLayout_2.addWidget(self.frame)
        self.vLayout_3.addWidget(self.groupBox)

        self.resolutionFrame = QFrame(self.frame)
        self.resolutionFrame.setFrameShape(QFrame.StyledPanel)
        self.resolutionFrame.setFrameShadow(QFrame.Raised)
        self.resolutionFrame.setObjectName("resolutionFrame")
        self.horizontalLayout4 = QHBoxLayout(self.resolutionFrame)
        self.horizontalLayout4.setObjectName("horizontalLayout4")
        self.label_resolution = QLabel(self.resolutionFrame)
        self.label_resolution.setObjectName("label_resolution")
        self.label_resolution.setText("Print Resolution (dpi):")
        self.horizontalLayout4.addWidget(self.label_resolution)
        self.spinResolution = QSpinBox(self.resolutionFrame)
        self.spinResolution.setObjectName("spinResolution")
        self.spinResolution.setMinimum(0)
        self.spinResolution.setMaximum(1000)
        self.spinResolution.setValue(300)
        self.horizontalLayout4.addWidget(self.spinResolution)
        #         self.verticalLayout.addWidget(self.frame_2)
        self.vLayout_3.addWidget(self.resolutionFrame)

        self.gbTable = GroupBox(self.propertyWidget)
        self.gbTable.Caption = "Table"
        self.vLayout_3.addWidget(self.gbTable)

        self.mTableView = QTableView(self.gbTable)
        self.gbTable.Add = self.mTableView
        hHeder = self.mTableView.horizontalHeader()
        hHeder.setVisible(False)
        vHeder = self.mTableView.verticalHeader()
        vHeder.setVisible(False)
        # self.mTableView.setFixedHeight(70)
        # self.mTableView.setFixedWidth(comp.paperWidth() - 40)

        # self.stdItemModel = QStandardItemModel()
        # self.

        self.spaceItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                     QSizePolicy.Expanding)
        self.vLayout_3.addItem(self.spaceItem)

        self.groupBox.setTitle("Label Property")
        self.label.setText("Label Text:")
        self.btnLabelFont.setText("Label Font")
        self.btnLabelColor.setText("Label Color")
        self.label_2.setText("Label Rotation:")
        self.chbBackgroundEnable.setText("Background Enable")
        self.groupBox.setEnabled(False)
        self.connect(self.btnLabelFont, SIGNAL("clicked()"),
                     self.btnLabelFontClick)
        self.connect(self.btnLabelColor, SIGNAL("clicked()"),
                     self.btnLabelColorClick)
        self.connect(self.chbBackgroundEnable, SIGNAL("clicked()"),
                     self.chbBackgroundEnableClick)
        self.labelText.textChanged.connect(self.labelTextChanged)
        self.spinLabelRotation.valueChanged.connect(
            self.spinLabelRotationValueChanged)
        layout.addLayout(hLayout)
        #
        self.btnBack = QPushButton()
        self.btnBack.setText("back")
        footerLayout = QHBoxLayout()
        footerLayout.addWidget(self.btnBack)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        footerLayout.addWidget(self.buttonBox)
        layout.addLayout(footerLayout)
        self.setLayout(layout)

        deleteItemKey = QShortcut(QKeySequence(Qt.Key_Delete), self)
        deleteItemKey.activated.connect(self.deleteItem)

        # self.btnBack.clicked.connect(self.back)
        self.connect(self.buttonBox, SIGNAL("accepted()"), self.acceptMethod)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.btnCancel = self.buttonBox.button(QDialogButtonBox.Cancel)
        self.view.setCurrentTool(QgsComposerView.Select)

        self.btnLabelColor.setVisible(False)
        # self.btnBack.setVisible(False)
        self.chbBackgroundEnable.setVisible(False)
        #         self.view.emit(SIGNAL("actionFinished"))

        #         if self.scene.plotStyle() != QgsComposition.Preview:
        #         self.scene.setPlotStyle(QgsComposition.Preview)
        #         self.mapItem.setPreviewMode(QgsComposerMap.Render)
        #         self.mapItem.updateCachedImage()
        #         self.mapItem.setSelected(True)
        self.mComposition = comp
        self.composerMapItem = self.mComposition.composerMapItems()[0]
        self.composerMapItem.setUpdatesEnabled(True)
        self.mStdModel = model

        self.mTableView.setModel(self.mStdModel)
        self.mTableView.setSpan(0, 0, 1, 6)
        self.mTableView.setSpan(1, 0, 1, 2)
        self.mTableView.setSpan(2, 0, 2, 1)
        self.mTableView.setSpan(4, 0, 1, 2)
        self.mTableView.setSpan(5, 0, 1, 2)
        self.mTableView.setSpan(6, 0, 1, 2)

        self.mTableView.setSpan(0, 6, 1, 8)
        self.mTableView.setSpan(1, 7, 1, 4)
        self.mTableView.setSpan(1, 11, 1, 3)
        self.mTableView.setSpan(2, 7, 1, 4)
        self.mTableView.setSpan(2, 11, 1, 3)

    def acceptMethod(self):
        # self.mStdModel.setItem(0, QStandardItem("nnnnnnnn"))
        filePath = QFileDialog.getSaveFileName(
            self, "Save PDF File", QCoreApplication.applicationDirPath(),
            "pdf files(*.pdf )")
        if filePath == "":
            return
        self.mComposition.clearSelection()
        self.mComposition.setPrintResolution(self.spinResolution.value())
        resultPdf = self.mComposition.exportAsPDF(filePath)
        if resultPdf:
            message = QMessageBox.information(self, "Result",
                                              "Successful export PDF")
        else:
            message = QMessageBox.information(self, "Result",
                                              "Don't export PDF")

    def rePresent(self, comp, model):
        self.mComposition = comp
        self.mStdModel = model
        self.view.setComposition(comp)
        self.scene = self.view.composition()

    def back(self):
        self.done(2)

    def spinLabelRotationValueChanged(self, rotationValue):
        self.selectedLabelItem.setItemRotation(rotationValue)

    def cursorPosChangedEvent(self, scenePointF):
        self.scenePoint = scenePointF
#         i = 100

    def labelTextChanged(self):
        self.selectedLabelItem.beginCommand(
            "Label text changed", QgsComposerMergeCommand.ComposerLabelSetText)
        self.selectedLabelItem.blockSignals(True)
        self.selectedLabelItem.setText(self.labelText.toPlainText())
        self.selectedLabelItem.update()
        self.selectedLabelItem.blockSignals(False)
        self.selectedLabelItem.endCommand()

    def chbBackgroundEnableClick(self):
        if self.chbBackgroundEnable.isChecked():
            self.selectedLabelItem.setBackgroundEnabled(True)
            self.mapItem.updateCachedImage()
        else:
            self.selectedLabelItem.setBackgroundEnabled(False)
            self.mapItem.updateCachedImage()

    def btnLabelFontClick(self):
        dlgFont = QFontDialog(self)
        dlgFont.setCurrentFont(self.selectedLabelItem.font())
        result = dlgFont.exec_()
        if result == 1:
            self.labelFont = dlgFont.selectedFont()
        else:
            self.labelFont = QFont()

        self.selectedLabelItem.setFont(self.labelFont)

    def btnLabelColorClick(self):
        dlgColor = QColorDialog(self)
        dlgColor.setCurrentColor(self.selectedLabelItem.fontColor())
        result = dlgColor.exec_()
        if result == 1:
            self.labelColor = dlgColor.selectedColor()
            self.selectedLabelItem.setFontColor(self.labelColor)

    def createTempleteAction(self):
        if self.templeteCreateAction.isChecked() and self.basePMCheck:
            font = QFont("Arial", 13)
            font.setItalic(True)
            self.compLabel1 = QgsComposerLabel(self.scene)
            self.compLabel1.setFont(font)
            self.compLabel1.setText("South China Sea")
            self.compLabel1.setBackgroundEnabled(False)
            self.compLabel1.setItemPosition(156, 100)
            self.compLabel1.adjustSizeToText()
            self.compLabel1.setItemRotation(60)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel1)

            self.compLabel2 = QgsComposerLabel(self.scene)
            self.compLabel2.setFont(font)
            self.compLabel2.setText("Straits Of Malacca")
            self.compLabel2.setBackgroundEnabled(False)
            self.compLabel2.setItemPosition(35, 100)
            self.compLabel2.adjustSizeToText()
            self.compLabel2.setItemRotation(60)
            self.scene.addItem(self.compLabel2)

            font.setItalic(False)
            self.compLabel3 = QgsComposerLabel(self.scene)
            self.compLabel3.setFont(font)
            self.compLabel3.setBackgroundEnabled(False)
            self.compLabel3.setText("THAILAND")
            self.compLabel3.setItemPosition(68, 60)
            self.compLabel3.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel3)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel4 = QgsComposerLabel(self.scene)
            self.compLabel4.setFont(font)
            self.compLabel4.setBackgroundEnabled(False)
            self.compLabel4.setText("SINGAPORE")
            self.compLabel4.setItemPosition(141, 218)
            self.compLabel4.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel4)
            self.templeteCreateAction.setChecked(False)
            self.compLabel4.setSelected(True)
        elif self.templeteCreateAction.isChecked(
        ) and self.basePMCheck == False:
            font = QFont("Arial", 14)
            font.setItalic(True)
            self.compLabel5 = QgsComposerLabel(self.scene)
            self.compLabel5.setFont(font)
            self.compLabel5.setText("South China Sea")
            self.compLabel5.setBackgroundEnabled(False)
            self.compLabel5.setItemPosition(108, 86)
            self.compLabel5.adjustSizeToText()
            self.compLabel5.setItemRotation(-45)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel5)

            self.compLabel6 = QgsComposerLabel(self.scene)
            self.compLabel6.setFont(font)
            self.compLabel6.setText("Sulu Sea")
            self.compLabel6.setBackgroundEnabled(False)
            self.compLabel6.setItemPosition(236, 38)
            self.compLabel6.adjustSizeToText()
            self.compLabel6.setItemRotation(45)
            self.scene.addItem(self.compLabel6)

            font.setItalic(False)
            self.compLabel7 = QgsComposerLabel(self.scene)
            self.compLabel7.setFont(font)
            self.compLabel7.setBackgroundEnabled(False)
            self.compLabel7.setText("Celebes Sea")
            self.compLabel7.setItemPosition(242, 112)
            self.compLabel7.adjustSizeToText()
            self.compLabel7.setItemRotation(-45)
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel7)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel8 = QgsComposerLabel(self.scene)
            self.compLabel8.setFont(font)
            self.compLabel8.setBackgroundEnabled(False)
            self.compLabel8.setText("INDONESIA\n(Kalimantan)")
            self.compLabel8.setItemPosition(172, 148, 32, 16)
            #             self.compLabel8.setHAlign(Qt.AlignHCenter)
            #             self.compLabel8.setVAlign(Qt.AlignVCenter)
            #             self.compLabel8.setFrameEnabled(False)
            #             self.compLabel8.setItemPosition()
            #             self.compLabel8.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel8)

            self.compLabel9 = QgsComposerLabel(self.scene)
            self.compLabel9.setFont(font)
            self.compLabel9.setBackgroundEnabled(False)
            self.compLabel9.setText("BRUNEI")
            self.compLabel9.setItemPosition(136, 83)
            self.compLabel9.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel9)
            self.templeteCreateAction.setChecked(False)

        pass

    def actionMapRefresh_triggered(self):

        self.view.setCurrentTool(QgsComposerView.AddRectangle)

    def setSelectionTool(self):
        self.view.deleteSelectedItems()
        font = QFont("Arial", 14)
        newLabelItem = QgsComposerLabel(self.scene)
        newLabelItem.setText("QGIS")
        newLabelItem.setFont(font)

        newLabelItem.setItemPosition(self.scenePoint.x(), self.scenePoint.y())
        newLabelItem.adjustSizeToText()

        self.scene.addItem(newLabelItem)
        #         selectItemPoint = self.scene.composerItemAt(self.scenePoint)
        newLabelItem.setSelected(True)
        self.groupBox.setEnabled(True)
        self.selectedLabelItem = newLabelItem
        #         txt = self.selectedLabelItem.text()
        #         textDoc = QTextDocument(txt)
        self.labelText.setPlainText(self.selectedLabelItem.text())
        #         self.scene.setSelectedItem(self.newLabelItem)

        self.view.setCurrentTool(QgsComposerView.Select)
        #         self.selectedLabelItem = self.view.currentTool()
        self.textItemAction.setChecked(False)

    def selectedItemDisplay(self, item):

        if self.scene.plotStyle() != QgsComposition.Preview:
            self.scene.setPlotStyle(QgsComposition.Preview)
            self.mapItem.setPreviewMode(QgsComposerMap.Render)
            self.mapItem.updateCachedImage()
        item._class_ = QgsComposerLabel
        #         selectedItems = self.scene.selectedComposerItems(True)
        #         if isinstance(item, QgsComposerItem):
        #             self.selectedLabelItem = item
        #         if isinstance(item, QGraphicsRectItem):
        #             self.selectedLabelItem = item
        if isinstance(item, QgsComposerLabel):
            self.selectedLabelItem = item
            self.groupBox.setEnabled(True)
            self.labelText.setPlainText(self.selectedLabelItem.text())
            self.spinLabelRotation.setValue(self.selectedLabelItem.rotation())
        else:
            self.groupBox.setEnabled(False)
#         print "debug"
        itemName = self.view.currentTool()
        if itemName == 5:
            item.setText("label")
        pass

    def deleteItem(self):
        self.view.deleteSelectedItems()
Exemplo n.º 57
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.º 58
0
class EditorGeneral(QWidget):
    """EditorGeneral widget class."""

    def __init__(self, parent):
        super(EditorGeneral, self).__init__()
        self._preferences, vbox = parent, QVBoxLayout(self)
        self.original_style = copy.copy(resources.CUSTOM_SCHEME)
        self.current_scheme, self._modified_editors = 'default', []
        self._font = settings.FONT

        groupBoxMini = QGroupBox(
            translations.TR_PREFERENCES_EDITOR_GENERAL_MINIMAP)
        groupBoxTypo = QGroupBox(
            translations.TR_PREFERENCES_EDITOR_GENERAL_TYPOGRAPHY)
        groupBoxScheme = QGroupBox(
            translations.TR_PREFERENCES_EDITOR_GENERAL_SCHEME)

        #Minimap
        formMini = QGridLayout(groupBoxMini)
        formMini.setContentsMargins(5, 15, 5, 5)
        self._checkShowMinimap = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_GENERAL_ENABLE_MINIMAP)
        self._spinMaxOpacity = QSpinBox()
        self._spinMaxOpacity.setRange(0, 100)
        self._spinMaxOpacity.setSuffix("% Max.")
        self._spinMinOpacity = QSpinBox()
        self._spinMinOpacity.setRange(0, 100)
        self._spinMinOpacity.setSuffix("% Min.")
        self._spinSize = QSpinBox()
        self._spinSize.setMaximum(100)
        self._spinSize.setMinimum(0)
        self._spinSize.setSuffix(
            translations.TR_PREFERENCES_EDITOR_GENERAL_AREA_MINIMAP)
        formMini.addWidget(self._checkShowMinimap, 0, 1)
        formMini.addWidget(QLabel(
            translations.TR_PREFERENCES_EDITOR_GENERAL_SIZE_MINIMAP), 1, 0,
            Qt.AlignRight)
        formMini.addWidget(self._spinSize, 1, 1)
        formMini.addWidget(QLabel(
            translations.TR_PREFERENCES_EDITOR_GENERAL_OPACITY), 2, 0,
            Qt.AlignRight)
        formMini.addWidget(self._spinMinOpacity, 2, 1)
        formMini.addWidget(self._spinMaxOpacity, 2, 2)
        #Typo
        gridTypo = QGridLayout(groupBoxTypo)
        gridTypo.setContentsMargins(5, 15, 5, 5)
        self._btnEditorFont = QPushButton('')
        gridTypo.addWidget(QLabel(
            translations.TR_PREFERENCES_EDITOR_GENERAL_EDITOR_FONT), 0, 0,
            Qt.AlignRight)
        gridTypo.addWidget(self._btnEditorFont, 0, 1)
        #Scheme
        vboxScheme = QVBoxLayout(groupBoxScheme)
        vboxScheme.setContentsMargins(5, 15, 5, 5)
        self._listScheme = QListWidget()
        vboxScheme.addWidget(self._listScheme)
        hbox = QHBoxLayout()
        btnDownload = QPushButton(
            translations.TR_PREFERENCES_EDITOR_DOWNLOAD_SCHEME)
        btnDownload.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.connect(btnDownload, SIGNAL("clicked()"),
                     self._open_schemes_manager)
        hbox.addWidget(btnDownload)
        btnAdd = QPushButton(QIcon(":img/add"),
                             translations.TR_EDITOR_CREATE_SCHEME)
        btnAdd.setIconSize(QSize(16, 16))
        btnAdd.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.connect(btnAdd, SIGNAL("clicked()"), self._open_schemes_designer)
        btnRemove = QPushButton(QIcon(":img/delete"),
                                translations.TR_EDITOR_REMOVE_SCHEME)
        btnRemove.setIconSize(QSize(16, 16))
        btnRemove.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.connect(btnRemove, SIGNAL("clicked()"), self._remove_scheme)
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        hbox.addWidget(btnAdd)
        hbox.addWidget(btnRemove)
        vboxScheme.addLayout(hbox)

        vbox.addWidget(groupBoxMini)
        vbox.addWidget(groupBoxTypo)
        vbox.addWidget(groupBoxScheme)

        #Settings
        qsettings = IDE.ninja_settings()
        qsettings.beginGroup('preferences')
        qsettings.beginGroup('editor')
        self._checkShowMinimap.setChecked(settings.SHOW_MINIMAP)
        if settings.IS_MAC_OS:
            self._spinMinOpacity.setValue(100)
            self._spinMaxOpacity.setValue(100)
            self._spinMinOpacity.setDisabled(True)
            self._spinMaxOpacity.setDisabled(True)
        else:
            self._spinMinOpacity.setValue(settings.MINIMAP_MIN_OPACITY * 100)
            self._spinMaxOpacity.setValue(settings.MINIMAP_MAX_OPACITY * 100)
        self._spinSize.setValue(settings.SIZE_PROPORTION * 100)
        btnText = ', '.join(self._font.toString().split(',')[0:2])
        self._btnEditorFont.setText(btnText)
        self._listScheme.clear()
        self._listScheme.addItem('default')
        self._schemes = json_manager.load_editor_skins()
        for item in self._schemes:
            self._listScheme.addItem(item)
        items = self._listScheme.findItems(
            qsettings.value('scheme', defaultValue='',
                            type='QString'), Qt.MatchExactly)
        if items:
            self._listScheme.setCurrentItem(items[0])
        else:
            self._listScheme.setCurrentRow(0)
        qsettings.endGroup()
        qsettings.endGroup()

        #Signals
        self.connect(self._btnEditorFont,
                     SIGNAL("clicked()"), self._load_editor_font)
        self.connect(self._listScheme, SIGNAL("itemSelectionChanged()"),
                     self._preview_style)
        self.connect(self._preferences, SIGNAL("savePreferences()"), self.save)

    def _open_schemes_manager(self):
        ninjaide = IDE.get_service("ide")
        ninjaide.show_schemes()
        # refresh schemes

    def _open_schemes_designer(self):
        name = self._listScheme.currentItem().text()
        scheme = self._schemes.get(name, resources.COLOR_SCHEME)
        designer = preferences_editor_scheme_designer.EditorSchemeDesigner(
            scheme, self)
        designer.exec_()
        if designer.saved:
            scheme_name = designer.line_name.text()
            scheme = designer.original_style
            self._schemes[scheme_name] = scheme
            result = self._listScheme.findItems(scheme_name, Qt.MatchExactly)
            if not result:
                self._listScheme.addItem(scheme_name)

    def _remove_scheme(self):
        name = self._listScheme.currentItem().text()
        fileName = ('{0}.color'.format(
            file_manager.create_path(resources.EDITOR_SKINS, name)))
        file_manager.delete_file(fileName)
        item = self._listScheme.takeItem(self._listScheme.currentRow())
        del item

    def hideEvent(self, event):
        super(EditorGeneral, self).hideEvent(event)
        resources.CUSTOM_SCHEME = self.original_style
        for editorWidget in self._modified_editors:
            try:
                editorWidget.restyle(editorWidget.lang)
            except RuntimeError:
                print('the editor has been removed')

    def _preview_style(self):
        scheme = self._listScheme.currentItem().text()
        if scheme == self.current_scheme:
            return
        main_container = IDE.get_service('main_container')
        if not main_container:
            return
        editorWidget = main_container.get_current_editor()
        if editorWidget is not None:
            resources.CUSTOM_SCHEME = self._schemes.get(
                scheme,
                resources.COLOR_SCHEME)
            editorWidget.restyle(editorWidget.lang)
            self._modified_editors.append(editorWidget)
        self.current_scheme = scheme

    def _load_editor_font(self):
        try:
            font, ok = QFontDialog.getFont(self._font, self)
            if ok:
                self._font = font
                btnText = ', '.join(self._font.toString().split(',')[0:2])
                self._btnEditorFont.setText(btnText)
        except:
            QMessageBox.warning(
                self,
                translations.TR_PREFERENCES_EDITOR_GENERAL_FONT_MESSAGE_TITLE,
                translations.TR_PREFERENCES_EDITOR_GENERAL_FONT_MESSAGE_BODY)

    def save(self):
        qsettings = IDE.ninja_settings()
        settings.FONT = self._font
        qsettings.setValue('preferences/editor/font', settings.FONT)
        settings.SHOW_MINIMAP = self._checkShowMinimap.isChecked()
        settings.MINIMAP_MAX_OPACITY = self._spinMaxOpacity.value() / 100.0
        settings.MINIMAP_MIN_OPACITY = self._spinMinOpacity.value() / 100.0
        settings.SIZE_PROPORTION = self._spinSize.value() / 100.0
        qsettings.setValue('preferences/editor/minimapMaxOpacity',
                           settings.MINIMAP_MAX_OPACITY)
        qsettings.setValue('preferences/editor/minimapMinOpacity',
                           settings.MINIMAP_MIN_OPACITY)
        qsettings.setValue('preferences/editor/minimapSizeProportion',
                           settings.SIZE_PROPORTION)
        qsettings.setValue('preferences/editor/minimapShow',
                           settings.SHOW_MINIMAP)
        scheme = self._listScheme.currentItem().text()
        resources.CUSTOM_SCHEME = self._schemes.get(scheme,
                                                    resources.COLOR_SCHEME)
        qsettings.setValue('preferences/editor/scheme', scheme)
Exemplo n.º 59
0
class AnalogInV2(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletAnalogInV2, *args)

        self.ai = self.device

        self.cbe_voltage = CallbackEmulator(self.ai.get_voltage,
                                            self.cb_voltage,
                                            self.increase_error_count)

        self.current_voltage = None  # float, V

        plots = [('Voltage', Qt.red, lambda: self.current_voltage,
                  format_voltage)]
        self.plot_widget = PlotWidget('Voltage [V]', plots)

        self.spin_average = QSpinBox()
        self.spin_average.setMinimum(1)
        self.spin_average.setMaximum(50)
        self.spin_average.setSingleStep(1)
        self.spin_average.setValue(50)
        self.spin_average.editingFinished.connect(self.spin_average_finished)

        layout_h1 = QHBoxLayout()
        layout_h1.addWidget(QLabel('Moving Average Length:'))
        layout_h1.addWidget(self.spin_average)
        layout_h1.addStretch()

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(layout_h1)

    def get_moving_average_async(self, average):
        self.spin_average.setValue(average)

    def start(self):
        async_call(self.ai.get_moving_average, None,
                   self.get_moving_average_async, self.increase_error_count)
        async_call(self.ai.get_voltage, None, self.cb_voltage,
                   self.increase_error_count)
        self.cbe_voltage.set_period(100)

        self.plot_widget.stop = False

    def stop(self):
        self.cbe_voltage.set_period(0)

        self.plot_widget.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletAnalogInV2.DEVICE_IDENTIFIER

    def cb_voltage(self, voltage):
        self.current_voltage = voltage / 1000.0

    def spin_average_finished(self):
        self.ai.set_moving_average(self.spin_average.value())