コード例 #1
0
ファイル: widget.py プロジェクト: 4myPAL/freeseer
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)
コード例 #2
0
ファイル: AddWordsDialog.py プロジェクト: michaupl/wordtester
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)
コード例 #3
0
ファイル: ensemblefetcher.py プロジェクト: rolk/ert
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)
コード例 #4
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)
コード例 #5
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
コード例 #6
0
ファイル: Config.py プロジェクト: sarahdi/openfisca
 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
コード例 #7
0
ファイル: qthelpers.py プロジェクト: sarahdi/openfisca
    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
コード例 #8
0
class SpinBoxImageView(QHBoxLayout):
    valueChanged = pyqtSignal(int)
    def __init__(self, parentView, backgroundColor, foregroundColor,
                 value, height, fontSize):
        QHBoxLayout.__init__(self)
        self.backgroundColor = backgroundColor
        self.foregroundColor = foregroundColor

        self.labelLayout = QVBoxLayout()
        self.upLabel = LabelButtons('spin-up', parentView,
                                    backgroundColor, foregroundColor,
                                    height/2, height/2)
        self.labelLayout.addWidget(self.upLabel)
        self.upLabel.clicked.connect(self.on_upLabel)

        self.downLabel = LabelButtons('spin-down', parentView,
                                      backgroundColor,
                                      foregroundColor, height/2,
                                      height/2)
        self.labelLayout.addWidget(self.downLabel)
        self.downLabel.clicked.connect(self.on_downLabel)

        self.addLayout(self.labelLayout)

        self.spinBox = QSpinBox()
        self.spinBox.valueChanged.connect(self.spinBoxValueChanged)
        self.addWidget(self.spinBox)
        self.spinBox.setToolTip("Spinbox")
        self.spinBox.setButtonSymbols(QAbstractSpinBox.NoButtons)
        self.spinBox.setAlignment(Qt.AlignRight)
        self.spinBox.setMaximum(value)
        self.spinBox.setMaximumHeight(height)
        self.spinBox.setSuffix("/" + str(value))
        font = self.spinBox.font()
        font.setPixelSize(fontSize)
        self.spinBox.setFont(font)
        self.do_draw()

    def do_draw(self):
        r, g, b, a = self.foregroundColor.getRgb()
        rgb = "rgb({0},{1},{2})".format(r, g, b)
        sheet = TEMPLATE.format(rgb,
                                self.backgroundColor.name())
        self.spinBox.setStyleSheet(sheet)

    def spinBoxValueChanged(self, value):
        self.valueChanged.emit(value)

    def setValue(self, value):
        self.spinBox.setValue(value)

    def setNewValue(self, value):
        self.spinBox.setMaximum(value)
        self.spinBox.setSuffix("/" + str(value))

    def on_upLabel(self):
        self.spinBox.setValue(self.spinBox.value() + 1)

    def on_downLabel(self):
        self.spinBox.setValue(self.spinBox.value() - 1)
コード例 #9
0
ファイル: clientes.py プロジェクト: dravix/pyventa
    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)
	
コード例 #10
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)
コード例 #11
0
ファイル: widget.py プロジェクト: joanma100/freeseer
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
コード例 #12
0
ファイル: progress.py プロジェクト: superactive/Virux
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):")
コード例 #13
0
class SpinBoxImageView(QHBoxLayout):
    valueChanged = pyqtSignal(int)
    def __init__(self, backgroundColor, foregroundColor, value, height, fontSize):
        QHBoxLayout.__init__(self)
        self.backgroundColor = backgroundColor
        self.foregroundColor = foregroundColor
        
        self.labelLayout = QVBoxLayout()
        self.upLabel = LabelButtons(backgroundColor, foregroundColor, height/2, height/2)
        self.labelLayout.addWidget(self.upLabel)
        self.upLabel.setSpinBoxUpIcon()
        self.upLabel.clicked.connect(self.on_upLabel)
        
        self.downLabel = LabelButtons(backgroundColor, foregroundColor, height/2, height/2)
        self.labelLayout.addWidget(self.downLabel)
        self.downLabel.setSpinBoxDownIcon()
        self.downLabel.clicked.connect(self.on_downLabel)
        
        self.addLayout(self.labelLayout)

        
        self.spinBox = QSpinBox()
        self.spinBox.valueChanged.connect(self.spinBoxValueChanged)
        self.addWidget(self.spinBox)
        self.spinBox.setToolTip("Spinbox")
        self.spinBox.setButtonSymbols(QAbstractSpinBox.NoButtons)
        self.spinBox.setAlignment(Qt.AlignRight)
        self.spinBox.setMaximum(value)
        self.spinBox.setMaximumHeight(height)
        self.spinBox.setSuffix("/" + str(value))
        font = self.spinBox.font()
        font.setPixelSize(fontSize)
        self.spinBox.setFont(font)
        rgb = foregroundColor.getRgb()
        rgba_string = "rgba("+str(rgb[0])+","+str(rgb[1])+","+str(rgb[2])+","+str(0.6*100)+"%)"
        self.spinBox.setStyleSheet("QSpinBox { color: " + rgba_string + "; font: bold; background-color: " + str(backgroundColor.name()) + "; border:0;}")

    def changeOpacity(self, opacity):
        rgb = self.foregroundColor.getRgb()
        rgba_string = "rgba("+str(rgb[0])+","+str(rgb[1])+","+str(rgb[2])+","+str(opacity*100)+"%)"
        self.spinBox.setStyleSheet("QSpinBox { color: " + rgba_string + "; font: bold; background-color: " + str(self.backgroundColor.name()) + "; border:0;}")
        self.upLabel.changeOpacity(opacity)
        self.downLabel.changeOpacity(opacity)

    def spinBoxValueChanged(self, value):
        self.valueChanged.emit(value)    
    
    def setValue(self, value):
        self.spinBox.setValue(value)
    
    def setNewValue(self, value):
        self.spinBox.setMaximum(value)
        self.spinBox.setSuffix("/" + str(value))
    
    def on_upLabel(self):
        self.spinBox.setValue(self.spinBox.value() + 1)
        
    def on_downLabel(self):
        self.spinBox.setValue(self.spinBox.value() - 1)
コード例 #14
0
ファイル: floatcolumn.py プロジェクト: diatel/microhex
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()
コード例 #15
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
コード例 #16
0
    def addSpinboxes(self, n):
        spb = []
        for i in range(n):
            spinbox = QSpinBox()
            spinbox.setMaximum(1000)
            spb.append(spinbox)
            self.layout.addWidget(spinbox)

        for i in range(n-1):
            spb[i].valueChanged.connect(spb[i + 1].setMinimum)
コード例 #17
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)
コード例 #18
0
ファイル: widget.py プロジェクト: Blakstar26/freeseer
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
コード例 #19
0
ファイル: widget.py プロジェクト: Blakstar26/freeseer
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)
コード例 #20
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
コード例 #21
0
ファイル: labelingImport.py プロジェクト: kkiefer/ilastik
    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()
コード例 #22
0
ファイル: labelingImport.py プロジェクト: kkiefer/ilastik
    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()
コード例 #23
0
    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)
コード例 #24
0
ファイル: integer_spinner.py プロジェクト: jonerduarte/ert
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)
コード例 #25
0
ファイル: EkdWidgets.py プロジェクト: Ptaah/Ekd
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)
コード例 #26
0
ファイル: Declaration.py プロジェクト: sarahdi/openfisca
 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
コード例 #27
0
ファイル: sliceSelectorHud.py プロジェクト: burcin/volumina
def _get_pos_widget(name, backgroundColor, foregroundColor):
    label = QLabel()
    label.setAttribute(Qt.WA_TransparentForMouseEvents, True)

    pixmap = QPixmap(25*10, 25*10)
    pixmap.fill(backgroundColor)
    painter = QPainter()
    painter.begin(pixmap)
    pen = QPen(foregroundColor)
    painter.setPen(pen)
    painter.setRenderHint(QPainter.Antialiasing)
    font = QFont()
    font.setBold(True)
    font.setPixelSize(25*10-30)
    path = QPainterPath()
    path.addText(QPointF(50, 25*10-50), font, name)
    brush = QBrush(foregroundColor)
    painter.setBrush(brush)
    painter.drawPath(path)
    painter.setFont(font)
    painter.end()
    pixmap = pixmap.scaled(QSize(20,20),
                           Qt.KeepAspectRatio,
                           Qt.SmoothTransformation)
    label.setPixmap(pixmap)

    spinbox = QSpinBox()
    spinbox.setAttribute(Qt.WA_TransparentForMouseEvents, True)
    spinbox.setEnabled(False)
    spinbox.setAlignment(Qt.AlignCenter)
    spinbox.setToolTip("{0} Spin Box".format(name))
    spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons)
    spinbox.setMaximumHeight(20)
    spinbox.setMaximum(9999)
    font = spinbox.font()
    font.setPixelSize(14)
    spinbox.setFont(font)
    sheet = TEMPLATE.format(foregroundColor.name(),
                            backgroundColor.name())
    spinbox.setStyleSheet(sheet)
    return label, spinbox
コード例 #28
0
def _get_pos_widget(name, backgroundColor, foregroundColor):
    label = QLabel()
    label.setAttribute(Qt.WA_TransparentForMouseEvents, True)

    pixmap = QPixmap(25*10, 25*10)
    pixmap.fill(backgroundColor)
    painter = QPainter()
    painter.begin(pixmap)
    pen = QPen(foregroundColor)
    painter.setPen(pen)
    painter.setRenderHint(QPainter.Antialiasing)
    font = QFont()
    font.setBold(True)
    font.setPixelSize(25*10-30)
    path = QPainterPath()
    path.addText(QPointF(50, 25*10-50), font, name)
    brush = QBrush(foregroundColor)
    painter.setBrush(brush)
    painter.drawPath(path)
    painter.setFont(font)
    painter.end()
    pixmap = pixmap.scaled(QSize(20,20),
                           Qt.KeepAspectRatio,
                           Qt.SmoothTransformation)
    label.setPixmap(pixmap)

    spinbox = QSpinBox()
    spinbox.setAttribute(Qt.WA_TransparentForMouseEvents, True)
    spinbox.setEnabled(False)
    spinbox.setAlignment(Qt.AlignCenter)
    spinbox.setToolTip("{0} Spin Box".format(name))
    spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons)
    spinbox.setMaximumHeight(20)
    spinbox.setMaximum(9999)
    font = spinbox.font()
    font.setPixelSize(14)
    spinbox.setFont(font)
    sheet = TEMPLATE.format(foregroundColor.name(),
                            backgroundColor.name())
    spinbox.setStyleSheet(sheet)
    return label, spinbox
コード例 #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
        layout.addRow(self.label_audio_quality, self.spinbox_audio_quality)

        #
        # 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
        layout.addRow(self.label_video_quality, self.spinbox_video_quality)

        #
        # 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)
コード例 #30
0
ファイル: charcolumn.py プロジェクト: diatel/microhex
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()
コード例 #31
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)
コード例 #32
0
ファイル: installwizard.py プロジェクト: gjhiggins/electrum
    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
コード例 #33
0
ファイル: qregistry.py プロジェクト: vertrex/destruct
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)
コード例 #34
0
ファイル: Config.py プロジェクト: TibbersBear/openfisca
 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
コード例 #35
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()
コード例 #36
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())
コード例 #37
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())
コード例 #38
0
ファイル: widget.py プロジェクト: riolowry/freeseer
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)
コード例 #39
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):")
コード例 #40
0
ファイル: 2669.py プロジェクト: jlg234bob/PPQT
 def createEditor(self, parent, style, index):
     if index.column() != 3: return None
     sb = QSpinBox(parent)
     sb.setMaximum(2000)
     return sb
コード例 #41
0
class MainWindow(QWidget):
    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(500, 300)

        self.mainLayout = QHBoxLayout()
        self.chooseLayout = QHBoxLayout()
        self.layout = QVBoxLayout()
        self.pixLayout = QHBoxLayout()
        self.thresholdLayout = QHBoxLayout()
        self.timeLayout = QHBoxLayout()
        self.contoursLayout = QHBoxLayout()
        self.setLayout(self.mainLayout)
        self.setWindowTitle(
            "Image To Gcode V1.0 ----- build By yizheneng [email protected]")

        self.imageLabel = QLabel("image")

        self.mainLayout.addWidget(self.imageLabel)
        self.mainLayout.addLayout(self.layout)
        self.mainLayout.setStretchFactor(self.layout, 1)
        self.mainLayout.setStretchFactor(self.imageLabel, 3)

        self.pixLengthLabel = QLabel(u"像素大小(mm):")
        self.pixDoubleSpinBox = QDoubleSpinBox()
        self.pixDoubleSpinBox.setValue(1)
        self.pixDoubleSpinBox.setDecimals(6)
        self.pixLayout.addWidget(self.pixLengthLabel)
        self.pixLayout.addWidget(self.pixDoubleSpinBox)

        self.thresholdLabel = QLabel(u"阈值:")
        self.thresholdSpinBox = QSpinBox()
        self.thresholdSpinBox.valueChanged.connect(self.ThresholdValChange)
        self.thresholdSpinBox.setMaximum(255)
        self.thresholdSpinBox.setValue(120)
        self.thresholdLayout.addWidget(self.thresholdLabel)
        self.thresholdLayout.addWidget(self.thresholdSpinBox)

        self.timeLabel = QLabel(u"灼烧时间:")
        self.timeDoubleSpinBox = QDoubleSpinBox()
        self.timeDoubleSpinBox.setValue(0.3)
        self.timeLayout.addWidget(self.timeLabel)
        self.timeLayout.addWidget(self.timeDoubleSpinBox)

        self.chooseLabel = QLabel(u"只雕刻轮廓:")
        self.chooseBox = QCheckBox()
        self.chooseLayout.addWidget(self.chooseLabel)
        self.chooseLayout.addWidget(self.chooseBox)
        self.chooseBox.stateChanged.connect(self.ChooseValChanged)

        self.contoursWidthLabel = QLabel(u"边框宽度")
        self.ContoursWidthSpinBox = QSpinBox()
        self.ContoursWidthSpinBox.setEnabled(False)
        self.ContoursWidthSpinBox.setValue(1)
        self.contoursLayout.addWidget(self.contoursWidthLabel)
        self.contoursLayout.addWidget(self.ContoursWidthSpinBox)

        self.loadImageButton = QPushButton(u"加载图片")
        self.loadImageButton.clicked.connect(self.LoadImageButtonClicked)
        self.previewButton = QPushButton(u"预览")
        self.previewButton.clicked.connect(self.ThresholdValChange)
        self.makeCodeButton = QPushButton(u"生成G代码")
        self.makeCodeButton.clicked.connect(self.MakeGcode)

        self.layout.addLayout(self.pixLayout)
        self.layout.addLayout(self.thresholdLayout)
        self.layout.addLayout(self.timeLayout)
        self.layout.addLayout(self.chooseLayout)
        self.layout.addLayout(self.contoursLayout)
        self.layout.addWidget(self.loadImageButton)
        self.layout.addWidget(self.previewButton)
        self.layout.addWidget(self.makeCodeButton)

    def LoadImageButtonClicked(self):
        self.filePath = QFileDialog.getOpenFileName(self, u"选择图片文件", "",
                                                    "Images (*.bmp)")
        if self.filePath == "":
            QMessageBox.warning(self, u"发生错误", u"没有选择可以识别的文件!!")
            return

        self.srcImage = QImage(self.filePath)
        self.grayImage = QImage(self.srcImage.size(), QImage.Format_Indexed8)

        for i in range(256):
            self.grayImage.setColor(i, qRgb(i, i, i))

        for i in range(self.srcImage.width()):
            for j in range(self.srcImage.height()):
                temp = qGray(self.srcImage.pixel(i, j))
                self.grayImage.setPixel(i, j, temp)

        self.srcImage = QImage(self.grayImage)
        self.resultImage = QImage(self.grayImage)
        self.imageLabel.setPixmap(QPixmap(self.srcImage))

    def ChooseValChanged(self):
        self.ContoursWidthSpinBox.setEnabled(self.chooseBox.isChecked())

    def ThresholdValChange(self):
        for i in range(self.srcImage.width()):
            for j in range(self.srcImage.height()):
                temp = self.srcImage.pixelIndex(i, j)
                if (temp >= self.thresholdSpinBox.value()):
                    self.grayImage.setPixel(i, j, 255)
                else:
                    self.grayImage.setPixel(i, j, 0)
        self.resultImage = QImage(self.grayImage)
        #如果选中了只雕刻轮廓
        if self.chooseBox.isChecked():
            img = np.zeros(
                (self.grayImage.height(), self.grayImage.width(), 1), np.uint8)
            for i in range(self.grayImage.width()):
                for j in range(self.grayImage.height()):
                    img[j, i] = self.grayImage.pixelIndex(i, j)
            #提取轮廓
            contours = cv.findContours(img, cv.RETR_LIST,
                                       cv.CHAIN_APPROX_SIMPLE)
            img = np.zeros(
                (self.grayImage.height(), self.grayImage.width(), 1), np.uint8)
            cv.drawContours(img, contours[1][:-1], -1, (255, 255, 255),
                            self.ContoursWidthSpinBox.value())
            #转换轮廓到显示界面
            for i in range(self.resultImage.width()):
                for j in range(self.resultImage.height()):
                    if img[j, i] == 0:
                        self.resultImage.setPixel(i, j, 255)
                    else:
                        self.resultImage.setPixel(i, j, 0)

        self.imageLabel.setPixmap(QPixmap(self.resultImage))

    def MakeGcode(self):
        path = QFileDialog.getSaveFileName(self, u"选择保存路径", "", " (*.nc)")
        if path == "":
            QMessageBox.warning(self, u"发生错误", u"路径错误!!")
            return

        f = open(path, 'w')
        f.write("M5\n")

        for i in range(self.resultImage.width()):
            flag = False
            #检测这一行是否有点
            for j in range(self.resultImage.height()):
                if self.resultImage.pixelIndex(i, j) < 128:
                    flag = True
                    break
            #如果这一行都没有点则跳过这一行
            if flag:
                f.write("G0 Y%f\n" % (i * self.pixDoubleSpinBox.value()))
            else:
                continue

            if (i % 2) > 0:
                for j in range(self.resultImage.height()):
                    if self.resultImage.pixelIndex(i, j) < 128:
                        f.write("G0 X%f\n" %
                                (j * self.pixDoubleSpinBox.value()))
                        f.write("M3\n")
                        f.write("G4 P%f\n" % self.timeDoubleSpinBox.value())
                        f.write("M5\n")
            else:
                for j in range(self.resultImage.height())[::-1]:
                    if self.resultImage.pixelIndex(i, j) < 128:
                        f.write("G0 X%f\n" %
                                (j * self.pixDoubleSpinBox.value()))
                        f.write("M3\n")
                        f.write("G4 P%f\n" % self.timeDoubleSpinBox.value())
                        f.write("M5\n")

        f.write("M5\n")
        f.write("G0 X0 Y0\n")
        f.close()
        QMessageBox.information(self, u"成功", u"生成G代码文件成功!!")
コード例 #42
0
ファイル: uiBasicWidget.py プロジェクト: YGRCG/TradeSim
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()
コード例 #43
0
ファイル: ac_current.py プロジェクト: fscherwi/brickv
class ACCurrent(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletACCurrent, *args)

        self.acc = self.device

        self.cbe_current = CallbackEmulator(self.acc.get_current,
                                            self.cb_current,
                                            self.increase_error_count)

        self.current_label = CurrentLabel('Current: ')

        self.current_value = None

        plot_list = [['', Qt.red, self.get_current_value]]
        self.plot_widget = PlotWidget('Current [A]', plot_list)

        layout_h2 = QHBoxLayout()
        layout_h2.addStretch()
        layout_h2.addWidget(self.current_label)
        layout_h2.addStretch()

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h2)
        layout.addWidget(self.plot_widget)

        self.label_average = QLabel('Length of moving average:')
        self.spin_average = QSpinBox()
        self.spin_average.setMinimum(1)
        self.spin_average.setMaximum(50)
        self.spin_average.setSingleStep(1)
        self.spin_average.setValue(50)
        self.spin_average.editingFinished.connect(self.spin_average_finished)
        
        self.label_range = QLabel('Current Range: ')
        self.combo_range = QComboBox()
        self.combo_range.addItem("0") # TODO: Adjust ranges
        self.combo_range.addItem("1")
        self.combo_range.currentIndexChanged.connect(self.new_config)

        layout_h1 = QHBoxLayout()
        layout_h1.addStretch()
        layout_h1.addWidget(self.label_average)
        layout_h1.addWidget(self.spin_average)
        layout_h1.addStretch()
        layout_h1.addWidget(self.label_range)
        layout_h1.addWidget(self.combo_range)
        layout_h1.addStretch()
        layout.addLayout(layout_h1)
        
    def get_configuration_async(self, conf):
        self.combo_range.setCurrentIndex(conf)

    def get_moving_average_async(self, average):
        self.spin_average.setValue(average)
        
    def new_config(self, value):
        try:
            self.acc.set_configuration(value)
        except:
            pass

    def start(self):
        async_call(self.acc.get_configuration, None, self.get_configuration_async, self.increase_error_count)
        async_call(self.acc.get_moving_average, None, self.get_moving_average_async, self.increase_error_count)
        async_call(self.acc.get_current, None, self.cb_current, self.increase_error_count)
        self.cbe_current.set_period(100)

        self.plot_widget.stop = False

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

        self.plot_widget.stop = True

    def destroy(self):
        pass

    def get_url_part(self):
        return 'ac_current'

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

    def get_current_value(self):
        return self.current_value

    def cb_current(self, current):
        c = round(current/1000.0, 2)
        self.current_value = c
        self.current_label.setText('%6.02f' % c)

    def spin_average_finished(self):
        self.acc.set_moving_average(self.spin_average.value())
コード例 #44
0
class ConfigWidget(DefaultConfigWidget):

    def __init__(self, plugin):
        DefaultConfigWidget.__init__(self, plugin)
        c = plugin_prefs[STORE_NAME]
        all_tags = get_current_db().all_tags()

        other_group_box = QGroupBox('Other options', self)
        self.l.addWidget(other_group_box, self.l.rowCount(), 0, 1, 2)
        other_group_box_layout = QVBoxLayout()
        other_group_box.setLayout(other_group_box_layout)

        max_label = QLabel('Maximum title/author search matches to evaluate (1 = fastest):', self)
        max_label.setToolTip('Kyobobook do not always have links to large covers for every ISBN\n'
                             'of the same book. Increasing this value will take effect when doing\n'
                             'title/author searches to consider more ISBN editions.\n\n'
                             'This will increase the potential likelihood of getting a larger cover\n'
                             'though does not guarantee it.')
        other_group_box_layout.addWidget(max_label) #, 0, 0, 1, 1)
        self.max_downloads_spin = QSpinBox(self)
        self.max_downloads_spin.setMinimum(1)
        self.max_downloads_spin.setMaximum(20)
        self.max_downloads_spin.setProperty('value', c.get(KEY_MAX_DOWNLOADS, DEFAULT_STORE_VALUES[KEY_MAX_DOWNLOADS]))
        other_group_box_layout.addWidget(self.max_downloads_spin)#, 0, 1, 1, 1)
        #other_group_box_layout.setColumnStretch(2, 1)


        # by sseeookk, category 20140315
        self.get_category_checkbox = QCheckBox('Add Kyobobook Categories to Calibre tags', self)
        self.get_category_checkbox.setToolTip('Add Kyobobook Categories to Calibre tags(ex, [Domestic Books > History > Korea Culture / History Journey]).')
        self.get_category_checkbox.setChecked(c[KEY_GET_CATEGORY])
        other_group_box_layout.addWidget(self.get_category_checkbox)
        
        
        self.all_authors_checkbox = QCheckBox('Get all contributing authors (e.g. illustrators, series editors etc)', self)
        self.all_authors_checkbox.setToolTip('Kyobobook for some books will list all of the contributing authors and\n'
                                              'the type of contribution like (Editor), (Illustrator) etc.\n\n'
                                              'When this option is checked, all contributing authors are retrieved.\n\n'
                                              'When unchecked (default) only the primary author(s) are returned which\n'
                                              'are those that either have no contribution type specified, or have the\n'
                                              'value of (Kyobobook Author).\n\n'
                                              'If there is no primary author then only those with the same contribution\n'
                                              'type as the first author are returned.\n'
                                              'e.g. "A, B (Illustrator)" will return author A\n'
                                              'e.g. "A (Kyobobook Author)" will return author A\n'
                                              'e.g. "A (Editor), B (Editor), C (Illustrator)" will return authors A & B\n'
                                              'e.g. "A (Editor), B (Series Editor)" will return author A\n')
        self.all_authors_checkbox.setChecked(c[KEY_GET_ALL_AUTHORS])
        other_group_box_layout.addWidget(self.all_authors_checkbox)
        
        # Add by sseeookk, 20140315
        self.toc_checkbox = QCheckBox('Append TOC from Features tab if available to comments', self)
        self.toc_checkbox.setToolTip('Kyobobook for textbooks on their website have a Features tab which\n'
                                      'contains a table of contents for the book. Checking this option will\n'
                                      'append the TOC to the bottom of the Synopsis in the comments field')
        self.toc_checkbox.setChecked(c.get(KEY_APPEND_TOC, DEFAULT_STORE_VALUES[KEY_APPEND_TOC]))
        # other_group_box_layout.addWidget(self.toc_checkbox, 2, 0, 1, 3)
        other_group_box_layout.addWidget(self.toc_checkbox)


    def commit(self):
        DefaultConfigWidget.commit(self)
        new_prefs = {}
        new_prefs[KEY_MAX_DOWNLOADS] = int(unicode(self.max_downloads_spin.value()))
        new_prefs[KEY_GET_CATEGORY] = self.get_category_checkbox.checkState() == Qt.Checked
        new_prefs[KEY_GET_ALL_AUTHORS] = self.all_authors_checkbox.checkState() == Qt.Checked
        new_prefs[KEY_APPEND_TOC] = self.toc_checkbox.checkState() == Qt.Checked
        plugin_prefs[STORE_NAME] = new_prefs
コード例 #45
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())
コード例 #46
0
class ACCurrent(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletACCurrent, *args)

        self.acc = self.device

        self.cbe_current = CallbackEmulator(self.acc.get_current,
                                            self.cb_current,
                                            self.increase_error_count)

        self.current_current = None  # float, A

        plots = [('Current', Qt.red, lambda: self.current_current,
                  format_current)]
        self.plot_widget = PlotWidget('Current [A]', plots)

        self.label_average = QLabel('Moving Average Length:')
        self.spin_average = QSpinBox()
        self.spin_average.setMinimum(1)
        self.spin_average.setMaximum(50)
        self.spin_average.setSingleStep(1)
        self.spin_average.setValue(50)
        self.spin_average.editingFinished.connect(self.spin_average_finished)

        self.label_range = QLabel('Current Range:')
        self.combo_range = QComboBox()
        self.combo_range.addItem("0")  # TODO: Adjust ranges
        self.combo_range.addItem("1")
        self.combo_range.currentIndexChanged.connect(self.new_config)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.label_average)
        hlayout.addWidget(self.spin_average)
        hlayout.addStretch()
        hlayout.addWidget(self.label_range)
        hlayout.addWidget(self.combo_range)

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

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

    def get_configuration_async(self, conf):
        self.combo_range.setCurrentIndex(conf)

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

    def new_config(self, value):
        try:
            self.acc.set_configuration(value)
        except:
            pass

    def start(self):
        async_call(self.acc.get_configuration, None,
                   self.get_configuration_async, self.increase_error_count)
        async_call(self.acc.get_moving_average, None,
                   self.get_moving_average_async, self.increase_error_count)
        async_call(self.acc.get_current, None, self.cb_current,
                   self.increase_error_count)
        self.cbe_current.set_period(100)

        self.plot_widget.stop = False

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

        self.plot_widget.stop = True

    def destroy(self):
        pass

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

    def cb_current(self, current):
        self.current_current = current / 1000.0

    def spin_average_finished(self):
        self.acc.set_moving_average(self.spin_average.value())
コード例 #47
0
class PiezoSpeaker(PluginBase):
    qtcb_beep_finished = pyqtSignal()
    qtcb_morse_finished = pyqtSignal()

    def __init__(self, *args):
        PluginBase.__init__(self, BrickletPiezoSpeaker, *args)

        self.ps = self.device

        self.qtcb_beep_finished.connect(self.cb_beep)
        self.ps.register_callback(self.ps.CALLBACK_BEEP_FINISHED,
                                  self.qtcb_beep_finished.emit)
        self.qtcb_morse_finished.connect(self.cb_morse)
        self.ps.register_callback(self.ps.CALLBACK_MORSE_CODE_FINISHED,
                                  self.qtcb_morse_finished.emit)

        self.has_stoppable_beep = self.firmware_version >= (2, 0, 2)

        self.frequency_label = QLabel('Frequency (585Hz-7100Hz): ')
        self.frequency_box = QSpinBox()
        self.frequency_box.setMinimum(585)
        self.frequency_box.setMaximum(7100)
        self.frequency_box.setValue(1000)
        self.frequency_layout = QHBoxLayout()
        self.frequency_layout.addWidget(self.frequency_label)
        self.frequency_layout.addWidget(self.frequency_box)
        self.frequency_layout.addStretch()

        self.beep_box = QSpinBox()
        self.beep_box.setMinimum(0)
        self.beep_box.setMaximum(2147483647)
        self.beep_box.setValue(1000)
        self.beep_box.setSizePolicy(QSizePolicy.Expanding,
                                    QSizePolicy.Preferred)
        self.beep_label = QLabel('Duration (ms): ')
        self.beep_button = QPushButton('Send Beep')
        self.beep_layout = QHBoxLayout()
        self.beep_layout.addWidget(self.beep_label)
        self.beep_layout.addWidget(self.beep_box)
        self.beep_layout.addWidget(self.beep_button)

        self.morse_edit = QLineEdit()
        self.morse_edit.setText('- .. -. -.- . .-. ..-. --- .-. --. .')
        self.morse_edit.setMaxLength(60)
        self.morse_label = QLabel('Morse Code: ')
        self.morse_button = QPushButton('Send Morse Code')
        self.morse_layout = QHBoxLayout()
        self.morse_layout.addWidget(self.morse_label)
        self.morse_layout.addWidget(self.morse_edit)
        self.morse_layout.addWidget(self.morse_button)

        self.calibrate_button = QPushButton('Calibrate')
        self.scale_button = QPushButton('Play Scale')
        self.scale_layout = QHBoxLayout()
        self.scale_layout.addWidget(self.scale_button)
        self.scale_layout.addWidget(self.calibrate_button)
        self.scale_layout.addStretch()

        self.calibrate_layout = QHBoxLayout()
        self.calibrate_layout.addStretch()

        self.scale_timer = QTimer()
        self.scale_timer.setInterval(25)
        self.scale_time = 585

        self.status_label = QLabel('')

        self.beep_button.clicked.connect(self.beep_clicked)
        self.morse_button.clicked.connect(self.morse_clicked)
        self.scale_button.clicked.connect(self.scale_clicked)
        self.scale_timer.timeout.connect(self.scale_timeout)
        self.calibrate_button.clicked.connect(self.calibrate_clicked)

        layout = QVBoxLayout(self)
        layout.addLayout(self.frequency_layout)
        layout.addLayout(self.beep_layout)
        layout.addLayout(self.morse_layout)
        layout.addLayout(self.scale_layout)
        layout.addWidget(self.status_label)
        #        layout.addLayout(self.calibrate_layout)
        layout.addStretch()

    def start(self):
        pass

    def stop(self):
        pass

    def destroy(self):
        pass

    def get_url_part(self):
        return 'piezo_speaker'

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

    def cb_beep(self):
        self.beep_button.setDisabled(False)
        self.morse_button.setDisabled(False)
        self.scale_button.setDisabled(False)
        self.status_label.setText('')

    def cb_morse(self):
        self.beep_button.setDisabled(False)
        self.morse_button.setDisabled(False)
        self.scale_button.setDisabled(False)
        self.status_label.setText('')

    def calibrate_clicked(self):
        self.status_label.setText('Calibrating')
        self.status_label.repaint()
        QApplication.processEvents()
        self.ps.calibrate()
        self.status_label.setText('New calibration stored in EEPROM')

    def scale_timeout(self):
        try:
            self.status_label.setText(str(self.scale_time) + 'Hz')
            self.ps.beep(40, self.scale_time)
        except ip_connection.Error:
            return

        self.scale_time += 50
        if self.scale_time > 7100:
            self.scale_time = 585
            self.scale_timer.stop()

    def scale_clicked(self):
        self.scale_time = 585
        self.scale_timeout()
        self.scale_timer.start()
        self.beep_button.setDisabled(True)
        self.morse_button.setDisabled(True)
        self.scale_button.setDisabled(True)

    def beep_clicked(self):
        freq = self.frequency_box.value()
        duration = self.beep_box.value()

        try:
            self.ps.beep(duration, freq)
        except ip_connection.Error:
            return

        if duration > 0 or not self.has_stoppable_beep:
            self.beep_button.setDisabled(True)
            self.morse_button.setDisabled(True)
            self.scale_button.setDisabled(True)
            self.status_label.setText('Beeping...')

    def morse_clicked(self):
        freq = self.frequency_box.value()
        morse = self.morse_edit.text()
        try:
            self.ps.morse_code(morse, freq)
        except ip_connection.Error:
            return

        self.beep_button.setDisabled(True)
        self.morse_button.setDisabled(True)
        self.scale_button.setDisabled(True)
        self.status_label.setText('Beeping...')
コード例 #48
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)
コード例 #49
0
ファイル: analog_out.py プロジェクト: jose1711/brickv
class AnalogOut(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletAnalogOut, *args)

        self.ao = self.device

        self.voltage_label = QLabel('Output Voltage [mV]:')
        self.voltage_box = QSpinBox()
        self.voltage_box.setMinimum(0)
        self.voltage_box.setMaximum(5000)
        self.voltage_box.setSingleStep(1)
        self.mode_label = QLabel('Mode:')
        self.mode_combo = QComboBox()
        self.mode_combo.addItem("Normal")
        self.mode_combo.addItem("1 kOhm Resistor to GND")
        self.mode_combo.addItem("100 kOhm resistor to GND")
        self.mode_combo.addItem("500 kOhm resistor to GND")

        layout_h1 = QHBoxLayout()
        layout_h1.addStretch()
        layout_h1.addWidget(self.voltage_label)
        layout_h1.addWidget(self.voltage_box)
        layout_h1.addStretch()

        layout_h2 = QHBoxLayout()
        layout_h2.addStretch()
        layout_h2.addWidget(self.mode_label)
        layout_h2.addWidget(self.mode_combo)
        layout_h2.addStretch()

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h2)
        layout.addLayout(layout_h1)
        layout.addStretch()

        self.voltage_box.editingFinished.connect(self.voltage_finished)
        self.mode_combo.currentIndexChanged.connect(self.mode_changed)

    def start(self):
        async_call(self.ao.get_voltage, None, self.voltage_box.setValue,
                   self.increase_error_count)
        async_call(self.ao.get_mode, None, self.mode_combo.setCurrentIndex,
                   self.increase_error_count)

    def stop(self):
        pass

    def destroy(self):
        pass

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

    def voltage_finished(self):
        value = self.voltage_box.value()
        try:
            self.ao.set_voltage(value)
        except ip_connection.Error:
            return

        self.mode_combo.setCurrentIndex(0)

    def mode_changed(self, mode):
        try:
            self.ao.set_mode(mode)
        except ip_connection.Error:
            return

        self.voltage_box.setValue(0)
コード例 #50
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())
コード例 #51
0
class NewConfigurationDialog(QDialog):
    """A dialog for selecting defaults for a new configuration."""
    def __init__(self, configuration_path, parent=None):
        QDialog.__init__(self, parent)

        self.setModal(True)
        self.setWindowTitle("New configuration file")
        self.setMinimumWidth(250)
        self.setMinimumHeight(150)

        layout = QFormLayout()

        directory, filename = os.path.split(configuration_path)

        if directory.strip() == "":
            directory = os.path.abspath(os.curdir)
            self.configuration_path = "%s/%s" % (directory, filename)
        else:
            self.configuration_path = configuration_path

        configuration_location = QLabel()
        configuration_location.setText(directory)

        configuration_name = QLabel()
        configuration_name.setText(filename)

        self.db_type = QComboBox()
        self.db_type.addItem("BLOCK_FS")
        self.db_type.addItem("PLAIN")

        self.first_case_name = QLineEdit()
        self.first_case_name.setText("default")
        self.connect(self.first_case_name, SIGNAL('textChanged(QString)'),
                     self._validateName)

        self.num_realizations = QSpinBox()
        self.num_realizations.setMinimum(1)
        self.num_realizations.setMaximum(1000)
        self.num_realizations.setValue(10)

        self.storage_path = QLineEdit()
        self.storage_path.setText("Storage")
        self.connect(self.storage_path, SIGNAL('textChanged(QString)'),
                     self._validateName)

        layout.addRow(createSpace(10))
        layout.addRow("Configuration name:", configuration_name)
        layout.addRow("Configuration location:", configuration_location)
        layout.addRow("Path to store DBase:", self.storage_path)
        layout.addRow("DBase type:", self.db_type)
        layout.addRow("Name of first case:", self.first_case_name)
        layout.addRow("Number of realizations", self.num_realizations)
        layout.addRow(createSpace(10))

        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        self.ok_button = buttons.button(QDialogButtonBox.Ok)

        layout.addRow(buttons)

        self.connect(buttons, SIGNAL('accepted()'), self.accept)
        self.connect(buttons, SIGNAL('rejected()'), self.reject)

        self.setLayout(layout)

    def getNumberOfRealizations(self):
        return self.num_realizations.value()

    def getConfigurationPath(self):
        return self.configuration_path

    def getCaseName(self):
        """Return the name of the first case."""
        return str(self.first_case_name.text()).strip()

    def getDBaseType(self):
        """Return the DBase type"""
        return str(self.db_type.currentText())

    def getStoragePath(self):
        """Return the DBase storage path"""
        return str(self.storage_path.text()).strip()

    def _validateName(self, name):
        name = str(name)
        enabled = len(name) > 0 and name.find(" ") == -1
        self.ok_button.setEnabled(enabled)
コード例 #52
0
ファイル: load_cell.py プロジェクト: jose1711/brickv
class LoadCell(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletLoadCell, *args)

        self.lc = self.device

        self.cbe_weight = CallbackEmulator(self.lc.get_weight, self.cb_weight,
                                           self.increase_error_count)

        self.gain = 0  # 128x
        self.current_weight = None  # int, g
        self.calibration = None

        plots = [('Weight', Qt.red, lambda: self.current_weight, format_weight)
                 ]
        self.plot_widget = PlotWidget('Weight [g]', plots)

        self.button_calibration = QPushButton("Calibration...")
        self.button_calibration.clicked.connect(
            self.button_calibration_clicked)

        self.button_tare = QPushButton("Tare")
        self.button_tare.clicked.connect(self.button_tare_clicked)

        self.enable_led = QCheckBox("Enable LED")
        self.enable_led.stateChanged.connect(self.enable_led_changed)

        self.spin_average = QSpinBox()
        self.spin_average.setMinimum(0)
        self.spin_average.setMaximum(40)
        self.spin_average.setSingleStep(1)
        self.spin_average.setValue(5)
        self.spin_average.editingFinished.connect(self.spin_average_finished)
        self.label_average = QLabel('Moving Average Length:')

        self.rate_label = QLabel('Rate:')
        self.rate_combo = QComboBox()
        self.rate_combo.addItem("10 Hz")
        self.rate_combo.addItem("80 Hz")
        self.rate_combo.currentIndexChanged.connect(self.new_config)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.label_average)
        hlayout.addWidget(self.spin_average)
        hlayout.addWidget(self.rate_label)
        hlayout.addWidget(self.rate_combo)
        hlayout.addStretch()
        hlayout.addWidget(self.button_calibration)
        hlayout.addWidget(self.button_tare)
        hlayout.addWidget(self.enable_led)

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

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

    def start(self):
        async_call(self.lc.is_led_on, None, self.is_led_on_async,
                   self.increase_error_count)
        async_call(self.lc.get_configuration, None,
                   self.get_configuration_async, self.increase_error_count)
        async_call(self.lc.get_moving_average, None,
                   self.get_moving_average_async, self.increase_error_count)
        async_call(self.lc.get_weight, None, self.cb_weight,
                   self.increase_error_count)
        self.cbe_weight.set_period(100)

        self.plot_widget.stop = False

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

        self.plot_widget.stop = True

    def destroy(self):
        if self.calibration:
            self.calibration.close()

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

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

    def get_configuration_async(self, conf):
        self.gain = conf.gain
        self.rate_combo.setCurrentIndex(conf.rate)

    def is_led_on_async(self, value):
        if value:
            self.enable_led.setChecked(True)
        else:
            self.enable_led.setChecked(False)

    def button_calibration_clicked(self):
        if self.calibration is None:
            self.calibration = Calibration(self)

        self.button_calibration.setEnabled(False)
        self.calibration.show()

    def button_tare_clicked(self):
        self.lc.tare()

    def enable_led_changed(self, state):
        if state == Qt.Checked:
            self.lc.led_on()
        else:
            self.lc.led_off()

    def new_config(self, value):
        rate = self.rate_combo.currentIndex()
        self.lc.set_configuration(rate, self.gain)

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

    def cb_weight(self, weight):
        self.current_weight = weight
コード例 #53
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()
コード例 #54
0
ファイル: dmx.py プロジェクト: jose1711/brickv
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletDMX, *args)

        self.setupUi(self)

        self.dmx = self.device

        self.wait_for_first_read = True

        self.dmx_overview = DMXOverview(self)
        self.layout_dmx_overview.insertWidget(1, self.dmx_overview)

        self.qtcb_frame_started.connect(self.cb_frame_started)
        self.qtcb_frame.connect(self.cb_frame)

        self.mode_combobox.currentIndexChanged.connect(self.mode_changed)
        self.frame_duration_spinbox.valueChanged.connect(
            self.frame_duration_changed)

        self.address_spinboxes = []
        self.address_slider = []

        for i in range(512):
            spinbox = QSpinBox()
            spinbox.setMinimum(0)
            spinbox.setMaximum(255)

            slider = QSlider(Qt.Horizontal)
            slider.setMinimum(0)
            slider.setMaximum(255)

            spinbox.valueChanged.connect(slider.setValue)
            slider.valueChanged.connect(spinbox.setValue)

            def get_frame_value_changed_func(i):
                return lambda x: self.frame_value_changed(i, x)

            slider.valueChanged.connect(get_frame_value_changed_func(i))

            self.address_table.setCellWidget(i, 0, spinbox)
            self.address_table.setCellWidget(i, 1, slider)

            self.address_spinboxes.append(spinbox)
            self.address_slider.append(slider)

        self.address_table.horizontalHeader().setStretchLastSection(True)
        self.address_table.show()

        self.current_frame = [0] * 512

        self.com_led_off_action = QAction('Off', self)
        self.com_led_off_action.triggered.connect(
            lambda: self.dmx.set_communication_led_config(
                BrickletDMX.COMMUNICATION_LED_CONFIG_OFF))
        self.com_led_on_action = QAction('On', self)
        self.com_led_on_action.triggered.connect(
            lambda: self.dmx.set_communication_led_config(
                BrickletDMX.COMMUNICATION_LED_CONFIG_ON))
        self.com_led_show_heartbeat_action = QAction('Show Heartbeat', self)
        self.com_led_show_heartbeat_action.triggered.connect(
            lambda: self.dmx.set_communication_led_config(
                BrickletDMX.COMMUNICATION_LED_CONFIG_SHOW_HEARTBEAT))
        self.com_led_show_communication_action = QAction('Show Com', self)
        self.com_led_show_communication_action.triggered.connect(
            lambda: self.dmx.set_communication_led_config(
                BrickletDMX.COMMUNICATION_LED_CONFIG_SHOW_COMMUNICATION))

        self.extra_configs += [(1, 'Com LED:', [
            self.com_led_off_action, self.com_led_on_action,
            self.com_led_show_heartbeat_action,
            self.com_led_show_communication_action
        ])]

        self.error_led_off_action = QAction('Off', self)
        self.error_led_off_action.triggered.connect(
            lambda: self.dmx.set_error_led_config(BrickletDMX.
                                                  ERROR_LED_CONFIG_OFF))
        self.error_led_on_action = QAction('On', self)
        self.error_led_on_action.triggered.connect(
            lambda: self.dmx.set_error_led_config(BrickletDMX.
                                                  ERROR_LED_CONFIG_ON))
        self.error_led_show_heartbeat_action = QAction('Show Heartbeat', self)
        self.error_led_show_heartbeat_action.triggered.connect(
            lambda: self.dmx.set_error_led_config(
                BrickletDMX.ERROR_LED_CONFIG_SHOW_HEARTBEAT))
        self.error_led_show_error_action = QAction('Show Error', self)
        self.error_led_show_error_action.triggered.connect(
            lambda: self.dmx.set_error_led_config(BrickletDMX.
                                                  ERROR_LED_CONFIG_SHOW_ERROR))

        self.extra_configs += [(1, 'Error LED:', [
            self.error_led_off_action, self.error_led_on_action,
            self.error_led_show_heartbeat_action,
            self.error_led_show_error_action
        ])]
コード例 #55
0
class LaserRangeFinder(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletLaserRangeFinder, *args)

        self.lrf = self.device

        self.cbe_distance = CallbackEmulator(self.lrf.get_distance,
                                             self.cb_distance,
                                             self.increase_error_count)
        self.cbe_velocity = CallbackEmulator(self.lrf.get_velocity,
                                             self.cb_velocity,
                                             self.increase_error_count)

        self.current_distance = None  # int, cm
        self.current_velocity = None  # float, m/s

        plots_distance = [('Distance', Qt.red, lambda: self.current_distance,
                           format_distance)]
        plots_velocity = [('Velocity', Qt.red, lambda: self.current_velocity,
                           '{:.2f} m/s'.format)]
        self.plot_widget_distance = PlotWidget('Distance [cm]', plots_distance)
        self.plot_widget_velocity = PlotWidget('Velocity [m/s]',
                                               plots_velocity)

        self.mode_label = QLabel('Mode:')
        self.mode_combo = QComboBox()
        self.mode_combo.addItem("Distance: 1cm resolution, 40m max")
        self.mode_combo.addItem("Velocity: 0.10 m/s resolution, 12.70m/s max")
        self.mode_combo.addItem("Velocity: 0.25 m/s resolution, 31.75m/s max")
        self.mode_combo.addItem("Velocity: 0.50 m/s resolution, 63.50m/s max")
        self.mode_combo.addItem("Velocity: 1.00 m/s resolution, 127.00m/s max")
        self.mode_combo.currentIndexChanged.connect(self.mode_changed)
        self.mode_combo.hide()

        self.label_average_distance = QLabel('Moving Average for Distance:')

        self.spin_average_distance = QSpinBox()
        self.spin_average_distance.setMinimum(0)
        self.spin_average_distance.setMaximum(50)
        self.spin_average_distance.setSingleStep(1)
        self.spin_average_distance.setValue(10)
        self.spin_average_distance.editingFinished.connect(
            self.spin_average_finished)

        self.label_average_velocity = QLabel('Moving Average for Velocity:')

        self.spin_average_velocity = QSpinBox()
        self.spin_average_velocity.setMinimum(0)
        self.spin_average_velocity.setMaximum(50)
        self.spin_average_velocity.setSingleStep(1)
        self.spin_average_velocity.setValue(10)
        self.spin_average_velocity.editingFinished.connect(
            self.spin_average_finished)

        self.enable_laser = QCheckBox("Enable Laser")
        self.enable_laser.stateChanged.connect(self.enable_laser_changed)

        self.label_acquisition_count = QLabel('Acquisition Count:')
        self.spin_acquisition_count = QSpinBox()
        self.spin_acquisition_count.setMinimum(1)
        self.spin_acquisition_count.setMaximum(255)
        self.spin_acquisition_count.setSingleStep(1)
        self.spin_acquisition_count.setValue(128)

        self.enable_qick_termination = QCheckBox("Quick Termination")

        self.label_threshold = QLabel('Threshold:')
        self.threshold = QCheckBox("Automatic Threshold")

        self.spin_threshold = QSpinBox()
        self.spin_threshold.setMinimum(1)
        self.spin_threshold.setMaximum(255)
        self.spin_threshold.setSingleStep(1)
        self.spin_threshold.setValue(1)

        self.label_frequency = QLabel('Frequency [Hz]:')
        self.frequency = QCheckBox(
            "Automatic Frequency (Disable for Velocity)")

        self.spin_frequency = QSpinBox()
        self.spin_frequency.setMinimum(10)
        self.spin_frequency.setMaximum(500)
        self.spin_frequency.setSingleStep(1)
        self.spin_frequency.setValue(10)

        self.spin_acquisition_count.editingFinished.connect(
            self.configuration_changed)
        self.enable_qick_termination.stateChanged.connect(
            self.configuration_changed)
        self.spin_threshold.editingFinished.connect(self.configuration_changed)
        self.threshold.stateChanged.connect(self.configuration_changed)
        self.spin_frequency.editingFinished.connect(self.configuration_changed)
        self.frequency.stateChanged.connect(self.configuration_changed)

        layout_h1 = QHBoxLayout()
        layout_h1.addWidget(self.plot_widget_distance)
        layout_h1.addWidget(self.plot_widget_velocity)

        layout_h2 = QHBoxLayout()
        layout_h2.addWidget(self.mode_label)
        layout_h2.addWidget(self.mode_combo)
        layout_h2.addWidget(self.label_average_distance)
        layout_h2.addWidget(self.spin_average_distance)
        layout_h2.addWidget(self.label_average_velocity)
        layout_h2.addWidget(self.spin_average_velocity)
        layout_h2.addStretch()
        layout_h2.addWidget(self.enable_laser)

        layout_h3 = QHBoxLayout()
        layout_h3.addWidget(self.label_frequency)
        layout_h3.addWidget(self.spin_frequency)
        layout_h3.addWidget(self.frequency)
        layout_h3.addStretch()
        layout_h3.addWidget(self.enable_qick_termination)

        layout_h4 = QHBoxLayout()
        layout_h4.addWidget(self.label_threshold)
        layout_h4.addWidget(self.spin_threshold)
        layout_h4.addWidget(self.threshold)
        layout_h4.addStretch()
        layout_h4.addWidget(self.label_acquisition_count)
        layout_h4.addWidget(self.spin_acquisition_count)

        self.widgets_distance = [
            self.plot_widget_distance, self.spin_average_distance,
            self.label_average_distance
        ]
        self.widgets_velocity = [
            self.plot_widget_velocity, self.spin_average_velocity,
            self.label_average_velocity
        ]

        for w in self.widgets_distance:
            w.hide()
        for w in self.widgets_velocity:
            w.hide()

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

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h1)
        layout.addWidget(line)
        layout.addLayout(layout_h2)
        layout.addLayout(layout_h3)
        layout.addLayout(layout_h4)

        self.has_sensor_hardware_version_api = self.firmware_version >= (2, 0,
                                                                         3)
        self.has_configuration_api = self.firmware_version >= (2, 0, 3)

    def start(self):
        if self.has_sensor_hardware_version_api:
            async_call(self.lrf.get_sensor_hardware_version, None,
                       self.get_sensor_hardware_version_async,
                       self.increase_error_count)
        else:
            self.get_sensor_hardware_version_async(1)

        if self.has_configuration_api:
            async_call(self.lrf.get_configuration, None,
                       self.get_configuration_async, self.increase_error_count)

        async_call(self.lrf.get_mode, None, self.get_mode_async,
                   self.increase_error_count)
        async_call(self.lrf.is_laser_enabled, None,
                   self.is_laser_enabled_async, self.increase_error_count)
        async_call(self.lrf.get_moving_average, None,
                   self.get_moving_average_async, self.increase_error_count)
        async_call(self.lrf.get_distance, None, self.cb_distance,
                   self.increase_error_count)
        async_call(self.lrf.get_velocity, None, self.cb_velocity,
                   self.increase_error_count)
        self.cbe_distance.set_period(25)
        self.cbe_velocity.set_period(25)

        self.plot_widget_distance.stop = False
        self.plot_widget_velocity.stop = False

    def stop(self):
        self.cbe_distance.set_period(0)
        self.cbe_velocity.set_period(0)

        self.plot_widget_distance.stop = True
        self.plot_widget_velocity.stop = True

    def destroy(self):
        pass

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

    def is_laser_enabled_async(self, enabled):
        if enabled:
            self.enable_laser.setChecked(True)
        else:
            self.enable_laser.setChecked(False)

    def enable_laser_changed(self, state):
        if state == Qt.Checked:
            self.lrf.enable_laser()
        else:
            self.lrf.disable_laser()

    def mode_changed(self, value):
        if value < 0 or value > 4:
            return

        self.lrf.set_mode(value)
        if value == 0:
            for w in self.widgets_velocity:
                w.hide()
            for w in self.widgets_distance:
                w.show()
        else:
            for w in self.widgets_distance:
                w.hide()
            for w in self.widgets_velocity:
                w.show()

    def cb_distance(self, distance):
        self.current_distance = distance

    def cb_velocity(self, velocity):
        self.current_velocity = velocity / 100.0

    def configuration_changed(self):
        acquisition_count = self.spin_acquisition_count.value()
        enable_quick_termination = self.enable_qick_termination.isChecked()

        if self.threshold.isChecked():
            threshold = 0
        else:
            threshold = self.spin_threshold.value()

        if self.frequency.isChecked():
            frequency = 0
            for w in self.widgets_velocity:
                w.hide()
        else:
            frequency = self.spin_frequency.value()
            for w in self.widgets_velocity:
                w.show()

        self.spin_threshold.setDisabled(threshold == 0)
        self.spin_frequency.setDisabled(frequency == 0)

        self.lrf.set_configuration(acquisition_count, enable_quick_termination,
                                   threshold, frequency)

    def get_configuration_async(self, conf):
        self.spin_acquisition_count.blockSignals(True)
        self.spin_acquisition_count.setValue(conf.acquisition_count)
        self.spin_acquisition_count.blockSignals(False)

        self.enable_qick_termination.blockSignals(True)
        self.enable_qick_termination.setChecked(conf.enable_quick_termination)
        self.enable_qick_termination.blockSignals(False)

        self.spin_threshold.blockSignals(True)
        self.spin_threshold.setValue(conf.threshold_value)
        self.spin_threshold.setDisabled(conf.threshold_value == 0)
        self.spin_threshold.blockSignals(False)

        self.spin_frequency.blockSignals(True)
        self.spin_frequency.setValue(conf.measurement_frequency)
        self.spin_frequency.setDisabled(conf.measurement_frequency == 0)
        self.spin_frequency.blockSignals(False)

        self.threshold.blockSignals(True)
        self.threshold.setChecked(conf.threshold_value == 0)
        self.threshold.blockSignals(False)

        self.frequency.blockSignals(True)
        self.frequency.setChecked(conf.measurement_frequency == 0)
        self.frequency.blockSignals(False)

        self.configuration_changed()

    def get_sensor_hardware_version_async(self, value):
        if value == 1:
            self.mode_combo.show()
            self.mode_label.show()
            self.label_acquisition_count.hide()
            self.spin_acquisition_count.hide()
            self.enable_qick_termination.hide()
            self.label_threshold.hide()
            self.spin_threshold.hide()
            self.threshold.hide()
            self.label_frequency.hide()
            self.spin_frequency.hide()
            self.frequency.hide()
        else:
            self.mode_combo.hide()
            self.mode_label.hide()
            self.label_acquisition_count.show()
            self.spin_acquisition_count.show()
            self.enable_qick_termination.show()
            self.label_threshold.show()
            self.spin_threshold.show()
            self.threshold.show()
            self.label_frequency.show()
            self.spin_frequency.show()
            self.frequency.show()

            for w in self.widgets_distance:
                w.show()
            for w in self.widgets_velocity:
                w.show()

    def get_mode_async(self, value):
        self.mode_combo.setCurrentIndex(value)
        self.mode_changed(value)

    def get_moving_average_async(self, avg):
        self.spin_average_distance.setValue(avg.distance_average_length)
        self.spin_average_velocity.setValue(avg.velocity_average_length)

    def spin_average_finished(self):
        self.lrf.set_moving_average(self.spin_average_distance.value(),
                                    self.spin_average_velocity.value())
コード例 #56
0
class CNSViewerWidget(QWidget):
    def __init__(self, path_to_df=None, df=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        #Apply QThreading to this step for larger cns files.
        if df is None:
            self.df = read_cns(path_to_df)
        else:
            self.df = df
        self.orig_df = self.df.copy()  #Make copy.
        # self.df.reset_index(inplace=True)
        self.max_rows = 10
        self.render_ui()
        self.map_events()
        self.refresh()
        self.jupyter_notebook_widget.pushVariables({
            "df": self.df,
            "orig_df": self.orig_df,
            "viewer": self.df_widget,
            "refresh": self.refresh,
            "display": self.display
        })

    def display(self, obj):
        try:
            html = obj._repr_html_()
        except:
            html = str(obj)
        self.df_widget.setHtml(html)

    def render_ui(self):
        """Builds the UI"""
        self.tab_widget = QTabWidget()

        #Filter Ops tab
        self.filter_ops_widget = CNSFilterOpsWidget(columns=self.df.columns)
        commands_widget = QWidget()
        self.command_label = QLabel("Command:")
        self.command_text_area = LNTextEdit()
        self.command_text_area.edit.setReadOnly(True)
        self.command_show_button = QPushButton("Apply")
        self.command_editable_checkbox = QCheckBox("Editable")
        self.command_editable_checkbox.setChecked(False)
        commands_widget_layout = QGridLayout()
        commands_widget_layout.addWidget(self.filter_ops_widget, 0, 0, 2, 2,
                                         Qt.AlignTop)
        commands_widget_layout.addWidget(self.command_label, 2, 0, 1, 1,
                                         Qt.AlignLeft | Qt.AlignTop)
        commands_widget_layout.addWidget(self.command_text_area, 3, 0, 2, 2,
                                         Qt.AlignTop)
        commands_widget_layout.addWidget(self.command_editable_checkbox, 5, 0,
                                         1, 0, Qt.AlignLeft)
        commands_widget_layout.addWidget(self.command_show_button, 5, 1, 1, 1,
                                         Qt.AlignRight)
        commands_widget.setLayout(commands_widget_layout)

        # self.tab_widget.addTab(self.filter_ops_widget, "n00b Mode")

        #Commands Tab
        self.tab_widget.addTab(commands_widget, "Raw Commands")

        ipython_filter_widget = QWidget()
        self.jupyter_notebook_widget = QIPythonWidget()
        ipython_filter_widget_layout = QVBoxLayout()
        ipython_filter_widget_layout.addWidget(self.jupyter_notebook_widget)
        ipython_filter_widget.setLayout(ipython_filter_widget_layout)
        self.tab_widget.addTab(ipython_filter_widget, "Jupyter Mode")

        self.view_combobox = QComboBox()
        modes = ["Show First", "Show Last", "All", "Describe", "Filtered"]
        for mode in modes:
            self.view_combobox.addItem(mode)

        self.max_rows_spinbox = QSpinBox()
        #Map the change event to refresh the dataframe.
        self.max_rows_spinbox.setMinimum(0)
        self.max_rows_spinbox.setMaximum(self.df.shape[0])
        self.max_rows_spinbox.setValue(self.max_rows)
        self.max_rows_spinbox.setSuffix(" rows")

        self.refresh_button = QPushButton("Refresh")

        self.df_widget = QTextEdit()
        self.df_widget.setReadOnly(True)

        self.save_button = QPushButton("Save File")

        df_layout = QGridLayout()
        df_layout.addWidget(self.view_combobox, 0, 0)
        df_layout.addWidget(self.max_rows_spinbox, 0, 1)
        df_layout.addWidget(self.refresh_button, 0, 2)
        df_layout.addWidget(self.df_widget, 1, 0, 4, 10)

        layout = QGridLayout()
        layout.addWidget(self.tab_widget, 0, 0, 3, 1,
                         Qt.AlignLeft | Qt.AlignTop)
        layout.addLayout(df_layout, 0, 1, 7, 7)
        layout.addWidget(self.save_button, 3, 0, 1, 1, Qt.AlignLeft)
        self.setLayout(layout)

    def map_events(self):
        self.refresh_button.clicked.connect(self.refresh)
        self.view_combobox.currentIndexChanged.connect(self.toggle_max_rows)
        self.command_show_button.clicked.connect(self.exec_command)
        self.filter_ops_widget.add_signal.connect(self.add_filter_op)
        self.command_editable_checkbox.stateChanged.connect(
            self.toggle_command_area)

    def toggle_command_area(self):
        self.command_text_area.edit.setReadOnly(not (
            self.command_editable_checkbox.isChecked()))

    def add_filter_op(self):
        command = self.filter_ops_widget.get_command_string()
        existing_commands = str(
            self.command_text_area.edit.toPlainText()).strip()
        if existing_commands != "":
            command = "\n{}".format(command)
        self.command_text_area.edit.appendPlainText(command)
        self.filter_ops_widget.reset()

    def exec_command(self):
        #Reset df to original.
        self.df = self.orig_df.copy()
        command = str(self.command_text_area.getText())
        try:
            exec(command)
        except Exception as e:
            print("Failed to execute!")
            print(repr(e))
        self.view_combobox.setCurrentIndex(4)
        self.refresh()

    def toggle_max_rows(self):
        mode = str(self.view_combobox.currentText()).lower()
        if mode in ["show first", "show last"]:
            self.max_rows_spinbox.setEnabled(True)
        else:
            self.max_rows_spinbox.setEnabled(False)

    def refresh(self):
        mode = str(self.view_combobox.currentText()).lower()
        if mode == "show first":
            self.max_rows = self.max_rows_spinbox.value()
            self.df_widget.setHtml(self.df.head(n=self.max_rows)._repr_html_())
        elif mode == "show last":
            self.max_rows = self.max_rows_spinbox.value()
            self.df_widget.setHtml(self.df.tail(n=self.max_rows)._repr_html_())
        elif mode == "describe":
            self.df_widget.setHtml(self.df.describe()._repr_html_())
        elif mode == "filtered":
            self.df_widget.setHtml(self.df._repr_html_())
        else:
            self.df_widget.setHtml(self.df._repr_html_())
コード例 #57
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()
コード例 #58
0
ファイル: widget.py プロジェクト: yiqideren/freeseer
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
コード例 #59
0
ファイル: screenshot.py プロジェクト: TaceyWong/pyqt4_learn
class ScreenShot(QWidget):
    def __init__(self):
        super(ScreenShot, self).__init__()

        self.initUI()

    def initUI(self):
        self.originalPixmap = QPixmap()

        self.screenshotLabel = QLabel("screenshotlabel", self)
        self.screenshotLabel.setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Expanding)
        self.screenshotLabel.setAlignment(Qt.AlignCenter)

        self.screenGeometry = QApplication.desktop().screenGeometry(
        )  # Qrect()
        print self.screenGeometry, self.screenGeometry.width()
        self.screenshotLabel.setMinimumSize(self.screenGeometry.width() / 8,
                                            self.screenGeometry.height() / 8)

        mainlayout = QVBoxLayout(self)
        mainlayout.addWidget(self.screenshotLabel)

        self.optionsGroupBox = QGroupBox(u"选项", self)

        self.hideThisWindowCheckBox = QCheckBox(u"隐藏这个窗口",
                                                self.optionsGroupBox)
        self.optionsGroupBoxLayout = QGridLayout(self.optionsGroupBox)

        mainlayout.addWidget(self.optionsGroupBox)
        self.delaySpinBox = QSpinBox(self.optionsGroupBox)
        self.delaySpinBox.setSuffix(u"s")
        self.delaySpinBox.setMaximum(60)

        self.optionsGroupBoxLayout.addWidget(QLabel(u"截屏延时:", self), 0, 0)
        self.optionsGroupBoxLayout.addWidget(self.delaySpinBox, 0, 1)
        self.optionsGroupBoxLayout.addWidget(self.hideThisWindowCheckBox, 1, 0)

        buttonLayout = QHBoxLayout()

        self.newScreenshotButton = QPushButton(u"新截图", self)
        self.newScreenshotButton.clicked.connect(self.__newScreenshot)
        buttonLayout.addWidget(self.newScreenshotButton)

        saveScreenshotButton = QPushButton(u"保存截图", self)
        buttonLayout.addWidget(saveScreenshotButton)

        quitScreenshotButton = QPushButton(u"退出截图", self)
        quitScreenshotButton.setShortcut("Ctrl+Q")
        buttonLayout.addWidget(saveScreenshotButton)
        buttonLayout.addStretch()
        mainlayout.addLayout(buttonLayout)
        quitScreenshotButton.clicked.connect(self.close)

        saveScreenshotButton.clicked.connect(self.__saveScreenshot)
        self.delaySpinBox.valueChanged.connect(self.__updateCheckBox)
        self.delaySpinBox.setValue(5)
        self.setWindowTitle(u"截图")
        self.resize(300, 200)

    def resizeEvent(self, QResizeEvent):
        scaledSize = self.originalPixmap.size()
        scaledSize.scale(self.screenshotLabel.size(), Qt.KeepAspectRatio)
        if (not self.screenshotLabel.pixmap()) or (
                scaledSize != self.screenshotLabel.pixmap().size()):
            self.__updateScreenshotLabel()

    def __newScreenshot(self):
        if self.hideThisWindowCheckBox.isChecked():
            self.hide()

        self.newScreenshotButton.setDisabled(True)

        QTimer.singleShot(self.delaySpinBox.value() * 1000, self.__shootScreen)

    def __saveScreenshot(self):
        format = "png"
        initialPath = QDesktopServices.storageLocation(
            QDesktopServices.PicturesLocation)
        # initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
        if initialPath.isEmpty():
            initialPath = QDir.currentPath()
        initialPath += "/untitled." + format

        fileDialog = QtGui.QFileDialog(self, u"存储为", initialPath)
        fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        fileDialog.setFileMode(QtGui.QFileDialog.AnyFile)
        fileDialog.setDirectory(initialPath)
        mimeTypes = QStringList()

        for bf in QImageWriter.supportedImageFormats():
            mimeTypes.append(QLatin1String(bf))

        # fileDialog.setMin setMimeTypeFilters(mimeTypes)
        # fileDialog.selectMimeTypeFilter("image/" + format);
        fileDialog.setDefaultSuffix(format)
        if fileDialog.accept():
            return

        fileName = fileDialog.selectedFiles().first()

        if not self.originalPixmap.save(fileName):
            QtGui.QMessageBox.Warning(
                self, u"保存错误",
                u"图像无法存储到 \"%s\"." % str(QDir.toNativeSeparators(fileName)))

    def __shootScreen(self):

        if self.delaySpinBox.value() != 0:
            QApplication.beep()

        self.originalPixmap = QPixmap.grabWindow(
            QApplication.desktop().winId())
        self.__updateScreenshotLabel()

        self.newScreenshotButton.setDisabled(False)
        if self.hideThisWindowCheckBox.isChecked():
            self.show()

    def __updateCheckBox(self):
        print "sssss"
        if self.delaySpinBox.value() == 0:
            self.hideThisWindowCheckBox.setDisabled(True)
            self.hideThisWindowCheckBox.setChecked(False)
        else:
            self.hideThisWindowCheckBox.setDisabled(False)

    def __updateScreenshotLabel(self):
        self.screenshotLabel.setPixmap(
            self.originalPixmap.scaled(self.screenshotLabel.size(),
                                       Qt.KeepAspectRatio,
                                       Qt.SmoothTransformation))
コード例 #60
0
class TaskGeneratorDialog(QDialog):
    def __init__(self, nbprocessors):
        QDialog.__init__(self)
        self.layout = QVBoxLayout(self)
        self.taskset = None

        # Utilizations:
        vbox_utilizations = QVBoxLayout()
        group = QGroupBox("Task Utilizations:")

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Generator:", self))
        self.comboGenerator = QComboBox()
        self.comboGenerator.addItem("RandFixedSum")
        self.comboGenerator.addItem("UUniFast-Discard")
        self.comboGenerator.addItem("Kato's method")
        self.comboGenerator.currentIndexChanged.connect(self.generator_changed)
        hbox.addWidget(self.comboGenerator)
        vbox_utilizations.addLayout(hbox)

        # Load slider + spinner:
        hbox_load = QHBoxLayout()
        sld = _DoubleSlider(QtCore.Qt.Horizontal, self)
        sld.setMinimum(0)
        sld.setMaximum(32)
        self.spin_load = QDoubleSpinBox(self)
        self.spin_load.setMinimum(0)
        self.spin_load.setMaximum(32)
        self.spin_load.setSingleStep(0.1)
        hbox_load.addWidget(QLabel("Total utilization: ", self))
        hbox_load.addWidget(sld)
        hbox_load.addWidget(self.spin_load)
        sld.doubleValueChanged.connect(self.spin_load.setValue)
        self.spin_load.valueChanged.connect(sld.setValue)
        self.spin_load.setValue(nbprocessors / 2.)
        vbox_utilizations.addLayout(hbox_load)

        # Number of periodic tasks:
        self.hbox_tasks = QHBoxLayout()
        self.spin_tasks = QSpinBox(self)
        self.spin_tasks.setMinimum(0)
        self.spin_tasks.setMaximum(999)  # That's arbitrary.
        self.hbox_tasks.addWidget(QLabel("Number of periodic tasks: ", self))
        self.hbox_tasks.addStretch(1)
        self.hbox_tasks.addWidget(self.spin_tasks)
        vbox_utilizations.addLayout(self.hbox_tasks)

        # Number of sporadic tasks:
        self.hbox_sporadic_tasks = QHBoxLayout()
        self.spin_sporadic_tasks = QSpinBox(self)
        self.spin_sporadic_tasks.setMinimum(0)
        self.spin_sporadic_tasks.setMaximum(999)  # That's arbitrary.
        self.hbox_sporadic_tasks.addWidget(
            QLabel("Number of sporadic tasks: ", self))
        self.hbox_sporadic_tasks.addStretch(1)
        self.hbox_sporadic_tasks.addWidget(self.spin_sporadic_tasks)
        vbox_utilizations.addLayout(self.hbox_sporadic_tasks)

        # Min / Max utilizations
        self.hbox_utilizations = QHBoxLayout()
        self.hbox_utilizations.addWidget(QLabel("Min/Max utilizations: ",
                                                self))
        self.interval_utilization = IntervalSpinner(self,
                                                    min_=0,
                                                    max_=1,
                                                    step=.01,
                                                    round_option=False)
        self.hbox_utilizations.addWidget(self.interval_utilization)
        vbox_utilizations.addLayout(self.hbox_utilizations)

        group.setLayout(vbox_utilizations)
        self.layout.addWidget(group)

        # Periods:
        vbox_periods = QVBoxLayout()
        group = QGroupBox("Task Periods:")

        # Log uniform
        self.lunif = QRadioButton("log-uniform distribution between:")
        vbox_periods.addWidget(self.lunif)
        self.lunif.setChecked(True)

        self.lunif_interval = IntervalSpinner(self)
        self.lunif_interval.setEnabled(self.lunif.isChecked())
        self.lunif.toggled.connect(self.lunif_interval.setEnabled)
        vbox_periods.addWidget(self.lunif_interval)

        # Uniform
        self.unif = QRadioButton("uniform distribution between:")
        vbox_periods.addWidget(self.unif)

        self.unif_interval = IntervalSpinner(self)
        self.unif_interval.setEnabled(self.unif.isChecked())
        self.unif.toggled.connect(self.unif_interval.setEnabled)
        vbox_periods.addWidget(self.unif_interval)

        # Discrete
        discrete = QRadioButton("chosen among these (space separated) values:")
        vbox_periods.addWidget(discrete)

        self.periods = QLineEdit(self)
        self.periods.setValidator(
            QRegExpValidator(QRegExp("^\\d*(\.\\d*)?( \\d*(\.\\d*)?)*$")))

        vbox_periods.addWidget(self.periods)
        self.periods.setEnabled(discrete.isChecked())
        discrete.toggled.connect(self.periods.setEnabled)
        vbox_periods.addStretch(1)

        group.setLayout(vbox_periods)
        self.layout.addWidget(group)

        buttonBox = QDialogButtonBox()
        cancel = buttonBox.addButton(QDialogButtonBox.Cancel)
        generate = buttonBox.addButton("Generate", QDialogButtonBox.AcceptRole)
        cancel.clicked.connect(self.reject)
        generate.clicked.connect(self.generate)
        self.layout.addWidget(buttonBox)

        self.show_randfixedsum_options()

    def generator_changed(self, value):
        if value == 2:
            self.show_kato_options()
        else:
            self.show_randfixedsum_options()

    def show_randfixedsum_options(self):
        for i in range(self.hbox_utilizations.count()):
            self.hbox_utilizations.itemAt(i).widget().hide()
        for i in range(self.hbox_tasks.count()):
            if self.hbox_tasks.itemAt(i).widget():
                self.hbox_tasks.itemAt(i).widget().show()
        for i in range(self.hbox_sporadic_tasks.count()):
            if self.hbox_sporadic_tasks.itemAt(i).widget():
                self.hbox_sporadic_tasks.itemAt(i).widget().show()

    def show_kato_options(self):
        for i in range(self.hbox_utilizations.count()):
            if self.hbox_utilizations.itemAt(i).widget():
                self.hbox_utilizations.itemAt(i).widget().show()
        for i in range(self.hbox_tasks.count()):
            if self.hbox_tasks.itemAt(i).widget():
                self.hbox_tasks.itemAt(i).widget().hide()
        for i in range(self.hbox_sporadic_tasks.count()):
            if self.hbox_sporadic_tasks.itemAt(i).widget():
                self.hbox_sporadic_tasks.itemAt(i).widget().hide()

    def get_min_utilization(self):
        return self.interval_utilization.getMin()

    def get_max_utilization(self):
        return self.interval_utilization.getMax()

    def generate(self):
        if self.comboGenerator.currentIndex() == 0:
            n = self.get_nb_tasks()
            u = StaffordRandFixedSum(n, self.get_utilization(), 1)
        elif self.comboGenerator.currentIndex() == 1:
            n = self.get_nb_tasks()
            u = UUniFastDiscard(n, self.get_utilization(), 1)
        else:
            u = gen_kato_utilizations(1, self.get_min_utilization(),
                                      self.get_max_utilization(),
                                      self.get_utilization())
            n = len(u[0])

        p_types = self.get_periods()
        if p_types[0] == "unif":
            p = gen_periods_uniform(n, 1, p_types[1], p_types[2], p_types[3])
        elif p_types[0] == "lunif":
            p = gen_periods_loguniform(n, 1, p_types[1], p_types[2],
                                       p_types[3])
        else:
            p = gen_periods_discrete(n, 1, p_types[1])
        if u and p:
            self.taskset = gen_tasksets(u, p)[0]
            self.accept()
        elif not u:
            QMessageBox.warning(
                self, "Generation failed",
                "Please check the utilization and the number of tasks.")
        else:
            QMessageBox.warning(self, "Generation failed",
                                "Pleache check the periods.")

    def get_nb_tasks(self):
        return self.spin_tasks.value() + self.spin_sporadic_tasks.value()

    def get_nb_periodic_tasks(self):
        return self.spin_tasks.value()

    def get_nb_sporadic_tasks(self):
        return self.spin_sporadic_tasks.value()

    def get_utilization(self):
        return self.spin_load.value()

    def get_periods(self):
        if self.unif.isChecked():
            return ("unif", self.unif_interval.getMin(),
                    self.unif_interval.getMax(), self.unif_interval.getRound())
        elif self.lunif.isChecked():
            return ("lunif", self.lunif_interval.getMin(),
                    self.lunif_interval.getMax(),
                    self.lunif_interval.getRound())
        else:
            return ("discrete", map(float, str(self.periods.text()).split()))