Пример #1
1
 def createEditor( self, parent, option, index ):
     if index.column() == CANTIDAD:
         spinbox = QSpinBox( parent )
         spinbox.setRange( 0, index.model().lines[index.row()].maxquantity )
         spinbox.setSingleStep( 1 )
         return spinbox
     else:
         QStyledItemDelegate.createEditor( self, parent, option, index )
Пример #2
0
class MikidownCfgDialog(QDialog):
    def __init__(self, parent=None):
        super(MikidownCfgDialog, self).__init__(parent)
        #tab = QWidget()
        #tab2 = QWidget()
        self.recentNotesCount = QSpinBox()
        recent_notes_n = Mikibook.settings.value('recentNotesNumber',type=int, defaultValue=20)
        self.recentNotesCount.setValue(recent_notes_n)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        self.hltCfg = MikidownHighlightCfgWidget(parent=self)

        layout = QGridLayout(self)
        layout.addWidget(QLabel("# of recently viewed notes to keep"),0,0,1,1)
        layout.addWidget(self.recentNotesCount,0,1,1,1)
        qs = QScrollArea(self)
        qs.setWidget(self.hltCfg)
        layout.addWidget(qs,1,0,1,2)
        layout.addWidget(self.buttonBox,2,0,1,2)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def accept(self):
        Mikibook.settings.setValue('recentNotesNumber', self.recentNotesCount.value())
        Mikibook.setHighlighterColors(self.hltCfg.configToList())

        #then make mikidown use these settings NOW
        self.parent().loadHighlighter()
        QDialog.accept(self)
Пример #3
0
class ProjectData(QWidget):

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

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

        grid.addWidget(QLabel(self.tr("Indentation: ")), 6, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent._item.indentation)
        self.spinIndentation.setMinimum(1)
        grid.addWidget(self.spinIndentation, 6, 1)
        self.checkUseTabs = QCheckBox(self.tr("Use Tabs."))
        self.checkUseTabs.setChecked(self._parent._item.useTabs)
        grid.addWidget(self.checkUseTabs, 6, 2)
Пример #4
0
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)

        self.setRange(0, 255)
        self.setValue(default_value)
Пример #5
0
    def createEditor(self, parent, option, index):
        if index.column() == CANTIDAD:
            spinbox = QSpinBox(parent)
            spinbox.setRange(0, 1000)
            spinbox.setSingleStep(1)
            return spinbox
        elif index.column() == DENOMINACION:

            model = index.model()

            self.proxymodel.setSourceModel(self.denominationsmodel)

            current = model.index(index.row(), IDDENOMINACION).data().toInt()[0]
            self.proxymodel.setFilterRegExp(self.filter(model, current))

            sp = super(ArqueoDelegate, self).createEditor(parent, option, index)

            sp.setColumnHidden(0)
            sp.setColumnHidden(2)
            sp.setColumnHidden(3)

            return sp

        else:
            return super(ArqueoDelegate, self).createEditor(parent, option, index)
Пример #6
0
class ConfigWidget(QWidget):

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

        layout = QFormLayout()
        self.setLayout(layout)

        self.label_ip = QLabel("IP")
        self.lineedit_ip = QLineEdit()
        layout.addRow(self.label_ip, self.lineedit_ip)

        self.label_port = QLabel("Port")
        self.spinbox_port = QSpinBox()
        self.spinbox_port.setMinimum(0)
        self.spinbox_port.setMaximum(65535)
        layout.addRow(self.label_port, self.spinbox_port)

        self.label_password = QLabel("Password")
        self.lineedit_password = QLineEdit()
        layout.addRow(self.label_password, self.lineedit_password)

        self.label_mount = QLabel("Mount")
        self.lineedit_mount = QLineEdit()
        layout.addRow(self.label_mount, self.lineedit_mount)
Пример #7
0
class DataConfigurationWidget(ConfigurationWidget):
    def __init__(self):
        ConfigurationWidget.__init__(self)

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

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

        self.setIndexBounds(0)

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

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

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

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

    def applyConfiguration(self, emit=True):
        user_data = {"state": self.getState(), "data_index": self.getIndex()}
        self.parameter.setUserData(user_data)
        self.emitConfigurationChanged(emit)
Пример #8
0
    def __init__(self, width, height, parent=None):
        super(ResizeDlg, self).__init__(parent)

        widthLabel = QLabel("&Width:")
        self.widthSpinBox = QSpinBox()
        widthLabel.setBuddy(self.widthSpinBox)
        self.widthSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
        self.widthSpinBox.setRange(4, width * 4)
        self.widthSpinBox.setValue(width)
        heightLabel = QLabel("&Height:")
        self.heightSpinBox = QSpinBox()
        heightLabel.setBuddy(self.heightSpinBox)
        self.heightSpinBox.setAlignment(Qt.AlignRight|
                                        Qt.AlignVCenter)
        self.heightSpinBox.setRange(4, height * 4)
        self.heightSpinBox.setValue(height)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                     QDialogButtonBox.Cancel)

        layout = QGridLayout()
        layout.addWidget(widthLabel, 0, 0)
        layout.addWidget(self.widthSpinBox, 0, 1)
        layout.addWidget(heightLabel, 1, 0)
        layout.addWidget(self.heightSpinBox, 1, 1)
        layout.addWidget(buttonBox, 2, 0, 1, 2)
        self.setLayout(layout)

        self.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(buttonBox, SIGNAL("rejected()"), self.reject)

        self.setWindowTitle("Image Changer - Resize")
	def __init__(self, leftFlow = 0, rightFlow = 0, maxFlow = 100, parent = None):
		super(YPipeWidget, self).__init__(parent)

		self.leftSpinBox = QSpinBox(self)
		self.leftSpinBox.setRange(0, maxFlow)
		self.leftSpinBox.setValue(leftFlow)
		self.leftSpinBox.setSuffix(" l/s")
		self.leftSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
		self.connect(self.leftSpinBox, SIGNAL("valueChanged(int)"), self.valueChanged)

		self.rightSpinBox = QSpinBox(self)
		self.rightSpinBox.setRange(0, maxFlow)
		self.rightSpinBox.setValue(rightFlow)
		self.rightSpinBox.setSuffix(" l/s")
		self.rightSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
		self.connect(self.rightSpinBox, SIGNAL("valueChanged(int)"), self.valueChanged)

		self.label = QLabel(self)
		self.label.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
		self.label.setAlignment(Qt.AlignCenter)
		fm = QFontMetricsF(self.font())
		self.label.setMinimumWidth(fm.width(" 999 l/s "))

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

		self.setMinimumSize(self.minimumSizeHint())
		self.valueChanged()
Пример #10
0
 def __init__(self, page):
     super(Indenting, self).__init__(page)
     
     layout = QGridLayout(spacing=1)
     self.setLayout(layout)
     
     self.tabwidthBox = QSpinBox(minimum=1, maximum=99)
     self.tabwidthLabel = l = QLabel()
     l.setBuddy(self.tabwidthBox)
     
     self.nspacesBox = QSpinBox(minimum=0, maximum=99)
     self.nspacesLabel = l = QLabel()
     l.setBuddy(self.nspacesBox)
     
     self.dspacesBox = QSpinBox(minimum=0, maximum=99)
     self.dspacesLabel = l = QLabel()
     l.setBuddy(self.dspacesBox)
     
     layout.addWidget(self.tabwidthLabel, 0, 0)
     layout.addWidget(self.tabwidthBox, 0, 1)
     layout.addWidget(self.nspacesLabel, 1, 0)
     layout.addWidget(self.nspacesBox, 1, 1)
     layout.addWidget(self.dspacesLabel, 2, 0)
     layout.addWidget(self.dspacesBox, 2, 1)
     
     self.tabwidthBox.valueChanged.connect(page.changed)
     self.nspacesBox.valueChanged.connect(page.changed)
     self.dspacesBox.valueChanged.connect(page.changed)
     self.translateUI()
Пример #11
0
class Organ(KeyboardPart):
    @staticmethod
    def title(_=__builtin__._):
        return _("Organ")
    
    @staticmethod
    def short(_=__builtin__._):
        return _("abbreviation for Organ", "Org.")
    
    midiInstrument = 'church organ'

    def createWidgets(self, layout):
        super(Organ, self).createWidgets(layout)
        grid = layout.itemAt(layout.count() - 1).layout()
        self.pedalVoices = QSpinBox(minimum=0, maximum=4, value=1)
        self.pedalVoicesLabel = QLabel()
        self.pedalVoicesLabel.setBuddy(self.pedalVoices)
        grid.addWidget(self.pedalVoicesLabel, 2, 0)
        grid.addWidget(self.pedalVoices)
        
    def translateWidgets(self):
        super(Organ, self).translateWidgets()
        self.pedalVoicesLabel.setText(_("Pedal:"))
        self.pedalVoices.setToolTip(_(
            "Set to 0 to disable the pedal altogether."))
    
    def build(self, data, builder):
        super(Organ, self).build(data, builder)
        if self.pedalVoices.value():
            data.nodes.append(self.buildStaff(data, builder,
                'pedal', -1, self.pedalVoices.value(), clef="bass"))
Пример #12
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)
Пример #13
0
    def create_widget(self):
        """ Create the underlying QSpinBox widget.

        """
        widget = QSpinBox(self.parent_widget())
        widget.setKeyboardTracking(False)
        self.widget = widget
Пример #14
0
 class Dial(QDialog):
     choices =['flat', 'hanning', 'hamming', 'bartlett', 'blackman']
     def __init__(self, parent):
         QDialog.__init__(self, parent)
         f =QFormLayout(self)
         self.a =QSpinBox(self)
         self.a.setValue(30)
         self.b = QComboBox(self)
         self.b.addItems(self.choices)
         self.c= QDialogButtonBox(self)
         self.c.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
         f.addRow("window:" ,self.a)
         f.addRow("method:", self.b)
         f.addRow("", self.c)
         self.connect(self.c, SIGNAL("accepted()"), self.sendData)
         self.connect(self.c, SIGNAL("rejected()"), self.reinitialize)
     
     def sendData(self):
         self.parent().window = self.a.value()
         self.parent().method = self.b.currentText()
         self.close()
     
     def reinitialize(self):
         self.parent().window = None
         self.parent().method = None
         self.close()
Пример #15
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):")
Пример #16
0
    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)
Пример #17
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
Пример #18
0
 def __init__(self, observed, prop, parent=None):
     QSpinBox.__init__(self, parent)
     self.getter = lambda: prop.fget(observed)
     self.setter = lambda x: prop.fset(observed, x)
     observed.register(self.update)
     self.setValue(self.getter())
     self.connect(self, SIGNAL('valueChanged(int)'), self.setter)
Пример #19
0
    def __init__(self, parent=None):
        super(MikidownCfgDialog, self).__init__(parent)
        #tab = QWidget()
        #tab2 = QWidget()
        self.setWindowTitle(self.tr("Settings - mikidown"))
        self.recentNotesCount = QSpinBox()
        recent_notes_n = Mikibook.settings.value('recentNotesNumber',type=int, defaultValue=20)
        self.recentNotesCount.setValue(recent_notes_n)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        self.hltCfg = MikidownHighlightCfgWidget(parent=self)
        self.tabWidth = QSpinBox(self)
        self.tabWidth.setRange(2, 8)
        self.tabWidth.setSingleStep(2)
        self.iconTheme = QLineEdit(self)
        self.iconTheme.setText(Mikibook.settings.value('iconTheme', QIcon.themeName()))

        self.editorFont = QFontButton(parent=self)
        fontval = QFont()
        fontfam = Mikibook.settings.value('editorFont', defaultValue=None)
        fontsize = Mikibook.settings.value('editorFontSize', type=int, defaultValue=12)
        if fontfam is not None:
            fontval.setFamily(fontfam)
        fontval.setPointSize(fontsize)

        self.headerScalesFont = QCheckBox(self)
        if Mikibook.settings.value('headerScaleFont', type=bool, defaultValue=True):
            self.headerScalesFont.setCheckState(Qt.Checked)
        else:
            self.headerScalesFont.setCheckState(Qt.Unchecked)

        self.editorFont.font = fontval

        self.tabWidth.setValue(Mikibook.settings.value('tabWidth', type=int, defaultValue=4))

        self.tabToSpaces = QCheckBox(self)
        if Mikibook.settings.value('tabInsertsSpaces', type=bool, defaultValue=True):
            self.tabToSpaces.setCheckState(Qt.Checked)
        else:
            self.tabToSpaces.setCheckState(Qt.Unchecked)

        layout = QGridLayout(self)
        layout.addWidget(QLabel(self.tr("# of recently viewed notes to keep")),0,0,1,1)
        layout.addWidget(self.recentNotesCount,0,1,1,1)
        layout.addWidget(QLabel(self.tr("Editor font")), 1, 0, 1, 1)
        layout.addWidget(self.editorFont, 1, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Header rank scales editor font?")), 2, 0, 1, 1)
        layout.addWidget(self.headerScalesFont, 2, 1, 1, 1)
        qs = QScrollArea(self)
        qs.setWidget(self.hltCfg)
        layout.addWidget(QLabel(self.tr("Tabs expand to spaces?")), 3, 0, 1, 1)
        layout.addWidget(self.tabToSpaces, 3, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Tab width")), 4, 0, 1, 1)
        layout.addWidget(self.tabWidth, 4, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Icon Theme")),5,0,1,1)
        layout.addWidget(self.iconTheme,5,1,1,1)
        layout.addWidget(qs,6,0,1,2)
        layout.addWidget(self.buttonBox,7,0,1,2)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
Пример #20
0
    def __init__(self, page):
        super(MusicView, self).__init__(page)
        
        layout = QGridLayout()
        self.setLayout(layout)

        self.magnifierSizeLabel = QLabel()
        self.magnifierSizeSlider = QSlider(Qt.Horizontal, valueChanged=self.changed)
        self.magnifierSizeSlider.setSingleStep(50)
        self.magnifierSizeSlider.setRange(*popplerview.MagnifierSettings.sizeRange)
        self.magnifierSizeSpinBox = QSpinBox()
        self.magnifierSizeSpinBox.setRange(*popplerview.MagnifierSettings.sizeRange)
        self.magnifierSizeSpinBox.valueChanged.connect(self.magnifierSizeSlider.setValue)
        self.magnifierSizeSlider.valueChanged.connect(self.magnifierSizeSpinBox.setValue)
        layout.addWidget(self.magnifierSizeLabel, 0, 0)
        layout.addWidget(self.magnifierSizeSlider, 0, 1)
        layout.addWidget(self.magnifierSizeSpinBox, 0, 2)
        
        self.magnifierScaleLabel = QLabel()
        self.magnifierScaleSlider = QSlider(Qt.Horizontal, valueChanged=self.changed)
        self.magnifierScaleSlider.setSingleStep(50)
        self.magnifierScaleSlider.setRange(*popplerview.MagnifierSettings.scaleRange)
        self.magnifierScaleSpinBox = QSpinBox()
        self.magnifierScaleSpinBox.setRange(*popplerview.MagnifierSettings.scaleRange)
        self.magnifierScaleSpinBox.valueChanged.connect(self.magnifierScaleSlider.setValue)
        self.magnifierScaleSlider.valueChanged.connect(self.magnifierScaleSpinBox.setValue)
        layout.addWidget(self.magnifierScaleLabel, 1, 0)
        layout.addWidget(self.magnifierScaleSlider, 1, 1)
        layout.addWidget(self.magnifierScaleSpinBox, 1, 2)
        
        app.translateUI(self)
Пример #21
0
class ConfigWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QFormLayout()
        self.setLayout(layout)

        self.label_ip = QLabel("IP")
        self.lineedit_ip = QLineEdit()
        layout.addRow(self.label_ip, self.lineedit_ip)

        self.label_port = QLabel("Port")
        self.spinbox_port = QSpinBox()
        self.spinbox_port.setMinimum(0)
        self.spinbox_port.setMaximum(65535)
        layout.addRow(self.label_port, self.spinbox_port)

        self.label_password = QLabel("Password")
        self.lineedit_password = QLineEdit()
        layout.addRow(self.label_password, self.lineedit_password)

        self.label_mount = QLabel("Mount")
        self.lineedit_mount = QLineEdit()
        layout.addRow(self.label_mount, self.lineedit_mount)

        #
        # Audio Quality
        #

        self.label_audio_quality = QLabel("Audio Quality")
        self.spinbox_audio_quality = QDoubleSpinBox()
        self.spinbox_audio_quality.setMinimum(0.0)
        self.spinbox_audio_quality.setMaximum(1.0)
        self.spinbox_audio_quality.setSingleStep(0.1)
        self.spinbox_audio_quality.setDecimals(1)
        self.spinbox_audio_quality.setValue(0.3)  # Default value 0.3

        #
        # Video Quality
        #

        self.label_video_quality = QLabel("Video Quality (kb/s)")
        self.spinbox_video_quality = QSpinBox()
        self.spinbox_video_quality.setMinimum(0)
        self.spinbox_video_quality.setMaximum(16777215)
        self.spinbox_video_quality.setValue(2400)  # Default value 2400

    def get_video_quality_layout(self):
        layout_video_quality = QHBoxLayout()
        layout_video_quality.addWidget(self.label_video_quality)
        layout_video_quality.addWidget(self.spinbox_video_quality)

        return layout_video_quality

    def get_audio_quality_layout(self):
        layout_audio_quality = QHBoxLayout()
        layout_audio_quality.addWidget(self.label_audio_quality)
        layout_audio_quality.addWidget(self.spinbox_audio_quality)

        return layout_audio_quality
Пример #22
0
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

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

        """
        # Size policy
        self._spin_box_size_policy = QSizePolicy(
            QSizePolicy.Fixed, QSizePolicy.Fixed)

        super(PointParameterWidget, self).__init__(parameter, parent)

        self._input_x = QSpinBox()
        self._input_x.setValue(self._parameter.value[0])
        tool_tip = 'X'
        self._input_x.setToolTip(tool_tip)
        self._input_x.setSizePolicy(self._spin_box_size_policy)

        self._input_y = QSpinBox()
        self._input_y.setValue(self._parameter.value[1])
        tool_tip = 'Y'
        self._input_y.setToolTip(tool_tip)
        self._input_y.setSizePolicy(self._spin_box_size_policy)

        self._inner_input_layout.addWidget(self._input_x)
        self._inner_input_layout.addWidget(self._input_y)
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)
Пример #24
0
    def __init__(self, low, upp, parent=None):
        QWidget.__init__(self, parent)
        self.layout = QHBoxLayout(self)
        self._spin_start = QSpinBox(self)
        self._spin_end = QSpinBox(self)
        self.layout.addWidget(self._spin_start)

        self._slider = QxtSpanSlider(self)
        self._slider.setHandleMovementMode(QxtSpanSlider.NoOverlapping)

        self._slider.lowerPositionChanged.connect(lambda x: self._spin_start.setValue(x))
        self._slider.upperPositionChanged.connect(lambda x: self._spin_end.setValue(x))
        self._spin_start.valueChanged.connect(
            lambda x: self._slider.setLowerPosition(x)
            if x < self._slider.upperValue
            else self._spin_start.setValue(self._slider.upperValue - 1))
        self._spin_end.valueChanged.connect(
            lambda x: self._slider.setUpperPosition(x)
            if x > self._slider.lowerValue
            else self._spin_end.setValue(self._slider.lowerValue + 1))

        self.layout.addWidget(self._slider)
        self.layout.addWidget(self._spin_end)

        self.setRange(low, upp)
        self.setSpan(low, upp)
Пример #25
0
 def createEditor(self, parent, option, index):
     if index.column() == NUMAJUSTE:
         spinbox = QSpinBox(parent)
         spinbox.setRange(-1000, 1000)
         spinbox.setSingleStep(1)
         return spinbox
     else:
         QStyledItemDelegate.createEditor(self, parent, option, index)
Пример #26
0
    def __init__(self, items):
        QSpinBox.__init__(self)
        self.setMinimumWidth(75)

        self.__string_converter = str
        self.__items = items

        self.setRange(0, len(items) - 1)
        self.setValue(len(items) - 1)
Пример #27
0
    def __init__(self, parent=None):
        QSpinBox.__init__(self, parent)

        self._app = QApplication.instance().window

        self.setRange(0, 0)
        self.setValue(0)
        
        self._waveViews = {}
Пример #28
0
class PianoStaffPart(Part):
    """Base class for parts creating a piano staff."""
    def createWidgets(self, layout):
        self.label = QLabel(wordWrap=True)
        self.upperVoicesLabel = QLabel()
        self.lowerVoicesLabel = QLabel()
        self.upperVoices = QSpinBox(minimum=1, maximum=4, value=1)
        self.lowerVoices = QSpinBox(minimum=1, maximum=4, value=1)
        
        self.upperVoicesLabel.setBuddy(self.upperVoices)
        self.lowerVoicesLabel.setBuddy(self.lowerVoices)
        
        layout.addWidget(self.label)
        grid = QGridLayout()
        grid.addWidget(self.upperVoicesLabel, 0, 0)
        grid.addWidget(self.upperVoices, 0, 1)
        grid.addWidget(self.lowerVoicesLabel, 1, 0)
        grid.addWidget(self.lowerVoices, 1, 1)
        layout.addLayout(grid)
    
    def translateWidgets(self):
        self.label.setText('{0} <i>({1})</i>'.format(
            _("Adjust how many separate voices you want on each staff."),
            _("This is primarily useful when you write polyphonic music "
              "like a fuge.")))
        self.upperVoicesLabel.setText(_("Right hand:"))
        self.lowerVoicesLabel.setText(_("Left hand:"))
    
    def buildStaff(self, data, builder, name, octave, numVoices=1, node=None, clef=None):
        """Build a staff with the given number of voices and name."""
        staff = ly.dom.Staff(name, parent=node)
        builder.setMidiInstrument(staff, self.midiInstrument)
        c = ly.dom.Seqr(staff)
        if clef:
            ly.dom.Clef(clef, c)
        if numVoices == 1:
            a = data.assignMusic(name, octave)
            ly.dom.Identifier(a.name, c)
        else:
            c = ly.dom.Sim(c)
            for i in range(1, numVoices):
                a = data.assignMusic(name + ly.util.int2text(i), octave)
                ly.dom.Identifier(a.name, c)
                ly.dom.VoiceSeparator(c)
            a = data.assignMusic(name + ly.util.int2text(numVoices), octave)
            ly.dom.Identifier(a.name, c)
        return staff

    def build(self, data, builder):
        """ Setup structure for a 2-staff PianoStaff. """
        p = ly.dom.PianoStaff()
        builder.setInstrumentNamesFromPart(p, self, data)
        s = ly.dom.Sim(p)
        # add two staves, with a respective number of voices.
        self.buildStaff(data, builder, 'right', 1, self.upperVoices.value(), s)
        self.buildStaff(data, builder, 'left', 0, self.lowerVoices.value(), s, "bass")
        data.nodes.append(p)
Пример #29
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)
Пример #30
0
 def __init__(self, parent, connPlugin, logger):
     super(statTimelineTab, self).__init__(parent)
     lay = QGridLayout(self)
     vw = statTimelineWidget(parent, connPlugin, logger)
     lay.addWidget(vw, 0, 0, 1, 2)
     lay.addWidget(QLabel("Scale:"), 1, 0, Qt.AlignRight)
     spinbox = QSpinBox(self)
     spinbox.setValue(vw.getScale())
     spinbox.valueChanged.connect(vw.setScale)
     lay.addWidget(spinbox, 1, 1)
Пример #31
0
    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(self.tr("Name:")), 0, 0)
        self.name = QLineEdit()
        if self._parent._item.name == '':
            self.name.setText(
                file_manager.get_basename(self._parent._item.path))
        else:
            self.name.setText(self._parent._item.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(self.tr("Project Location:")), 1, 0)
        self.txtPath = QLineEdit()
        self.txtPath.setReadOnly(True)
        self.txtPath.setText(self._parent._item.path)
        grid.addWidget(self.txtPath, 1, 1)
        grid.addWidget(QLabel(self.tr("Project Type:")), 2, 0)
        self.txtType = QLineEdit()
        completer = QCompleter(sorted(settings.PROJECT_TYPES))
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.txtType.setCompleter(completer)
        self.txtType.setText(self._parent._item.projectType)
        grid.addWidget(self.txtType, 2, 1)
        grid.addWidget(QLabel(self.tr("Description:")), 3, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent._item.description)
        grid.addWidget(self.description, 3, 1)
        grid.addWidget(QLabel(self.tr("URL:")), 4, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent._item.url)
        grid.addWidget(self.url, 4, 1)
        grid.addWidget(QLabel(self.tr("Licence:")), 5, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('Mozilla Public License 2.0')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        index = self.cboLicense.findText(self._parent._item.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 5, 1)

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

        grid.addWidget(QLabel(self.tr("Indentation: ")), 7, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent._item.indentation)
        self.spinIndentation.setMinimum(1)
        grid.addWidget(self.spinIndentation, 7, 1)
        self.checkUseTabs = QCheckBox(self.tr("Use Tabs."))
        self.checkUseTabs.setChecked(self._parent._item.useTabs)
        grid.addWidget(self.checkUseTabs, 7, 2)
Пример #32
0
class NumberBoxPanel(QWidget):
    def __init__(self, parent, resoution = "0.0000"):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("NumberBoxPanel" + str(len(parent.findChildren(NumberBoxPanel))))


        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0,0,0,0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        if resoution != None:
            self.numberBox = QLineEdit(self.frameBoxPanel)
            self.numberBox.setEnabled(True)
            font = QFont()
            font.setBold(False)
            font.setWeight(50)
            self.numberBox.setFont(font)
            self.numberBox.setObjectName(self.objectName() + "_numberBox")
            self.numberBox.setText("0.0")
            self.numberBox.setMinimumWidth(70)
            self.numberBox.setMaximumWidth(70)
            self.hLayoutframeBoxPanel.addWidget(self.numberBox)
            self.numberBox.textChanged.connect(self.numberBoxChanged)
            self.numberBox.editingFinished.connect(self.numberBoxEditingFinished)
        else:
            self.numberBox = QSpinBox(self.frameBoxPanel)
            self.numberBox.setObjectName(self.objectName() + "_numberBox")
            self.numberBox.setMinimumWidth(70)
            self.numberBox.setMaximumWidth(70)
            self.numberBox.setMinimum(-100000000)
            self.numberBox.setMaximum(100000000)
            self.numberBox.setValue(1)
            self.hLayoutframeBoxPanel.addWidget(self.numberBox)

        self.imageButton = QPushButton(self.frameBoxPanel)

        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)


        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.numberResolution = resoution
        str0 = String.Number2String(6.6788, "0.0000")
        self.Value = 0
        self.captionUnits = ""
    def imageButtonClicked(self):
        self.emit(SIGNAL("Event_1"), self)
    def method_6(self, string_0):
        return "%s%s\t%f %s"%(string_0, self.Caption, self.Value, self.CaptionUnits);
    def numberBoxEditingFinished(self):
        self.emit(SIGNAL("editingFinished"), self)
    def numberBoxChanged(self):
        try:
            test = float(self.numberBox.text())
            self.emit(SIGNAL("Event_0"), self)
        except:
            if self.numberBox.text() == "" or self.numberBox.text() == "-" or self.numberBox.text() == "+":
                return
            str0 = "You must input the float type in \"%s\"."%(self.Caption)
            QMessageBox.warning(self, "Warning" , str0)
            self.numberBox.setText("0.0")

    def get_CaptionUnits(self):
        return self.captionUnits
    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits
    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption
    def set_Caption(self, captionStr):
        if self.CaptionUnits != "" and self.CaptionUnits != None:
            self.captionLabel.setText(QString(captionStr + "(") + self.CaptionUnits + QString("):"))
        else:
            self.captionLabel.setText(captionStr + ":")
    Caption = property(get_Caption, set_Caption, None, None)

    def get_Visible(self):
        return self.isVisible()
    def set_Visible(self, bool):
        self.setVisible(bool)
    Visible = property(get_Visible, set_Visible, None, None)

    def get_Value(self):
        try:
            if self.numberResolution != None:
                return float(self.numberBox.text())
            else:
                return self.numberBox.value()
        except:
            return 0.0

    def set_Value(self, valueFloat):
        if self.numberResolution != None:
            if valueFloat == None or valueFloat == "":
                rStr = String.Number2String(0, self.numberResolution)
                self.numberBox.setText(rStr)
                return
            try:
                test = float(valueFloat)
                rStr = String.Number2String(test, self.numberResolution)
                self.numberBox.setText(rStr)
            except:
                str0 = "You must put the float type in \"%s\"."%(self.Caption)
                QMessageBox.warning(self, "Warning" , str0)
                rStr = String.Number2String(0, self.numberResolution)
                self.numberBox.setText(rStr)
        else:
            try:
                test = int(valueFloat)
                self.numberBox.setValue(test)
            except:
                str0 = "You must put the float type in \"%s\"."%(self.Caption)
                QMessageBox.warning(self, "Warning" , str0)
                self.numberBox.setValue(0)
    Value = property(get_Value, set_Value, None, None)

    # def get_IsEmpty(self):
    #     return self.numberBox.text() == "" or self.numberBox.text() == None
    # IsEmpty = property(get_IsEmpty, None, None, None)

    def get_ReadOnly(self):
        return self.numberBox.isReadOnly()
    def set_ReadOnly(self, bool):
        self.numberBox.setReadOnly(bool)
    ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))
    LabelWidth = property(None, set_LabelWidth, None, None)

    def set_Width(self, width):
        self.numberBox.setMinimumSize(QSize(width, 0))
        self.numberBox.setMaximumSize(QSize(width, 16777215))
    Width = property(None, set_Width, None, None)

    def get_Enabled(self):
        return self.isEnabled()
    def set_Enabled(self, bool):
        self.setEnabled(bool)
    Enabled = property(get_Enabled, set_Enabled, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal, QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)
    Button = property(None, set_Button, None, None)
Пример #33
0
class ProfileDockWidget(QDockWidget):
    """
    DockWidget class to display the profile
    """

    closeSignal = pyqtSignal()

    def __init__(self, iface, geometry, mntButton=False, zerosButton=False):
        """
        Constructor
        :param iface: interface
        :param width: dock widget geometry
        """
        QDockWidget.__init__(self)
        self.setWindowTitle(
            QCoreApplication.translate("VDLTools", "Profile Tool"))
        self.__iface = iface
        self.__geom = geometry
        self.__canvas = self.__iface.mapCanvas()
        self.__types = ['PDF', 'PNG']  # ], 'SVG', 'PS']
        self.__libs = []
        if Qwt5_loaded:
            self.__lib = 'Qwt5'
            self.__libs.append('Qwt5')
            if matplotlib_loaded:
                self.__libs.append('Matplotlib')
        elif matplotlib_loaded:
            self.__lib = 'Matplotlib'
            self.__libs.append('Matplotlib')
        else:
            self.__lib = None
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "No graph lib available (qwt5 or matplotlib)"),
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)

        self.__doTracking = False
        self.__vline = None

        self.__profiles = None
        self.__numLines = None
        self.__mntPoints = None

        self.__marker = None
        self.__tabmouseevent = None

        if self.__geom is not None:
            self.setGeometry(self.__geom)

        self.__contentWidget = QWidget()
        self.setWidget(self.__contentWidget)

        self.__boxLayout = QHBoxLayout()
        self.__contentWidget.setLayout(self.__boxLayout)

        self.__plotFrame = QFrame()
        self.__frameLayout = QHBoxLayout()
        self.__plotFrame.setLayout(self.__frameLayout)

        self.__printLayout = QHBoxLayout()
        self.__printLayout.addWidget(self.__plotFrame)

        self.__legendLayout = QVBoxLayout()
        self.__printLayout.addLayout(self.__legendLayout)

        self.__printWdg = QWidget()
        self.__printWdg.setLayout(self.__printLayout)

        self.__plotWdg = None
        self.__scaleButton = None
        self.__changePlotWidget()

        size = QSize(150, 20)

        self.__boxLayout.addWidget(self.__printWdg)

        self.__vertLayout = QVBoxLayout()

        self.__libCombo = QComboBox()
        self.__libCombo.setFixedSize(size)
        self.__libCombo.addItems(self.__libs)
        self.__vertLayout.addWidget(self.__libCombo)
        self.__libCombo.currentIndexChanged.connect(self.__setLib)

        if mntButton:
            self.__displayMnt = False
            self.__mntButton = QPushButton(
                QCoreApplication.translate("VDLTools", "Display MNT"))
            self.__mntButton.setFixedSize(size)
            self.__mntButton.clicked.connect(self.__mnt)
            self.__vertLayout.addWidget(self.__mntButton)

        if zerosButton:
            self.__displayZeros = False
            self.__zerosButton = QPushButton(
                QCoreApplication.translate("VDLTools", "Display Zeros"))
            self.__zerosButton.setFixedSize(size)
            self.__zerosButton.clicked.connect(self.__zeros)
            self.__vertLayout.addWidget(self.__zerosButton)
        else:
            self.__displayZeros = True

        self.__scale11 = False
        self.__scaleButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Scale 1:1"))
        self.__scaleButton.setFixedSize(size)
        self.__scaleButton.clicked.connect(self.__scale)
        if self.__lib == 'Qwt5':
            self.__scaleButton.setVisible(True)
        else:
            self.__scaleButton.setVisible(False)
        self.__vertLayout.addWidget(self.__scaleButton)

        self.__maxLabel = QLabel("y max")
        self.__maxLabel.setFixedSize(size)
        self.__vertLayout.addWidget(self.__maxLabel)
        self.__maxSpin = QSpinBox()
        self.__maxSpin.setFixedSize(size)
        self.__maxSpin.setRange(-10000, 10000)
        self.__maxSpin.valueChanged.connect(self.__reScalePlot)
        self.__vertLayout.addWidget(self.__maxSpin)
        self.__vertLayout.insertSpacing(10, 20)

        self.__minLabel = QLabel("y min")
        self.__minLabel.setFixedSize(size)
        self.__vertLayout.addWidget(self.__minLabel)
        self.__minSpin = QSpinBox()
        self.__minSpin.setFixedSize(size)
        self.__minSpin.setRange(-10000, 10000)
        self.__minSpin.valueChanged.connect(self.__reScalePlot)
        self.__vertLayout.addWidget(self.__minSpin)
        self.__vertLayout.insertSpacing(10, 40)

        self.__typeCombo = QComboBox()
        self.__typeCombo.setFixedSize(size)
        self.__typeCombo.addItems(self.__types)
        self.__vertLayout.addWidget(self.__typeCombo)
        self.__saveButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Save"))
        self.__saveButton.setFixedSize(size)
        self.__saveButton.clicked.connect(self.__save)
        self.__vertLayout.addWidget(self.__saveButton)

        self.__boxLayout.addLayout(self.__vertLayout)

        self.__maxSpin.setEnabled(False)
        self.__minSpin.setEnabled(False)

        self.__colors = []
        for cn in QColor.colorNames():
            qc = QColor(cn)
            val = qc.red() + qc.green() + qc.blue()
            if 0 < val < 450:
                self.__colors.append(cn)

    def mntButton(self):
        """
        To get the mnt button instance
        :return: mnt button instance
        """
        return self.__mntButton

    def zerosButton(self):
        """
        To get the zeros button instance
        :return: zeros button instance
        """
        return self.__zerosButton

    def scaleButton(self):
        """
        To get the scale button instance
        :return: scale button instance
        """
        return self.__scaleButton

    def displayMnt(self):
        """
        To get if we want to display mnt
        :return: true or false
        """
        return self.__displayMnt

    def __scale(self):
        if self.__scale11:
            self.__scale11 = False
            self.__scaleButton.setText(
                QCoreApplication.translate("VDLTools", "Scale 1:1"))
        else:
            self.__scale11 = True
            self.__scaleButton.setText(
                QCoreApplication.translate("VDLTools", "Auto scale"))

    def __mnt(self):
        """
        To toggle mnt display choice
        """
        if self.__displayMnt:
            self.__displayMnt = False
            self.__mntButton.setText(
                QCoreApplication.translate("VDLTools", "Display MNT"))
        else:
            self.__displayMnt = True
            self.__mntButton.setText(
                QCoreApplication.translate("VDLTools", "Remove MNT"))

    def __zeros(self):
        """
        To toggle if we want to display zero elevations or not
        """
        if self.__displayZeros:
            self.__displayZeros = False
            self.__zerosButton.setText(
                QCoreApplication.translate("VDLTools", "Display Zeros"))
        else:
            self.__displayZeros = True
            self.__zerosButton.setText(
                QCoreApplication.translate("VDLTools", "Remove Zeros"))

    def __changePlotWidget(self):
        """
        When plot widget is change (qwt <-> matplotlib)
        """
        self.__activateMouseTracking(False)
        while self.__frameLayout.count():
            child = self.__frameLayout.takeAt(0)
            child.widget().deleteLater()
        self.__plotWdg = None

        if self.__lib == 'Qwt5':
            self.__plotWdg = QwtPlot(self.__plotFrame)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(10)
            sizePolicy.setVerticalStretch(0)
            self.__plotWdg.setSizePolicy(sizePolicy)
            self.__plotWdg.setAutoFillBackground(False)
            # Decoration
            self.__plotWdg.setCanvasBackground(Qt.white)
            self.__plotWdg.plotLayout().setAlignCanvasToScales(False)
            self.__plotWdg.plotLayout().setSpacing(100)
            self.__plotWdg.plotLayout().setCanvasMargin(10, QwtPlot.xBottom)
            self.__plotWdg.plotLayout().setCanvasMargin(10, QwtPlot.yLeft)
            title = QwtText(
                QCoreApplication.translate("VDLTools", "Distance [m]"))
            title.setFont(QFont("Helvetica", 10))
            self.__plotWdg.setAxisTitle(QwtPlot.xBottom, title)
            title.setText(
                QCoreApplication.translate("VDLTools", "Elevation [m]"))
            title.setFont(QFont("Helvetica", 10))
            self.__plotWdg.setAxisTitle(QwtPlot.yLeft, title)
            self.__zoomer = QwtPlotZoomer(QwtPlot.xBottom, QwtPlot.yLeft,
                                          QwtPicker.DragSelection,
                                          QwtPicker.AlwaysOff,
                                          self.__plotWdg.canvas())
            self.__zoomer.zoomed.connect(self.__scaleZoom)
            self.__zoomer.setRubberBandPen(QPen(Qt.blue))
            grid = QwtPlotGrid()
            grid.setPen(QPen(QColor('grey'), 0, Qt.DotLine))
            grid.attach(self.__plotWdg)
            self.__frameLayout.addWidget(self.__plotWdg)
            if self.__scaleButton is not None:
                self.__scaleButton.setVisible(True)

        elif self.__lib == 'Matplotlib':
            fig = Figure((1.0, 1.0),
                         linewidth=0.0,
                         subplotpars=SubplotParams(left=0,
                                                   bottom=0,
                                                   right=1,
                                                   top=1,
                                                   wspace=0,
                                                   hspace=0))

            font = {'family': 'arial', 'weight': 'normal', 'size': 12}
            rc('font', **font)

            rect = fig.patch
            rect.set_facecolor((0.9, 0.9, 0.9))

            self.__axes = fig.add_axes((0.07, 0.16, 0.92, 0.82))
            self.__axes.set_xbound(0, 1000)
            self.__axes.set_ybound(0, 1000)
            self.__manageMatplotlibAxe(self.__axes)
            self.__plotWdg = FigureCanvasQTAgg(fig)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            self.__plotWdg.setSizePolicy(sizePolicy)
            self.__frameLayout.addWidget(self.__plotWdg)
            if self.__scaleButton is not None:
                self.__scaleButton.setVisible(False)

    def setProfiles(self, profiles, numLines):
        """
        To set the profiles
        :param profiles: profiles : positions with elevations (for line and points)
        :param numLines: number of selected connected lines
        """
        self.__numLines = numLines
        self.__profiles = profiles
        if self.__lib == 'Matplotlib':
            self.__prepare_points()

    def __getLinearPoints(self):
        """
        To extract the linear points of the profile
        """
        profileLen = 0
        self.__profiles[0]['l'] = profileLen
        for i in range(0, len(self.__profiles) - 1):
            x1 = float(self.__profiles[i]['x'])
            y1 = float(self.__profiles[i]['y'])
            x2 = float(self.__profiles[i + 1]['x'])
            y2 = float(self.__profiles[i + 1]['y'])
            profileLen += sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) *
                                                          (y2 - y1)))
            self.__profiles[i + 1]['l'] = profileLen

    def __getMnt(self, settings):
        """
        To get the MNT data for the profile
        :param settings: settings containing MNT url
        """
        if settings is None or settings.mntUrl is None or settings.mntUrl == "None":
            url = 'https://map.lausanne.ch/prod/wsgi/profile.json'
        elif settings.mntUrl == "":
            return
        else:
            url = settings.mntUrl
        names = ['MNT', 'MNS', 'Rocher (approx.)']
        data = "layers=MNT%2CMNS%2CRocher%20(approx.)&geom=%7B%22type%22%3A%22LineString%22%2C%22coordinates%22%3A%5B"

        pos = 0
        for i in range(len(self.__profiles)):
            if pos > 0:
                data += "%2C"
            pos += 1
            data += "%5B" + str(self.__profiles[i]['x']) + "%2C" + str(
                self.__profiles[i]['y']) + "%5D"
        data += "%5D%7D&nbPoints=" + str(
            int(self.__profiles[len(self.__profiles) - 1]['l'] + 1))
        try:
            response = requests.post(url, data=data)
            j = response.text
            j_obj = json.loads(j)
            profile = j_obj['profile']
            self.__mntPoints = []
            self.__mntPoints.append(names)
            mnt_l = []
            mnt_z = []
            for p in range(len(names)):
                z = []
                mnt_z.append(z)
            for pt in profile:
                mnt_l.append(float(pt['dist']))
                values = pt['values']
                for p in range(len(names)):
                    if names[p] in values:
                        mnt_z[p].append(float(values[names[p]]))
                    else:
                        mnt_z[p].append(None)
            self.__mntPoints.append(mnt_l)
            self.__mntPoints.append(mnt_z)
        except HTTPError as e:
            self.__iface.messageBar().pushMessage(
                QCoreApplication.translate("VDLTools", "HTTP Error"),
                QCoreApplication.translate("VDLTools", "status error") + "[" +
                str(e.code) + "] : " + e.reason,
                level=QgsMessageBar.CRITICAL,
                duration=0)
        except URLError as e:
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "URL Error"),
                                                  e.reason,
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)
        except ValueError as e:
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "No MNT values here"),
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)

    def attachCurves(self, names, settings, usedMnts):
        """
        To attach the curves for the layers to the profile
        :param names: layers names
        :param settings: project settings
        :param usedMnts: if use mnt or not
        """
        if (self.__profiles is None) or (self.__profiles == 0):
            return

        self.__getLinearPoints()
        if usedMnts is not None and (usedMnts[0] or usedMnts[1]
                                     or usedMnts[2]):
            self.__getMnt(settings)

        c = 0

        if self.__mntPoints is not None:
            for p in range(len(self.__mntPoints[0])):
                if usedMnts[p]:
                    legend = QLabel("<font color='" + self.__colors[c] + "'>" +
                                    self.__mntPoints[0][p] + "</font>")
                    self.__legendLayout.addWidget(legend)

                    if self.__lib == 'Qwt5':

                        xx = [
                            list(g) for k, g in itertools.groupby(
                                self.__mntPoints[1], lambda x: x is None)
                            if not k
                        ]
                        yy = [
                            list(g) for k, g in itertools.groupby(
                                self.__mntPoints[2][p], lambda x: x is None)
                            if not k
                        ]

                        for j in range(len(xx)):
                            curve = QwtPlotCurve(self.__mntPoints[0][p])
                            curve.setData(xx[j], yy[j])
                            curve.setPen(QPen(QColor(self.__colors[c]), 3))
                            curve.attach(self.__plotWdg)

                    elif self.__lib == 'Matplotlib':
                        qcol = QColor(self.__colors[c])
                        self.__plotWdg.figure.get_axes()[0].plot(
                            self.__mntPoints[1],
                            self.__mntPoints[2][p],
                            gid=self.__mntPoints[0][p],
                            linewidth=3)
                        tmp = self.__plotWdg.figure.get_axes()[0].get_lines()
                        for t in range(len(tmp)):
                            if self.__mntPoints[0][p] == tmp[t].get_gid():
                                tmp[c].set_color((old_div(qcol.red(), 255.0),
                                                  old_div(qcol.green(), 255.0),
                                                  old_div(qcol.blue(), 255.0),
                                                  old_div(qcol.alpha(),
                                                          255.0)))
                                self.__plotWdg.draw()
                                break
                    c += 1

        if 'z' in self.__profiles[0]:
            for i in range(len(self.__profiles[0]['z'])):
                if i < self.__numLines:
                    v = 0
                else:
                    v = i - self.__numLines + 1
                name = names[v]
                xx = []
                yy = []
                for prof in self.__profiles:
                    if isinstance(prof['z'][i], list):
                        for z in prof['z'][i]:
                            xx.append(prof['l'])
                            yy.append(z)
                    else:
                        xx.append(prof['l'])
                        yy.append(prof['z'][i])

                for j in range(len(yy)):
                    if yy[j] is None:
                        xx[j] = None

                if i == 0 or i > (self.__numLines - 1):
                    legend = QLabel("<font color='" + self.__colors[c] + "'>" +
                                    name + "</font>")
                    self.__legendLayout.addWidget(legend)

                if self.__lib == 'Qwt5':

                    # Split xx and yy into single lines at None values
                    xx = [
                        list(g)
                        for k, g in itertools.groupby(xx, lambda x: x is None)
                        if not k
                    ]
                    yy = [
                        list(g)
                        for k, g in itertools.groupby(yy, lambda x: x is None)
                        if not k
                    ]

                    # Create & attach one QwtPlotCurve per one single line
                    for j in range(len(xx)):
                        curve = QwtPlotCurve(name)
                        curve.setData(xx[j], yy[j])
                        curve.setPen(QPen(QColor(self.__colors[c]), 3))
                        if i > (self.__numLines - 1):
                            curve.setStyle(QwtPlotCurve.Dots)
                            pen = QPen(QColor(self.__colors[c]), 8)
                            pen.setCapStyle(Qt.RoundCap)
                            curve.setPen(pen)
                        curve.attach(self.__plotWdg)

                elif self.__lib == 'Matplotlib':
                    qcol = QColor(self.__colors[c])
                    if i < self.__numLines:
                        self.__plotWdg.figure.get_axes()[0].plot(xx,
                                                                 yy,
                                                                 gid=name,
                                                                 linewidth=3)
                    else:
                        self.__plotWdg.figure.get_axes()[0].plot(
                            xx,
                            yy,
                            gid=name,
                            linewidth=5,
                            marker='o',
                            linestyle='None')
                    tmp = self.__plotWdg.figure.get_axes()[0].get_lines()
                    for t in range(len(tmp)):
                        if name == tmp[t].get_gid():
                            tmp[c].set_color(
                                (old_div(qcol.red(),
                                         255.0), old_div(qcol.green(), 255.0),
                                 old_div(qcol.blue(),
                                         255.0), old_div(qcol.alpha(), 255.0)))
                            self.__plotWdg.draw()
                            break
                c += 1

        # scaling this
        try:
            self.__reScalePlot(None, True)
        except:
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "Rescale problem... (trace printed)"),
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)
            print(sys.exc_info()[0], traceback.format_exc())
        if self.__lib == 'Qwt5':
            self.__plotWdg.replot()
        elif self.__lib == 'Matplotlib':
            self.__plotWdg.figure.get_axes()[0].redraw_in_frame()
            self.__plotWdg.draw()
            self.__activateMouseTracking(True)
            self.__marker.show()

    def __scaleZoom(self):
        if self.__scale11:
            rect = self.__zoomer.zoomRect()
            plot = self.__zoomer.plot()
            width = plot.canvas().width()
            height = plot.canvas().height()
            length = rect.right() - rect.left()
            density = length / width
            interval = density * height
            middle = (rect.top() + rect.bottom()) / 2
            maximumValue = middle + (interval / 2)
            minimumValue = middle - (interval / 2)

            inter = pow(10, floor(log10(length)))
            if length / inter > 5:
                inter = 2 * inter
            step = inter / 2
            plot.setAxisScale(2, rect.left(), rect.right(), step)
            plot.setAxisScale(0, minimumValue, maximumValue, step)
            plot.replot()

    def __reScalePlot(self, value=None, auto=False):
        """
        To rescale the profile plot depending to the bounds
        :param value: juste because connections give value
        :param auto: if automatic ranges calcul is wanted
        """
        if (self.__profiles is None) or (self.__profiles == 0):
            self.__plotWdg.replot()
            return

        length = 0
        for i in range(len(self.__profiles)):
            if (ceil(self.__profiles[i]['l'])) > length:
                length = ceil(self.__profiles[i]['l'])
        if self.__lib == 'Qwt5':
            self.__plotWdg.setAxisScale(2, 0, length, 0)
        elif self.__lib == 'Matplotlib':
            self.__plotWdg.figure.get_axes()[0].set_xbound(0, length)

        minimumValue = self.__minSpin.value()
        maximumValue = self.__maxSpin.value()

        # to set max y and min y displayed
        if auto:
            minimumValue = 1000000000
            maximumValue = -1000000000
            for i in range(len(self.__profiles)):
                if 'z' in self.__profiles[i]:
                    mini = self.__minTab(self.__profiles[i]['z'])
                    if (mini > 0
                            or self.__displayZeros) and mini < minimumValue:
                        minimumValue = ceil(mini) - 1
                    maxi = self.__maxTab(self.__profiles[i]['z'])
                    if maxi > maximumValue:
                        maximumValue = floor(maxi) + 1
                if self.__mntPoints is not None:
                    for pts in self.__mntPoints[2]:
                        miniMnt = self.__minTab(pts)
                        if (miniMnt > 0 or self.__displayZeros
                            ) and miniMnt < minimumValue:
                            minimumValue = ceil(miniMnt) - 1
                        maxiMnt = self.__maxTab(pts)
                        if maxiMnt > maximumValue:
                            maximumValue = floor(maxiMnt) + 1

        if self.__scale11:
            width = self.__plotWdg.canvas().width()
            height = self.__plotWdg.canvas().height()
            density = length / width
            interval = density * height
            middle = (maximumValue + minimumValue) / 2
            maximumValue = middle + (interval / 2)
            minimumValue = middle - (interval / 2)

        self.__maxSpin.valueChanged.disconnect(self.__reScalePlot)
        self.__maxSpin.setValue(maximumValue)
        self.__maxSpin.valueChanged.connect(self.__reScalePlot)
        self.__minSpin.valueChanged.disconnect(self.__reScalePlot)
        self.__minSpin.setValue(minimumValue)
        self.__minSpin.valueChanged.connect(self.__reScalePlot)
        self.__maxSpin.setEnabled(True)
        self.__minSpin.setEnabled(True)

        # to draw vertical lines
        for i in range(len(self.__profiles)):
            zz = []
            for j in range(self.__numLines):
                if self.__profiles[i]['z'][j] is not None:
                    zz.append(j)
            color = None
            if len(zz) == 2:
                width = 3
                color = QColor('red')
            else:
                width = 1

            if self.__lib == 'Qwt5':
                vertLine = QwtPlotMarker()
                vertLine.setLineStyle(QwtPlotMarker.VLine)
                pen = vertLine.linePen()
                pen.setWidth(width)
                if color is not None:
                    pen.setColor(color)
                vertLine.setLinePen(pen)
                vertLine.setXValue(self.__profiles[i]['l'])
                label = vertLine.label()
                label.setText(str(i))
                vertLine.setLabel(label)
                vertLine.setLabelAlignment(Qt.AlignLeft)
                vertLine.attach(self.__plotWdg)
            elif self.__lib == 'Matplotlib':
                self.__plotWdg.figure.get_axes()[0].vlines(
                    self.__profiles[i]['l'],
                    minimumValue,
                    maximumValue,
                    linewidth=width)

        if minimumValue < maximumValue:
            if self.__lib == 'Qwt5':
                step = 0
                if self.__scale11:
                    inter = pow(10, floor(log10(length)))
                    if length / inter > 5:
                        inter = 2 * inter
                    step = inter / 2
                    self.__plotWdg.setAxisScale(2, 0, length, step)
                self.__plotWdg.setAxisScale(0, minimumValue, maximumValue,
                                            step)
                self.__plotWdg.replot()
            elif self.__lib == 'Matplotlib':
                self.__plotWdg.figure.get_axes()[0].set_ybound(
                    minimumValue, maximumValue)
                self.__plotWdg.figure.get_axes()[0].redraw_in_frame()
                self.__plotWdg.draw()

        if self.__lib == 'Qwt5':
            rect = QRectF(0, minimumValue, length, maximumValue - minimumValue)
            self.__zoomer.setZoomBase(rect)

    @staticmethod
    def __minTab(tab):
        """
        To get the minimum value in a table
        :param tab: table to scan
        :return: minimum value
        """
        mini = 1000000000
        for t in tab:
            if isinstance(t, list):
                for ti in t:
                    if ti is None:
                        continue
                    if ti < mini:
                        mini = ti
            else:
                if t is None:
                    continue
                if t < mini:
                    mini = t
        return mini

    @staticmethod
    def __maxTab(tab):
        """
        To get the maximum value in a table
        :param tab: table to scan
        :return: maximum value
        """
        maxi = -1000000000
        for t in tab:
            if isinstance(t, list):
                for ti in t:
                    if ti is None:
                        continue
                    if ti > maxi:
                        maxi = ti
            else:
                if t is None:
                    continue
                if t > maxi:
                    maxi = t
        return maxi

    def __setLib(self):
        """
        To set the new widget library (qwt <-> matplotlib)
        """
        self.__lib = self.__libs[self.__libCombo.currentIndex()]
        self.__changePlotWidget()

    def __save(self):
        """
        To save the profile in a file, on selected format
        """
        idx = self.__typeCombo.currentIndex()
        if idx == 0:
            self.__outPDF()
        elif idx == 1:
            self.__outPNG()
        else:
            self.__iface.messageBar().pushMessage(
                QCoreApplication.translate("VDLTools", "Invalid index ") +
                str(idx),
                level=QgsMessageBar.CRITICAL,
                duration=0)

    def __outPDF(self):
        """
        To save the profile as pdf file
        """
        fileName = QFileDialog.getSaveFileName(
            self.__iface.mainWindow(),
            QCoreApplication.translate("VDLTools", "Save As"),
            QCoreApplication.translate("VDLTools", "Profile.pdf"),
            "Portable Document Format (*.pdf)")
        if fileName is not None:
            if self.__lib == 'Qwt5':
                printer = QPrinter()
                printer.setCreator(
                    QCoreApplication.translate("VDLTools",
                                               "QGIS Profile Plugin"))
                printer.setOutputFileName(fileName)
                printer.setOutputFormat(QPrinter.PdfFormat)
                printer.setOrientation(QPrinter.Landscape)
                self.__plotWdg.print_(printer)
            elif self.__lib == 'Matplotlib':
                self.__plotWdg.figure.savefig(str(fileName))

    def __outPNG(self):
        """
        To save the profile as png file
        """
        fileName = QFileDialog.getSaveFileName(
            self.__iface.mainWindow(),
            QCoreApplication.translate("VDLTools", "Save As"),
            QCoreApplication.translate("VDLTools", "Profile.png"),
            "Portable Network Graphics (*.png)")
        if fileName is not None:
            QPixmap.grabWidget(self.__printWdg).save(fileName, "PNG")

    def clearData(self):
        """
        To clear the displayed data
        """
        if self.__profiles is None:
            return
        if self.__lib == 'Qwt5':
            self.__plotWdg.clear()
            self.__profiles = None
            temp1 = self.__plotWdg.itemList()
            for j in range(len(temp1)):
                if temp1[j].rtti() == QwtPlotItem.Rtti_PlotCurve:
                    temp1[j].detach()
        elif self.__lib == 'Matplotlib':
            self.__plotWdg.figure.get_axes()[0].cla()
            self.__manageMatplotlibAxe(self.__plotWdg.figure.get_axes()[0])
        self.__maxSpin.setEnabled(False)
        self.__minSpin.setEnabled(False)
        self.__maxSpin.valueChanged.disconnect(self.__reScalePlot)
        self.__maxSpin.setValue(0)
        self.__maxSpin.valueChanged.connect(self.__reScalePlot)
        self.__minSpin.valueChanged.disconnect(self.__reScalePlot)
        self.__minSpin.setValue(0)
        self.__minSpin.valueChanged.connect(self.__reScalePlot)

        # clear legend
        while self.__legendLayout.count():
            child = self.__legendLayout.takeAt(0)
            child.widget().deleteLater()

    def __manageMatplotlibAxe(self, axe):
        """
        To manage the axes for matplotlib library
        :param axe: the axes element
        """
        axe.grid()
        axe.tick_params(axis="both",
                        which="major",
                        direction="out",
                        length=10,
                        width=1,
                        bottom=True,
                        top=False,
                        left=True,
                        right=False)
        axe.minorticks_on()
        axe.tick_params(axis="both",
                        which="minor",
                        direction="out",
                        length=5,
                        width=1,
                        bottom=True,
                        top=False,
                        left=True,
                        right=False)
        axe.set_xlabel(QCoreApplication.translate("VDLTools", "Distance [m]"))
        axe.set_ylabel(QCoreApplication.translate("VDLTools", "Elevation [m]"))

    def __activateMouseTracking(self, activate):
        """
        To (de)activate the mouse tracking on the profile for matplotlib library
        :param activate: true to activate, false to deactivate
        """
        if activate:
            self.__doTracking = True
            self.__loadRubber()
            self.cid = self.__plotWdg.mpl_connect('motion_notify_event',
                                                  self.__mouseevent_mpl)
        elif self.__doTracking:
            self.__doTracking = False
            self.__plotWdg.mpl_disconnect(self.cid)
            if self.__marker is not None:
                self.__canvas.scene().removeItem(self.__marker)
            try:
                if self.__vline is not None:
                    self.__plotWdg.figure.get_axes()[0].lines.remove(
                        self.__vline)
                    self.__plotWdg.draw()
            except Exception as e:
                self.__iface.messageBar().pushMessage(
                    QCoreApplication.translate(
                        "VDLTools", "Tracking exception : ") + str(e),
                    level=QgsMessageBar.CRITICAL,
                    duration=0)

    def __mouseevent_mpl(self, event):
        """
        To manage matplotlib mouse tracking event
        :param event: mouse tracking event
        """
        if event.xdata is not None:
            try:
                if self.__vline is not None:
                    self.__plotWdg.figure.get_axes()[0].lines.remove(
                        self.__vline)
            except Exception as e:
                self.__iface.messageBar().pushMessage(
                    QCoreApplication.translate(
                        "VDLTools", "Mouse event exception : ") + str(e),
                    level=QgsMessageBar.CRITICAL,
                    duration=0)
            xdata = float(event.xdata)
            self.__vline = self.__plotWdg.figure.get_axes()[0].axvline(
                xdata, linewidth=2, color='k')
            self.__plotWdg.draw()
            i = 1
            while i < len(self.__tabmouseevent
                          ) - 1 and xdata > self.__tabmouseevent[i][0]:
                i += 1
            i -= 1

            x = self.__tabmouseevent[i][1] + (
                self.__tabmouseevent[i + 1][1] - self.__tabmouseevent[i][1]
            ) / (self.__tabmouseevent[i + 1][0] - self.__tabmouseevent[i][0]
                 ) * (xdata - self.__tabmouseevent[i][0])
            y = self.__tabmouseevent[i][2] + (
                self.__tabmouseevent[i + 1][2] - self.__tabmouseevent[i][2]
            ) / (self.__tabmouseevent[i + 1][0] - self.__tabmouseevent[i][0]
                 ) * (xdata - self.__tabmouseevent[i][0])
            self.__marker.show()
            self.__marker.setCenter(QgsPoint(x, y))

    def __loadRubber(self):
        """
        To load te rubber band for mouse tracking on map
        """
        self.__marker = QgsVertexMarker(self.__canvas)
        self.__marker.setIconSize(5)
        self.__marker.setIconType(QgsVertexMarker.ICON_BOX)
        self.__marker.setPenWidth(3)

    def __prepare_points(self):
        """
        To prepare the points on map for mouse tracking on profile
        """
        self.__tabmouseevent = []
        length = 0
        for i, point in enumerate(self.__profiles):
            if i == 0:
                self.__tabmouseevent.append([0, point['x'], point['y']])
            else:
                length += ((self.__profiles[i]['x'] -
                            self.__profiles[i - 1]['x'])**2 +
                           (self.__profiles[i]['y'] -
                            self.__profiles[i - 1]['y'])**2)**0.5
                self.__tabmouseevent.append(
                    [float(length),
                     float(point['x']),
                     float(point['y'])])

    def closeEvent(self, event):
        """
        When the dock widget is closed
        :param event: close event
        """
        if self.__maxSpin is not None:
            Signal.safelyDisconnect(self.__maxSpin.valueChanged,
                                    self.__reScalePlot)
            self.__maxSpin = None
        if self.__minSpin is not None:
            Signal.safelyDisconnect(self.__minSpin.valueChanged,
                                    self.__reScalePlot)
            self.__minSpin = None
        if self.__saveButton is not None:
            Signal.safelyDisconnect(self.__saveButton.clicked, self.__save)
            self.__saveButton = None
        if self.__libCombo is not None:
            Signal.safelyDisconnect(self.__libCombo.currentIndexChanged,
                                    self.__setLib)
            self.__libCombo = None
        self.closeSignal.emit()
        if self.__marker is not None:
            self.__marker.hide()
        QDockWidget.closeEvent(self, event)
Пример #34
0
class OrbitCorrGeneral(QtGui.QWidget):
    """
    A general orbit correction or local bump panel.
    """
    def __init__(self, bpms, cors, parent = None):
        super(OrbitCorrGeneral, self).__init__(parent)

        self.bpms, self.cors = bpms, cors
        self.sb = [bpm.sb for bpm in self.bpms]
        self.x0, self.y0 = None, None
        self._update_current_orbit()

        self.table = QTableWidget(len(self.bpms), 9)
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table.setHorizontalHeaderLabels(
            ['BPM Name', 's', "Beta X", "Beta Y",
             "Eta X", 'X Bump', 'Y Bump', "Target X", "Target Y"])
        self._twiss = getTwiss([b.name for b in self.bpms],
                               ["s", "betax", "betay", "etax"])
        for i,bpm in enumerate(self.bpms):
            it = QTableWidgetItem(bpm.name)
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            self.table.setItem(i, 0, it)

            it = QTableWidgetItem(str(bpm.sb))
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            #it.setMinimumWidth(80)
            self.table.setItem(i, 1, it)
            self.table.setItem(i, 2,
                               QTableWidgetItem("%.4f" % self._twiss[i,1]))
            self.table.setItem(i, 3,
                               QTableWidgetItem("%.4f" % self._twiss[i,2]))
            self.table.setItem(i, 4,
                               QTableWidgetItem("%.4f" % self._twiss[i,3]))

            for j in range(5, 9):
                it = QTableWidgetItem(str(0.0))
                it.setData(Qt.DisplayRole, str(0.0))
                it.setFlags(it.flags() | Qt.ItemIsEditable)
                self.table.setItem(i, j, it) 
            # use the current orbit 
            #self.table.item(i,4).setData(Qt.DisplayRole, str(self.x0[i]))
            #self.table.item(i,5).setData(Qt.DisplayRole, str(self.y0[i]))

        #self.connect(self.table, SIGNAL("cellClicked(int, int)"),
        #             self._cell_clicked)
        self.table.resizeColumnsToContents()
        #self.table.horizontalHeader().setStretchLastSection(True)
        #for i in range(4):
        #    print "width", i, self.table.columnWidth(i)
        #self.table.setColumnWidth(0, 300)
        self.table.setColumnWidth(1, 80)

        vbox1 = QtGui.QVBoxLayout()
        frmbox = QFormLayout()
        self.base_orbit_box = QtGui.QComboBox()
        #self.base_orbit_box.addItems([
        #        "Current Orbit", "All Zeros"])
        self.base_orbit_box.addItems(["All Zeros", "Current Orbit"])
        frmbox.addRow("Orbit Base", self.base_orbit_box)
        grp = QtGui.QGroupBox("Local Bump")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        frmbox = QFormLayout()
        hln1 = QtGui.QFrame()
        hln1.setLineWidth(3)
        hln1.setFrameStyle(QtGui.QFrame.Sunken)
        hln1.setFrameShape(QtGui.QFrame.HLine)
        frmbox.addRow(hln1)
        self.repeatbox = QSpinBox()
        self.repeatbox.setRange(1, 20)
        self.repeatbox.setValue(3)
        # or connect the returnPressed() signal
        frmbox.addRow("&Repeat correction", self.repeatbox)

        self.rcondbox = QLineEdit()
        self.rcondbox.setValidator(QDoubleValidator(0, 1, 0, self))
        self.rcondbox.setText("1e-2")
        frmbox.addRow("r&cond for SVD", self.rcondbox)

        self.scalebox = QDoubleSpinBox()
        self.scalebox.setRange(0.01, 5.00)
        self.scalebox.setSingleStep(0.01)
        self.scalebox.setValue(0.68)
        frmbox.addRow("&Scale correctors", self.scalebox)

        #hln2 = QtGui.QFrame()
        #hln2.setLineWidth(3)
        #hln2.setFrameStyle(QtGui.QFrame.Sunken)
        #hln2.setFrameShape(QtGui.QFrame.HLine)
        #frmbox.addRow(hln2)

        self.progress = QProgressBar()
        self.progress.setMaximum(self.repeatbox.value())
        self.progress.setMaximumHeight(15)
        frmbox.addRow("Progress", self.progress)
        grp = QtGui.QGroupBox("Correction")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        #vbox.addStretch(1.0)
        #self.qdb = QDialogButtonBox(self)
        #self.qdb.addButton("APP", QDialogButtonBox.ApplyRole)
        #self.qdb.addButton("R", QDialogButtonBox.ResetRole)
        #btn.setDefault(True)
        #self.qdb.addButton(QDialogButtonBox.Cancel)
        #self.qdb.addButton(QDialogButtonBox.Help)

        gbox = QtGui.QGridLayout()
        btn = QPushButton("Clear")
        self.connect(btn, SIGNAL("clicked()"), self.resetBumps)
        gbox.addWidget(btn, 0, 1)
        self.correctOrbitBtn = QPushButton("Apply")
        #self.correctOrbitBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.correctOrbitBtn.setStyleSheet("QPushButton:disabled { color: gray }");
        self.connect(self.correctOrbitBtn, SIGNAL("clicked()"), self.call_apply)
        self.correctOrbitBtn.setDefault(True)
        gbox.addWidget(self.correctOrbitBtn, 1, 1)
        gbox.setColumnStretch(0, 1)

        vbox1.addStretch()
        vbox1.addLayout(gbox)
        
        hbox1 = QtGui.QHBoxLayout()
        hbox1.addWidget(self.table, 2)
        hbox1.addLayout(vbox1, 0)
        self.setLayout(hbox1)

        self.connect(self.base_orbit_box,
                     SIGNAL("currentIndexChanged(QString)"), 
                     self.updateTargetOrbit)
        self.connect(self.repeatbox, SIGNAL("valueChanged(int)"),
                     self.progress.setMaximum)
        self.connect(self.table, SIGNAL("cellChanged (int, int)"),
                     self.updateBump)

        #self.updateTargetOrbit(self.base_orbit_box.currentText())

    def _update_current_orbit(self):
        pvx = [bpm.pv(field="x", handle="readback")[0] for bpm in self.bpms]
        pvy = [bpm.pv(field="y", handle="readback")[0] for bpm in self.bpms]
        self.x0 = [float(v) if v.ok else np.nan for v in catools.caget(pvx)]
        self.y0 = [float(v) if v.ok else np.nan for v in catools.caget(pvy)]

    def resetBumps(self):
        jx0, jy0 = 5, 6
        for i in range(self.table.rowCount()):
            self.table.item(i, jx0).setData(Qt.DisplayRole, str(0.0))
            self.table.item(i, jy0).setData(Qt.DisplayRole, str(0.0))
        #self.updateTargetOrbit(self.base_orbit_box.currentText())

    def call_apply(self):
        #print "apply the orbit"
        obt = []
        jx, jy = 7, 8
        for i in range(self.table.rowCount()):
            x1,err = self.table.item(i, jx).data(Qt.DisplayRole).toFloat()
            y1,err = self.table.item(i, jy).data(Qt.DisplayRole).toFloat()
            obt.append([x1, y1])

        self.correctOrbitBtn.setEnabled(False)
        nrepeat = self.repeatbox.value()
        kw = { "scale": float(self.scalebox.text()),
               "rcond": float(self.rcondbox.text()) }
        self.progress.setValue(0)
        QApplication.processEvents()
        for i in range(nrepeat):
            err, msg = setLocalBump(self.bpms, self.cors, obt, **kw)
            self.progress.setValue(i+1)
            QApplication.processEvents()
            if err != 0:
                QtGui.QMessageBox.critical(
                    self, "Local Orbit Bump", 
                    "ERROR: {0}\nAbort.".format(msg),
                    QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
                break
       
        self.correctOrbitBtn.setEnabled(True)

    def getTargetOrbit(self):
        x = [self.table.item(i,7).data(Qt.DisplayRole).toFloat()[0]
             for i in range(self.table.rowCount())]
        y = [self.table.item(i,8).data(Qt.DisplayRole).toFloat()[0]
             for i in range(self.table.rowCount())]
        return (self.sb, x), (self.sb, y)

    def updateTargetOrbit(self, baseobt):
        if baseobt == "All Zeros":
            jx0, jx1 = 5, 7
            jy0, jy1 = 6, 8
            for i in range(self.table.rowCount()):
                it0 = self.table.item(i, jx0)
                it1 = self.table.item(i, jx1)
                it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole))
                it0 = self.table.item(i, jy0)
                it1 = self.table.item(i, jy1)
                it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole))
        elif baseobt == "Current Orbit":
            self._update_current_orbit()
            jx0, jx1 = 5, 7
            jy0, jy1 = 6, 8
            for i in range(self.table.rowCount()):
                dx0,err = self.table.item(i, jx0).data(Qt.DisplayRole).toFloat()
                it = self.table.item(i, jx1)
                it.setData(Qt.DisplayRole, self.x0[i] + dx0)

                dy0,err = self.table.item(i, jy0).data(Qt.DisplayRole).toFloat()
                it = self.table.item(i, jy1)
                it.setData(Qt.DisplayRole, self.y0[i] + dy0)
        #self._update_orbit_plot()
        x, y = self.getTargetOrbit()
        self.emit(SIGNAL("targetOrbitChanged(PyQt_PyObject, PyQt_PyObject)"),
                  x, y)

    def updateBump(self, row, col):
        #print "updating ", row, col
        if col == 5 or col == 6:
            self.updateTargetOrbit(self.base_orbit_box.currentText())
        painter.setBrush(Qt.darkYellow)
        painter.drawPolygon(QPolygonF(triangle))


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    form = QDialog()

    sliderLabel = QLabel("&Fraction")
    slider = FractionSlider(denominator=12)
    sliderLabel.setBuddy(slider)

    denominatorLabel = QLabel("&Denominator")
    denominatorSpinBox = QSpinBox()
    denominatorLabel.setBuddy(denominatorSpinBox)
    denominatorSpinBox.setRange(3, 60)
    denominatorSpinBox.setValue(slider.fraction()[1])
    denominatorSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

    numeratorLabel = QLabel("Numberator")
    numeratorLCD = QLCDNumber()
    numeratorLCD.setSegmentStyle(QLCDNumber.Flat)

    layout = QGridLayout()
    layout.addWidget(sliderLabel, 0, 0)
    layout.addWidget(slider, 0, 1, 1, 5)
    layout.addWidget(numeratorLabel, 1, 0)
    layout.addWidget(numeratorLCD, 1, 1)
    layout.addWidget(denominatorLabel, 1, 2)
Пример #36
0
    def create_widgets(self):
        """creates the display window"""
        # Text Size
        self.font_size = QLabel("Text Size:")
        self.font_size_edit = QSpinBox(self)
        self.font_size_edit.setValue(self._default_font_size)
        self.font_size_edit.setRange(7, 20)
        self.font_size_button = QPushButton("Default")

        #-----------------------------------------------------------------------
        # Annotation Color
        self.label_color = QLabel("Label Color:")
        self.label_color_edit = QPushButtonColor(self.label_color_int)

        # Background Color
        self.background_color = QLabel("Background Color:")
        self.background_color_edit = QPushButtonColor(self.background_color_int)

        # Label Color
        self.text_color = QLabel("Text Color:")
        self.text_color_edit = QPushButtonColor(self.text_color_int)

        #-----------------------------------------------------------------------
        # Label Size
        self.label_size = QLabel("Label Size (3D Text):")
        self.label_size_edit = QDoubleSpinBox(self)
        self.label_size_edit.setRange(0.0, self.dim_max)

        log_dim = log10(self.dim_max)
        decimals = int(ceil(abs(log_dim)))
        decimals = max(6, decimals)
        self.label_size_edit.setDecimals(decimals)
        #self.label_size_edit.setSingleStep(self.dim_max / 100.)
        self.label_size_edit.setSingleStep(self.dim_max / 1000.)
        self.label_size_edit.setValue(self._label_size)

        #-----------------------------------------------------------------------
        # Picker Size
        self.picker_size = QLabel("Picker Size (% of Screen):")
        self.picker_size_edit = QDoubleSpinBox(self)
        self.picker_size_edit.setRange(0., 10.)

        log_dim = log10(self.dim_max)
        decimals = int(ceil(abs(log_dim)))

        decimals = max(6, decimals)
        self.picker_size_edit.setDecimals(decimals)
        self.picker_size_edit.setSingleStep(10. / 5000.)
        self.picker_size_edit.setValue(self._picker_size)

        #-----------------------------------------------------------------------
        # Clipping Min
        self.clipping_min = QLabel("Clipping Min:")
        self.clipping_min_edit = QLineEdit(str(self._default_clipping_min))
        self.clipping_min_button = QPushButton("Default")

        # Clipping Max
        self.clipping_max = QLabel("Clipping Max:")
        self.clipping_max_edit = QLineEdit(str(self._default_clipping_max))
        self.clipping_max_button = QPushButton("Default")

        #-----------------------------------------------------------------------
        # closing
        self.apply_button = QPushButton("Apply")
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")
Пример #37
0
class TradingWidget(QFrame):
    """简单交易组件"""
    signal = QtCore.pyqtSignal(type(Event()))

    directionList = [DIRECTION_LONG, DIRECTION_SHORT]

    offsetList = [
        OFFSET_OPEN, OFFSET_CLOSE, OFFSET_CLOSEYESTERDAY, OFFSET_CLOSETODAY
    ]

    priceTypeList = [PRICETYPE_LIMITPRICE, PRICETYPE_VWAP, PRICETYPE_TWAP]

    exchangeList = [
        EXCHANGE_NONE, EXCHANGE_CFFEX, EXCHANGE_SHFE, EXCHANGE_DCE,
        EXCHANGE_CZCE, EXCHANGE_SSE, EXCHANGE_SZSE, EXCHANGE_SGE,
        EXCHANGE_HKEX, EXCHANGE_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')

        # 查询合约
        vtSymbol = symbol
        contract = self.mainEngine.getContract(symbol)

        # 清空价格数量
        self.spinPrice.setValue(0)
        self.spinVolume.setValue(0)

        if contract:
            vtSymbol = contract.vtSymbol
            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 self.signalemit != None:
            self.eventEngine.unregister(EVENT_TICK + self.symbol,
                                        self.signalemit)

        self.signalemit = self.signal.emit
        self.eventEngine.register(EVENT_TICK + vtSymbol, self.signalemit)

        # 订阅合约
        self.mainEngine.subscribe(contract.vtSymbol, gatewayName)

        # 更新组件当前交易的合约
        self.symbol = vtSymbol

    # ----------------------------------------------------------------------
    def updateTick(self, event):
        """更新行情"""
        tick = event.dict_['data']

        if tick.vtSymbol == self.symbol:
            self.labelBidPrice1.setText(str(tick.bidPrice1))
            self.labelAskPrice1.setText(str(tick.askPrice1))
            self.labelBidVolume1.setText(str(tick.bidVolume1))
            self.labelAskVolume1.setText(str(tick.askVolume1))

            if tick.bidPrice2:
                self.labelBidPrice2.setText(str(tick.bidPrice2))
                self.labelBidPrice3.setText(str(tick.bidPrice3))
                self.labelBidPrice4.setText(str(tick.bidPrice4))
                self.labelBidPrice5.setText(str(tick.bidPrice5))

                self.labelAskPrice2.setText(str(tick.askPrice2))
                self.labelAskPrice3.setText(str(tick.askPrice3))
                self.labelAskPrice4.setText(str(tick.askPrice4))
                self.labelAskPrice5.setText(str(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(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

        # 查询合约
        if exchange:
            vtSymbol = '.'.join([symbol, exchange])
            contract = self.mainEngine.getContract(vtSymbol)
        else:
            vtSymbol = symbol
            contract = self.mainEngine.getContract(symbol)

        if contract:
            gatewayName = contract.gatewayName
            exchange = contract.exchange  # 保证有交易所代码

        req = VtOrderReq()
        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()
Пример #38
0
class EditGeometryProperties(QDialog):
    force = True
    allow_update = True
    def __init__(self, data, win_parent=None):
        """
        +------------------+
        | Edit Actor Props |
        +------------------+------+
        |  Name1                  |
        |  Name2                  |
        |  Name3                  |
        |  Name4                  |
        |                         |
        |  Active_Name    main    |
        |  Color          box     |
        |  Line_Width     2       |
        |  Point_Size     2       |
        |  Bar_Scale      2       |
        |  Opacity        0.5     |
        |  Show/Hide              |
        |                         |
        |    Apply   OK   Cancel  |
        +-------------------------+
        """
        QDialog.__init__(self, win_parent)
        self.setWindowTitle('Edit Geometry Properties')

        #default
        self.win_parent = win_parent
        self.out_data = data

        self.keys = sorted(data.keys())
        self.keys = data.keys()
        keys = self.keys
        nrows = len(keys)
        self.active_key = 'main'#keys[0]

        items = keys

        header_labels = ['Groups']
        table_model = Model(items, header_labels, self)
        view = CustomQTableView(self) #Call your custom QTableView here
        view.setModel(table_model)
        if qt_version == 4:
            view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        self.table = view

        actor_obj = data[self.active_key]
        name = actor_obj.name
        line_width = actor_obj.line_width
        point_size = actor_obj.point_size
        bar_scale = actor_obj.bar_scale
        opacity = actor_obj.opacity
        color = actor_obj.color
        show = actor_obj.is_visible
        self.representation = actor_obj.representation

        # table
        header = self.table.horizontalHeader()
        header.setStretchLastSection(True)

        self._default_is_apply = False
        self.name = QLabel("Name:")
        self.name_edit = QLineEdit(str(name))
        self.name_edit.setDisabled(True)

        self.color = QLabel("Color:")
        self.color_edit = QPushButton()
        #self.color_edit.setFlat(True)

        color = self.out_data[self.active_key].color
        qcolor = QtGui.QColor()
        qcolor.setRgb(*color)
        #print('color =%s' % str(color))
        palette = QtGui.QPalette(self.color_edit.palette()) # make a copy of the palette
        #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \
                         #qcolor)
        palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue'))  # ButtonText
        self.color_edit.setPalette(palette)

        self.color_edit.setStyleSheet("QPushButton {"
                                      "background-color: rgb(%s, %s, %s);" % tuple(color) +
                                      #"border:1px solid rgb(255, 170, 255); "
                                      "}")

        self.use_slider = True
        self.is_opacity_edit_active = False
        self.is_opacity_edit_slider_active = False

        self.is_line_width_edit_active = False
        self.is_line_width_edit_slider_active = False

        self.is_point_size_edit_active = False
        self.is_point_size_edit_slider_active = False

        self.is_bar_scale_edit_active = False
        self.is_bar_scale_edit_slider_active = False

        self.opacity = QLabel("Opacity:")
        self.opacity_edit = QDoubleSpinBox(self)
        self.opacity_edit.setRange(0.1, 1.0)
        self.opacity_edit.setDecimals(1)
        self.opacity_edit.setSingleStep(0.1)
        self.opacity_edit.setValue(opacity)
        if self.use_slider:
            self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.opacity_slider_edit.setRange(1, 10)
            self.opacity_slider_edit.setValue(opacity * 10)
            self.opacity_slider_edit.setTickInterval(1)
            self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow)

        self.line_width = QLabel("Line Width:")
        self.line_width_edit = QSpinBox(self)
        self.line_width_edit.setRange(1, 15)
        self.line_width_edit.setSingleStep(1)
        self.line_width_edit.setValue(line_width)
        if self.use_slider:
            self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.line_width_slider_edit.setRange(1, 15)
            self.line_width_slider_edit.setValue(line_width)
            self.line_width_slider_edit.setTickInterval(1)
            self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow)

        if self.representation in ['point', 'surface']:
            self.line_width.setEnabled(False)
            self.line_width_edit.setEnabled(False)
            self.line_width_slider_edit.setEnabled(False)

        self.point_size = QLabel("Point Size:")
        self.point_size_edit = QSpinBox(self)
        self.point_size_edit.setRange(1, 15)
        self.point_size_edit.setSingleStep(1)
        self.point_size_edit.setValue(point_size)
        self.point_size.setVisible(False)
        self.point_size_edit.setVisible(False)
        if self.use_slider:
            self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.point_size_slider_edit.setRange(1, 15)
            self.point_size_slider_edit.setValue(point_size)
            self.point_size_slider_edit.setTickInterval(1)
            self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow)
            self.point_size_slider_edit.setVisible(False)

        if self.representation in ['wire', 'surface']:
            self.point_size.setEnabled(False)
            self.point_size_edit.setEnabled(False)
            if self.use_slider:
                self.point_size_slider_edit.setEnabled(False)

        self.bar_scale = QLabel("Bar Scale:")
        self.bar_scale_edit = QDoubleSpinBox(self)
        #self.bar_scale_edit.setRange(0.01, 1.0)  # was 0.1
        #self.bar_scale_edit.setRange(0.05, 5.0)
        self.bar_scale_edit.setDecimals(1)
        #self.bar_scale_edit.setSingleStep(bar_scale / 10.)
        self.bar_scale_edit.setSingleStep(0.1)
        self.bar_scale_edit.setValue(bar_scale)

        #if self.use_slider:
            #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal)
            #self.bar_scale_slider_edit.setRange(1, 100)  # 1/0.05 = 100/5.0
            #self.bar_scale_slider_edit.setValue(opacity * 0.05)
            #self.bar_scale_slider_edit.setTickInterval(10)
            #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow)

        if self.representation != 'bar':
            self.bar_scale.setEnabled(False)
            self.bar_scale_edit.setEnabled(False)
            self.bar_scale.setVisible(False)
            self.bar_scale_edit.setVisible(False)
            #self.bar_scale_slider_edit.setVisible(False)
            #self.bar_scale_slider_edit.setEnabled(False)

        # show/hide
        self.checkbox_show = QCheckBox("Show")
        self.checkbox_hide = QCheckBox("Hide")
        self.checkbox_show.setChecked(show)
        self.checkbox_hide.setChecked(not show)

        if name == 'main':
            self.color.setEnabled(False)
            self.color_edit.setEnabled(False)
            self.point_size.setEnabled(False)
            self.point_size_edit.setEnabled(False)
            if self.use_slider:
                self.point_size_slider_edit.setEnabled(False)


        # closing
        # self.apply_button = QPushButton("Apply")
        #if self._default_is_apply:
            #self.apply_button.setDisabled(True)

        # self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Close")

        self.create_layout()
        self.set_connections()

    def on_update_geometry_properties_window(self, data):
        """Not Implemented"""
        return
        new_keys = sorted(data.keys())
        if self.active_key in new_keys:
            i = new_keys.index(self.active_key)
        else:
            i = 0
        self.table.update_data(new_keys)
        self.out_data = data
        self.update_active_key(i)

    def update_active_key(self, index):
        """
        Parameters
        ----------
        index : PyQt4.QtCore.QModelIndex
            the index of the list

        Internal Parameters
        -------------------
        name : str
            the name of obj
        obj : CoordProperties, AltGeometry
            the storage object for things like line_width, point_size, etc.
        """
        old_obj = self.out_data[self.active_key]
        old_obj.line_width = self.line_width_edit.value()
        old_obj.point_size = self.point_size_edit.value()
        old_obj.bar_scale = self.bar_scale_edit.value()
        old_obj.opacity = self.opacity_edit.value()
        old_obj.is_visible = self.checkbox_show.isChecked()

        if qt_version == 4:
            name = str(index.data().toString())
        else:
            name = str(index.data())
            print('name = %r' % name)
        #i = self.keys.index(self.active_key)

        self.active_key = name
        self.name_edit.setText(name)
        obj = self.out_data[name]
        if isinstance(obj, CoordProperties):
            opacity = 1.0
            representation = 'coord'
            is_visible = obj.is_visible
        elif isinstance(obj, AltGeometry):
            line_width = obj.line_width
            point_size = obj.point_size
            bar_scale = obj.bar_scale
            opacity = obj.opacity
            representation = obj.representation
            is_visible = obj.is_visible

            self.color_edit.setStyleSheet("QPushButton {"
                                          "background-color: rgb(%s, %s, %s);" % tuple(obj.color) +
                                          #"border:1px solid rgb(255, 170, 255); "
                                          "}")
            self.allow_update = False
            self.force = False
            self.line_width_edit.setValue(line_width)
            self.point_size_edit.setValue(point_size)
            self.bar_scale_edit.setValue(bar_scale)
            self.force = True
            self.allow_update = True
        else:
            raise NotImplementedError(obj)

        allowed_representations = [
            'main', 'surface', 'coord', 'toggle', 'wire', 'point', 'bar']

        if self.representation != representation:
            self.representation = representation
            if representation not in allowed_representations:
                msg = 'name=%r; representation=%r is invalid\nrepresentations=%r' % (
                    name, representation, allowed_representations)

            if self.representation == 'coord':
                self.color.setVisible(False)
                self.color_edit.setVisible(False)
                self.line_width.setVisible(False)
                self.line_width_edit.setVisible(False)
                self.point_size.setVisible(False)
                self.point_size_edit.setVisible(False)
                self.bar_scale.setVisible(False)
                self.bar_scale_edit.setVisible(False)
                self.opacity.setVisible(False)
                self.opacity_edit.setVisible(False)
                if self.use_slider:
                    self.opacity_slider_edit.setVisible(False)
                    self.point_size_slider_edit.setVisible(False)
                    self.line_width_slider_edit.setVisible(False)
                    #self.bar_scale_slider_edit.setVisible(False)
            else:
                self.color.setVisible(True)
                self.color_edit.setVisible(True)
                self.line_width.setVisible(True)
                self.line_width_edit.setVisible(True)
                self.point_size.setVisible(True)
                self.point_size_edit.setVisible(True)
                self.bar_scale.setVisible(True)
                #self.bar_scale_edit.setVisible(True)
                self.opacity.setVisible(True)
                self.opacity_edit.setVisible(True)
                if self.use_slider:
                    self.opacity_slider_edit.setVisible(True)
                    self.line_width_slider_edit.setVisible(True)
                    self.point_size_slider_edit.setVisible(True)
                    #self.bar_scale_slider_edit.setVisible(True)

                if name == 'main':
                    self.color.setEnabled(False)
                    self.color_edit.setEnabled(False)
                    self.point_size.setEnabled(False)
                    self.point_size_edit.setEnabled(False)
                    self.line_width.setEnabled(True)
                    self.line_width_edit.setEnabled(True)
                    self.bar_scale.setEnabled(False)
                    self.bar_scale_edit.setEnabled(False)
                    show_points = False
                    show_line_width = True
                    show_bar_scale = False
                    if self.use_slider:
                        self.line_width_slider_edit.setEnabled(True)
                        #self.bar_scale_slider_edit.setVisible(False)
                else:
                    self.color.setEnabled(True)
                    self.color_edit.setEnabled(True)

                    show_points = False
                    if self.representation in ['point', 'wire+point']:
                        show_points = True

                    show_line_width = False
                    if self.representation in ['wire', 'wire+point', 'bar']:
                        show_line_width = True

                    if representation == 'bar':
                        show_bar_scale = True
                    else:
                        show_bar_scale = False
                    #self.bar_scale_button.setVisible(show_bar_scale)
                    #self.bar_scale_edit.setSingleStep(bar_scale / 10.)
                    #if self.use_slider:
                        #self.bar_scale_slider_edit.setEnabled(False)

                self.point_size.setEnabled(show_points)
                self.point_size_edit.setEnabled(show_points)
                self.point_size.setVisible(show_points)
                self.point_size_edit.setVisible(show_points)

                self.line_width.setEnabled(show_line_width)
                self.line_width_edit.setEnabled(show_line_width)

                self.bar_scale.setEnabled(show_bar_scale)
                self.bar_scale_edit.setEnabled(show_bar_scale)
                self.bar_scale.setVisible(show_bar_scale)
                self.bar_scale_edit.setVisible(show_bar_scale)
                if self.use_slider:
                    self.point_size_slider_edit.setEnabled(show_points)
                    self.point_size_slider_edit.setVisible(show_points)
                    self.line_width_slider_edit.setEnabled(show_line_width)


            #if self.representation in ['wire', 'surface']:

        self.opacity_edit.setValue(opacity)
        #if self.use_slider:
            #self.opacity_slider_edit.setValue(opacity*10)
        self.checkbox_show.setChecked(is_visible)
        self.checkbox_hide.setChecked(not is_visible)

        passed = self.on_validate()
        #self.on_apply(force=True)  # TODO: was turned on...do I want this???
        #self.allow_update = True

    #def on_name_select(self):
        #print('on_name_select')
        #return

    def create_layout(self):
        ok_cancel_box = QHBoxLayout()
        # ok_cancel_box.addWidget(self.apply_button)
        # ok_cancel_box.addWidget(self.ok_button)
        ok_cancel_box.addWidget(self.cancel_button)

        grid = QGridLayout()

        irow = 0
        grid.addWidget(self.name, irow, 0)
        grid.addWidget(self.name_edit, irow, 1)
        irow += 1

        grid.addWidget(self.color, irow, 0)
        grid.addWidget(self.color_edit, irow, 1)
        irow += 1

        grid.addWidget(self.opacity, irow, 0)
        if self.use_slider:
            grid.addWidget(self.opacity_edit, irow, 2)
            grid.addWidget(self.opacity_slider_edit, irow, 1)
        else:
            grid.addWidget(self.opacity_edit, irow, 1)
        irow += 1

        grid.addWidget(self.line_width, irow, 0)
        if self.use_slider:
            grid.addWidget(self.line_width_edit, irow, 2)
            grid.addWidget(self.line_width_slider_edit, irow, 1)
        else:
            grid.addWidget(self.line_width_edit, irow, 1)
        irow += 1

        grid.addWidget(self.point_size, irow, 0)
        if self.use_slider:
            grid.addWidget(self.point_size_edit, irow, 2)
            grid.addWidget(self.point_size_slider_edit, irow, 1)
        else:
            grid.addWidget(self.point_size_edit, irow, 1)
        irow += 1

        grid.addWidget(self.bar_scale, irow, 0)
        if self.use_slider and 0:
            grid.addWidget(self.bar_scale_edit, irow, 2)
            grid.addWidget(self.bar_scale_slider_edit, irow, 1)
        else:
            grid.addWidget(self.bar_scale_edit, irow, 1)
        irow += 1

        checkboxs = QButtonGroup(self)
        checkboxs.addButton(self.checkbox_show)
        checkboxs.addButton(self.checkbox_hide)

        vbox = QVBoxLayout()
        vbox.addWidget(self.table)
        vbox.addLayout(grid)

        if 0:
            vbox.addWidget(self.checkbox_show)
            vbox.addWidget(self.checkbox_hide)
        else:
            vbox1 = QVBoxLayout()
            vbox1.addWidget(self.checkbox_show)
            vbox1.addWidget(self.checkbox_hide)
            vbox.addLayout(vbox1)

        vbox.addStretch()
        #vbox.addWidget(self.check_apply)
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)

    def set_connections(self):
        # self.opacity_edit.connect(arg0, QObject, arg1)
        if qt_version == 4:
            self.connect(self.opacity_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity)
                #self.connect(self.opacity_slider_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity)
                #grid.addWidget(self.opacity_slider_edit, irow, 1)

            # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width)
            # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size)

            # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_line_width)
            # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_point_size)
            self.connect(self.line_width_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width)
            self.connect(self.point_size_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size)
            self.connect(self.bar_scale_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_bar_scale)
        else:
            self.opacity_edit.valueChanged.connect(self.on_opacity)
            self.line_width_edit.valueChanged.connect(self.on_line_width)
            self.point_size_edit.valueChanged.connect(self.on_point_size)
            self.bar_scale_edit.valueChanged.connect(self.on_bar_scale)

        if self.use_slider:
            self.opacity_slider_edit.valueChanged.connect(self.on_opacity_slider)
            self.line_width_slider_edit.valueChanged.connect(self.on_line_width_slider)
            self.point_size_slider_edit.valueChanged.connect(self.on_point_size_slider)
            #self.bar_scale_slider_edit.valueChanged.connect(self.on_bar_scale_slider)



        # self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity)
        # self.connect(self.line_width, QtCore.SIGNAL('clicked()'), self.on_line_width)
        # self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size)

        if qt_version == 4:
            self.connect(self.color_edit, QtCore.SIGNAL('clicked()'), self.on_color)
            self.connect(self.checkbox_show, QtCore.SIGNAL('clicked()'), self.on_show)
            self.connect(self.checkbox_hide, QtCore.SIGNAL('clicked()'), self.on_hide)
            #self.connect(self.check_apply, QtCore.SIGNAL('clicked()'), self.on_check_apply)

            # self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply)
            # self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok)
            self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel)
            self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
        else:
            self.color_edit.clicked.connect(self.on_color)
            self.checkbox_show.clicked.connect(self.on_show)
            self.checkbox_hide.clicked.connect(self.on_hide)
            self.cancel_button.clicked.connect(self.on_cancel)
            # closeEvent

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()

    def closeEvent(self, event):
        self.on_cancel()

    def on_color(self):
        name = self.active_key
        obj = self.out_data[name]
        rgb_color_ints = obj.color

        msg = name
        col = QtGui.QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a %s color" % msg)
        if col.isValid():
            color = col.getRgbF()[:3]
            obj.color = color
            #print('new_color =', color)
            self.color_edit.setStyleSheet("QPushButton {"
                                          "background-color: rgb(%s, %s, %s);" % tuple(obj.color) +
                                          #"border:1px solid rgb(255, 170, 255); "
                                          "}")
        self.on_apply(force=self.force)

    def on_show(self):
        name = self.active_key
        is_checked = self.checkbox_show.isChecked()
        self.out_data[name].is_visible = is_checked
        self.on_apply(force=self.force)

    def on_hide(self):
        name = self.active_key
        is_checked = self.checkbox_hide.isChecked()
        self.out_data[name].is_visible = not is_checked
        self.on_apply(force=self.force)

    def on_line_width(self):
        self.is_line_width_edit_active = True
        name = self.active_key
        line_width = self.line_width_edit.value()
        self.out_data[name].line_width = line_width
        if not self.is_line_width_edit_slider_active:
            if self.use_slider:
                self.line_width_slider_edit.setValue(line_width)
            self.is_line_width_edit_active = False
        self.on_apply(force=self.force)
        self.is_line_width_edit_active = False

    def on_line_width_slider(self):
        self.is_line_width_edit_slider_active = True
        name = self.active_key
        line_width = self.line_width_slider_edit.value()
        if not self.is_line_width_edit_active:
            self.line_width_edit.setValue(line_width)
        self.is_line_width_edit_slider_active = False

    def on_point_size(self):
        self.is_point_size_edit_active = True
        name = self.active_key
        point_size = self.point_size_edit.value()
        self.out_data[name].point_size = point_size
        if not self.is_point_size_edit_slider_active:
            if self.use_slider:
                self.point_size_slider_edit.setValue(point_size)
            self.is_point_size_edit_active = False
        self.on_apply(force=self.force)
        self.is_point_size_edit_active = False

    def on_point_size_slider(self):
        self.is_point_size_edit_slider_active = True
        name = self.active_key
        point_size = self.point_size_slider_edit.value()
        if not self.is_point_size_edit_active:
            self.point_size_edit.setValue(point_size)
        self.is_point_size_edit_slider_active = False

    def on_bar_scale(self):
        self.is_bar_scale_edit_active = True
        name = self.active_key
        float_bar_scale = self.bar_scale_edit.value()
        self.out_data[name].bar_scale = float_bar_scale
        if not self.is_bar_scale_edit_slider_active:
            int_bar_scale = int(round(float_bar_scale * 20, 0))
            #if self.use_slider:
                #self.bar_scale_slider_edit.setValue(int_bar_scale)
            self.is_bar_scale_edit_active = False
        self.on_apply(force=self.force)
        self.is_bar_scale_edit_active = False

    def on_bar_scale_slider(self):
        self.is_bar_scale_edit_slider_active = True
        name = self.active_key
        int_bar_scale = self.bar_scale_slider_edit.value()
        if not self.is_bar_scale_edit_active:
            float_bar_scale = int_bar_scale / 20.
            self.bar_scale_edit.setValue(float_bar_scale)
        self.is_bar_scale_edit_slider_active = False

    def on_opacity(self):
        self.is_opacity_edit_active = True
        name = self.active_key
        float_opacity = self.opacity_edit.value()
        self.out_data[name].opacity = float_opacity
        if not self.is_opacity_edit_slider_active:
            int_opacity = int(round(float_opacity * 10, 0))
            if self.use_slider:
                self.opacity_slider_edit.setValue(int_opacity)
            self.is_opacity_edit_active = False
        self.on_apply(force=self.force)
        self.is_opacity_edit_active = False

    def on_opacity_slider(self):
        self.is_opacity_edit_slider_active = True
        name = self.active_key
        int_opacity = self.opacity_slider_edit.value()
        if not self.is_opacity_edit_active:
            float_opacity = int_opacity / 10.
            self.opacity_edit.setValue(float_opacity)
        self.is_opacity_edit_slider_active = False

    #def on_axis(self, text):
        ##print(self.combo_axis.itemText())
        #self._axis = str(text)
        #self.plane.setText('Point on %s? Plane:' % self._axis)
        #self.point_a.setText('Point on %s Axis:' % self._axis)
        #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane))

    #def on_plane(self, text):
        #self._plane = str(text)
        #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane))

    def on_check_apply(self):
        is_checked = self.check_apply.isChecked()
        self.apply_button.setDisabled(is_checked)

    def _on_float(self, field):
        try:
            eval_float_from_string(field.text())
            field.setStyleSheet("QLineEdit{background: white;}")
        except ValueError:
            field.setStyleSheet("QLineEdit{background: red;}")

    #def on_default_name(self):
        #self.name_edit.setText(str(self._default_name))
        #self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    #def check_float(self, cell):
        #text = cell.text()
        #try:
            #value = eval_float_from_string(text)
            #cell.setStyleSheet("QLineEdit{background: white;}")
            #return value, True
        #except ValueError:
            #cell.setStyleSheet("QLineEdit{background: red;}")
            #return None, False

    #def check_name(self, cell):
        #text = str(cell.text()).strip()
        #if len(text):
            #cell.setStyleSheet("QLineEdit{background: white;}")
            #return text, True
        #else:
            #cell.setStyleSheet("QLineEdit{background: red;}")
            #return None, False

    def on_validate(self):
        self.out_data['clicked_ok'] = True
        self.out_data['clicked_cancel'] = False

        old_obj = self.out_data[self.active_key]
        old_obj.line_width = self.line_width_edit.value()
        old_obj.point_size = self.point_size_edit.value()
        old_obj.bar_scale = self.bar_scale_edit.value()
        old_obj.opacity = self.opacity_edit.value()
        old_obj.is_visible = self.checkbox_show.isChecked()
        return True
        #name_value, flag0 = self.check_name(self.name_edit)
        #ox_value, flag1 = self.check_float(self.transparency_edit)
        #if flag0 and flag1:
            #self.out_data['clicked_ok'] = True
            #return True
        #return False

    def on_apply(self, force=False):
        passed = self.on_validate()
        if (passed or force) and self.allow_update:
            self.win_parent.on_update_geometry_properties(self.out_data)
        return passed

    def on_cancel(self):
        passed = self.on_apply(force=True)
        if passed:
            self.close()
Пример #39
0
    def __init__(self, data, win_parent=None):
        """
        +------------------+
        | Edit Actor Props |
        +------------------+------+
        |  Name1                  |
        |  Name2                  |
        |  Name3                  |
        |  Name4                  |
        |                         |
        |  Active_Name    main    |
        |  Color          box     |
        |  Line_Width     2       |
        |  Point_Size     2       |
        |  Bar_Scale      2       |
        |  Opacity        0.5     |
        |  Show/Hide              |
        |                         |
        |    Apply   OK   Cancel  |
        +-------------------------+
        """
        QDialog.__init__(self, win_parent)
        self.setWindowTitle('Edit Geometry Properties')

        #default
        self.win_parent = win_parent
        self.out_data = data

        self.keys = sorted(data.keys())
        self.keys = data.keys()
        keys = self.keys
        nrows = len(keys)
        self.active_key = 'main'#keys[0]

        items = keys

        header_labels = ['Groups']
        table_model = Model(items, header_labels, self)
        view = CustomQTableView(self) #Call your custom QTableView here
        view.setModel(table_model)
        if qt_version == 4:
            view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        self.table = view

        actor_obj = data[self.active_key]
        name = actor_obj.name
        line_width = actor_obj.line_width
        point_size = actor_obj.point_size
        bar_scale = actor_obj.bar_scale
        opacity = actor_obj.opacity
        color = actor_obj.color
        show = actor_obj.is_visible
        self.representation = actor_obj.representation

        # table
        header = self.table.horizontalHeader()
        header.setStretchLastSection(True)

        self._default_is_apply = False
        self.name = QLabel("Name:")
        self.name_edit = QLineEdit(str(name))
        self.name_edit.setDisabled(True)

        self.color = QLabel("Color:")
        self.color_edit = QPushButton()
        #self.color_edit.setFlat(True)

        color = self.out_data[self.active_key].color
        qcolor = QtGui.QColor()
        qcolor.setRgb(*color)
        #print('color =%s' % str(color))
        palette = QtGui.QPalette(self.color_edit.palette()) # make a copy of the palette
        #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \
                         #qcolor)
        palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue'))  # ButtonText
        self.color_edit.setPalette(palette)

        self.color_edit.setStyleSheet("QPushButton {"
                                      "background-color: rgb(%s, %s, %s);" % tuple(color) +
                                      #"border:1px solid rgb(255, 170, 255); "
                                      "}")

        self.use_slider = True
        self.is_opacity_edit_active = False
        self.is_opacity_edit_slider_active = False

        self.is_line_width_edit_active = False
        self.is_line_width_edit_slider_active = False

        self.is_point_size_edit_active = False
        self.is_point_size_edit_slider_active = False

        self.is_bar_scale_edit_active = False
        self.is_bar_scale_edit_slider_active = False

        self.opacity = QLabel("Opacity:")
        self.opacity_edit = QDoubleSpinBox(self)
        self.opacity_edit.setRange(0.1, 1.0)
        self.opacity_edit.setDecimals(1)
        self.opacity_edit.setSingleStep(0.1)
        self.opacity_edit.setValue(opacity)
        if self.use_slider:
            self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.opacity_slider_edit.setRange(1, 10)
            self.opacity_slider_edit.setValue(opacity * 10)
            self.opacity_slider_edit.setTickInterval(1)
            self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow)

        self.line_width = QLabel("Line Width:")
        self.line_width_edit = QSpinBox(self)
        self.line_width_edit.setRange(1, 15)
        self.line_width_edit.setSingleStep(1)
        self.line_width_edit.setValue(line_width)
        if self.use_slider:
            self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.line_width_slider_edit.setRange(1, 15)
            self.line_width_slider_edit.setValue(line_width)
            self.line_width_slider_edit.setTickInterval(1)
            self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow)

        if self.representation in ['point', 'surface']:
            self.line_width.setEnabled(False)
            self.line_width_edit.setEnabled(False)
            self.line_width_slider_edit.setEnabled(False)

        self.point_size = QLabel("Point Size:")
        self.point_size_edit = QSpinBox(self)
        self.point_size_edit.setRange(1, 15)
        self.point_size_edit.setSingleStep(1)
        self.point_size_edit.setValue(point_size)
        self.point_size.setVisible(False)
        self.point_size_edit.setVisible(False)
        if self.use_slider:
            self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.point_size_slider_edit.setRange(1, 15)
            self.point_size_slider_edit.setValue(point_size)
            self.point_size_slider_edit.setTickInterval(1)
            self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow)
            self.point_size_slider_edit.setVisible(False)

        if self.representation in ['wire', 'surface']:
            self.point_size.setEnabled(False)
            self.point_size_edit.setEnabled(False)
            if self.use_slider:
                self.point_size_slider_edit.setEnabled(False)

        self.bar_scale = QLabel("Bar Scale:")
        self.bar_scale_edit = QDoubleSpinBox(self)
        #self.bar_scale_edit.setRange(0.01, 1.0)  # was 0.1
        #self.bar_scale_edit.setRange(0.05, 5.0)
        self.bar_scale_edit.setDecimals(1)
        #self.bar_scale_edit.setSingleStep(bar_scale / 10.)
        self.bar_scale_edit.setSingleStep(0.1)
        self.bar_scale_edit.setValue(bar_scale)

        #if self.use_slider:
            #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal)
            #self.bar_scale_slider_edit.setRange(1, 100)  # 1/0.05 = 100/5.0
            #self.bar_scale_slider_edit.setValue(opacity * 0.05)
            #self.bar_scale_slider_edit.setTickInterval(10)
            #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow)

        if self.representation != 'bar':
            self.bar_scale.setEnabled(False)
            self.bar_scale_edit.setEnabled(False)
            self.bar_scale.setVisible(False)
            self.bar_scale_edit.setVisible(False)
            #self.bar_scale_slider_edit.setVisible(False)
            #self.bar_scale_slider_edit.setEnabled(False)

        # show/hide
        self.checkbox_show = QCheckBox("Show")
        self.checkbox_hide = QCheckBox("Hide")
        self.checkbox_show.setChecked(show)
        self.checkbox_hide.setChecked(not show)

        if name == 'main':
            self.color.setEnabled(False)
            self.color_edit.setEnabled(False)
            self.point_size.setEnabled(False)
            self.point_size_edit.setEnabled(False)
            if self.use_slider:
                self.point_size_slider_edit.setEnabled(False)


        # closing
        # self.apply_button = QPushButton("Apply")
        #if self._default_is_apply:
            #self.apply_button.setDisabled(True)

        # self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Close")

        self.create_layout()
        self.set_connections()
Пример #40
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.setupUi(self)
        self.setWindowTitle('DMX Test Tool by LauerSystems')

        # create and setup ipcon

        self.ipcon = IPConnection()
        self.ipcon.connect(HOST, PORT)
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.qtcb_ipcon_enumerate.emit)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.qtcb_ipcon_connected.emit)

        self.dmx = BrickletDMX(UID_DMX, self.ipcon)
        self.label_image.setText("Started!")

        #Configs
        self.wait_for_first_read = True

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

        self.dmx.set_dmx_mode(BrickletDMX.DMX_MODE_MASTER)
        print("DMX Mode [0=Master; 1=Slave]: " + str(self.dmx.get_dmx_mode()))
        self.dmx.set_frame_duration(200)
        print("Frame Duration [ms]: " + str(self.dmx.get_frame_duration()))

        self.address_spinboxes = []
        self.address_slider = []
        print("Config Ende")

        for i in range(20):
            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)
            print("Erzeuge Set: " + str(i))

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

        self.current_frame = [0] * 512

        print(self.current_frame)

        self.dmx.register_callback(self.dmx.CALLBACK_FRAME_STARTED,
                                   self.qtcb_frame_started.emit)
        self.dmx.register_callback(self.dmx.CALLBACK_FRAME,
                                   self.qtcb_frame.emit)
        self.dmx.set_frame_callback_config(True, False, True, False)
Пример #41
0
class NumberFormatDlg(QDialog):
    def __init__(self, format, callback, parent=None):
        super(NumberFormatDlg, self).__init__(parent)

        punctuationRe = QRegExp(r"[ ,;:.]")
        thousandsLabel = QLabel("&Thousands separator")
        self.thousandsEdit = QLineEdit(format["thousandsseparator"])
        thousandsLabel.setBuddy(self.thousandsEdit)
        self.thousandsEdit.setMaxLength(1)
        self.thousandsEdit.setValidator(QRegExpValidator(punctuationRe, self))
        decimalMarkerLabel = QLabel("Decimal &marker")
        self.decimalMarkerEdit = QLineEdit(format["decimalmarker"])
        decimalMarkerLabel.setBuddy(self.decimalMarkerEdit)
        self.decimalMarkerEdit.setMaxLength(1)
        self.decimalMarkerEdit.setValidator(
            QRegExpValidator(punctuationRe, self))
        self.decimalMarkerEdit.setInputMask("X")
        decimalPlacesLabel = QLabel("&Decimal places")
        self.decimalPlacesSpinBox = QSpinBox()
        decimalPlacesLabel.setBuddy(self.decimalPlacesSpinBox)
        self.decimalPlacesSpinBox.setRange(0, 6)
        self.decimalPlacesSpinBox.setValue(format["decimalplaces"])
        self.redNegativesCheckBox = QCheckBox("&Red negative numbers")
        self.redNegativesCheckBox.setChecked(format["rednegatives"])

        self.format = format
        self.callback = callback

        grid = QGridLayout()
        grid.addWidget(thousandsLabel, 0, 0)
        grid.addWidget(self.thousandsEdit, 0, 1)
        grid.addWidget(decimalMarkerLabel, 1, 0)
        grid.addWidget(self.decimalMarkerEdit, 1, 1)
        grid.addWidget(decimalPlacesLabel, 2, 0)
        grid.addWidget(self.decimalPlacesSpinBox, 2, 1)
        grid.addWidget(self.redNegativesCheckBox, 3, 0, 1, 2)
        self.setLayout(grid)

        self.connect(self.thousandsEdit, SIGNAL("textEdited(QString)"),
                     self.checkAndFix)
        self.connect(self.decimalMarkerEdit, SIGNAL("textEdited(QString)"),
                     self.checkAndFix)
        self.connect(self.decimalPlacesSpinBox, SIGNAL("valueChanged(int)"),
                     self.apply)
        self.connect(self.redNegativesCheckBox, SIGNAL("toggled(bool)"),
                     self.apply)
        self.setWindowTitle("Set Number Format (`Live')")

    def checkAndFix(self):
        thousands = unicode(self.thousandsEdit.text())
        decimal = unicode(self.decimalMarkerEdit.text())
        if thousands == decimal:
            self.thousandsEdit.clear()
            self.thousandsEdit.setFocus()
        if len(decimal) == 0:
            self.decimalMarkerEdit.setText(".")
            self.decimalMarkerEdit.selectAll()
            self.decimalMarkerEdit.setFocus()
        self.apply()

    def apply(self):
        self.format["thousandsseparator"] = (unicode(
            self.thousandsEdit.text()))
        self.format["decimalmarker"] = (unicode(self.decimalMarkerEdit.text()))
        self.format["decimalplaces"] = (self.decimalPlacesSpinBox.value())
        self.format["rednegatives"] = (self.redNegativesCheckBox.isChecked())
        self.callback()
Пример #42
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.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.storage_path.textChanged.connect(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("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)

        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)

        self.setLayout(layout)

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

    def getConfigurationPath(self):
        return self.configuration_path

    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)
Пример #43
0
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(435, 580)
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))

        self.gbGeneral = GroupBox(Form)
        self.gbGeneral.Caption = "General"
        self.verticalLayout.addWidget(self.gbGeneral)

        # self.cmbAerodrome = ComboBoxPanel(self.gbGeneral, True)
        # self.cmbAerodrome.Caption = "Aerodrome"
        # self.cmbAerodrome.LabelWidth = 120
        # self.gbGeneral.Add = self.cmbAerodrome
        #
        # self.cmbRwyDir = ComboBoxPanel(self.gbGeneral, True)
        # self.cmbRwyDir.Caption = "Runway Direction"
        # self.cmbRwyDir.LabelWidth = 120
        # self.cmbRwyDir.Width = 120
        # self.gbGeneral.Add = self.cmbRwyDir

        self.cmbRnavSpecification = ComboBoxPanel(self.gbGeneral)
        self.cmbRnavSpecification.Caption = "Rnav Specification"
        self.cmbRnavSpecification.LabelWidth = 150
        self.gbGeneral.Add = self.cmbRnavSpecification

        self.frameChbThree = Frame(self.gbGeneral, "HL")
        self.gbGeneral.Add = self.frameChbThree

        self.chbUseTwoWpt = CheckBox(self.frameChbThree)
        self.chbUseTwoWpt.Caption = "Use 2 Waypoints"
        self.frameChbThree.Add = self.chbUseTwoWpt

        self.chbInsertSymbol = CheckBox(self.frameChbThree)
        self.chbInsertSymbol.Caption = "Insert Symbol(s)"
        self.frameChbThree.Add = self.chbInsertSymbol

        self.chbCatH = CheckBox(self.frameChbThree)
        self.chbCatH.Caption = "Cat.H"
        self.frameChbThree.Add = self.chbCatH

        self.cmbPhaseOfFlight = ComboBoxPanel(self.gbGeneral)
        self.cmbPhaseOfFlight.Caption = "Phase Of Flight"
        self.cmbPhaseOfFlight.LabelWidth = 150
        self.gbGeneral.Add = self.cmbPhaseOfFlight

        self.pnlArp = PositionPanel(self.gbGeneral)
        self.pnlArp.Caption = "Aerodrome Reference Point(ARP)"
        self.pnlArp.btnCalculater.hide()
        self.pnlArp.hideframe_Altitude()
        self.gbGeneral.Add = self.pnlArp

        self.gbWaypoint1 = GroupBox(self.gbGeneral)
        self.gbWaypoint1.Caption = "Waypoint1"
        self.gbGeneral.Add = self.gbWaypoint1

        self.cmbType1 = ComboBoxPanel(self.gbWaypoint1)
        self.cmbType1.Caption = "Type"
        self.cmbType1.LabelWidth = 150
        self.gbWaypoint1.Add = self.cmbType1

        self.pnlTolerances = RnavTolerancesPanel(self.gbWaypoint1)
        self.pnlTolerances.set_Att(Distance(0.8, DistanceUnits.NM))
        self.pnlTolerances.set_Xtt(Distance(1, DistanceUnits.NM))
        self.pnlTolerances.set_Asw(Distance(2, DistanceUnits.NM))
        self.gbWaypoint1.Add = self.pnlTolerances

        self.pnlWaypoint1 = PositionPanel(self.gbWaypoint1)
        self.pnlWaypoint1.btnCalculater.hide()
        self.pnlWaypoint1.hideframe_Altitude()
        self.gbWaypoint1.Add = self.pnlWaypoint1

        self.gbWaypoint2 = GroupBox(self.gbGeneral)
        self.gbWaypoint2.Caption = "Waypoint2"
        self.gbGeneral.Add = self.gbWaypoint2

        self.cmbType2 = ComboBoxPanel(self.gbWaypoint2)
        self.cmbType2.Caption = "Type"
        self.cmbType2.LabelWidth = 150
        self.gbWaypoint2.Add = self.cmbType2

        self.pnlTolerances2 = RnavTolerancesPanel(self.gbWaypoint2)
        self.pnlTolerances2.set_Att(Distance(0.8, DistanceUnits.NM))
        self.pnlTolerances2.set_Xtt(Distance(1, DistanceUnits.NM))
        self.pnlTolerances2.set_Asw(Distance(2, DistanceUnits.NM))
        self.gbWaypoint2.Add = self.pnlTolerances2

        self.pnlWaypoint2 = PositionPanel(self.gbWaypoint2)
        self.pnlWaypoint2.btnCalculater.hide()
        self.pnlWaypoint2.hideframe_Altitude()
        self.gbWaypoint2.Add = self.pnlWaypoint2

        self.frmRadioBtns = Frame(self.gbGeneral, "HL")
        self.gbGeneral.Add = self.frmRadioBtns

        self.rdnTF = QRadioButton(self.frmRadioBtns)
        self.rdnTF.setObjectName("rdnTF")
        self.rdnTF.setText("TF")
        self.rdnTF.setChecked(True)
        self.frmRadioBtns.Add = self.rdnTF

        self.rdnDF = QRadioButton(self.frmRadioBtns)
        self.rdnDF.setObjectName("rdnDF")
        self.rdnDF.setText("DF")
        self.frmRadioBtns.Add = self.rdnDF

        self.rdnCF = QRadioButton(self.frmRadioBtns)
        self.rdnCF.setObjectName("rdnCF")
        self.rdnCF.setText("CF")
        self.frmRadioBtns.Add = self.rdnCF


        self.chbCircularArcs = CheckBox(self.gbGeneral)
        self.chbCircularArcs.Caption = "Use Circular Arcs Method for Turns <= 30"
        self.gbGeneral.Add = self.chbCircularArcs

        self.gbParameters = GroupBox(Form)
        self.gbParameters.Caption = "Parameters"
        self.verticalLayout.addWidget(self.gbParameters)

        self.cmbSelectionMode = ComboBoxPanel(self.gbParameters)
        self.cmbSelectionMode.Caption = "Selection Mode"
        self.cmbSelectionMode.LabelWidth = 150
        self.gbParameters.Add = self.cmbSelectionMode


        self.pnlInbound = TrackRadialBoxPanel(self.gbParameters)
        self.pnlInbound.Caption = "In-bound Track"
        self.pnlInbound.LabelWidth = 150
        self.gbParameters.Add = self.pnlInbound

        self.pnlOutbound = TrackRadialBoxPanel(self.gbParameters)
        self.pnlOutbound.Caption = "Out-bound Track"
        self.pnlOutbound.LabelWidth = 150
        self.gbParameters.Add = self.pnlOutbound


        # icon = QIcon()
        # icon.addPixmap(QPixmap(_fromUtf8("Resource/coordinate_capture.png")), QIcon.Normal, QIcon.Off)

        self.pnlIas = SpeedBoxPanel(self.gbParameters)
        self.pnlIas.Caption = "IAS"
        self.pnlIas.LabelWidth = 150
        self.pnlIas.Value = Speed(250)
        self.gbParameters.Add = self.pnlIas

        self.pnlTas = SpeedBoxPanel(self.gbParameters)
        self.pnlTas.Caption = "TAS"
        self.pnlTas.Enabled = False
        self.pnlTas.LabelWidth = 150
        self.gbParameters.Add = self.pnlTas

        self.pnlAltitude = AltitudeBoxPanel(self.gbParameters)
        self.pnlAltitude.Caption = "Altitude"
        self.pnlAltitude.LabelWidth = 150
        self.pnlAltitude.Value = Altitude(1000)
        self.gbParameters.Add = self.pnlAltitude

        self.pnlIsa = NumberBoxPanel(self.gbParameters, "0.0")
        self.pnlIsa.CaptionUnits = define._degreeStr + "C"
        self.pnlIsa.Caption = "ISA"
        self.pnlIsa.LabelWidth = 150
        self.pnlIsa.Value = 15
        self.gbParameters.Add = self.pnlIsa

        self.pnlBankAngle = NumberBoxPanel(self.gbParameters, "0.0")
        self.pnlBankAngle.CaptionUnits = define._degreeStr
        self.pnlBankAngle.Caption = "Bank Angle"
        self.pnlBankAngle.LabelWidth = 150
        self.pnlBankAngle.Value = 25
        self.gbParameters.Add = self.pnlBankAngle

        self.pnlBankEstTime = NumberBoxPanel(self.gbParameters, "0.0")
        self.pnlBankEstTime.Caption = "Bank Establishment Time"
        self.pnlBankEstTime.Value = 1
        self.pnlBankEstTime.LabelWidth = 150
        self.pnlBankEstTime.Value = 5
        self.gbParameters.Add = self.pnlBankEstTime

        self.pnlPilotTime = NumberBoxPanel(self.gbParameters, "0.0")
        self.pnlPilotTime.Caption = "Pilot Reaction Time"
        self.pnlPilotTime.Value = 6
        self.pnlPilotTime.LabelWidth = 150
        self.gbParameters.Add = self.pnlPilotTime

        self.pnlWind = WindPanel(self.gbParameters)
        self.pnlWind.LabelWidth = 145
        self.gbParameters.Add = self.pnlWind

        self.pnlPrimaryMoc = AltitudeBoxPanel(self.gbParameters)
        self.pnlPrimaryMoc.Caption = "Primary Moc"
        self.pnlPrimaryMoc.LabelWidth = 150
        self.gbParameters.Add = self.pnlPrimaryMoc

        self.cmbConstructionType = ComboBoxPanel(self.gbParameters)
        self.cmbConstructionType.Caption = "Construction Type"
        self.cmbConstructionType.LabelWidth = 150
        self.gbParameters.Add = self.cmbConstructionType

        self.frameMOCmultipiler = Frame(self.gbParameters, "HL")
        self.gbParameters.Add = self.frameMOCmultipiler

        self.labelMOCmultipiler = QLabel(self.frameMOCmultipiler)
        self.labelMOCmultipiler.setMinimumSize(QSize(145, 0))
        self.labelMOCmultipiler.setMaximumSize(QSize(145, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.labelMOCmultipiler.setFont(font)
        self.labelMOCmultipiler.setObjectName(_fromUtf8("labelMOCmultipiler"))
        self.labelMOCmultipiler.setText("MOCmultipiler")
        self.frameMOCmultipiler.Add = self.labelMOCmultipiler

        self.mocSpinBox = QSpinBox(self.frameMOCmultipiler)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mocSpinBox.sizePolicy().hasHeightForWidth())
        self.mocSpinBox.setSizePolicy(sizePolicy)
        self.mocSpinBox.setMinimumSize(QSize(70, 0))
        self.mocSpinBox.setMaximumSize(QSize(70, 16777215))
        self.mocSpinBox.setMinimum(1)
        self.mocSpinBox.setObjectName(_fromUtf8("mocSpinBox"))
        self.frameMOCmultipiler.Add = self.mocSpinBox

        spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.frameMOCmultipiler.layoutBoxPanel.addItem(spacerItem)

        self.chbDrawTolerance = CheckBox(self.gbParameters)
        self.chbDrawTolerance.Caption = "Draw Waypoint Tolerance"
        self.gbParameters.Add = self.chbDrawTolerance
Пример #44
0
class ResizeDlg(QDialog):
    def __init__(self, width, height, parent=None):
        super(ResizeDlg, self).__init__(parent)

        widthLabel = QLabel(self.tr("&Width:"))
        self.widthSpinBox = QSpinBox()
        widthLabel.setBuddy(self.widthSpinBox)
        self.widthSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.widthSpinBox.setRange(4, width * 4)
        self.widthSpinBox.setValue(width)
        heightLabel = QLabel(self.tr("&Height:"))
        self.heightSpinBox = QSpinBox()
        heightLabel.setBuddy(self.heightSpinBox)
        self.heightSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.heightSpinBox.setRange(4, height * 4)
        self.heightSpinBox.setValue(height)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)

        layout = QGridLayout()
        layout.addWidget(widthLabel, 0, 0)
        layout.addWidget(self.widthSpinBox, 0, 1)
        layout.addWidget(heightLabel, 1, 0)
        layout.addWidget(self.heightSpinBox, 1, 1)
        layout.addWidget(buttonBox, 2, 0, 1, 2)
        self.setLayout(layout)

        self.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(buttonBox, SIGNAL("rejected()"), self.reject)

        self.setWindowTitle(self.tr("Image Changer - Resize"))

    def result(self):
        return self.widthSpinBox.value(), self.heightSpinBox.value()
Пример #45
0
    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
Пример #46
0
class EditNodeProperties(QDialog):
    def __init__(self, data, win_parent=None):
        """
        +-----------------+
        | Edit Node Props |
        +-----------------+------+
        |  LEwingTip             |
        |  Node2                 |
        |  Node3                 |
        |  Node4                 |
        |                        |
        |  All Nodes:            |
        |    Color     red       |
        |    PointSize 3         |
        |    Opacity   0.3       |
        |    Show/Hide           |
        |                        |
        |  Name        LEwingTip |
        |  Location    X Y Z     |
        |  Coord       0         |
        |  CoordType   R, C, S   |
        |                        |
        |   Previous     Next    |
        |                        |
        |          Close         |
        +------------------------+
        """
        QDialog.__init__(self, win_parent)
        self.setWindowTitle('Edit Node Properties')

        #default
        self.win_parent = win_parent
        self.out_data = data

        point_properties = data['point_properties']
        print(point_properties)
        #name = point_properties.name
        point_size = point_properties.point_size
        opacity = point_properties.opacity
        color = point_properties.color
        show = point_properties.is_visible

        self.points = data['points']

        self.keys = sorted(self.points.keys())
        keys = self.keys
        #nrows = len(keys)

        active_point = data['active_point']
        #self.active_key = keys[0]
        self.active_key = active_point
        name = self.active_key
        description = self.points[self.active_key][0]

        self._use_old_table = False
        items = ['Node %i' % val for val in keys]
        header_labels = ['Nodes']
        table_model = Model(items, header_labels, self)
        view = SingleChoiceQTableView(self)  #Call your custom QTableView here
        view.setModel(table_model)
        if qt_version in [4, 'pyside']:
            view.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        else:
            view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table = view

        #self.representation = actor_obj.representation
        #print('rep =', self.representation)

        table = self.table
        #headers = [QtCore.QString('Groups')]

        header = table.horizontalHeader()
        header.setStretchLastSection(True)

        #----------------------------------------------
        #self._default_is_apply = False

        self.color = QLabel("Color:")
        self.color_edit = QPushButton()
        #self.color_edit.setFlat(True)

        color = self.out_data['point_properties'].color
        opacity = self.out_data['point_properties'].opacity
        show = self.out_data['point_properties'].is_visible
        #color = self.out_data[self.active_key].color
        qcolor = QColor()
        qcolor.setRgb(*color)
        #print('color =%s' % str(color))
        palette = QPalette(
            self.color_edit.palette())  # make a copy of the palette
        #palette.setColor(QPalette.Active, QPalette.Base, \
        #qcolor)
        palette.setColor(QPalette.Background, QColor('blue'))  # ButtonText
        self.color_edit.setPalette(palette)

        self.color_edit.setStyleSheet("QPushButton {"
                                      "background-color: rgb(%s, %s, %s);" %
                                      tuple(color) +
                                      #"border:1px solid rgb(255, 170, 255); "
                                      "}")

        self.all_nodes_header = QLabel("All Nodes:")
        self.point_size = QLabel("Point Size:")
        self.point_size_edit = QSpinBox(self)
        self.point_size_edit.setRange(1, 10)
        self.point_size_edit.setSingleStep(1)
        self.point_size_edit.setValue(point_size)

        self.opacity = QLabel("Opacity:")
        self.opacity_edit = QDoubleSpinBox(self)
        self.opacity_edit.setRange(0.1, 1.0)
        self.opacity_edit.setDecimals(1)
        self.opacity_edit.setSingleStep(0.1)
        self.opacity_edit.setValue(opacity)

        # show/hide
        self.checkbox_show = QCheckBox("Show")
        self.checkbox_hide = QCheckBox("Hide")
        self.checkbox_show.setChecked(show)
        self.checkbox_hide.setChecked(not show)

        #----------------------------------------------
        self.nodes_header = QLabel("Single Node:")
        self.name = QLabel("ID:")
        self.name_edit = QLineEdit('Node %i' % name)
        self.name_edit.setDisabled(True)

        self.description = QLabel("Description:")
        self.description_edit = QLineEdit(str(description))
        #self.description_edit.setDisabled(True)

        location_x = 0.1
        location_y = 0.1
        location_z = 0.1
        self.location = QLabel("Location:")
        self.location_x_edit = QDoubleSpinBox(self)
        self.location_y_edit = QDoubleSpinBox(self)
        self.location_z_edit = QDoubleSpinBox(self)
        #self.location_x_edit.setDecimals(1)
        delta_x = abs(location_x) / 100. if location_x != 0.0 else 0.1
        delta_y = abs(location_y) / 100. if location_y != 0.0 else 0.1
        delta_z = abs(location_z) / 100. if location_z != 0.0 else 0.1
        self.location_x_edit.setSingleStep(delta_x)
        self.location_y_edit.setSingleStep(delta_y)
        self.location_z_edit.setSingleStep(delta_z)
        self.location_x_edit.setValue(location_x)
        self.location_y_edit.setValue(location_y)
        self.location_z_edit.setValue(location_z)

        self.coord = QLabel("Coord:")
        self.coord_edit = QSpinBox(self)
        self.coord_edit.setRange(0, 99999999)
        #self.coord_edit.setSingleStep(1)
        self.coord_edit.setValue(0)

        self.coord_type = QLabel("Coord Type:")
        #----------------------------------------------

        # closing
        #if self._default_is_apply:
        #self.apply_button.setDisabled(True)

        self.close_button = QPushButton("Close")

        self.create_layout()
        self.set_connections()

    def update_active_key(self, index):
        name = self.active_key
        old_obj = self.out_data['points'][name]
        #self.active_key
        #self.points[self.active_key]
        old_obj[0] = str(self.description_edit.text())
        #old_obj.coord = self.description_edit.value()
        #old_obj.description = self.description_edit.value()
        #old_obj.description = self.description_edit.value()

        str_name = str(index.data().toString())
        name = int(str_name[5:])
        #i = self.keys.index(self.active_key)

        self.active_key = name
        point = self.points[self.active_key]

        #1  : ['LERoot', 0, 'R', 1.0, 2.0, 3.0],
        self.name_edit.setText(str(self.active_key))
        self.description_edit.setText(point[0])

        self.coord_edit.setValue(point[1])
        if point[2] == 'R':
            self.radio_rectangular.setChecked(True)
        elif point[2] == 'C':
            self.radio_cylindrical.setChecked(True)
        elif point[2] == 'S':
            self.radio_spherical.setChecked(True)

        self.location_x_edit.setValue(point[3])
        self.location_y_edit.setValue(point[4])
        self.location_z_edit.setValue(point[5])
        #obj = self.out_data[name]
        #point_size = obj.point_size
        #opacity = obj.opacity
        #representation = obj.representation
        #is_visible = obj.is_visible

        #self.opacity_edit.setValue(opacity)
        #self.checkbox_show.setChecked(is_visible)
        #self.checkbox_hide.setChecked(not is_visible)

    #def on_name_select(self):
    #print('on_name_select')
    #return

    def create_layout(self):
        cancel_box = QHBoxLayout()
        cancel_box.addWidget(self.close_button)

        grid1 = QGridLayout()
        grid2 = QGridLayout()

        #-----------------------------------------
        # setup
        self.radio_rectangular = QRadioButton('Rectangular')
        self.radio_cylindrical = QRadioButton('Cylindrical')
        self.radio_spherical = QRadioButton('Spherical')

        coord_type_layout = QHBoxLayout()
        coord_type_layout.addWidget(self.radio_rectangular)
        coord_type_layout.addWidget(self.radio_cylindrical)
        coord_type_layout.addWidget(self.radio_spherical)

        location_layout = QHBoxLayout()
        location_layout.addWidget(self.location_x_edit)
        location_layout.addWidget(self.location_y_edit)
        location_layout.addWidget(self.location_z_edit)

        checkboxs = QButtonGroup(self)
        checkboxs.addButton(self.checkbox_show)
        checkboxs.addButton(self.checkbox_hide)

        vbox1 = QVBoxLayout()
        vbox1.addWidget(self.checkbox_show)
        vbox1.addWidget(self.checkbox_hide)
        #vbox1.addLayout(checkboxs)

        #-----------------------------------------
        irow = 0
        grid1.addWidget(self.all_nodes_header, irow, 0)
        irow += 1

        grid1.addWidget(self.color, irow, 0)
        grid1.addWidget(self.color_edit, irow, 1)
        irow += 1

        grid1.addWidget(self.opacity, irow, 0)
        grid1.addWidget(self.opacity_edit, irow, 1)
        irow += 1

        grid1.addWidget(self.point_size, irow, 0)
        grid1.addWidget(self.point_size_edit, irow, 1)
        irow += 1

        #-----------------------------------------
        irow = 0
        grid2.addWidget(self.nodes_header, irow, 0)
        irow += 1

        grid2.addWidget(self.name, irow, 0)
        grid2.addWidget(self.name_edit, irow, 1)
        irow += 1

        grid2.addWidget(self.description, irow, 0)
        grid2.addWidget(self.description_edit, irow, 1)
        irow += 1

        #|  All Nodes:            |
        #|    Color     red       |
        #|    PointSize 3         |
        #|    Opacity   0.3       |
        #|    Show/Hide           |
        #|                        |
        #|  Name        LEwingTip |
        #|  Location    X Y Z     |
        #|  Coord       0         |
        #|  CoordType   R, C, S   |
        #|                        |
        #|   Previous     Next    |
        grid2.addWidget(self.coord, irow, 0)
        grid2.addWidget(self.coord_edit, irow, 1)
        irow += 1

        grid2.addWidget(self.coord_type, irow, 0)
        grid2.addLayout(coord_type_layout, irow, 1)
        irow += 1

        grid2.addWidget(self.location, irow, 0)
        grid2.addLayout(location_layout, irow, 1)
        irow += 1

        #------------------------------------

        vbox = QVBoxLayout()
        vbox.addLayout(grid1)
        vbox.addLayout(vbox1)
        vbox.addStretch()
        vbox.addWidget(self.table)

        vbox.addLayout(grid2)
        vbox.addStretch()
        #vbox.addWidget(self.check_apply)
        vbox.addLayout(cancel_box)
        self.setLayout(vbox)

    def set_connections(self):
        if qt_version == 4:
            self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'),
                         self.on_opacity)
            self.connect(self.point_size, QtCore.SIGNAL('clicked()'),
                         self.on_point_size)
            self.connect(self.color_edit, QtCore.SIGNAL('clicked()'),
                         self.on_color)
            self.connect(self.checkbox_show, QtCore.SIGNAL('clicked()'),
                         self.on_show)
            self.connect(self.checkbox_hide, QtCore.SIGNAL('clicked()'),
                         self.on_hide)

            self.connect(self.description_edit,
                         QtCore.SIGNAL("valueChanged(int)"),
                         self.on_description)
            self.connect(self.coord_edit, QtCore.SIGNAL("valueChanged(int)"),
                         self.on_coord)
            self.connect(self.radio_rectangular, QtCore.SIGNAL('clicked()'),
                         self.on_coord_type)
            self.connect(self.radio_cylindrical, QtCore.SIGNAL('clicked()'),
                         self.on_coord_type)
            self.connect(self.radio_spherical, QtCore.SIGNAL('clicked()'),
                         self.on_coord_type)

            self.connect(self.location_x_edit, QtCore.SIGNAL('clicked()'),
                         self.on_location_x)
            self.connect(self.location_y_edit, QtCore.SIGNAL('clicked()'),
                         self.on_location_y)
            self.connect(self.location_z_edit, QtCore.SIGNAL('clicked()'),
                         self.on_location_z)

            self.connect(self.close_button, QtCore.SIGNAL('clicked()'),
                         self.on_close)

            #self.connect(self.check_apply, QtCore.SIGNAL('clicked()'), self.on_check_apply)

            #self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply)
            #self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok)
            #self.connect(self.close_button, QtCore.SIGNAL('clicked()'), self.on_close)
        else:
            pass
            #self.opacity_edit.clicked.connect(self.on_opacity)
            #self.point_size.clicked.connect(self.on_point_size)
            #self.color_edit.clicked.connect(self.on_color)
            #self.checkbox_show.clicked.connect(self.on_show)
            #self.checkbox_hide.clicked.connect(self.on_hide)

            #self.description_edit.valueChanged.connect(self.on_description)
            #self.coord_edit.valueChanged.connect(self.on_coord)
            #self.radio_rectangular.clicked.connect(self.on_coord_type)
            #self.radio_cylindrical.clicked.connect(self.on_coord_type)
            #self.radio_spherical.clicked.connect(self.on_coord_type)

            #self.location_x_edit.clicked.connect(self.on_location_x)
            #self.location_y_edit.clicked.connect(self.on_location_y)
            #self.location_z_edit.clicked.connect(self.on_location_z)
            self.close_button.clicked.connect(self.on_close)

    def on_color(self):
        obj = self.out_data['point_properties']
        rgb_color_ints = obj.color

        msg = 'Points'
        col = QColorDialog.getColor(QColor(*rgb_color_ints), self,
                                    "Choose a %s color" % msg)
        if col.isValid():
            color = col.getRgbF()[:3]
            obj.color = color
            #print('new_color =', color)
            self.color_edit.setStyleSheet(
                "QPushButton {"
                "background-color: rgb(%s, %s, %s);" % tuple(obj.color) +
                #"border:1px solid rgb(255, 170, 255); "
                "}")

    def on_show(self):
        is_checked = self.checkbox_show.isChecked()
        self.out_data['point_properties'].is_visible = is_checked

    def on_hide(self):
        is_checked = self.checkbox_hide.isChecked()
        self.out_data['point_properties'].is_visible = not is_checked

    def on_point_size(self):
        point_size = self.point_size_edit.value()
        self.out_data['point_properties'].point_size = point_size

    def on_opacity(self):
        opacity = self.opacity_edit.value()
        self.out_data['point_properties'].opacity = opacity

    def on_description(self):
        #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0],
        name = self.active_key
        description = self.description_edit.value()
        self.out_data['points'][name][0] = description

    def on_coord(self):
        #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0],
        name = self.active_key
        coord_id = self.coord_edit.value()
        self.out_data['points'][name][1] = coord_id

    def on_coord_type(self):
        #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0],
        name = self.active_key
        if self.radio_rectangular.isChecked():
            coord_type = 'R'
        elif self.radio_cylindrical.isChecked():
            coord_type = 'C'
        elif self.radio_spherical.isChecked():
            coord_type = 'S'
        else:
            raise NotImplementedError()
        self.out_data['points'][name][2] = coord_type

    def on_location_x(self):
        #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0],
        name = self.active_key
        value = self.coord_edit.value()
        self.out_data['points'][name][3] = value

    def on_location_y(self):
        #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0],
        name = self.active_key
        value = self.coord_edit.value()
        self.out_data['points'][name][4] = value

    def on_location_z(self):
        #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0],
        name = self.active_key
        value = self.coord_edit.value()
        self.out_data['points'][name][5] = value

    def closeEvent(self, event):
        event.accept()

    #def on_default_name(self):
    #self.name_edit.setText(str(self._default_name))
    #self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    #def check_float(self, cell):
    #text = cell.text()
    #try:
    #value = eval_float_from_string(text)
    #cell.setStyleSheet("QLineEdit{background: white;}")
    #return value, True
    #except ValueError:
    #cell.setStyleSheet("QLineEdit{background: red;}")
    #return None, False

    #def check_name(self, cell):
    #text = str(cell.text()).strip()
    #if len(text):
    #cell.setStyleSheet("QLineEdit{background: white;}")
    #return text, True
    #else:
    #cell.setStyleSheet("QLineEdit{background: red;}")
    #return None, False

    def on_validate(self):
        self.out_data['clicked_ok'] = True
        self.out_data['clicked_cancel'] = False

        old_obj = self.out_data[self.active_key]
        old_obj.point_size = self.point_size_edit.value()
        old_obj.opacity = self.opacity_edit.value()
        old_obj.is_visible = self.checkbox_show.isChecked()
        return True
        #name_value, flag0 = self.check_name(self.name_edit)
        #ox_value, flag1 = self.check_float(self.transparency_edit)
        #if flag0 and flag1:
        #self.out_data['clicked_ok'] = True
        #return True
        #return False

    def on_apply(self):
        passed = self.on_validate()
        if passed:
            self.win_parent.on_update_gui_nodes(self.out_data)
        return passed

    def on_ok(self):
        passed = self.on_apply()
        if passed:
            self.close()
            #self.destroy()

    def on_close(self):
        self.out_data['clicked_close'] = True
        self.close()
Пример #47
0
#!/usr/bin/env python
#coding=utf-8

from PyQt4.QtCore import Qt, QObject, SIGNAL, SLOT
from PyQt4.QtGui import QApplication
from PyQt4.QtGui import QWidget, QSpinBox, QSlider, QHBoxLayout
import sys

if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = QWidget()
    window.setWindowTitle("Enter Your Age")

    spinBox = QSpinBox()
    slider = QSlider(Qt.Horizontal)
    spinBox.setRange(0, 130)
    slider.setRange(0, 130)

    QObject.connect(spinBox, SIGNAL("valueChanged(int)"), slider,
                    SLOT("setValue(int)"))

    QObject.connect(slider, SIGNAL("valueChanged(int)"), spinBox,
                    SLOT("setValue(int)"))

    spinBox.setValue(35)

    layout = QHBoxLayout()  # 水平布局
    layout.addWidget(spinBox)  # 添加 水平 布局
    layout.addWidget(slider)  # 添加 水平 布局
Пример #48
0
    def __init__(self, parent, resoution = "0.0000"):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("NumberBoxPanel" + str(len(parent.findChildren(NumberBoxPanel))))


        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0,0,0,0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        if resoution != None:
            self.numberBox = QLineEdit(self.frameBoxPanel)
            self.numberBox.setEnabled(True)
            font = QFont()
            font.setBold(False)
            font.setWeight(50)
            self.numberBox.setFont(font)
            self.numberBox.setObjectName(self.objectName() + "_numberBox")
            self.numberBox.setText("0.0")
            self.numberBox.setMinimumWidth(70)
            self.numberBox.setMaximumWidth(70)
            self.hLayoutframeBoxPanel.addWidget(self.numberBox)
            self.numberBox.textChanged.connect(self.numberBoxChanged)
            self.numberBox.editingFinished.connect(self.numberBoxEditingFinished)
        else:
            self.numberBox = QSpinBox(self.frameBoxPanel)
            self.numberBox.setObjectName(self.objectName() + "_numberBox")
            self.numberBox.setMinimumWidth(70)
            self.numberBox.setMaximumWidth(70)
            self.numberBox.setMinimum(-100000000)
            self.numberBox.setMaximum(100000000)
            self.numberBox.setValue(1)
            self.hLayoutframeBoxPanel.addWidget(self.numberBox)

        self.imageButton = QPushButton(self.frameBoxPanel)

        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)


        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.numberResolution = resoution
        str0 = String.Number2String(6.6788, "0.0000")
        self.Value = 0
        self.captionUnits = ""
Пример #49
0
class PreferencesWindow(PyDialog):
    """
    +-------------+
    | Preferences |
    +------------------------------+
    | Text Size     ______ Default |
    | Label Color   ______         |
    | Label Size    ______         |
    | Picker Size   ______         |
    | Back Color    ______         |
    | Text Color    ______         |
    |                              |
    |       Apply OK Cancel        |
    +------------------------------+
    """
    def __init__(self, data, win_parent=None):
        """
        Saves the data members from data and
        performs type checks
        """
        PyDialog.__init__(self, data, win_parent)

        self._updated_preference = False

        self._default_font_size = data['font_size']
        self._default_clipping_min = data['clipping_min']
        self._default_clipping_max = data['clipping_max']

        #label_color_float = data['label_color']
        self._label_size = data['label_size']
        #self.out_data = data
        self.dim_max = data['dim_max']
        self._picker_size = data['picker_size'] * 100.

        self.label_color_float, self.label_color_int = _check_color(data['label_color'])
        self.background_color_float, self.background_color_int = _check_color(
            data['background_color'])
        self.text_color_float, self.text_color_int = _check_color(data['text_color'])

        #self.setupUi(self)
        self.setWindowTitle('Preferences')
        self.create_widgets()
        self.create_layout()
        self.set_connections()
        self.on_set_font(self._default_font_size)
        #self.show()

    def create_widgets(self):
        """creates the display window"""
        # Text Size
        self.font_size = QLabel("Text Size:")
        self.font_size_edit = QSpinBox(self)
        self.font_size_edit.setValue(self._default_font_size)
        self.font_size_edit.setRange(7, 20)
        self.font_size_button = QPushButton("Default")

        #-----------------------------------------------------------------------
        # Annotation Color
        self.label_color = QLabel("Label Color:")
        self.label_color_edit = QPushButtonColor(self.label_color_int)

        # Background Color
        self.background_color = QLabel("Background Color:")
        self.background_color_edit = QPushButtonColor(self.background_color_int)

        # Label Color
        self.text_color = QLabel("Text Color:")
        self.text_color_edit = QPushButtonColor(self.text_color_int)

        #-----------------------------------------------------------------------
        # Label Size
        self.label_size = QLabel("Label Size (3D Text):")
        self.label_size_edit = QDoubleSpinBox(self)
        self.label_size_edit.setRange(0.0, self.dim_max)

        log_dim = log10(self.dim_max)
        decimals = int(ceil(abs(log_dim)))
        decimals = max(6, decimals)
        self.label_size_edit.setDecimals(decimals)
        #self.label_size_edit.setSingleStep(self.dim_max / 100.)
        self.label_size_edit.setSingleStep(self.dim_max / 1000.)
        self.label_size_edit.setValue(self._label_size)

        #-----------------------------------------------------------------------
        # Picker Size
        self.picker_size = QLabel("Picker Size (% of Screen):")
        self.picker_size_edit = QDoubleSpinBox(self)
        self.picker_size_edit.setRange(0., 10.)

        log_dim = log10(self.dim_max)
        decimals = int(ceil(abs(log_dim)))

        decimals = max(6, decimals)
        self.picker_size_edit.setDecimals(decimals)
        self.picker_size_edit.setSingleStep(10. / 5000.)
        self.picker_size_edit.setValue(self._picker_size)

        #-----------------------------------------------------------------------
        # Clipping Min
        self.clipping_min = QLabel("Clipping Min:")
        self.clipping_min_edit = QLineEdit(str(self._default_clipping_min))
        self.clipping_min_button = QPushButton("Default")

        # Clipping Max
        self.clipping_max = QLabel("Clipping Max:")
        self.clipping_max_edit = QLineEdit(str(self._default_clipping_max))
        self.clipping_max_button = QPushButton("Default")

        #-----------------------------------------------------------------------
        # closing
        self.apply_button = QPushButton("Apply")
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")

    def create_layout(self):
        grid = QGridLayout()

        grid.addWidget(self.font_size, 0, 0)
        grid.addWidget(self.font_size_edit, 0, 1)
        grid.addWidget(self.font_size_button, 0, 2)

        grid.addWidget(self.background_color, 1, 0)
        grid.addWidget(self.background_color_edit, 1, 1)

        grid.addWidget(self.text_color, 2, 0)
        grid.addWidget(self.text_color_edit, 2, 1)

        grid.addWidget(self.label_color, 3, 0)
        grid.addWidget(self.label_color_edit, 3, 1)

        grid.addWidget(self.label_size, 4, 0)
        grid.addWidget(self.label_size_edit, 4, 1)

        grid.addWidget(self.picker_size, 5, 0)
        grid.addWidget(self.picker_size_edit, 5, 1)

        #grid.addWidget(self.clipping_min, 6, 0)
        #grid.addWidget(self.clipping_min_edit, 6, 1)
        #grid.addWidget(self.clipping_min_button, 6, 2)

        #grid.addWidget(self.clipping_max, 7, 0)
        #grid.addWidget(self.clipping_max_edit, 7, 1)
        #grid.addWidget(self.clipping_max_button, 7, 2)

        ok_cancel_box = QHBoxLayout()
        ok_cancel_box.addWidget(self.apply_button)
        ok_cancel_box.addWidget(self.ok_button)
        ok_cancel_box.addWidget(self.cancel_button)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)

        vbox.addStretch()
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)

    def set_connections(self):
        self.font_size_button.clicked.connect(self.on_default_font_size)
        self.font_size_edit.valueChanged.connect(self.on_set_font)

        self.label_size_edit.editingFinished.connect(self.on_label_size)
        self.label_size_edit.valueChanged.connect(self.on_label_size)
        self.label_color_edit.clicked.connect(self.on_label_color)

        self.background_color_edit.clicked.connect(self.on_background_color)
        self.text_color_edit.clicked.connect(self.on_text_color)

        self.picker_size_edit.valueChanged.connect(self.on_picker_size)
        self.picker_size_edit.editingFinished.connect(self.on_picker_size)
        self.picker_size_edit.valueChanged.connect(self.on_picker_size)

        self.clipping_min_button.clicked.connect(self.on_default_clipping_min)
        self.clipping_max_button.clicked.connect(self.on_default_clipping_max)

        self.apply_button.clicked.connect(self.on_apply)
        self.ok_button.clicked.connect(self.on_ok)
        self.cancel_button.clicked.connect(self.on_cancel)
        # closeEvent

    def on_set_font(self, value=None):
        """update the font for the current window"""
        if value is None:
            value = self.font_size_edit.value()
        font = QtGui.QFont()
        font.setPointSize(value)
        self.setFont(font)

    def update_label_size_color(self):
        if self.win_parent is not None:
            self.win_parent.set_labelsize_color(self._label_size, self.label_color_float)

    def on_label_color(self):
        rgb_color_ints = self.label_color_int
        title = "Choose a label color"
        passed, rgb_color_ints, rgb_color_floats = self.on_color(
            self.label_color_edit, rgb_color_ints, title)
        if passed:
            self.label_color_int = rgb_color_ints
            self.label_color_float = rgb_color_floats
            self.update_label_size_color()

    def on_background_color(self):
        """ Choose a background color """
        rgb_color_ints = self.background_color_int
        title = "Choose a background color"
        passed, rgb_color_ints, rgb_color_floats = self.on_color(
            self.background_color_edit, rgb_color_ints, title)
        if passed:
            self.background_color_int = rgb_color_ints
            self.background_color_float = rgb_color_floats
            if self.win_parent is not None:
                self.win_parent.set_background_color(rgb_color_floats)

    def on_text_color(self):
        """ Choose a text color """
        rgb_color_ints = self.text_color_int
        title = "Choose a text color"
        passed, rgb_color_ints, rgb_color_floats = self.on_color(
            self.text_color_edit, rgb_color_ints, title)
        if passed:
            self.text_color_int = rgb_color_ints
            self.text_color_float = rgb_color_floats
            if self.win_parent is not None:
                self.win_parent.set_text_color(rgb_color_floats)

    def on_color(self, color_edit, rgb_color_ints, title):
        """pops a color dialog"""
        col = QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self,
                                    title)
        if not col.isValid():
            return False, rgb_color_ints, None

        color_float = col.getRgbF()[:3]  # floats
        color_int = [int(colori * 255) for colori in color_float]

        assert isinstance(color_float[0], float), color_float
        assert isinstance(color_int[0], int), color_int

        color_edit.setStyleSheet(
            "QPushButton {"
            "background-color: rgb(%s, %s, %s);" % tuple(color_int) +
            #"border:1px solid rgb(255, 170, 255); "
            "}")
        return True, color_int, color_float

    def on_label_size(self):
        self._label_size = float(self.label_size_edit.text())
        #self.on_apply(force=True)
        #self.min_edit.setText(str(self._default_min))
        #self.min_edit.setStyleSheet("QLineEdit{background: white;}")
        self.update_label_size_color()

    def on_picker_size(self):
        self._picker_size = float(self.picker_size_edit.text())
        if self.win_parent is not None:
            self.win_parent.element_picker_size = self._picker_size / 100.
        #self.on_apply(force=True)

    def on_default_font_size(self):
        self.font_size_edit.setValue(self._default_font_size)
        self.on_set_font(self._default_font_size)

    def on_default_clipping_min(self):
        self.clipping_min_edit.setText(str(self._default_clipping_min))
        self.clipping_min_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_clipping_max(self):
        self.clipping_max_edit.setText(str(self._default_clipping_max))
        self.clipping_max_edit.setStyleSheet("QLineEdit{background: white;}")

    @staticmethod
    def check_float(cell):
        text = cell.text()
        value = float(text)
        return value, True

    @staticmethod
    def check_label_float(cell):
        text = cell.text()
        try:
            value = eval_float_from_string(text)
            cell.setStyleSheet("QLineEdit{background: white;}")
            return value, True
        except ValueError:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    def on_validate(self):
        font_size_value, flag0 = self.check_float(self.font_size_edit)
        label_size_value, flag1 = self.check_float(self.label_size_edit)
        assert isinstance(self.label_color_float[0], float), self.label_color_float
        assert isinstance(self.label_color_int[0], int), self.label_color_int
        picker_size_value, flag2 = self.check_float(self.picker_size_edit)

        clipping_min_value, flag3 = self.check_label_float(self.clipping_min_edit)
        clipping_max_value, flag4 = self.check_label_float(self.clipping_max_edit)

        if all([flag0, flag1, flag2, flag3, flag4]):
            self._label_size = label_size_value
            self._picker_size = picker_size_value

            self.out_data['font_size'] = int(font_size_value)
            self.out_data['clipping_min'] = min(clipping_min_value, clipping_max_value)
            self.out_data['clipping_max'] = max(clipping_min_value, clipping_max_value)
            self.out_data['clicked_ok'] = True
            return True
        return False

    def on_apply(self, force=False):
        passed = self.on_validate()
        if (passed or force) and self.win_parent is not None:
            self.win_parent.on_set_font_size(self.out_data['font_size'])

            #self.win_parent.set_labelsize_color(self._label_size, self.label_color_float)
            #self.win_parent.element_picker_size = self._picker_size / 100.
        if passed and self.win_parent is not None:
            self.win_parent._apply_clipping(self.out_data)
        return passed

    def on_ok(self):
        passed = self.on_apply()
        if passed:
            self.close()
            #self.destroy()

    def on_cancel(self):
        self.out_data['close'] = True
        self.close()
Пример #50
0
class NumberFormatDlg(QDialog):

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

        thousandsLabel = QLabel("&Thousands separator")
        self.thousandsEdit = QLineEdit(format["thousandsseparator"])
        thousandsLabel.setBuddy(self.thousandsEdit)
        decimalMarkerLabel = QLabel("Decimal &marker")
        self.decimalMarkerEdit = QLineEdit(format["decimalmarker"])
        decimalMarkerLabel.setBuddy(self.decimalMarkerEdit)
        decimalPlacesLabel = QLabel("&Decimal places")
        self.decimalPlacesSpinBox = QSpinBox()
        decimalPlacesLabel.setBuddy(self.decimalPlacesSpinBox)
        self.decimalPlacesSpinBox.setRange(0, 6)
        self.decimalPlacesSpinBox.setValue(format["decimalplaces"])
        self.redNegativesCheckBox = QCheckBox("&Red negative numbers")
        self.redNegativesCheckBox.setChecked(format["rednegatives"])

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                     QDialogButtonBox.Cancel)

        self.format = format.copy()

        grid = QGridLayout()
        grid.addWidget(thousandsLabel, 0, 0)
        grid.addWidget(self.thousandsEdit, 0, 1)
        grid.addWidget(decimalMarkerLabel, 1, 0)
        grid.addWidget(self.decimalMarkerEdit, 1, 1)
        grid.addWidget(decimalPlacesLabel, 2, 0)
        grid.addWidget(self.decimalPlacesSpinBox, 2, 1)
        grid.addWidget(self.redNegativesCheckBox, 3, 0, 1, 2)
        grid.addWidget(buttonBox, 4, 0, 1, 2)
        self.setLayout(grid)

        self.connect(buttonBox, SIGNAL("accepted()"),
                     self, SLOT("accept()"))
        self.connect(buttonBox, SIGNAL("rejected()"),
                     self, SLOT("reject()"))
        self.setWindowTitle("Set Number Format (Modal)")


    def accept(self):
        class ThousandsError(Exception): pass
        class DecimalError(Exception): pass
        Punctuation = frozenset(" ,;:.")

        thousands = unicode(self.thousandsEdit.text())
        decimal = unicode(self.decimalMarkerEdit.text())
        try:
            if len(decimal) == 0:
                raise DecimalError, ("The decimal marker may not be "
                                     "empty.")
            if len(thousands) > 1:
                raise ThousandsError, ("The thousands separator may "
                                       "only be empty or one character.")
            if len(decimal) > 1:
                raise DecimalError, ("The decimal marker must be "
                                     "one character.")
            if thousands == decimal:
                raise ThousandsError, ("The thousands separator and "
                              "the decimal marker must be different.")
            if thousands and thousands not in Punctuation:
                raise ThousandsError, ("The thousands separator must "
                                       "be a punctuation symbol.")
            if decimal not in Punctuation:
                raise DecimalError, ("The decimal marker must be a "
                                     "punctuation symbol.")
        except ThousandsError, e:
            QMessageBox.warning(self, "Thousands Separator Error",
                                unicode(e))
            self.thousandsEdit.selectAll()
            self.thousandsEdit.setFocus()
            return
        except DecimalError, e:
            QMessageBox.warning(self, "Decimal Marker Error",
                                unicode(e))
            self.decimalMarkerEdit.selectAll()
            self.decimalMarkerEdit.setFocus()
            return
Пример #51
0
    def __init__(self, bpms, cors, parent = None):
        super(OrbitCorrGeneral, self).__init__(parent)

        self.bpms, self.cors = bpms, cors
        self.sb = [bpm.sb for bpm in self.bpms]
        self.x0, self.y0 = None, None
        self._update_current_orbit()

        self.table = QTableWidget(len(self.bpms), 9)
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table.setHorizontalHeaderLabels(
            ['BPM Name', 's', "Beta X", "Beta Y",
             "Eta X", 'X Bump', 'Y Bump', "Target X", "Target Y"])
        self._twiss = getTwiss([b.name for b in self.bpms],
                               ["s", "betax", "betay", "etax"])
        for i,bpm in enumerate(self.bpms):
            it = QTableWidgetItem(bpm.name)
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            self.table.setItem(i, 0, it)

            it = QTableWidgetItem(str(bpm.sb))
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            #it.setMinimumWidth(80)
            self.table.setItem(i, 1, it)
            self.table.setItem(i, 2,
                               QTableWidgetItem("%.4f" % self._twiss[i,1]))
            self.table.setItem(i, 3,
                               QTableWidgetItem("%.4f" % self._twiss[i,2]))
            self.table.setItem(i, 4,
                               QTableWidgetItem("%.4f" % self._twiss[i,3]))

            for j in range(5, 9):
                it = QTableWidgetItem(str(0.0))
                it.setData(Qt.DisplayRole, str(0.0))
                it.setFlags(it.flags() | Qt.ItemIsEditable)
                self.table.setItem(i, j, it) 
            # use the current orbit 
            #self.table.item(i,4).setData(Qt.DisplayRole, str(self.x0[i]))
            #self.table.item(i,5).setData(Qt.DisplayRole, str(self.y0[i]))

        #self.connect(self.table, SIGNAL("cellClicked(int, int)"),
        #             self._cell_clicked)
        self.table.resizeColumnsToContents()
        #self.table.horizontalHeader().setStretchLastSection(True)
        #for i in range(4):
        #    print "width", i, self.table.columnWidth(i)
        #self.table.setColumnWidth(0, 300)
        self.table.setColumnWidth(1, 80)

        vbox1 = QtGui.QVBoxLayout()
        frmbox = QFormLayout()
        self.base_orbit_box = QtGui.QComboBox()
        #self.base_orbit_box.addItems([
        #        "Current Orbit", "All Zeros"])
        self.base_orbit_box.addItems(["All Zeros", "Current Orbit"])
        frmbox.addRow("Orbit Base", self.base_orbit_box)
        grp = QtGui.QGroupBox("Local Bump")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        frmbox = QFormLayout()
        hln1 = QtGui.QFrame()
        hln1.setLineWidth(3)
        hln1.setFrameStyle(QtGui.QFrame.Sunken)
        hln1.setFrameShape(QtGui.QFrame.HLine)
        frmbox.addRow(hln1)
        self.repeatbox = QSpinBox()
        self.repeatbox.setRange(1, 20)
        self.repeatbox.setValue(3)
        # or connect the returnPressed() signal
        frmbox.addRow("&Repeat correction", self.repeatbox)

        self.rcondbox = QLineEdit()
        self.rcondbox.setValidator(QDoubleValidator(0, 1, 0, self))
        self.rcondbox.setText("1e-2")
        frmbox.addRow("r&cond for SVD", self.rcondbox)

        self.scalebox = QDoubleSpinBox()
        self.scalebox.setRange(0.01, 5.00)
        self.scalebox.setSingleStep(0.01)
        self.scalebox.setValue(0.68)
        frmbox.addRow("&Scale correctors", self.scalebox)

        #hln2 = QtGui.QFrame()
        #hln2.setLineWidth(3)
        #hln2.setFrameStyle(QtGui.QFrame.Sunken)
        #hln2.setFrameShape(QtGui.QFrame.HLine)
        #frmbox.addRow(hln2)

        self.progress = QProgressBar()
        self.progress.setMaximum(self.repeatbox.value())
        self.progress.setMaximumHeight(15)
        frmbox.addRow("Progress", self.progress)
        grp = QtGui.QGroupBox("Correction")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        #vbox.addStretch(1.0)
        #self.qdb = QDialogButtonBox(self)
        #self.qdb.addButton("APP", QDialogButtonBox.ApplyRole)
        #self.qdb.addButton("R", QDialogButtonBox.ResetRole)
        #btn.setDefault(True)
        #self.qdb.addButton(QDialogButtonBox.Cancel)
        #self.qdb.addButton(QDialogButtonBox.Help)

        gbox = QtGui.QGridLayout()
        btn = QPushButton("Clear")
        self.connect(btn, SIGNAL("clicked()"), self.resetBumps)
        gbox.addWidget(btn, 0, 1)
        self.correctOrbitBtn = QPushButton("Apply")
        #self.correctOrbitBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.correctOrbitBtn.setStyleSheet("QPushButton:disabled { color: gray }");
        self.connect(self.correctOrbitBtn, SIGNAL("clicked()"), self.call_apply)
        self.correctOrbitBtn.setDefault(True)
        gbox.addWidget(self.correctOrbitBtn, 1, 1)
        gbox.setColumnStretch(0, 1)

        vbox1.addStretch()
        vbox1.addLayout(gbox)
        
        hbox1 = QtGui.QHBoxLayout()
        hbox1.addWidget(self.table, 2)
        hbox1.addLayout(vbox1, 0)
        self.setLayout(hbox1)

        self.connect(self.base_orbit_box,
                     SIGNAL("currentIndexChanged(QString)"), 
                     self.updateTargetOrbit)
        self.connect(self.repeatbox, SIGNAL("valueChanged(int)"),
                     self.progress.setMaximum)
        self.connect(self.table, SIGNAL("cellChanged (int, int)"),
                     self.updateBump)
Пример #52
0
class Indenting(preferences.Group):
    def __init__(self, page):
        super(Indenting, self).__init__(page)

        layout = QGridLayout(spacing=1)
        self.setLayout(layout)

        self.tabwidthBox = QSpinBox(minimum=1, maximum=99)
        self.tabwidthLabel = l = QLabel()
        l.setBuddy(self.tabwidthBox)

        self.nspacesBox = QSpinBox(minimum=0, maximum=99)
        self.nspacesLabel = l = QLabel()
        l.setBuddy(self.nspacesBox)

        self.dspacesBox = QSpinBox(minimum=0, maximum=99)
        self.dspacesLabel = l = QLabel()
        l.setBuddy(self.dspacesBox)

        layout.addWidget(self.tabwidthLabel, 0, 0)
        layout.addWidget(self.tabwidthBox, 0, 1)
        layout.addWidget(self.nspacesLabel, 1, 0)
        layout.addWidget(self.nspacesBox, 1, 1)
        layout.addWidget(self.dspacesLabel, 2, 0)
        layout.addWidget(self.dspacesBox, 2, 1)

        self.tabwidthBox.valueChanged.connect(page.changed)
        self.nspacesBox.valueChanged.connect(page.changed)
        self.dspacesBox.valueChanged.connect(page.changed)
        self.translateUI()

    def translateUI(self):
        self.setTitle(_("Indenting Preferences"))
        self.tabwidthLabel.setText(_("Visible Tab Width:"))
        self.tabwidthBox.setToolTip(_(
            "The visible width of a Tab character in the editor."))
        self.nspacesLabel.setText(_("Indent text with:"))
        self.nspacesBox.setToolTip(_(
            "How many spaces to use for indenting one level.\n"
            "Move to zero to use a Tab character for indenting."))
        self.nspacesBox.setSpecialValueText(_("Tab"))
        self.dspacesLabel.setText(_("Tab outside indent inserts:"))
        self.dspacesBox.setToolTip(_(
            "How many spaces to insert when Tab is pressed outside the indent, "
            "elsewhere in the document.\n"
            "Move to zero to insert a literal Tab character in this case."))
        self.nspacesBox.setSpecialValueText(_("Tab"))
        self.dspacesBox.setSpecialValueText(_("Tab"))
        # L10N: abbreviation for "n spaces" in spinbox, n >= 1, no plural forms
        prefix, suffix = _("{num} spaces").split("{num}")
        self.nspacesBox.setPrefix(prefix)
        self.nspacesBox.setSuffix(suffix)
        self.dspacesBox.setPrefix(prefix)
        self.dspacesBox.setSuffix(suffix)

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("indent")
        self.tabwidthBox.setValue(s.value("tab_width", 8, int))
        self.nspacesBox.setValue(s.value("indent_spaces", 2, int))
        self.dspacesBox.setValue(s.value("document_spaces", 8, int))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("indent")
        s.setValue("tab_width", self.tabwidthBox.value())
        s.setValue("indent_spaces", self.nspacesBox.value())
        s.setValue("document_spaces", self.dspacesBox.value())
Пример #53
0
 def sizeHint(self, option, index):
     return QSpinBox().sizeHint()
Пример #54
0
    def __init__(self, data, win_parent=None):
        """
        +-----------------+
        | Edit Node Props |
        +-----------------+------+
        |  LEwingTip             |
        |  Node2                 |
        |  Node3                 |
        |  Node4                 |
        |                        |
        |  All Nodes:            |
        |    Color     red       |
        |    PointSize 3         |
        |    Opacity   0.3       |
        |    Show/Hide           |
        |                        |
        |  Name        LEwingTip |
        |  Location    X Y Z     |
        |  Coord       0         |
        |  CoordType   R, C, S   |
        |                        |
        |   Previous     Next    |
        |                        |
        |          Close         |
        +------------------------+
        """
        QDialog.__init__(self, win_parent)
        self.setWindowTitle('Edit Node Properties')

        #default
        self.win_parent = win_parent
        self.out_data = data

        point_properties = data['point_properties']
        print(point_properties)
        #name = point_properties.name
        point_size = point_properties.point_size
        opacity = point_properties.opacity
        color = point_properties.color
        show = point_properties.is_visible

        self.points = data['points']

        self.keys = sorted(self.points.keys())
        keys = self.keys
        #nrows = len(keys)

        active_point = data['active_point']
        #self.active_key = keys[0]
        self.active_key = active_point
        name = self.active_key
        description = self.points[self.active_key][0]

        self._use_old_table = False
        items = ['Node %i' % val for val in keys]
        header_labels = ['Nodes']
        table_model = Model(items, header_labels, self)
        view = SingleChoiceQTableView(self)  #Call your custom QTableView here
        view.setModel(table_model)
        if qt_version in [4, 'pyside']:
            view.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        else:
            view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table = view

        #self.representation = actor_obj.representation
        #print('rep =', self.representation)

        table = self.table
        #headers = [QtCore.QString('Groups')]

        header = table.horizontalHeader()
        header.setStretchLastSection(True)

        #----------------------------------------------
        #self._default_is_apply = False

        self.color = QLabel("Color:")
        self.color_edit = QPushButton()
        #self.color_edit.setFlat(True)

        color = self.out_data['point_properties'].color
        opacity = self.out_data['point_properties'].opacity
        show = self.out_data['point_properties'].is_visible
        #color = self.out_data[self.active_key].color
        qcolor = QColor()
        qcolor.setRgb(*color)
        #print('color =%s' % str(color))
        palette = QPalette(
            self.color_edit.palette())  # make a copy of the palette
        #palette.setColor(QPalette.Active, QPalette.Base, \
        #qcolor)
        palette.setColor(QPalette.Background, QColor('blue'))  # ButtonText
        self.color_edit.setPalette(palette)

        self.color_edit.setStyleSheet("QPushButton {"
                                      "background-color: rgb(%s, %s, %s);" %
                                      tuple(color) +
                                      #"border:1px solid rgb(255, 170, 255); "
                                      "}")

        self.all_nodes_header = QLabel("All Nodes:")
        self.point_size = QLabel("Point Size:")
        self.point_size_edit = QSpinBox(self)
        self.point_size_edit.setRange(1, 10)
        self.point_size_edit.setSingleStep(1)
        self.point_size_edit.setValue(point_size)

        self.opacity = QLabel("Opacity:")
        self.opacity_edit = QDoubleSpinBox(self)
        self.opacity_edit.setRange(0.1, 1.0)
        self.opacity_edit.setDecimals(1)
        self.opacity_edit.setSingleStep(0.1)
        self.opacity_edit.setValue(opacity)

        # show/hide
        self.checkbox_show = QCheckBox("Show")
        self.checkbox_hide = QCheckBox("Hide")
        self.checkbox_show.setChecked(show)
        self.checkbox_hide.setChecked(not show)

        #----------------------------------------------
        self.nodes_header = QLabel("Single Node:")
        self.name = QLabel("ID:")
        self.name_edit = QLineEdit('Node %i' % name)
        self.name_edit.setDisabled(True)

        self.description = QLabel("Description:")
        self.description_edit = QLineEdit(str(description))
        #self.description_edit.setDisabled(True)

        location_x = 0.1
        location_y = 0.1
        location_z = 0.1
        self.location = QLabel("Location:")
        self.location_x_edit = QDoubleSpinBox(self)
        self.location_y_edit = QDoubleSpinBox(self)
        self.location_z_edit = QDoubleSpinBox(self)
        #self.location_x_edit.setDecimals(1)
        delta_x = abs(location_x) / 100. if location_x != 0.0 else 0.1
        delta_y = abs(location_y) / 100. if location_y != 0.0 else 0.1
        delta_z = abs(location_z) / 100. if location_z != 0.0 else 0.1
        self.location_x_edit.setSingleStep(delta_x)
        self.location_y_edit.setSingleStep(delta_y)
        self.location_z_edit.setSingleStep(delta_z)
        self.location_x_edit.setValue(location_x)
        self.location_y_edit.setValue(location_y)
        self.location_z_edit.setValue(location_z)

        self.coord = QLabel("Coord:")
        self.coord_edit = QSpinBox(self)
        self.coord_edit.setRange(0, 99999999)
        #self.coord_edit.setSingleStep(1)
        self.coord_edit.setValue(0)

        self.coord_type = QLabel("Coord Type:")
        #----------------------------------------------

        # closing
        #if self._default_is_apply:
        #self.apply_button.setDisabled(True)

        self.close_button = QPushButton("Close")

        self.create_layout()
        self.set_connections()
Пример #55
0
 def __init__(self, value):
     QSpinBox.__init__(self)
     self._value = value
     if value.default:
         self.setValue(int(value.default))
    def initUI(self):

        # Choose file dialog
        loadFileBtn = QPushButton("Load files:")
        loadFileBtn.clicked.connect(self.loadImage)

        self.loadFileLine = []
        loadFileDialogBtn = []
        self.loadFileCB = []
        for i in range(0, 4):
            self.loadFileLine.append(QLineEdit(""))
            loadFileDialogBtn.append(QPushButton("..."))
            loadFileDialogBtn[i].setMaximumWidth(40)
            if (i > 0):
                self.loadFileCB.append(QCheckBox())
                # self.loadFileCB[i-1].stateChanged.connect(self.updateImage)
        loadFileDialogBtn[0].clicked.connect(lambda: self.openNewFileDialog(0))
        loadFileDialogBtn[1].clicked.connect(lambda: self.openNewFileDialog(1))
        loadFileDialogBtn[2].clicked.connect(lambda: self.openNewFileDialog(2))
        loadFileDialogBtn[3].clicked.connect(lambda: self.openNewFileDialog(3))
        loadFileDialogBtn[1].clicked.connect(
            lambda: self.loadFileCB[0].setChecked(True))
        loadFileDialogBtn[2].clicked.connect(
            lambda: self.loadFileCB[1].setChecked(True))
        loadFileDialogBtn[3].clicked.connect(
            lambda: self.loadFileCB[2].setChecked(True))

        self.labelImage = QLabel()

        labelChannels = QLabel("Channels:")
        self.comboChannel0 = QComboBox()
        self.comboChannel0.addItems(['G', 'L', 'S'])
        self.comboChannel0.currentIndexChanged.connect(self.updateImage)
        self.comboChannel1 = QComboBox()
        self.comboChannel1.addItems(['G', 'L', 'S'])
        self.comboChannel1.currentIndexChanged.connect(self.updateImage)
        self.comboChannel2 = QComboBox()
        self.comboChannel2.addItems(['G', 'L', 'S'])
        self.comboChannel2.currentIndexChanged.connect(self.updateImage)

        labelKernels = QLabel("Kernels:")
        self.kernel0SB = QSpinBox()
        self.kernel0SB.setMinimum(1)
        self.kernel0SB.setMaximum(31)
        self.kernel0SB.setValue(15)
        self.kernel0SB.setSingleStep(2)
        self.kernel0SB.valueChanged.connect(self.updateImage)
        self.kernel1SB = QSpinBox()
        self.kernel1SB.setMinimum(1)
        self.kernel1SB.setMaximum(31)
        self.kernel1SB.setValue(15)
        self.kernel1SB.setSingleStep(2)
        self.kernel1SB.valueChanged.connect(self.updateImage)
        self.kernel2SB = QSpinBox()
        self.kernel2SB.setMinimum(1)
        self.kernel2SB.setMaximum(31)
        self.kernel2SB.setValue(15)
        self.kernel2SB.setSingleStep(2)
        self.kernel2SB.valueChanged.connect(self.updateImage)

        self.labelSobelX = QLabel()
        self.chboxSobelX0 = QCheckBox()
        self.chboxSobelX0.stateChanged.connect(self.updateImage)
        self.chboxSobelX1 = QCheckBox()
        self.chboxSobelX1.stateChanged.connect(self.updateImage)
        self.chboxSobelX2 = QCheckBox()
        self.chboxSobelX2.stateChanged.connect(self.updateImage)
        self.slider1SobelX = QSlider(Qt.Horizontal)
        self.slider1SobelX.setMinimum(0)
        self.slider1SobelX.setMaximum(255)
        self.slider1SobelX.setValue(20)
        self.slider1SobelX.valueChanged.connect(self.sliderChange)
        self.slider2SobelX = QSlider(Qt.Horizontal)
        self.slider2SobelX.setMinimum(0)
        self.slider2SobelX.setMaximum(255)
        self.slider2SobelX.setValue(100)
        self.slider2SobelX.valueChanged.connect(self.sliderChange)

        self.labelSobelY = QLabel()
        self.chboxSobelY0 = QCheckBox()
        self.chboxSobelY0.stateChanged.connect(self.updateImage)
        self.chboxSobelY1 = QCheckBox()
        self.chboxSobelY1.stateChanged.connect(self.updateImage)
        self.chboxSobelY2 = QCheckBox()
        self.chboxSobelY2.stateChanged.connect(self.updateImage)
        self.slider1SobelY = QSlider(Qt.Horizontal)
        self.slider1SobelY.setMinimum(0)
        self.slider1SobelY.setMaximum(255)
        self.slider1SobelY.setValue(20)
        self.slider1SobelY.valueChanged.connect(self.sliderChange)
        self.slider2SobelY = QSlider(Qt.Horizontal)
        self.slider2SobelY.setMinimum(0)
        self.slider2SobelY.setMaximum(255)
        self.slider2SobelY.setValue(100)
        self.slider2SobelY.valueChanged.connect(self.sliderChange)

        self.labelSobelM = QLabel()
        self.chboxSobelM0 = QCheckBox()
        self.chboxSobelM0.stateChanged.connect(self.updateImage)
        self.chboxSobelM1 = QCheckBox()
        self.chboxSobelM1.stateChanged.connect(self.updateImage)
        self.chboxSobelM2 = QCheckBox()
        self.chboxSobelM2.stateChanged.connect(self.updateImage)
        self.slider1SobelM = QSlider(Qt.Horizontal)
        self.slider1SobelM.setMinimum(0)
        self.slider1SobelM.setMaximum(255)
        self.slider1SobelM.setValue(30)
        self.slider1SobelM.valueChanged.connect(self.sliderChange)
        self.slider2SobelM = QSlider(Qt.Horizontal)
        self.slider2SobelM.setMinimum(0)
        self.slider2SobelM.setMaximum(255)
        self.slider2SobelM.setValue(100)
        self.slider2SobelM.valueChanged.connect(self.sliderChange)

        self.labelSobelA = QLabel()
        self.chboxSobelA0 = QCheckBox()
        self.chboxSobelA0.stateChanged.connect(self.updateImage)
        self.chboxSobelA1 = QCheckBox()
        self.chboxSobelA1.stateChanged.connect(self.updateImage)
        self.chboxSobelA2 = QCheckBox()
        self.chboxSobelA2.stateChanged.connect(self.updateImage)
        self.slider1SobelA = QSlider(Qt.Horizontal)
        self.slider1SobelA.setMinimum(0)
        self.slider1SobelA.setMaximum(255)
        self.slider1SobelA.setValue(int(0.7 / np.pi * 510))
        self.slider1SobelA.valueChanged.connect(self.sliderChange)
        self.slider2SobelA = QSlider(Qt.Horizontal)
        self.slider2SobelA.setMinimum(0)
        self.slider2SobelA.setMaximum(255)
        self.slider2SobelA.setValue(int(1.3 / np.pi * 510))
        self.slider2SobelA.valueChanged.connect(self.sliderChange)

        self.sliderChange()

        # Layouts
        layoutMain = QVBoxLayout()
        layoutMain2 = QHBoxLayout()
        layoutSettings = QVBoxLayout()
        layoutChannels = QHBoxLayout()
        layoutKernelSB = QHBoxLayout()
        layoutChboxSobelX = QHBoxLayout()
        layoutChboxSobelY = QHBoxLayout()
        layoutChboxSobelM = QHBoxLayout()
        layoutChboxSobelA = QHBoxLayout()

        layoutsChooseFile = []
        for i in range(0, 4):
            layoutsChooseFile.append(QHBoxLayout())
            if i == 0:
                layoutsChooseFile[i].addWidget(loadFileBtn)
            else:
                layoutsChooseFile[i].addWidget(self.loadFileCB[i - 1])
            layoutsChooseFile[i].addWidget(self.loadFileLine[i])
            layoutsChooseFile[i].addWidget(loadFileDialogBtn[i])
            layoutMain.addLayout(layoutsChooseFile[i])

        layoutMain.addLayout(layoutMain2, 1)

        layoutMain2.addWidget(self.labelImage, 1)
        layoutMain2.addLayout(layoutSettings)

        layoutSettings.addWidget(labelChannels)
        layoutSettings.addLayout(layoutChannels)
        layoutChannels.addWidget(self.comboChannel0)
        layoutChannels.addWidget(self.comboChannel1)
        layoutChannels.addWidget(self.comboChannel2)
        layoutSettings.addWidget(labelKernels)
        layoutSettings.addLayout(layoutKernelSB)
        layoutKernelSB.addWidget(self.kernel0SB)
        layoutKernelSB.addWidget(self.kernel1SB)
        layoutKernelSB.addWidget(self.kernel2SB)
        layoutSettings.addWidget(self.labelSobelX)
        layoutSettings.addLayout(layoutChboxSobelX)
        layoutChboxSobelX.addWidget(self.chboxSobelX0)
        layoutChboxSobelX.addWidget(self.chboxSobelX1)
        layoutChboxSobelX.addWidget(self.chboxSobelX2)
        layoutSettings.addWidget(self.slider1SobelX)
        layoutSettings.addWidget(self.slider2SobelX)
        layoutSettings.addWidget(self.labelSobelY)
        layoutSettings.addLayout(layoutChboxSobelY)
        layoutChboxSobelY.addWidget(self.chboxSobelY0)
        layoutChboxSobelY.addWidget(self.chboxSobelY1)
        layoutChboxSobelY.addWidget(self.chboxSobelY2)
        layoutSettings.addWidget(self.slider1SobelY)
        layoutSettings.addWidget(self.slider2SobelY)
        layoutSettings.addWidget(self.labelSobelM)
        layoutSettings.addLayout(layoutChboxSobelM)
        layoutChboxSobelM.addWidget(self.chboxSobelM0)
        layoutChboxSobelM.addWidget(self.chboxSobelM1)
        layoutChboxSobelM.addWidget(self.chboxSobelM2)
        layoutSettings.addWidget(self.slider1SobelM)
        layoutSettings.addWidget(self.slider2SobelM)
        layoutSettings.addWidget(self.labelSobelA)
        layoutSettings.addLayout(layoutChboxSobelA)
        layoutChboxSobelA.addWidget(self.chboxSobelA0)
        layoutChboxSobelA.addWidget(self.chboxSobelA1)
        layoutChboxSobelA.addWidget(self.chboxSobelA2)
        layoutSettings.addWidget(self.slider1SobelA)
        layoutSettings.addWidget(self.slider2SobelA)
        layoutSettings.addStretch(1)

        mainWidget = QWidget()
        mainWidget.setLayout(layoutMain)
        self.setCentralWidget(mainWidget)
        self.showMaximized()
Пример #57
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
class ChooseThresholdsUI(QMainWindow):
    def __init__(self):
        super().__init__()

        self.baseImages = []

        self.SobelXTh = [0, 255]

        self.SobelYTh = [0, 255]

        self.SobelMTh = [0, 255]

        self.SobelATh = [0, 255]

        self.initUI()

    @pyqtSlot()
    def openNewFileDialog(self, index):
        """ @brief slot with open new file dialog
        """
        directory = os.path.dirname(self.loadFileLine[index].text())
        fileName = QFileDialog.getOpenFileName(self, 'Choose image', directory,
                                               'All files (*)')
        if isinstance(fileName, tuple):  # for PyQt5
            if fileName[0]:
                self.loadFileLine[index].setText(fileName[0])
        else:  # for PyQt4
            if fileName:
                self.loadFileLine[index].setText(fileName)

    @pyqtSlot()
    def loadImage(self):

        self.baseImages = []
        for i in range(0, 4):
            if (i > 0):
                if not self.loadFileCB[i - 1].isChecked():
                    continue
            image = cv2.imread(self.loadFileLine[i].text())
            if image is not None:
                self.baseImages.append(image)
        if len(self.baseImages) != 0:
            self.updateImage()

    @pyqtSlot()
    def sliderChange(self):
        self.SobelXTh[0] = self.slider1SobelX.value()
        self.SobelXTh[1] = self.slider2SobelX.value()
        self.labelSobelX.setText("SobelX th: {:03d} {:03d}".format(
            self.SobelXTh[0], self.SobelXTh[1]))

        self.SobelYTh[0] = self.slider1SobelY.value()
        self.SobelYTh[1] = self.slider2SobelY.value()
        self.labelSobelY.setText("SobelY th: {:03d} {:03d}".format(
            self.SobelYTh[0], self.SobelYTh[1]))

        self.SobelMTh[0] = self.slider1SobelM.value()
        self.SobelMTh[1] = self.slider2SobelM.value()
        self.labelSobelM.setText("SobelM th: {:03d} {:03d}".format(
            self.SobelMTh[0], self.SobelMTh[1]))

        self.SobelATh[0] = self.slider1SobelA.value() * np.pi / 510
        self.SobelATh[1] = self.slider2SobelA.value() * np.pi / 510
        self.labelSobelA.setText("SobelA th: {:1.3f} {:1.3f}".format(
            self.SobelATh[0], self.SobelATh[1]))

        self.updateImage()

    def initUI(self):

        # Choose file dialog
        loadFileBtn = QPushButton("Load files:")
        loadFileBtn.clicked.connect(self.loadImage)

        self.loadFileLine = []
        loadFileDialogBtn = []
        self.loadFileCB = []
        for i in range(0, 4):
            self.loadFileLine.append(QLineEdit(""))
            loadFileDialogBtn.append(QPushButton("..."))
            loadFileDialogBtn[i].setMaximumWidth(40)
            if (i > 0):
                self.loadFileCB.append(QCheckBox())
                # self.loadFileCB[i-1].stateChanged.connect(self.updateImage)
        loadFileDialogBtn[0].clicked.connect(lambda: self.openNewFileDialog(0))
        loadFileDialogBtn[1].clicked.connect(lambda: self.openNewFileDialog(1))
        loadFileDialogBtn[2].clicked.connect(lambda: self.openNewFileDialog(2))
        loadFileDialogBtn[3].clicked.connect(lambda: self.openNewFileDialog(3))
        loadFileDialogBtn[1].clicked.connect(
            lambda: self.loadFileCB[0].setChecked(True))
        loadFileDialogBtn[2].clicked.connect(
            lambda: self.loadFileCB[1].setChecked(True))
        loadFileDialogBtn[3].clicked.connect(
            lambda: self.loadFileCB[2].setChecked(True))

        self.labelImage = QLabel()

        labelChannels = QLabel("Channels:")
        self.comboChannel0 = QComboBox()
        self.comboChannel0.addItems(['G', 'L', 'S'])
        self.comboChannel0.currentIndexChanged.connect(self.updateImage)
        self.comboChannel1 = QComboBox()
        self.comboChannel1.addItems(['G', 'L', 'S'])
        self.comboChannel1.currentIndexChanged.connect(self.updateImage)
        self.comboChannel2 = QComboBox()
        self.comboChannel2.addItems(['G', 'L', 'S'])
        self.comboChannel2.currentIndexChanged.connect(self.updateImage)

        labelKernels = QLabel("Kernels:")
        self.kernel0SB = QSpinBox()
        self.kernel0SB.setMinimum(1)
        self.kernel0SB.setMaximum(31)
        self.kernel0SB.setValue(15)
        self.kernel0SB.setSingleStep(2)
        self.kernel0SB.valueChanged.connect(self.updateImage)
        self.kernel1SB = QSpinBox()
        self.kernel1SB.setMinimum(1)
        self.kernel1SB.setMaximum(31)
        self.kernel1SB.setValue(15)
        self.kernel1SB.setSingleStep(2)
        self.kernel1SB.valueChanged.connect(self.updateImage)
        self.kernel2SB = QSpinBox()
        self.kernel2SB.setMinimum(1)
        self.kernel2SB.setMaximum(31)
        self.kernel2SB.setValue(15)
        self.kernel2SB.setSingleStep(2)
        self.kernel2SB.valueChanged.connect(self.updateImage)

        self.labelSobelX = QLabel()
        self.chboxSobelX0 = QCheckBox()
        self.chboxSobelX0.stateChanged.connect(self.updateImage)
        self.chboxSobelX1 = QCheckBox()
        self.chboxSobelX1.stateChanged.connect(self.updateImage)
        self.chboxSobelX2 = QCheckBox()
        self.chboxSobelX2.stateChanged.connect(self.updateImage)
        self.slider1SobelX = QSlider(Qt.Horizontal)
        self.slider1SobelX.setMinimum(0)
        self.slider1SobelX.setMaximum(255)
        self.slider1SobelX.setValue(20)
        self.slider1SobelX.valueChanged.connect(self.sliderChange)
        self.slider2SobelX = QSlider(Qt.Horizontal)
        self.slider2SobelX.setMinimum(0)
        self.slider2SobelX.setMaximum(255)
        self.slider2SobelX.setValue(100)
        self.slider2SobelX.valueChanged.connect(self.sliderChange)

        self.labelSobelY = QLabel()
        self.chboxSobelY0 = QCheckBox()
        self.chboxSobelY0.stateChanged.connect(self.updateImage)
        self.chboxSobelY1 = QCheckBox()
        self.chboxSobelY1.stateChanged.connect(self.updateImage)
        self.chboxSobelY2 = QCheckBox()
        self.chboxSobelY2.stateChanged.connect(self.updateImage)
        self.slider1SobelY = QSlider(Qt.Horizontal)
        self.slider1SobelY.setMinimum(0)
        self.slider1SobelY.setMaximum(255)
        self.slider1SobelY.setValue(20)
        self.slider1SobelY.valueChanged.connect(self.sliderChange)
        self.slider2SobelY = QSlider(Qt.Horizontal)
        self.slider2SobelY.setMinimum(0)
        self.slider2SobelY.setMaximum(255)
        self.slider2SobelY.setValue(100)
        self.slider2SobelY.valueChanged.connect(self.sliderChange)

        self.labelSobelM = QLabel()
        self.chboxSobelM0 = QCheckBox()
        self.chboxSobelM0.stateChanged.connect(self.updateImage)
        self.chboxSobelM1 = QCheckBox()
        self.chboxSobelM1.stateChanged.connect(self.updateImage)
        self.chboxSobelM2 = QCheckBox()
        self.chboxSobelM2.stateChanged.connect(self.updateImage)
        self.slider1SobelM = QSlider(Qt.Horizontal)
        self.slider1SobelM.setMinimum(0)
        self.slider1SobelM.setMaximum(255)
        self.slider1SobelM.setValue(30)
        self.slider1SobelM.valueChanged.connect(self.sliderChange)
        self.slider2SobelM = QSlider(Qt.Horizontal)
        self.slider2SobelM.setMinimum(0)
        self.slider2SobelM.setMaximum(255)
        self.slider2SobelM.setValue(100)
        self.slider2SobelM.valueChanged.connect(self.sliderChange)

        self.labelSobelA = QLabel()
        self.chboxSobelA0 = QCheckBox()
        self.chboxSobelA0.stateChanged.connect(self.updateImage)
        self.chboxSobelA1 = QCheckBox()
        self.chboxSobelA1.stateChanged.connect(self.updateImage)
        self.chboxSobelA2 = QCheckBox()
        self.chboxSobelA2.stateChanged.connect(self.updateImage)
        self.slider1SobelA = QSlider(Qt.Horizontal)
        self.slider1SobelA.setMinimum(0)
        self.slider1SobelA.setMaximum(255)
        self.slider1SobelA.setValue(int(0.7 / np.pi * 510))
        self.slider1SobelA.valueChanged.connect(self.sliderChange)
        self.slider2SobelA = QSlider(Qt.Horizontal)
        self.slider2SobelA.setMinimum(0)
        self.slider2SobelA.setMaximum(255)
        self.slider2SobelA.setValue(int(1.3 / np.pi * 510))
        self.slider2SobelA.valueChanged.connect(self.sliderChange)

        self.sliderChange()

        # Layouts
        layoutMain = QVBoxLayout()
        layoutMain2 = QHBoxLayout()
        layoutSettings = QVBoxLayout()
        layoutChannels = QHBoxLayout()
        layoutKernelSB = QHBoxLayout()
        layoutChboxSobelX = QHBoxLayout()
        layoutChboxSobelY = QHBoxLayout()
        layoutChboxSobelM = QHBoxLayout()
        layoutChboxSobelA = QHBoxLayout()

        layoutsChooseFile = []
        for i in range(0, 4):
            layoutsChooseFile.append(QHBoxLayout())
            if i == 0:
                layoutsChooseFile[i].addWidget(loadFileBtn)
            else:
                layoutsChooseFile[i].addWidget(self.loadFileCB[i - 1])
            layoutsChooseFile[i].addWidget(self.loadFileLine[i])
            layoutsChooseFile[i].addWidget(loadFileDialogBtn[i])
            layoutMain.addLayout(layoutsChooseFile[i])

        layoutMain.addLayout(layoutMain2, 1)

        layoutMain2.addWidget(self.labelImage, 1)
        layoutMain2.addLayout(layoutSettings)

        layoutSettings.addWidget(labelChannels)
        layoutSettings.addLayout(layoutChannels)
        layoutChannels.addWidget(self.comboChannel0)
        layoutChannels.addWidget(self.comboChannel1)
        layoutChannels.addWidget(self.comboChannel2)
        layoutSettings.addWidget(labelKernels)
        layoutSettings.addLayout(layoutKernelSB)
        layoutKernelSB.addWidget(self.kernel0SB)
        layoutKernelSB.addWidget(self.kernel1SB)
        layoutKernelSB.addWidget(self.kernel2SB)
        layoutSettings.addWidget(self.labelSobelX)
        layoutSettings.addLayout(layoutChboxSobelX)
        layoutChboxSobelX.addWidget(self.chboxSobelX0)
        layoutChboxSobelX.addWidget(self.chboxSobelX1)
        layoutChboxSobelX.addWidget(self.chboxSobelX2)
        layoutSettings.addWidget(self.slider1SobelX)
        layoutSettings.addWidget(self.slider2SobelX)
        layoutSettings.addWidget(self.labelSobelY)
        layoutSettings.addLayout(layoutChboxSobelY)
        layoutChboxSobelY.addWidget(self.chboxSobelY0)
        layoutChboxSobelY.addWidget(self.chboxSobelY1)
        layoutChboxSobelY.addWidget(self.chboxSobelY2)
        layoutSettings.addWidget(self.slider1SobelY)
        layoutSettings.addWidget(self.slider2SobelY)
        layoutSettings.addWidget(self.labelSobelM)
        layoutSettings.addLayout(layoutChboxSobelM)
        layoutChboxSobelM.addWidget(self.chboxSobelM0)
        layoutChboxSobelM.addWidget(self.chboxSobelM1)
        layoutChboxSobelM.addWidget(self.chboxSobelM2)
        layoutSettings.addWidget(self.slider1SobelM)
        layoutSettings.addWidget(self.slider2SobelM)
        layoutSettings.addWidget(self.labelSobelA)
        layoutSettings.addLayout(layoutChboxSobelA)
        layoutChboxSobelA.addWidget(self.chboxSobelA0)
        layoutChboxSobelA.addWidget(self.chboxSobelA1)
        layoutChboxSobelA.addWidget(self.chboxSobelA2)
        layoutSettings.addWidget(self.slider1SobelA)
        layoutSettings.addWidget(self.slider2SobelA)
        layoutSettings.addStretch(1)

        mainWidget = QWidget()
        mainWidget.setLayout(layoutMain)
        self.setCentralWidget(mainWidget)
        self.showMaximized()

    def selectChannel(self, combo, N):
        if combo.currentText() == 'G':
            im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2GRAY)
        elif combo.currentText() == 'L':
            im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2HLS)[:, :, 1]
        elif combo.currentText() == 'S':
            im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2HLS)[:, :, 2]
        return im

    def updateOneImg(self, imN):

        changed = False

        if self.chboxSobelX0.isChecked() or self.chboxSobelY0.isChecked() or self.chboxSobelM0.isChecked() or \
                self.chboxSobelA0.isChecked():
            changed = True
            im = self.selectChannel(self.comboChannel0, imN)
            th = pipeline.Tresholds(im, kernel=self.kernel0SB.value())

            im0 = np.ones_like(im, dtype='uint8')
            if self.chboxSobelX0.isChecked():
                im0 = im0 & th.abs_sobel_thresh(orient='x',
                                                thresh=self.SobelXTh)
            if self.chboxSobelY0.isChecked():
                im0 = im0 & th.abs_sobel_thresh(orient='y',
                                                thresh=self.SobelYTh)
            if self.chboxSobelM0.isChecked():
                im0 = im0 & th.mag_thresh(thresh=self.SobelMTh)
            if self.chboxSobelA0.isChecked():
                im0 = im0 & th.dir_threshold(thresh=self.SobelATh)
        else:
            im0 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8')

        if self.chboxSobelX1.isChecked() or self.chboxSobelY1.isChecked() or self.chboxSobelM1.isChecked() or \
                self.chboxSobelA1.isChecked():
            changed = True
            im = self.selectChannel(self.comboChannel1, imN)
            th = pipeline.Tresholds(im, kernel=self.kernel1SB.value())

            im1 = np.ones_like(im, dtype='uint8')
            if self.chboxSobelX1.isChecked():
                im1 = im1 & th.abs_sobel_thresh(orient='x',
                                                thresh=self.SobelXTh)
            if self.chboxSobelY1.isChecked():
                im1 = im1 & th.abs_sobel_thresh(orient='y',
                                                thresh=self.SobelYTh)
            if self.chboxSobelM1.isChecked():
                im1 = im1 & th.mag_thresh(thresh=self.SobelMTh)
            if self.chboxSobelA1.isChecked():
                im1 = im1 & th.dir_threshold(thresh=self.SobelATh)
        else:
            im1 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8')

        if self.chboxSobelX2.isChecked() or self.chboxSobelY2.isChecked() or self.chboxSobelM2.isChecked() or \
                self.chboxSobelA2.isChecked():
            changed = True
            im = self.selectChannel(self.comboChannel2, imN)
            th = pipeline.Tresholds(im, kernel=self.kernel2SB.value())

            im2 = np.ones_like(im, dtype='uint8')
            if self.chboxSobelX2.isChecked():
                im2 = im2 & th.abs_sobel_thresh(orient='x',
                                                thresh=self.SobelXTh)
            if self.chboxSobelY2.isChecked():
                im2 = im2 & th.abs_sobel_thresh(orient='y',
                                                thresh=self.SobelYTh)
            if self.chboxSobelM2.isChecked():
                im2 = im2 & th.mag_thresh(thresh=self.SobelMTh)
            if self.chboxSobelA2.isChecked():
                im2 = im2 & th.dir_threshold(thresh=self.SobelATh)
        else:
            im2 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8')

        if not changed:
            imf = cv2.cvtColor(self.baseImages[imN], cv2.COLOR_BGR2RGB)
        else:
            imf = np.dstack((im0 * 255, im1 * 255, im2 * 255))

        return imf

    def updateImage(self):

        if len(self.baseImages) == 0:
            return

        imf = []
        for i in range(len(self.baseImages)):
            im = self.updateOneImg(i)
            imf.append(im)

        frameSize = (self.labelImage.size().width(),
                     self.labelImage.size().height(), 3)
        bytesPerLine = 3 * frameSize[0]

        if len(self.baseImages) == 1:
            frameImg = cv2.resize(imf[0], frameSize[0:2])
        else:
            frameImg = np.zeros([frameSize[1], frameSize[0], frameSize[2]],
                                dtype='uint8')
            midy = frameSize[1] // 2
            midx = frameSize[0] // 2
            # frameImg[0:midy, 0:midx, :] = 255
            frameImg[:midy, :midx, :] = cv2.resize(imf[0], (midx, midy))
            frameImg[:midy,
                     midx:midx * 2, :] = cv2.resize(imf[1], (midx, midy))
            if len(self.baseImages) >= 3:
                frameImg[midy:midy * 2, :midx, :] = cv2.resize(
                    imf[2], (midx, midy))
            if len(self.baseImages) >= 4:
                frameImg[midy:midy * 2,
                         midx:midx * 2, :] = cv2.resize(imf[3], (midx, midy))

        qImg = QImage(frameImg, frameSize[0], frameSize[1], bytesPerLine,
                      QImage.Format_RGB888)
        self.labelImage.setPixmap(QPixmap.fromImage(qImg))
Пример #59
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())
Пример #60
0
    def __init__(self, iface, geometry, mntButton=False, zerosButton=False):
        """
        Constructor
        :param iface: interface
        :param width: dock widget geometry
        """
        QDockWidget.__init__(self)
        self.setWindowTitle(
            QCoreApplication.translate("VDLTools", "Profile Tool"))
        self.__iface = iface
        self.__geom = geometry
        self.__canvas = self.__iface.mapCanvas()
        self.__types = ['PDF', 'PNG']  # ], 'SVG', 'PS']
        self.__libs = []
        if Qwt5_loaded:
            self.__lib = 'Qwt5'
            self.__libs.append('Qwt5')
            if matplotlib_loaded:
                self.__libs.append('Matplotlib')
        elif matplotlib_loaded:
            self.__lib = 'Matplotlib'
            self.__libs.append('Matplotlib')
        else:
            self.__lib = None
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "No graph lib available (qwt5 or matplotlib)"),
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)

        self.__doTracking = False
        self.__vline = None

        self.__profiles = None
        self.__numLines = None
        self.__mntPoints = None

        self.__marker = None
        self.__tabmouseevent = None

        if self.__geom is not None:
            self.setGeometry(self.__geom)

        self.__contentWidget = QWidget()
        self.setWidget(self.__contentWidget)

        self.__boxLayout = QHBoxLayout()
        self.__contentWidget.setLayout(self.__boxLayout)

        self.__plotFrame = QFrame()
        self.__frameLayout = QHBoxLayout()
        self.__plotFrame.setLayout(self.__frameLayout)

        self.__printLayout = QHBoxLayout()
        self.__printLayout.addWidget(self.__plotFrame)

        self.__legendLayout = QVBoxLayout()
        self.__printLayout.addLayout(self.__legendLayout)

        self.__printWdg = QWidget()
        self.__printWdg.setLayout(self.__printLayout)

        self.__plotWdg = None
        self.__scaleButton = None
        self.__changePlotWidget()

        size = QSize(150, 20)

        self.__boxLayout.addWidget(self.__printWdg)

        self.__vertLayout = QVBoxLayout()

        self.__libCombo = QComboBox()
        self.__libCombo.setFixedSize(size)
        self.__libCombo.addItems(self.__libs)
        self.__vertLayout.addWidget(self.__libCombo)
        self.__libCombo.currentIndexChanged.connect(self.__setLib)

        if mntButton:
            self.__displayMnt = False
            self.__mntButton = QPushButton(
                QCoreApplication.translate("VDLTools", "Display MNT"))
            self.__mntButton.setFixedSize(size)
            self.__mntButton.clicked.connect(self.__mnt)
            self.__vertLayout.addWidget(self.__mntButton)

        if zerosButton:
            self.__displayZeros = False
            self.__zerosButton = QPushButton(
                QCoreApplication.translate("VDLTools", "Display Zeros"))
            self.__zerosButton.setFixedSize(size)
            self.__zerosButton.clicked.connect(self.__zeros)
            self.__vertLayout.addWidget(self.__zerosButton)
        else:
            self.__displayZeros = True

        self.__scale11 = False
        self.__scaleButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Scale 1:1"))
        self.__scaleButton.setFixedSize(size)
        self.__scaleButton.clicked.connect(self.__scale)
        if self.__lib == 'Qwt5':
            self.__scaleButton.setVisible(True)
        else:
            self.__scaleButton.setVisible(False)
        self.__vertLayout.addWidget(self.__scaleButton)

        self.__maxLabel = QLabel("y max")
        self.__maxLabel.setFixedSize(size)
        self.__vertLayout.addWidget(self.__maxLabel)
        self.__maxSpin = QSpinBox()
        self.__maxSpin.setFixedSize(size)
        self.__maxSpin.setRange(-10000, 10000)
        self.__maxSpin.valueChanged.connect(self.__reScalePlot)
        self.__vertLayout.addWidget(self.__maxSpin)
        self.__vertLayout.insertSpacing(10, 20)

        self.__minLabel = QLabel("y min")
        self.__minLabel.setFixedSize(size)
        self.__vertLayout.addWidget(self.__minLabel)
        self.__minSpin = QSpinBox()
        self.__minSpin.setFixedSize(size)
        self.__minSpin.setRange(-10000, 10000)
        self.__minSpin.valueChanged.connect(self.__reScalePlot)
        self.__vertLayout.addWidget(self.__minSpin)
        self.__vertLayout.insertSpacing(10, 40)

        self.__typeCombo = QComboBox()
        self.__typeCombo.setFixedSize(size)
        self.__typeCombo.addItems(self.__types)
        self.__vertLayout.addWidget(self.__typeCombo)
        self.__saveButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Save"))
        self.__saveButton.setFixedSize(size)
        self.__saveButton.clicked.connect(self.__save)
        self.__vertLayout.addWidget(self.__saveButton)

        self.__boxLayout.addLayout(self.__vertLayout)

        self.__maxSpin.setEnabled(False)
        self.__minSpin.setEnabled(False)

        self.__colors = []
        for cn in QColor.colorNames():
            qc = QColor(cn)
            val = qc.red() + qc.green() + qc.blue()
            if 0 < val < 450:
                self.__colors.append(cn)