Example #1
0
    def __init__(self, pref):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)
        vbox.addWidget(QLabel('Configure the CSS (Skin) for this Application'))
        self.checkDefault = QCheckBox('Default')
        self.checkCustom = QCheckBox('Custom')
        self.checkNoSkin = QCheckBox('No Skin')
        hbox = QHBoxLayout()
        hbox.addWidget(self.checkDefault)
        hbox.addWidget(self.checkCustom)
        hbox.addWidget(self.checkNoSkin)
        vbox.addLayout(hbox)

        self.text = QPlainTextEdit()
        self.text.setEnabled(False)
        self.text.setPlainText(styles.css_styles)
        vbox.addWidget(self.text)
        if pref.get('noSkin', False):
            self.checkNoSkin.setCheckState(Qt.Checked)
        elif pref.get('custom', False):
            self.checkCustom.setCheckState(Qt.Checked)
            self.text.setEnabled(True)
            self.text.setPlainText(pref.get('skin', ''))
        else:
            self.checkDefault.setCheckState(Qt.Checked)

        self.connect(self.checkDefault, SIGNAL("stateChanged(int)"), self.use_default)
        self.connect(self.checkCustom, SIGNAL("stateChanged(int)"), self.use_custom)
        self.connect(self.checkNoSkin, SIGNAL("stateChanged(int)"), self.use_no_skin)
Example #2
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)
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)
Example #4
0
class DummyConfigWidget(QWidget, config.ConfigurationWidgetMixin):

    NAME_PREFIX = 'dummy'
    PROPERTY_MAP = dict(QCheckBox='checked', QLineEdit='text')
    CHANGED_SIGNAL_MAP = dict(QCheckBox='toggled', QLineEdit='textChanged')

    configurationChanged = pyqtSignal(bool)

    def __init__(self, config, parent=None):
        QWidget.__init__(self, parent)
        layout = QHBoxLayout(self)
        self.setLayout(layout)
        self.checkbox = QCheckBox(self)
        self.checkbox.setObjectName('dummy_checkbox')
        layout.addWidget(self.checkbox)
        self.lineedit = QLineEdit(self)
        self.lineedit.setObjectName('dummy_lineedit')
        layout.addWidget(self.lineedit)
        self._setup(config)

    def change(self, text, check_state):
        self.lineedit.setText(text)
        self.checkbox.setChecked(check_state)

    def check(self, text, check_state):
        __tracebackhide__ = True
        assert unicode(self.lineedit.text()) == text
        assert self.checkbox.isChecked() == check_state
Example #5
0
 def __init__(self, parent, info, widget, label):
     QCheckBox.__init__(self)
     self.__info = info
     self.__widget = widget
     self.setText(label)
     self.stateChangedWidget(Qt.Unchecked)
     self.initCallback()
Example #6
0
 def __init__(self, mainwin):
     self.mainwin = mainwin
     KDialog.__init__(self, mainwin)
     self.setCaption(i18n("Run LilyPond"))
     self.setButtons(KDialog.ButtonCode(
         KDialog.Help | KDialog.Ok | KDialog.Cancel ))
     self.setButtonText(KDialog.Ok, i18n("Run LilyPond"))
     self.setButtonIcon(KDialog.Ok, KIcon("run-lilypond"))
     self.setHelp("running")
     
     layout = QVBoxLayout(self.mainWidget())
     
     layout.addWidget(QLabel(i18n(
         "Select which LilyPond version you want to run:")))
         
     self.lilypond = QListWidget()
     self.lilypond.setIconSize(QSize(22, 22))
     self.lilypond.setSpacing(4)
     layout.addWidget(self.lilypond)
     
     self.preview = QCheckBox(i18n(
         "Run LilyPond in preview mode (with Point and Click)"))
     layout.addWidget(self.preview)
     
     self.verbose = QCheckBox(i18n("Run LilyPond with verbose output"))
     layout.addWidget(self.verbose)
class BooleanParameterWidget(GenericParameterWidget):
    """Widget class for boolean parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A BooleanParameter object.
        :type parameter: BooleanParameter

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

        self._check_box_input = QCheckBox()
        # Tooltips
        self.setToolTip('Tick here to enable ' + self._parameter.name)
        self._check_box_input.setChecked(self._parameter.value)

        self._inner_input_layout.addWidget(self._check_box_input)

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

        :returns: A BooleanParameter from the current state of widget

        """
        self._parameter.value = self._check_box_input.isChecked()
        return self._parameter
 def _setupUi(self):
     self.setWindowTitle(tr("Deletion Options"))
     self.resize(400, 270)
     self.verticalLayout = QVBoxLayout(self)
     self.msgLabel = QLabel()
     self.verticalLayout.addWidget(self.msgLabel)
     self.linkCheckbox = QCheckBox(tr("Link deleted files"))
     self.verticalLayout.addWidget(self.linkCheckbox)
     text = tr("After having deleted a duplicate, place a link targeting the reference file "
         "to replace the deleted file.")
     self.linkMessageLabel = QLabel(text)
     self.linkMessageLabel.setWordWrap(True)
     self.verticalLayout.addWidget(self.linkMessageLabel)
     self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False)
     self.verticalLayout.addWidget(self.linkTypeRadio)
     if not self.model.supports_links():
         self.linkCheckbox.setEnabled(False)
         self.linkTypeRadio.setEnabled(False)
         self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)"))
     self.directCheckbox = QCheckBox(tr("Directly delete files"))
     self.verticalLayout.addWidget(self.directCheckbox)
     text = tr("Instead of sending files to trash, delete them directly. This option is usually "
         "used as a workaround when the normal deletion method doesn't work.")
     self.directMessageLabel = QLabel(text)
     self.directMessageLabel.setWordWrap(True)
     self.verticalLayout.addWidget(self.directMessageLabel)
     self.buttonBox = QDialogButtonBox()
     self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole)
     self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole)
     self.verticalLayout.addWidget(self.buttonBox)
Example #9
0
class Login(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self)
        self.parent = parent
        self.resize(270, 160)
        self.verticalLayout = QVBoxLayout(self)
        self.label_username = QLabel(self)
        self.verticalLayout.addWidget(self.label_username)
        self.username = QLineEdit(self)
        self.verticalLayout.addWidget(self.username)
        self.label_password = QLabel(self)
        self.verticalLayout.addWidget(self.label_password)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)
        self.verticalLayout.addWidget(self.password)
        self.save_password = QCheckBox(self)
        self.verticalLayout.addWidget(self.save_password)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
                QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)
        self.label_username.setBuddy(self.username)
        self.label_password.setBuddy(self.password)
        self.setWindowIcon(get_icon(MAIL_IMAGE))
        self.setWindowTitle("Gmail Login")
        self.label_username.setText("Username")
        self.label_password.setText("Password")
        self.save_password.setText("Save password")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
Example #10
0
class BoolConfigControl(ConfigControl):
    def __init__(self, config_item):
        ConfigControl.__init__(self, config_item)

        self._init_ui()
        self.update_from_config()

    def _init_ui(self):
        lbl_bool = QLabel(self._config_item.tag())
        lbl_bool.setFixedWidth(self.LABEL_WIDTH)

        self._chk_box = QCheckBox()
        self._chk_box.setTristate(False)

        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.addWidget(lbl_bool)
        hbox.addWidget(self._chk_box)
        hbox.addStretch()

        self.setLayout(hbox)

    def update_from_config(self):
        state = 2 if self._config_item.value() == True else 0
        self._chk_box.setCheckState(state)

    def save_to_config(self):
        value = True if self._chk_box.checkState() == 2 else False
        self._config_item.set(value)
Example #11
0
    def __init__(self, values=None):
        RangeDialog.__init__(self, 'Darkening law range')
        self.setFixedHeight(102)

        grid = QGridLayout()
        grid.setAlignment(Qt.AlignTop)
        grid.setColumnStretch(1,1)

        self.checkboxes = []

        row = 1
        cell = 1
        for item in DarkeningLaw.items:
            checkbox = QCheckBox(item[0])
            checkbox.setObjectName(item[1])
            checkbox.stateChanged.connect(self._on_checkbox_state_changed)
            grid.addWidget(checkbox, row, cell)
            self.checkboxes.append(checkbox)

            if values and item[1] in values:
                checkbox.setChecked(True)

            cell += 1

            if cell > 2:
                cell = 1
                row += 1

        self.layout().insertLayout(0, grid)

        if not len(self.values()):
            self.ok_button.setDisabled(True)
Example #12
0
    def create_checkbox ( self, parent, label = '' ):
        """ Returns an adapted checkbox control.
        """
        control = QCheckBox( check_parent( parent ) )
        control.setText( label )

        return control_adapter_for( control )
Example #13
0
 def create_scedit(self, text, option, default=NoDefault, tip=None,
                   without_layout=False):
     label = QLabel(text)
     clayout = ColorLayout(QColor(Qt.black), self)
     clayout.lineedit.setMaximumWidth(80)
     if tip is not None:
         clayout.setToolTip(tip)
     cb_bold = QCheckBox()
     cb_bold.setIcon(get_icon("bold.png"))
     cb_bold.setToolTip(_("Bold"))
     cb_italic = QCheckBox()
     cb_italic.setIcon(get_icon("italic.png"))
     cb_italic.setToolTip(_("Italic"))
     self.scedits[(clayout, cb_bold, cb_italic)] = (option, default)
     if without_layout:
         return label, clayout, cb_bold, cb_italic
     layout = QHBoxLayout()
     layout.addWidget(label)
     layout.addLayout(clayout)
     layout.addSpacing(10)
     layout.addWidget(cb_bold)
     layout.addWidget(cb_italic)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
Example #14
0
class PianoStaff(StaffBase):
    def __init__(self, dialog):
        StaffBase.__init__(self, dialog)
        l = QLabel(i18n("Systems per page:"))
        l.setBuddy(self.systems)
        self.layout().addWidget(l, 0, 1, Qt.AlignRight)
        self.layout().addWidget(self.systems, 0, 2)
        self.clefs = QCheckBox(i18n("Clefs"))
        self.layout().addWidget(self.clefs, 1, 2)
        
    def name(self):
        return i18n("Piano Staff")
        
    def default(self):
        self.systems.setValue(6)
        self.clefs.setChecked(True)
    
    def music(self, layout):
        layout.setSpanBarContexts(['PianoStaff'])
        if not self.clefs.isChecked():
            layout.add('Staff', "\\override Clef #'transparent = ##t")
        if lilyPondVersion() < (2, 13, 4):
            spacing = "#'minimum-Y-extent = #'(-6 . 3)"
        elif lilyPondVersion() < (2, 14, 0):
            spacing = "#'next-staff-spacing = #'((space . 10))"
        else:
            spacing = "#'next-staff-spacing = #'((basic-distance . 10))"
        return ['\\new PianoStaff <<',
            '\\new Staff \\with {',
            '\\override VerticalAxisGroup ' + spacing,
            '} { \\clef treble \\music }',
            '\\new Staff { \\clef bass \\music }',
            '>>']
 def createEditor(self, parent, option, model_index):
     assert isinstance(self.parent(), HierarchicalChecklistView)
     checklist = self.parent().model().get_checklist_from_model_index(model_index)
     checkbox = QCheckBox(checklist.name, parent=parent)
     checkbox.setTristate(True)
     checkbox.stateChanged.connect(partial(self.parent().model().handle_checkstate, model_index))
     return checkbox
Example #16
0
 def __init__(self, id, logscale=False, style=True):
     QGroupBox.__init__(self)
     self.setTitle("Control Axes")
     self.setToolTip("<p>Control if/how axes are drawn</p>")
     self.xAxisCheckBox = QCheckBox("Show X axis")
     self.xAxisCheckBox.setChecked(True)
     self.yAxisCheckBox = QCheckBox("Show Y axis")
     self.yAxisCheckBox.setChecked(True)
     self.id = id
     hbox = HBoxLayout()
     hbox.addWidget(self.xAxisCheckBox)
     hbox.addWidget(self.yAxisCheckBox)
     vbox = VBoxLayout()
     vbox.addLayout(hbox)
     if logscale:
         self.xLogCheckBox = QCheckBox("Logarithmic X axis")
         self.yLogCheckBox = QCheckBox("Logarithmic Y axis")
         hbox = HBoxLayout()
         hbox.addWidget(self.xLogCheckBox)
         hbox.addWidget(self.yLogCheckBox)
         vbox.addLayout(hbox)
     if style:
         self.directionComboBox = QComboBox()
         self.directionComboBox.addItems(["Parallel to axis",
                                          "Horizontal",
                                          "Perpendicualr to axis",
                                          "Vertical"])
         directionLabel = QLabel("Axis label style:")
         directionLabel.setBuddy(self.directionComboBox)
         hbox = HBoxLayout()
         hbox.addWidget(directionLabel)
         hbox.addWidget(self.directionComboBox)
         vbox.addLayout(hbox)
     self.setLayout(vbox)
Example #17
0
	def populateConfigTable(self):
		self.clearConfigTable()
		list_keys = self.list_keys
		list_values = self.list_values
		search_string = str(self.ui.searchLineEdit.text()).lower()
		
		_metadata_table = self.list_metadata_selected
		_index = 0
		for _key in list_keys:
			_name = _key

			if (search_string.strip() != '') and \
			   (not(search_string in _name.lower())):
				continue

			self.ui.configureTable.insertRow(_index)

			_nameItem = QTableWidgetItem(_name)
			self.ui.configureTable.setItem(_index, 1, _nameItem)

			_yesNo = QCheckBox()
			_id = list_keys.index(_name)
			_value = list_values[_id]
			_yesNo.setChecked(_value)
			_yesNo.setText('')
			_yesNo.stateChanged.connect(self.configTableEdited)
			self.ui.configureTable.setCellWidget(_index, 0, _yesNo)
			
			[value, units] = self.retrieveValueUnits(_name)
			_valueItem = QTableWidgetItem(value)
			self.ui.configureTable.setItem(_index, 2, _valueItem)
			_unitsItem = QTableWidgetItem(units)
			self.ui.configureTable.setItem(_index, 3, _unitsItem)
			
			_index += 1
 def Set(self, widget : QtGui.QCheckBox, val : str):
     self.__CheckLen(widget)
     if not val in self.enum:
         raise GuiFieldUnknownMetaErr(val, widget, True)
     
     state = QtCore.Qt.Checked if (val == self.enum[0]) else QtCore.Qt.Unchecked  
     widget.setChecked(state)
Example #19
0
 def init(self,job):
     qc=QCheckBox()
     for i in self.checklist:
         qc=self.checkbox_list[i]
         print self.checklist[i]
         qc.setChecked(self.checklist[i])
     return
Example #20
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     layout.addSpacing(10)
     preamble = QLabel('This vault is locked.', self)
     layout.addWidget(preamble)
     passwdedt = QLineEdit(self)
     passwdedt.setPlaceholderText('Type password to unlock')
     passwdedt.setEchoMode(QLineEdit.Password)
     passwdedt.textChanged.connect(self.passwordChanged)
     passwdedt.returnPressed.connect(self.unlockVault)
     layout.addSpacing(10)
     layout.addWidget(passwdedt)
     self.passwdedt = passwdedt
     unlockcb = QCheckBox('Try unlock other vaults too', self)
     unlockcb.stateChanged.connect(self.saveConfig)
     unlockcb.setVisible(False)
     layout.addWidget(unlockcb)
     self.unlockcb = unlockcb
     status = QLabel('', self)
     status.setVisible(False)
     status.setContentsMargins(0, 10, 0, 0)
     layout.addWidget(status)
     self.status = status
     hbox = QHBoxLayout()
     unlockbtn = QPushButton('Unlock', self)
     unlockbtn.setFixedSize(unlockbtn.sizeHint())
     unlockbtn.clicked.connect(self.unlockVault)
     unlockbtn.setEnabled(False)
     hbox.addWidget(unlockbtn)
     self.unlockbtn = unlockbtn
     hbox.addStretch(100)
     layout.addSpacing(10)
     layout.addLayout(hbox)
     layout.addStretch(100)
Example #21
0
 def __init__(self, parent = None):
 
     QWidget.__init__(self, parent)
     
     self.table = QTableView()
     self.imageTable = QTableView()
     delegate = PixelDelegate(self)
     self.imageTable.setItemDelegate(delegate)
     self.imageTable.horizontalHeader().hide()
     self.imageTable.verticalHeader().hide()
     self.imageTable.setShowGrid(False)
     
     self.imageCombo = QComboBox()
     self.imageCombo.addItem("Dream", QVariant(":/Pictures/dream.png"))
     self.imageCombo.addItem("Teapot", QVariant(":/Pictures/teapot.png"))
     
     gridCheckBox = QCheckBox(self.tr("Show grid:"))
     gridCheckBox.setCheckState(Qt.Unchecked)
     
     self.connect(self.imageCombo, SIGNAL("currentIndexChanged(int)"),
                  self.setModel)
     self.connect(gridCheckBox, SIGNAL("toggled(bool)"),
                  self.imageTable, SLOT("setShowGrid(bool)"))
     
     self.imageCombo.setCurrentIndex(1)
     
     layout = QGridLayout()
     layout.addWidget(self.imageTable, 0, 0, 1, 2)
     layout.addWidget(self.table, 0, 2, 1, 2)
     layout.addWidget(gridCheckBox, 1, 0)
     layout.addWidget(self.imageCombo, 1, 1)
     self.setLayout(layout)
Example #22
0
    def add_check_box(self, advance_n=True, text='label text', name='',
                   text_align='', text_font=ARIAL_12, col=0, width=1,
                   parent=None, layout=None):
                       
        # if parent is input, add widget to parent
        if parent is None:
            parent = self
        
        if layout is None:
            NRow = parent.get_next_row_number(advance_n)
        chkbx = QCheckBox(text, parent)
        chkbx.setFont( text_font )
        
        if layout is None:
            if width==1:
                parent.grid.addWidget(chkbx,  NRow, col)
            else:
                parent.grid.addWidget(chkbx,  NRow, col, 1, width)
        else:
            layout.addWidget( chkbx )
        
        if text_align=='right':
            parent.grid.setAlignment(chkbx, Qt.AlignRight )

        if name:
            self.objectD['%s_check_box'%name] = chkbx
            self.input_widget_by_nameD[name] = (chkbx , 'check_box')
            
        chkbx.stateChanged.connect( lambda: self.check_box_changed( '%s_check_box'%name ) )   
Example #23
0
    def setupUi(self):
        self.setLayout(QVBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setSpacing(0)

        self.__mainLayout = QVBoxLayout()
        self.__mainLayout.setContentsMargins(0, 40, 0, 40)
        self.__mainLayout.setSpacing(65)

        self.layout().addLayout(self.__mainLayout)

        self.setStyleSheet(WELCOME_WIDGET_BUTTON_STYLE)

        bottom_bar = QWidget(objectName="bottom-bar")
        bottom_bar_layout = QHBoxLayout()
        bottom_bar_layout.setContentsMargins(20, 10, 20, 10)
        bottom_bar.setLayout(bottom_bar_layout)
        bottom_bar.setSizePolicy(QSizePolicy.MinimumExpanding,
                                 QSizePolicy.Maximum)

        check = QCheckBox(self.tr("Show at startup"), bottom_bar)
        check.setChecked(False)

        self.__showAtStartupCheck = check

        bottom_bar_layout.addWidget(check, alignment=Qt.AlignVCenter | \
                                    Qt.AlignLeft)

        self.layout().addWidget(bottom_bar, alignment=Qt.AlignBottom,
                                stretch=1)

        self.setSizeGripEnabled(False)
        self.setFixedSize(620, 390)
Example #24
0
 def __init__(self, config, parent, replication_checkbox=False, segmentation_checkbox=False):
     QDialog.__init__(self)
     self.setStyleSheet(parent.styleSheet())
     self.setWindowTitle("Method Settings")
     self.data = config             
     self.ui = {}
     self.area = QScrollArea()
     self.widget = QWidget()
     l = self._parseConfig(self.data, self.ui)
     self.widget.setLayout(l)
     self.area.setWidget(self.widget)
     self.area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
     self.layout = QVBoxLayout()
     self.layout.addWidget(self.area)
     if replication_checkbox:
         self.replication_checkbox = QCheckBox(self.tr("Allow replication"))
         self.layout.addWidget(self.replication_checkbox)
     if segmentation_checkbox:
         self.segmentation_checkbox = QCheckBox(self.tr("Generate assegnments in segments"))
         self.layout.addWidget(self.segmentation_checkbox)
     self.buttons = QHBoxLayout()
     self.ok = QPushButton("OK")
     self.cancel = QPushButton("Cancel")
     self.buttons.addWidget(self.ok)
     self.buttons.addWidget(self.cancel)
     self.layout.addLayout(self.buttons)
     self.setLayout(self.layout)
     QObject.connect(self.ok, SIGNAL("clicked()"), self.OK)
     QObject.connect(self.cancel, SIGNAL("clicked()"), self.Cancel)
Example #25
0
    def __init__(self, page):
        super(LogTool, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)

        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QDoubleSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)

        box = QHBoxLayout()
        box.addWidget(self.fontLabel)
        box.addWidget(self.fontChooser, 1)
        box.addWidget(self.fontSize)
        layout.addLayout(box)
        
        self.showlog = QCheckBox(toggled=self.changed)
        layout.addWidget(self.showlog)
        
        self.rawview = QCheckBox(toggled=self.changed)
        layout.addWidget(self.rawview)
        
        app.translateUI(self)
Example #26
0
def test_should_set_config_checkedvalue_on_true():
    checkbox = QCheckBox()
    assert not checkbox.isChecked()
    widget = CheckboxWidget(widget=checkbox)
    widget.config = config
    widget.setvalue('MyTrue')
    assert checkbox.isChecked()
 def __init__(self, value, parent=None):
     QGridLayout.__init__(self)
     font = tuple_to_qfont(value)
     assert font is not None
     
     # Font family
     self.family = QFontComboBox(parent)
     self.family.setCurrentFont(font)
     self.addWidget(self.family, 0, 0, 1, -1)
     
     # Font size
     self.size = QComboBox(parent)
     self.size.setEditable(True)
     sizelist = range(6, 12) + range(12, 30, 2) + [36, 48, 72]
     size = font.pointSize()
     if size not in sizelist:
         sizelist.append(size)
         sizelist.sort()
     self.size.addItems([str(s) for s in sizelist])
     self.size.setCurrentIndex(sizelist.index(size))
     self.addWidget(self.size, 1, 0)
     
     # Italic or not
     self.italic = QCheckBox(self.tr("Italic"), parent)
     self.italic.setChecked(font.italic())
     self.addWidget(self.italic, 1, 1)
     
     # Bold or not
     self.bold = QCheckBox(self.tr("Bold"), parent)
     self.bold.setChecked(font.bold())
     self.addWidget(self.bold, 1, 2)
Example #28
0
def test_should_return_uncheckedvalue_on_false():
    checkbox = QCheckBox()
    widget = CheckboxWidget(widget=checkbox)
    widget.config = config
    widget.setvalue('MyFalse')
    assert checkbox.isChecked() == False
    assert widget.value() == 'MyFalse'
Example #29
0
    def __init__(self, parent=None):
        super(DialogoReemplazo, self).__init__(parent)
        self.setWindowTitle(self.tr("Reemplazar"))
        box = QVBoxLayout(self)

        grilla = QGridLayout()
        grilla.addWidget(QLabel(self.tr("Buscar por:")), 0, 0)
        self.linea_busqueda = QLineEdit()
        self.linea_busqueda.setMinimumWidth(350)
        grilla.addWidget(self.linea_busqueda, 0, 1)
        grilla.addWidget(QLabel(self.tr("Reemplazar con:")), 1, 0)
        self.linea_reemplazo = QLineEdit()
        grilla.addWidget(self.linea_reemplazo, 1, 1)
        self.check_cs = QCheckBox(self.tr("Respetar Case Sensitive"))
        self.check_cs.setChecked(True)
        grilla.addWidget(self.check_cs, 2, 0)
        self.check_wo = QCheckBox(self.tr("Buscar palabra completa"))
        self.check_wo.setChecked(True)
        grilla.addWidget(self.check_wo, 2, 1)

        box_botones = QHBoxLayout()
        box_botones.addStretch(1)
        btn_buscar = QPushButton(self.tr("Buscar"))
        box_botones.addWidget(btn_buscar)
        btn_reemplazar = QPushButton(self.tr("Reemplazar"))
        box_botones.addWidget(btn_reemplazar)
        btn_reemplazar_todo = QPushButton(self.tr("Reemplazar todo"))
        box_botones.addWidget(btn_reemplazar_todo)

        box.addLayout(grilla)
        box.addLayout(box_botones)

        btn_reemplazar.clicked.connect(self._reemplazar)
        btn_buscar.clicked.connect(self._buscar)
        btn_reemplazar_todo.clicked.connect(self._reemplazar_todo)
Example #30
0
class Banjo(TablaturePart):
    @staticmethod
    def title(_=__builtin__._):
        return _("Banjo")

    @staticmethod
    def short(_=__builtin__._):
        return _("abbreviation for Banjo", "Bj.")

    midiInstrument = "banjo"
    tabFormat = "fret-number-tablature-format-banjo"
    tunings = (
        ("banjo-open-g-tuning", lambda: _("Open G-tuning (aDGBD)")),
        ("banjo-c-tuning", lambda: _("C-tuning (gCGBD)")),
        ("banjo-modal-tuning", lambda: _("Modal tuning (gDGCD)")),
        ("banjo-open-d-tuning", lambda: _("Open D-tuning (aDF#AD)")),
        ("banjo-open-dm-tuning", lambda: _("Open Dm-tuning (aDFAD)")),
    )

    def createTuningWidgets(self, layout):
        super(Banjo, self).createTuningWidgets(layout)
        self.fourStrings = QCheckBox()
        layout.addWidget(self.fourStrings)

    def translateTuningWidgets(self):
        super(Banjo, self).translateTuningWidgets()
        self.fourStrings.setText(_("Four strings (instead of five)"))

    def setTunings(self, tab):
        if not self.fourStrings.isChecked():
            super(Banjo, self).setTunings(tab)
        else:
            tab.getWith()["stringTunings"] = ly.dom.Scheme(
                "(four-string-banjo {0})".format(self.tunings[self.tuning.currentIndex()][0])
            )
Example #31
0
class ControlForm(QtGui.QDialog):
    def __init__(self, proxy, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)

        self.proxy = proxy
        self.proxy.lights_on_changed.connect(self.object_lights_on_changed)
        self.proxy.door_open_changed.connect(self.object_door_open_changed)
        self.proxy.color_changed.connect(self.object_color_changed)

    def on_lights_on_changed(self, value):
        proxy.lights_on = self.lights.isChecked()

    def on_door_open_changed(self, value):
        proxy.door_open = self.door_open.isChecked()

    def object_lights_on_changed(self, value, old_value, other):
        if value == self.lights.isChecked():
            return
        self.lights.setChecked(value)

    def object_door_open_changed(self, value, old_value, other):
        if value == self.door_open.isChecked():
            return
        self.door_open.setChecked(value)

    def object_color_changed(self, value, old_value, other):
        if value == self.color.text():
            return
        self.color.setText(value)
        self.color.textChanged.emit(value)

    def on_color_text_changed(self, value):
        self.color_box.setStyleSheet("QLabel { background-color: %s }" % value)

    def setupUi(self, parent):
        self.resize(275, 172)
        self.setWindowTitle('House')

        self.layout = QVBoxLayout(parent)
        self.layout.setSizeConstraint(QLayout.SetFixedSize)
        #align = (Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)

        self.layout1 = QHBoxLayout()
        self.label1 = QLabel()
        self.label1.setMinimumSize(QSize(100, 0))
        self.label1.setText('Lights:')
        self.lights = QCheckBox()
        self.lights.setTristate(False)
        self.layout1.addWidget(self.label1)
        self.layout1.addWidget(self.lights)

        self.layout2 = QHBoxLayout()
        self.label2 = QLabel()
        self.label2.setMinimumSize(QSize(100, 0))
        self.label2.setText('Front door:')
        self.door_open = QCheckBox()
        self.door_open.setTristate(False)
        self.layout2.addWidget(self.label2)
        self.layout2.addWidget(self.door_open)

        self.layout3 = QHBoxLayout()
        self.label3 = QLabel()
        self.label3.setMinimumSize(QSize(100, 0))
        self.label3.setText('Color:')
        self.color = QLineEdit()
        self.color.setReadOnly(True)
        self.color.textChanged.connect(self.on_color_text_changed)
        self.color_box = QLabel()
        self.color_box.setText('  ')
        self.layout3.addWidget(self.label3)
        self.layout3.addWidget(self.color)
        self.layout3.addWidget(self.color_box)

        self.lights.stateChanged.connect(self.on_lights_on_changed)
        self.door_open.stateChanged.connect(self.on_door_open_changed)

        self.layout.addLayout(self.layout1)
        self.layout.addLayout(self.layout2)
        self.layout.addLayout(self.layout3)
Example #32
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
Example #33
0
    def __init__(self, config_in, ncols=2):
        super(LisaConfigWindow, self).__init__()

        self.setWindowTitle('Lisa Config')
        self.config = ConfigManager()
        self.ncols = ncols
        # used with other module. If it is set, lisa config is deleted
        self.reset_config = False

        CHOICE_A = "{pairwise_alpha_per_mm2: 45, return_only_object_with_seeds: true}"
        # CHOICE_A = 23

        CHOICE_B = 2
        CHOICE_C = 3
        CHOICE_D = 4

        map_dict = {
            'Graph-Cut': CHOICE_A,
            'Choice B': CHOICE_B,
            'Choice C': CHOICE_C,
            'Choice D': CHOICE_D,
        }
        config_def = {
            'working_voxelsize_mm': 2.0,
            'save_filetype': 'pklz',
            # 'manualroi': True,
            'segparams': CHOICE_A,
        }

        config_def.update(config_in)

        self.config.set_defaults(config_def)

        gd = QGridLayout()
        gd_max_i = 0
        for key, value in config_in.items():
            if type(value) is int:
                sb = QSpinBox()
                sb.setRange(-100000, 100000)
            elif type(value) is float:
                sb = QDoubleSpinBox()
            elif type(value) is str:
                sb = QLineEdit()
            elif type(value) is bool:
                sb = QCheckBox()
            else:
                logger.error("Unexpected type in config dictionary")

            row = gd_max_i / self.ncols
            col = (gd_max_i % self.ncols) * 2

            gd.addWidget(QLabel(key), row, col + 1)
            gd.addWidget(sb, row, col + 2)
            self.config.add_handler(key, sb)
            gd_max_i += 1

        # gd.addWidget(QLabel("save filetype"), 1, 1)
        # te = QLineEdit()
        # gd.addWidget(te, 1, 2)
        # self.config.add_handler('save_filetype', te)
        #
        # gd.addWidget(QLabel("segmentation parameters"), 2, 1)
        # te = QLineEdit()
        # gd.addWidget(te, 2, 2)
        # self.config.add_handler('segparams', te)

        # cb = QCheckBox()
        # gd.addWidget(cb, 2, 2)
        # self.config.add_handler('active', cb)

        # gd.addWidget(QLabel("segmentation parameters"), 3, 1)
        # cmb = QComboBox()
        # cmb.addItems(map_dict.keys())
        # gd.addWidget(cmb, 3, 2)
        # self.config.add_handler('segparams', cmb, mapper=map_dict)

        self.current_config_output = QTextEdit()
        # rid.setColumnMinimumWidth(3, logo.width()/2)
        text_col = (self.ncols * 2) + 3
        gd.setColumnMinimumWidth(text_col, 500)
        gd.addWidget(self.current_config_output, 1, text_col,
                     (gd_max_i / 2) - 1, 1)

        btn_reset_config = QPushButton("Reset and quit", self)
        btn_reset_config.clicked.connect(self.btnResetConfig)
        gd.addWidget(btn_reset_config, 0, text_col)

        btn_save_config = QPushButton("Save and quit", self)
        btn_save_config.clicked.connect(self.btnSaveConfig)
        gd.addWidget(btn_save_config, (gd_max_i / 2), text_col)

        self.config.updated.connect(self.show_config)

        self.show_config()

        # my line
        self.setLayout(gd)
    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)
Example #35
0
class MusicView(preferences.Group):
    def __init__(self, page):
        super(MusicView, self).__init__(page)

        layout = QGridLayout()
        self.setLayout(layout)

        self.newerFilesOnly = QCheckBox(toggled=self.changed)
        layout.addWidget(self.newerFilesOnly, 0, 0, 1, 3)

        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, 1, 0)
        layout.addWidget(self.magnifierSizeSlider, 1, 1)
        layout.addWidget(self.magnifierSizeSpinBox, 1, 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, 2, 0)
        layout.addWidget(self.magnifierScaleSlider, 2, 1)
        layout.addWidget(self.magnifierScaleSpinBox, 2, 2)

        self.enableKineticScrolling = QCheckBox(toggled=self.changed)
        layout.addWidget(self.enableKineticScrolling)
        self.showScrollbars = QCheckBox(toggled=self.changed)
        layout.addWidget(self.showScrollbars)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Music View"))
        self.newerFilesOnly.setText(_("Only load updated PDF documents"))
        self.newerFilesOnly.setToolTip(
            _("If checked, Frescobaldi will not open PDF documents that are not\n"
              "up-to-date (i.e. the source file has been modified later)."))
        self.magnifierSizeLabel.setText(_("Magnifier Size:"))
        self.magnifierSizeLabel.setToolTip(
            _("Size of the magnifier glass (Ctrl+Click in the Music View)."))
        # L10N: as in "400 pixels", appended after number in spinbox, note the leading space
        self.magnifierSizeSpinBox.setSuffix(_(" pixels"))
        self.magnifierScaleLabel.setText(_("Magnifier Scale:"))
        self.magnifierScaleLabel.setToolTip(
            _("Magnification of the magnifier."))
        self.magnifierScaleSpinBox.setSuffix(_("percent unit sign", "%"))
        # L10N: "Kinetic Scrolling" is a checkbox label, as in "Enable Kinetic Scrolling"
        self.enableKineticScrolling.setText(_("Kinetic Scrolling"))
        self.showScrollbars.setText(_("Show Scrollbars"))

    def loadSettings(self):
        s = popplerview.MagnifierSettings.load()
        self.magnifierSizeSlider.setValue(s.size)
        self.magnifierScaleSlider.setValue(s.scale)

        s = QSettings()
        s.beginGroup("musicview")
        newerFilesOnly = s.value("newer_files_only", True, bool)
        self.newerFilesOnly.setChecked(newerFilesOnly)
        kineticScrollingActive = s.value("kinetic_scrolling", True, bool)
        self.enableKineticScrolling.setChecked(kineticScrollingActive)
        showScrollbars = s.value("show_scrollbars", True, bool)
        self.showScrollbars.setChecked(showScrollbars)

    def saveSettings(self):
        s = popplerview.MagnifierSettings()
        s.size = self.magnifierSizeSlider.value()
        s.scale = self.magnifierScaleSlider.value()
        s.save()

        s = QSettings()
        s.beginGroup("musicview")
        s.setValue("newer_files_only", self.newerFilesOnly.isChecked())
        s.setValue("kinetic_scrolling",
                   self.enableKineticScrolling.isChecked())
        s.setValue("show_scrollbars", self.showScrollbars.isChecked())
Example #36
0
    def createWidgets(self):
        """
        """
        # options
        self.mergeCheckBox = QCheckBox(self.tr("Merge all tests in one"))
        if self.core().settings().cfg()["export-tests"]["merge-all-tests"]:
            self.mergeCheckBox.setCheckState(Qt.Checked) 
            
        self.showTcNameCheckBox = QCheckBox(self.tr("Load with original test name"))
        if self.core().settings().cfg()["export-tests"]["original-test"]:
            self.showTcNameCheckBox.setCheckState(Qt.Checked) 
            
        self.replaceTcCheckBox = QCheckBox(self.tr("Replace testcase with testname"))
        if self.core().settings().cfg()["export-tests"]["replace-testcase"]:
            self.replaceTcCheckBox.setCheckState(Qt.Checked) 
            
        self.mergeStepsCheckBox = QCheckBox(self.tr("Merge all steps in one"))
        if self.core().settings().cfg()["export-tests"]["merge-all-steps"]:
            self.mergeStepsCheckBox.setCheckState(Qt.Checked) 
            
        self.addMissingFoldersCheckBox = QCheckBox(self.tr("Create missing folders"))
        if self.core().settings().cfg()["export-tests"]["add-folders"]:
            self.addMissingFoldersCheckBox.setCheckState(Qt.Checked) 
            
        self.overwriteTcCheckBox = QCheckBox(self.tr("Overwrite testcase(s)"))
        if self.core().settings().cfg()["export-tests"]["overwrite-tests"]:
            self.overwriteTcCheckBox.setCheckState(Qt.Checked) 
            
        # actions to export
        self.loadCsvButton = QPushButton(self.tr("Load CSV"), self)
        
        self.exportButton = QPushButton(self.tr("Export Test"), self)
        self.exportButton.setMinimumWidth(300)
        self.exportStatusLabel = QLabel( "Status: Disconnected", self)

        # tables definition
        self.testsTable = TestsTableView(self, core=self.core())
        self.stepsTable = StepsTableView(self, core=self.core())
        
        # options layout
        optionsTpLayout = QHBoxLayout()
        optionsTpLayout.addWidget(self.addMissingFoldersCheckBox)
        optionsTpLayout.addWidget(self.overwriteTcCheckBox)
        optionsTpLayout.addStretch(1)
        
        optionsLayout = QHBoxLayout()
        optionsLayout.addWidget(self.mergeCheckBox)
        optionsLayout.addWidget(self.showTcNameCheckBox)
        optionsLayout.addWidget(self.replaceTcCheckBox)
        optionsLayout.addStretch(1)
        
        layoutGrid = QGridLayout()
        layoutGrid.addWidget(QLabel("Remote TestPlan:"), 0, 0)
        layoutGrid.addLayout(optionsTpLayout, 0, 1)
        layoutGrid.addWidget(QLabel("Local Test:"), 1, 0)
        layoutGrid.addLayout(optionsLayout, 1, 1)
        layoutGrid.addWidget(QLabel("Tests Listing:"), 2, 0)
        layoutGrid.addWidget(self.testsTable, 2, 1)
        layoutGrid.addWidget(self.mergeStepsCheckBox, 3, 1)
        layoutGrid.addWidget(QLabel("Steps Listing:"), 4, 0)
        layoutGrid.addWidget(self.stepsTable, 4, 1)
        
        layoutRight = QHBoxLayout()
        layoutRight.addWidget(self.exportButton)
        layoutRight.addWidget(self.loadCsvButton)
        layoutRight.addWidget(self.exportStatusLabel)
        layoutRight.addStretch(1)
        
        layoutGrid.addWidget(QLabel("Controls:"), 5, 0)
        layoutGrid.addLayout(layoutRight, 5, 1)
        
        layoutMain = QVBoxLayout()
        layoutMain.addLayout(layoutGrid)
    
        self.setLayout(layoutMain)
Example #37
0
class RawView(QWidget, Logger.ClassLogger):
    """
    Raw view widget
    """
    def __init__(self,
                 parent,
                 data,
                 toCsv=False,
                 toHtml=False,
                 toXml=False,
                 toPrinter=False,
                 toTxt=False,
                 toPdf=False):
        """
        Raw view widget

        @param parent: 
        @type parent:
        """
        QWidget.__init__(self, parent)
        self.parent = parent
        self.__data = data

        self.toCsv = toCsv
        self.toXml = toXml
        self.toCsv = toCsv
        self.toHtml = toHtml
        self.toPrinter = toPrinter
        self.toTxt = toTxt
        self.toPdf = toPdf

        self.createActions()
        self.createWidgets()
        self.createToolbars()
        self.createConnections()

    def createWidgets(self):
        """
        Create qt widgets
        """
        # prepare menu
        self.toolbar = QToolBar(self)
        self.toolbar.setStyleSheet(
            "QToolBar { border: 0px }")  # remove 3D border
        self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        self.toolbarPlugins = QToolBar(self)
        self.toolbarPlugins.setStyleSheet(
            "QToolBar { border: 0px }")  # remove 3D border
        self.toolbarPlugins.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        self.pluginsBox = QGroupBox("Plugins")
        self.pluginsBox.setStyleSheet("""
                                           QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } 
                                           QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } 
                                           QGroupBox::title { subcontrol-position: bottom center;}
                                       """)
        layoutPlugins = QHBoxLayout()
        layoutPlugins.addWidget(self.toolbarPlugins)
        layoutPlugins.setContentsMargins(0, 0, 0, 0)
        self.pluginsBox.setLayout(layoutPlugins)
        self.pluginsBox.hide()

        self.exportBox = QGroupBox("Exports")
        self.exportBox.setStyleSheet("""
                                           QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } 
                                           QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } 
                                           QGroupBox::title { subcontrol-position: bottom center;}
                                       """)
        layoutExports = QHBoxLayout()
        layoutExports.addWidget(self.toolbar)
        layoutExports.setContentsMargins(0, 0, 0, 0)
        self.exportBox.setLayout(layoutExports)

        layout = QVBoxLayout()

        if self.toXml:
            self.txtEdit = QtHelper.RawXmlEditor(parent=self)
            self.txtEdit.setText(self.__data)
            # self.txtEdit.setUtf8(True)
            self.txtEdit.setFont(QFont("Courier", 9))
        else:
            self.txtEdit = QtHelper.RawEditor(parent=self)
            self.txtEdit.setTabStopWidth(10)
            self.txtEdit.setText(self.__data)
            self.txtEdit.setFont(QFont("Courier", 9))

        self.txtEdit.setMinimumWidth(650)
        self.txtEdit.setMinimumHeight(400)

        self.delGroup = QGroupBox("Remove line")
        self.delTG = QCheckBox("TESTGLOBAL")
        self.delTP = QCheckBox("TESTPLAN")
        self.delTS = QCheckBox("TESTSUITE")
        self.delTU = QCheckBox("TESTUNIT")
        self.delTA = QCheckBox("TESTABSTRACT")
        self.delTC = QCheckBox("TESTCASE")
        self.delSTP = QCheckBox("STEP")

        layoutDel = QHBoxLayout()
        layoutDel.addWidget(self.delTG)
        layoutDel.addWidget(self.delTP)
        layoutDel.addWidget(self.delTS)
        layoutDel.addWidget(self.delTU)
        layoutDel.addWidget(self.delTA)
        layoutDel.addWidget(self.delTC)
        layoutDel.addWidget(self.delSTP)
        self.delGroup.setLayout(layoutDel)

        if self.toXml: self.delGroup.setEnabled(False)

        layoutToolbars = QHBoxLayout()
        layoutToolbars.addWidget(self.exportBox)
        layoutToolbars.addWidget(self.pluginsBox)
        layoutToolbars.addStretch(1)
        layoutToolbars.setContentsMargins(5, 0, 0, 0)

        layout.addLayout(layoutToolbars)
        layout.addWidget(self.delGroup)
        layout.addWidget(self.txtEdit)
        if not self.toXml:
            self.rawFind = QtHelper.RawFind(parent=self,
                                            editor=self.txtEdit,
                                            buttonNext=True)
            layout.addWidget(self.rawFind)

        self.setLayout(layout)

    def createConnections(self):
        """
        All qt connections
        """
        self.delTG.stateChanged.connect(self.onRemoveLines)
        self.delTP.stateChanged.connect(self.onRemoveLines)
        self.delTS.stateChanged.connect(self.onRemoveLines)
        self.delTU.stateChanged.connect(self.onRemoveLines)
        self.delTA.stateChanged.connect(self.onRemoveLines)
        self.delTC.stateChanged.connect(self.onRemoveLines)
        self.delSTP.stateChanged.connect(self.onRemoveLines)

    def createActions(self):
        """
        Qt Actions
        """
        self.saveCsvAction = QtHelper.createAction(self,
                                                   "&To CSV",
                                                   self.saveCsv,
                                                   tip='Save to CSV file',
                                                   icon=QIcon(":/csv.png"))
        self.saveTxtAction = QtHelper.createAction(
            self,
            "&To TXT",
            self.saveTxt,
            tip='Save to TXT file',
            icon=QIcon(":/file-txt.png"))
        self.saveHtmlAction = QtHelper.createAction(self,
                                                    "&To HTML",
                                                    self.saveHtml,
                                                    tip='Save to HTML file',
                                                    icon=QIcon(":/web.png"))
        self.savePdfAction = QtHelper.createAction(self,
                                                   "&To PDF",
                                                   self.savePdf,
                                                   tip='Save to PDF file',
                                                   icon=QIcon(":/to_pdf.png"))
        self.saveXmlAction = QtHelper.createAction(self,
                                                   "&To XML",
                                                   self.saveXml,
                                                   tip='Save to XML file',
                                                   icon=QIcon(":/xml.png"))
        self.toPrinterAction = QtHelper.createAction(
            self,
            "&To Printer",
            self.savePrinter,
            tip='Print',
            icon=QIcon(":/printer.png"))

    def createToolbars(self):
        """
        Toolbar creation
        """
        self.toolbar.setObjectName("Export toolbar")
        if self.toCsv: self.toolbar.addAction(self.saveCsvAction)
        if self.toTxt: self.toolbar.addAction(self.saveTxtAction)
        if self.toHtml: self.toolbar.addAction(self.saveHtmlAction)
        if self.toPdf: self.toolbar.addAction(self.savePdfAction)
        if self.toXml: self.toolbar.addAction(self.saveXmlAction)
        if self.toPrinter: self.toolbar.addAction(self.toPrinterAction)
        self.toolbar.setIconSize(QSize(16, 16))

    def registerPlugin(self, pluginAction):
        """
        Register plugin
        """
        self.toolbarPlugins.addAction(pluginAction)
        self.toolbarPlugins.setIconSize(QSize(16, 16))
        self.pluginsBox.show()

    def onRemoveLines(self):
        """
        Called to remove lines
        """
        ret = []
        for l in self.__data.splitlines():
            if self.delTG.checkState() and l.startswith("TESTGLOBAL"):
                continue
            elif self.delTP.checkState() and l.startswith("TESTPLAN"):
                continue
            elif self.delTS.checkState() and l.startswith("TESTSUITE"):
                continue
            elif self.delTU.checkState() and l.startswith("TESTUNIT"):
                continue
            elif self.delTA.checkState() and l.startswith("TESTABSTRACT"):
                continue
            elif self.delTC.checkState() and l.startswith("TESTCASE"):
                continue
            elif self.delSTP.checkState() and l.startswith("STEP"):
                continue
            else:
                ret.append(l)
        self.txtEdit.setText("\n".join(ret))
        del ret

    def savePrinter(self):
        """
        Save to printer
        """
        printer = QPrinter()
        dialog = QPrintDialog(printer, self)
        dialog.setWindowTitle("Print")

        if dialog.exec_() != QDialog.Accepted:
            return

        if QtHelper.IS_QT5:  # new in v18
            self.fileName = printer
            self.txtEdit.page().toHtml(self.__toPrinter)
        else:
            doc = QTextDocument()
            doc.setPlainText(self.txtEdit.text())
            doc.print_(printer)

    def __toPrinter(self, html):
        """
        New in v18
        Callback from QWebpage
        """
        textEdit = QTextEdit(self)
        textEdit.setHtml(html)
        textEdit.print(self.fileName)
        textEdit.deleteLater()

        self.fileName = None

    def saveCsv(self):
        """
        Save to csv file
        """
        fileName = QFileDialog.getSaveFileName(
            self, "Save CSV file", "", "CSV file (*.csv);;All Files (*.*)")

        # new in v17.1
        if QtHelper.IS_QT5:
            _filename, _type = fileName
        else:
            _filename = fileName
        # end of new

        if _filename:
            try:
                f = open(_filename, 'w')
                f.write(self.txtEdit.toPlainText())
                f.close()
            except Exception as e:
                self.error('unable to save report file as txt: %s' % str(e))

    def saveTxt(self):
        """
        Save to txt file
        """
        fileName = QFileDialog.getSaveFileName(
            self, "Save TXT file", "", "TXT file (*.txt);;All Files (*.*)")

        # new in v17.1
        if QtHelper.IS_QT5:
            _filename, _type = fileName
        else:
            _filename = fileName
        # end of new

        if _filename:
            try:
                f = open(_filename, 'w')
                f.write(self.txtEdit.toPlainText())
                f.close()
            except Exception as e:
                self.error('unable to save report file as txt: %s' % str(e))

    def saveXml(self):
        """
        Save to xml file
        """
        fileName = QFileDialog.getSaveFileName(
            self, "Save XML file", "", "XML file (*.xml);;All Files (*.*)")

        # new in v17.1
        if QtHelper.IS_QT5:
            _filename, _type = fileName
        else:
            _filename = fileName
        # end of new

        if _filename:
            try:
                with codecs.open(_filename, "w", "utf-8") as f:
                    f.write(self.txtEdit.text())
            except Exception as e:
                self.error('unable to save design file as xml: %s' % str(e))

    def saveHtml(self):
        """
        Save to html file
        """
        fileName = QFileDialog.getSaveFileName(
            self, "Save HTML file", "", "HTML file (*.html);;All Files (*.*)")

        # new in v17.1
        if QtHelper.IS_QT5:
            _filename, _type = fileName
        else:
            _filename = fileName
        # end of new

        if _filename:
            try:
                f = open(_filename, 'w')
                f.write(self.txtEdit.toHtml())
                f.close()
            except Exception as e:
                self.error('unable to save report file as html: %s' % str(e))

    def savePdf(self):
        """
        Save pdf file
        """
        fileName = QFileDialog.getSaveFileName(
            self, 'Save to PDF', "", "PDF file (*.pdf);;All Files (*.*)")

        # new in v17.1
        if QtHelper.IS_QT5:
            _filename, _type = fileName
        else:
            _filename = fileName
        # end of new

        if _filename:
            printer = QPrinter(QPrinter.HighResolution)
            printer.setPageSize(QPrinter.A4)
            printer.setColorMode(QPrinter.Color)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(_filename)

            doc = QTextDocument()
            if self.toXml:
                doc.setPlainText(self.txtEdit.text())
            else:
                doc.setHtml(self.txtEdit.toHtml())
            doc.print_(printer)
Example #38
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle(
            QCoreApplication.translate("PythonConsole", "Python Console"))

        self.settings = QSettings()

        self.shell = ShellScintilla(self)
        self.setFocusProxy(self.shell)
        self.shellOut = ShellOutputScintilla(self)
        self.tabEditorWidget = EditorTabWidget(self)

        ##------------ UI -------------------------------

        self.splitterEditor = QSplitter(self)
        self.splitterEditor.setOrientation(Qt.Horizontal)
        self.splitterEditor.setHandleWidth(6)
        self.splitterEditor.setChildrenCollapsible(True)
        self.splitter = QSplitter(self.splitterEditor)
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setHandleWidth(3)
        self.splitter.setChildrenCollapsible(False)
        self.splitter.addWidget(self.shellOut)
        self.splitter.addWidget(self.shell)
        #self.splitterEditor.addWidget(self.tabEditorWidget)

        self.splitterObj = QSplitter(self.splitterEditor)
        self.splitterObj.setHandleWidth(3)
        self.splitterObj.setOrientation(Qt.Horizontal)
        #self.splitterObj.setSizes([0, 0])
        #self.splitterObj.setStretchFactor(0, 1)

        self.widgetEditor = QWidget(self.splitterObj)
        self.widgetFind = QWidget(self)

        self.listClassMethod = QTreeWidget(self.splitterObj)
        self.listClassMethod.setColumnCount(2)
        objInspLabel = QCoreApplication.translate("PythonConsole",
                                                  "Object Inspector")
        self.listClassMethod.setHeaderLabels([objInspLabel, ''])
        self.listClassMethod.setColumnHidden(1, True)
        self.listClassMethod.setAlternatingRowColors(True)

        #self.splitterEditor.addWidget(self.widgetEditor)
        #self.splitterObj.addWidget(self.listClassMethod)
        #self.splitterObj.addWidget(self.widgetEditor)

        # Hide side editor on start up
        self.splitterObj.hide()
        self.listClassMethod.hide()
        # Hide search widget on start up
        self.widgetFind.hide()

        sizes = self.splitter.sizes()
        self.splitter.setSizes(sizes)

        ##----------------Restore Settings------------------------------------

        self.restoreSettingsConsole()

        ##------------------Toolbar Editor-------------------------------------

        ## Action for Open File
        openFileBt = QCoreApplication.translate("PythonConsole", "Open file")
        self.openFileButton = QAction(self)
        self.openFileButton.setCheckable(False)
        self.openFileButton.setEnabled(True)
        self.openFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconOpenConsole.png"))
        self.openFileButton.setMenuRole(QAction.PreferencesRole)
        self.openFileButton.setIconVisibleInMenu(True)
        self.openFileButton.setToolTip(openFileBt)
        self.openFileButton.setText(openFileBt)
        ## Action for Save File
        saveFileBt = QCoreApplication.translate("PythonConsole", "Save")
        self.saveFileButton = QAction(self)
        self.saveFileButton.setCheckable(False)
        self.saveFileButton.setEnabled(False)
        self.saveFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveConsole.png"))
        self.saveFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveFileButton.setIconVisibleInMenu(True)
        self.saveFileButton.setToolTip(saveFileBt)
        self.saveFileButton.setText(saveFileBt)
        ## Action for Save File As
        saveAsFileBt = QCoreApplication.translate("PythonConsole",
                                                  "Save As...")
        self.saveAsFileButton = QAction(self)
        self.saveAsFileButton.setCheckable(False)
        self.saveAsFileButton.setEnabled(True)
        self.saveAsFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveAsConsole.png"))
        self.saveAsFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveAsFileButton.setIconVisibleInMenu(True)
        self.saveAsFileButton.setToolTip(saveAsFileBt)
        self.saveAsFileButton.setText(saveAsFileBt)
        ## Action Cut
        cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut")
        self.cutEditorButton = QAction(self)
        self.cutEditorButton.setCheckable(False)
        self.cutEditorButton.setEnabled(True)
        self.cutEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCutEditorConsole.png"))
        self.cutEditorButton.setMenuRole(QAction.PreferencesRole)
        self.cutEditorButton.setIconVisibleInMenu(True)
        self.cutEditorButton.setToolTip(cutEditorBt)
        self.cutEditorButton.setText(cutEditorBt)
        ## Action Copy
        copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy")
        self.copyEditorButton = QAction(self)
        self.copyEditorButton.setCheckable(False)
        self.copyEditorButton.setEnabled(True)
        self.copyEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png"))
        self.copyEditorButton.setMenuRole(QAction.PreferencesRole)
        self.copyEditorButton.setIconVisibleInMenu(True)
        self.copyEditorButton.setToolTip(copyEditorBt)
        self.copyEditorButton.setText(copyEditorBt)
        ## Action Paste
        pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste")
        self.pasteEditorButton = QAction(self)
        self.pasteEditorButton.setCheckable(False)
        self.pasteEditorButton.setEnabled(True)
        self.pasteEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png"))
        self.pasteEditorButton.setMenuRole(QAction.PreferencesRole)
        self.pasteEditorButton.setIconVisibleInMenu(True)
        self.pasteEditorButton.setToolTip(pasteEditorBt)
        self.pasteEditorButton.setText(pasteEditorBt)
        ## Action Run Script (subprocess)
        runScriptEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Run script")
        self.runScriptEditorButton = QAction(self)
        self.runScriptEditorButton.setCheckable(False)
        self.runScriptEditorButton.setEnabled(True)
        self.runScriptEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunScriptConsole.png"))
        self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole)
        self.runScriptEditorButton.setIconVisibleInMenu(True)
        self.runScriptEditorButton.setToolTip(runScriptEditorBt)
        self.runScriptEditorButton.setText(runScriptEditorBt)
        ## Action Run Script (subprocess)
        commentEditorBt = QCoreApplication.translate("PythonConsole",
                                                     "Comment")
        self.commentEditorButton = QAction(self)
        self.commentEditorButton.setCheckable(False)
        self.commentEditorButton.setEnabled(True)
        self.commentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconCommentEditorConsole.png"))
        self.commentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.commentEditorButton.setIconVisibleInMenu(True)
        self.commentEditorButton.setToolTip(commentEditorBt)
        self.commentEditorButton.setText(commentEditorBt)
        ## Action Run Script (subprocess)
        uncommentEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Uncomment")
        self.uncommentEditorButton = QAction(self)
        self.uncommentEditorButton.setCheckable(False)
        self.uncommentEditorButton.setEnabled(True)
        self.uncommentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconUncommentEditorConsole.png"))
        self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.uncommentEditorButton.setIconVisibleInMenu(True)
        self.uncommentEditorButton.setToolTip(uncommentEditorBt)
        self.uncommentEditorButton.setText(uncommentEditorBt)
        ## Action for Object browser
        objList = QCoreApplication.translate("PythonConsole",
                                             "Object Inspector")
        self.objectListButton = QAction(self)
        self.objectListButton.setCheckable(True)
        self.objectListButton.setEnabled(
            self.settings.value("pythonConsole/enableObjectInsp",
                                False,
                                type=bool))
        self.objectListButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png"))
        self.objectListButton.setMenuRole(QAction.PreferencesRole)
        self.objectListButton.setIconVisibleInMenu(True)
        self.objectListButton.setToolTip(objList)
        self.objectListButton.setText(objList)
        ## Action for Find text
        findText = QCoreApplication.translate("PythonConsole", "Find Text")
        self.findTextButton = QAction(self)
        self.findTextButton.setCheckable(True)
        self.findTextButton.setEnabled(True)
        self.findTextButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png"))
        self.findTextButton.setMenuRole(QAction.PreferencesRole)
        self.findTextButton.setIconVisibleInMenu(True)
        self.findTextButton.setToolTip(findText)
        self.findTextButton.setText(findText)

        ##----------------Toolbar Console-------------------------------------

        ## Action Show Editor
        showEditor = QCoreApplication.translate("PythonConsole", "Show editor")
        self.showEditorButton = QAction(self)
        self.showEditorButton.setEnabled(True)
        self.showEditorButton.setCheckable(True)
        self.showEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.showEditorButton.setMenuRole(QAction.PreferencesRole)
        self.showEditorButton.setIconVisibleInMenu(True)
        self.showEditorButton.setToolTip(showEditor)
        self.showEditorButton.setText(showEditor)
        ## Action for Clear button
        clearBt = QCoreApplication.translate("PythonConsole", "Clear console")
        self.clearButton = QAction(self)
        self.clearButton.setCheckable(False)
        self.clearButton.setEnabled(True)
        self.clearButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClearConsole.png"))
        self.clearButton.setMenuRole(QAction.PreferencesRole)
        self.clearButton.setIconVisibleInMenu(True)
        self.clearButton.setToolTip(clearBt)
        self.clearButton.setText(clearBt)
        ## Action for settings
        optionsBt = QCoreApplication.translate("PythonConsole", "Settings")
        self.optionsButton = QAction(self)
        self.optionsButton.setCheckable(False)
        self.optionsButton.setEnabled(True)
        self.optionsButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSettingsConsole.png"))
        self.optionsButton.setMenuRole(QAction.PreferencesRole)
        self.optionsButton.setIconVisibleInMenu(True)
        self.optionsButton.setToolTip(optionsBt)
        self.optionsButton.setText(optionsBt)
        ## Action menu for class
        actionClassBt = QCoreApplication.translate("PythonConsole",
                                                   "Import Class")
        self.actionClass = QAction(self)
        self.actionClass.setCheckable(False)
        self.actionClass.setEnabled(True)
        self.actionClass.setIcon(
            QgsApplication.getThemeIcon("console/iconClassConsole.png"))
        self.actionClass.setMenuRole(QAction.PreferencesRole)
        self.actionClass.setIconVisibleInMenu(True)
        self.actionClass.setToolTip(actionClassBt)
        self.actionClass.setText(actionClassBt)
        ## Import Processing class
        loadProcessingBt = QCoreApplication.translate(
            "PythonConsole", "Import Processing class")
        self.loadProcessingButton = QAction(self)
        self.loadProcessingButton.setCheckable(False)
        self.loadProcessingButton.setEnabled(True)
        self.loadProcessingButton.setIcon(
            QgsApplication.getThemeIcon("console/iconProcessingConsole.png"))
        self.loadProcessingButton.setMenuRole(QAction.PreferencesRole)
        self.loadProcessingButton.setIconVisibleInMenu(True)
        self.loadProcessingButton.setToolTip(loadProcessingBt)
        self.loadProcessingButton.setText(loadProcessingBt)
        ## Import QtCore class
        loadQtCoreBt = QCoreApplication.translate("PythonConsole",
                                                  "Import PyQt.QtCore class")
        self.loadQtCoreButton = QAction(self)
        self.loadQtCoreButton.setCheckable(False)
        self.loadQtCoreButton.setEnabled(True)
        self.loadQtCoreButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtCoreConsole.png"))
        self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtCoreButton.setIconVisibleInMenu(True)
        self.loadQtCoreButton.setToolTip(loadQtCoreBt)
        self.loadQtCoreButton.setText(loadQtCoreBt)
        ## Import QtGui class
        loadQtGuiBt = QCoreApplication.translate("PythonConsole",
                                                 "Import PyQt.QtGui class")
        self.loadQtGuiButton = QAction(self)
        self.loadQtGuiButton.setCheckable(False)
        self.loadQtGuiButton.setEnabled(True)
        self.loadQtGuiButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtGuiConsole.png"))
        self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtGuiButton.setIconVisibleInMenu(True)
        self.loadQtGuiButton.setToolTip(loadQtGuiBt)
        self.loadQtGuiButton.setText(loadQtGuiBt)
        ## Action for Run script
        runBt = QCoreApplication.translate("PythonConsole", "Run command")
        self.runButton = QAction(self)
        self.runButton.setCheckable(False)
        self.runButton.setEnabled(True)
        self.runButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunConsole.png"))
        self.runButton.setMenuRole(QAction.PreferencesRole)
        self.runButton.setIconVisibleInMenu(True)
        self.runButton.setToolTip(runBt)
        self.runButton.setText(runBt)
        ## Help action
        helpBt = QCoreApplication.translate("PythonConsole", "Help")
        self.helpButton = QAction(self)
        self.helpButton.setCheckable(False)
        self.helpButton.setEnabled(True)
        self.helpButton.setIcon(
            QgsApplication.getThemeIcon("console/iconHelpConsole.png"))
        self.helpButton.setMenuRole(QAction.PreferencesRole)
        self.helpButton.setIconVisibleInMenu(True)
        self.helpButton.setToolTip(helpBt)
        self.helpButton.setText(helpBt)

        self.toolBar = QToolBar()
        self.toolBar.setEnabled(True)
        self.toolBar.setFocusPolicy(Qt.NoFocus)
        self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBar.setLayoutDirection(Qt.LeftToRight)
        self.toolBar.setIconSize(QSize(24, 24))
        self.toolBar.setOrientation(Qt.Vertical)
        self.toolBar.setMovable(True)
        self.toolBar.setFloatable(True)
        self.toolBar.addAction(self.clearButton)
        self.toolBar.addAction(self.actionClass)
        self.toolBar.addAction(self.runButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.showEditorButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.optionsButton)
        self.toolBar.addAction(self.helpButton)

        self.toolBarEditor = QToolBar()
        # self.toolBarEditor.setStyleSheet('QToolBar{background-color: rgb(%s, %s, %s' % tuple(bkgrcolor) + ');\
        #                                   border-right: 1px solid rgb(%s, %s, %s' % tuple(bordercl) + ');}')
        self.toolBarEditor.setEnabled(False)
        self.toolBarEditor.setFocusPolicy(Qt.NoFocus)
        self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBarEditor.setLayoutDirection(Qt.LeftToRight)
        self.toolBarEditor.setIconSize(QSize(18, 18))
        self.toolBarEditor.setOrientation(Qt.Vertical)
        self.toolBarEditor.setMovable(True)
        self.toolBarEditor.setFloatable(True)
        self.toolBarEditor.addAction(self.openFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.saveFileButton)
        self.toolBarEditor.addAction(self.saveAsFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.findTextButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.cutEditorButton)
        self.toolBarEditor.addAction(self.copyEditorButton)
        self.toolBarEditor.addAction(self.pasteEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.commentEditorButton)
        self.toolBarEditor.addAction(self.uncommentEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.objectListButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.runScriptEditorButton)

        ## Menu Import Class
        self.classMenu = QMenu()
        self.classMenu.addAction(self.loadProcessingButton)
        self.classMenu.addAction(self.loadQtCoreButton)
        self.classMenu.addAction(self.loadQtGuiButton)
        cM = self.toolBar.widgetForAction(self.actionClass)
        cM.setMenu(self.classMenu)
        cM.setPopupMode(QToolButton.InstantPopup)

        self.widgetButton = QWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButton.sizePolicy().hasHeightForWidth())
        self.widgetButton.setSizePolicy(sizePolicy)

        self.widgetButtonEditor = QWidget(self.widgetEditor)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButtonEditor.sizePolicy().hasHeightForWidth())
        self.widgetButtonEditor.setSizePolicy(sizePolicy)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.shellOut.sizePolicy().hasHeightForWidth())
        self.shellOut.setSizePolicy(sizePolicy)

        self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        ##------------ Layout -------------------------------

        self.mainLayout = QGridLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1)
        self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1)

        self.layoutEditor = QGridLayout(self.widgetEditor)
        self.layoutEditor.setMargin(0)
        self.layoutEditor.setSpacing(0)
        self.layoutEditor.addWidget(self.widgetButtonEditor, 0, 0, 2, 1)
        self.layoutEditor.addWidget(self.tabEditorWidget, 0, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetFind, 1, 1, 1, 1)

        self.toolBarLayout = QGridLayout(self.widgetButton)
        self.toolBarLayout.setMargin(0)
        self.toolBarLayout.setSpacing(0)
        self.toolBarLayout.addWidget(self.toolBar)
        self.toolBarEditorLayout = QGridLayout(self.widgetButtonEditor)
        self.toolBarEditorLayout.setMargin(0)
        self.toolBarEditorLayout.setSpacing(0)
        self.toolBarEditorLayout.addWidget(self.toolBarEditor)

        ## Layout for the find widget
        self.layoutFind = QGridLayout(self.widgetFind)
        self.layoutFind.setContentsMargins(0, 0, 0, 0)
        self.lineEditFind = QgsFilterLineEdit()
        placeHolderTxt = QCoreApplication.translate("PythonConsole",
                                                    "Enter text to find...")

        if pyqtconfig.Configuration().qt_version >= 0x40700:
            self.lineEditFind.setPlaceholderText(placeHolderTxt)
        else:
            self.lineEditFind.setToolTip(placeHolderTxt)
        self.findNextButton = QToolButton()
        self.findNextButton.setEnabled(False)
        toolTipfindNext = QCoreApplication.translate("PythonConsole",
                                                     "Find Next")
        self.findNextButton.setToolTip(toolTipfindNext)
        self.findNextButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchNextEditorConsole.png"))
        self.findNextButton.setIconSize(QSize(24, 24))
        self.findNextButton.setAutoRaise(True)
        self.findPrevButton = QToolButton()
        self.findPrevButton.setEnabled(False)
        toolTipfindPrev = QCoreApplication.translate("PythonConsole",
                                                     "Find Previous")
        self.findPrevButton.setToolTip(toolTipfindPrev)
        self.findPrevButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchPrevEditorConsole.png"))
        self.findPrevButton.setIconSize(QSize(24, 24))
        self.findPrevButton.setAutoRaise(True)
        self.caseSensitive = QCheckBox()
        caseSensTr = QCoreApplication.translate("PythonConsole",
                                                "Case Sensitive")
        self.caseSensitive.setText(caseSensTr)
        self.wholeWord = QCheckBox()
        wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word")
        self.wholeWord.setText(wholeWordTr)
        self.wrapAround = QCheckBox()
        self.wrapAround.setChecked(True)
        wrapAroundTr = QCoreApplication.translate("PythonConsole",
                                                  "Wrap Around")
        self.wrapAround.setText(wrapAroundTr)
        self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1)
        self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1)
        self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1)
        self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1)
        self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1)
        self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1)

        ##------------ Add first Tab in Editor -------------------------------

        #self.tabEditorWidget.newTabEditor(tabName='first', filename=None)

        ##------------ Signal -------------------------------

        self.findTextButton.toggled.connect(self.findTextEditor)
        self.objectListButton.toggled.connect(self.toggleObjectListWidget)
        self.commentEditorButton.triggered.connect(self.commentCode)
        self.uncommentEditorButton.triggered.connect(self.uncommentCode)
        self.runScriptEditorButton.triggered.connect(self.runScriptEditor)
        self.cutEditorButton.triggered.connect(self.cutEditor)
        self.copyEditorButton.triggered.connect(self.copyEditor)
        self.pasteEditorButton.triggered.connect(self.pasteEditor)
        self.showEditorButton.toggled.connect(self.toggleEditor)
        self.clearButton.triggered.connect(self.shellOut.clearConsole)
        self.optionsButton.triggered.connect(self.openSettings)
        self.loadProcessingButton.triggered.connect(self.processing)
        self.loadQtCoreButton.triggered.connect(self.qtCore)
        self.loadQtGuiButton.triggered.connect(self.qtGui)
        self.runButton.triggered.connect(self.shell.entered)
        self.openFileButton.triggered.connect(self.openScriptFile)
        self.saveFileButton.triggered.connect(self.saveScriptFile)
        self.saveAsFileButton.triggered.connect(self.saveAsScriptFile)
        self.helpButton.triggered.connect(self.openHelp)
        self.connect(self.listClassMethod,
                     SIGNAL('itemClicked(QTreeWidgetItem*, int)'),
                     self.onClickGoToLine)
        self.lineEditFind.returnPressed.connect(self._findText)
        self.findNextButton.clicked.connect(self._findNext)
        self.findPrevButton.clicked.connect(self._findPrev)
        self.lineEditFind.textChanged.connect(self._textFindChanged)
Example #39
0
class PythonConsoleWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle(
            QCoreApplication.translate("PythonConsole", "Python Console"))

        self.settings = QSettings()

        self.shell = ShellScintilla(self)
        self.setFocusProxy(self.shell)
        self.shellOut = ShellOutputScintilla(self)
        self.tabEditorWidget = EditorTabWidget(self)

        ##------------ UI -------------------------------

        self.splitterEditor = QSplitter(self)
        self.splitterEditor.setOrientation(Qt.Horizontal)
        self.splitterEditor.setHandleWidth(6)
        self.splitterEditor.setChildrenCollapsible(True)
        self.splitter = QSplitter(self.splitterEditor)
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setHandleWidth(3)
        self.splitter.setChildrenCollapsible(False)
        self.splitter.addWidget(self.shellOut)
        self.splitter.addWidget(self.shell)
        #self.splitterEditor.addWidget(self.tabEditorWidget)

        self.splitterObj = QSplitter(self.splitterEditor)
        self.splitterObj.setHandleWidth(3)
        self.splitterObj.setOrientation(Qt.Horizontal)
        #self.splitterObj.setSizes([0, 0])
        #self.splitterObj.setStretchFactor(0, 1)

        self.widgetEditor = QWidget(self.splitterObj)
        self.widgetFind = QWidget(self)

        self.listClassMethod = QTreeWidget(self.splitterObj)
        self.listClassMethod.setColumnCount(2)
        objInspLabel = QCoreApplication.translate("PythonConsole",
                                                  "Object Inspector")
        self.listClassMethod.setHeaderLabels([objInspLabel, ''])
        self.listClassMethod.setColumnHidden(1, True)
        self.listClassMethod.setAlternatingRowColors(True)

        #self.splitterEditor.addWidget(self.widgetEditor)
        #self.splitterObj.addWidget(self.listClassMethod)
        #self.splitterObj.addWidget(self.widgetEditor)

        # Hide side editor on start up
        self.splitterObj.hide()
        self.listClassMethod.hide()
        # Hide search widget on start up
        self.widgetFind.hide()

        sizes = self.splitter.sizes()
        self.splitter.setSizes(sizes)

        ##----------------Restore Settings------------------------------------

        self.restoreSettingsConsole()

        ##------------------Toolbar Editor-------------------------------------

        ## Action for Open File
        openFileBt = QCoreApplication.translate("PythonConsole", "Open file")
        self.openFileButton = QAction(self)
        self.openFileButton.setCheckable(False)
        self.openFileButton.setEnabled(True)
        self.openFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconOpenConsole.png"))
        self.openFileButton.setMenuRole(QAction.PreferencesRole)
        self.openFileButton.setIconVisibleInMenu(True)
        self.openFileButton.setToolTip(openFileBt)
        self.openFileButton.setText(openFileBt)
        ## Action for Save File
        saveFileBt = QCoreApplication.translate("PythonConsole", "Save")
        self.saveFileButton = QAction(self)
        self.saveFileButton.setCheckable(False)
        self.saveFileButton.setEnabled(False)
        self.saveFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveConsole.png"))
        self.saveFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveFileButton.setIconVisibleInMenu(True)
        self.saveFileButton.setToolTip(saveFileBt)
        self.saveFileButton.setText(saveFileBt)
        ## Action for Save File As
        saveAsFileBt = QCoreApplication.translate("PythonConsole",
                                                  "Save As...")
        self.saveAsFileButton = QAction(self)
        self.saveAsFileButton.setCheckable(False)
        self.saveAsFileButton.setEnabled(True)
        self.saveAsFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveAsConsole.png"))
        self.saveAsFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveAsFileButton.setIconVisibleInMenu(True)
        self.saveAsFileButton.setToolTip(saveAsFileBt)
        self.saveAsFileButton.setText(saveAsFileBt)
        ## Action Cut
        cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut")
        self.cutEditorButton = QAction(self)
        self.cutEditorButton.setCheckable(False)
        self.cutEditorButton.setEnabled(True)
        self.cutEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCutEditorConsole.png"))
        self.cutEditorButton.setMenuRole(QAction.PreferencesRole)
        self.cutEditorButton.setIconVisibleInMenu(True)
        self.cutEditorButton.setToolTip(cutEditorBt)
        self.cutEditorButton.setText(cutEditorBt)
        ## Action Copy
        copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy")
        self.copyEditorButton = QAction(self)
        self.copyEditorButton.setCheckable(False)
        self.copyEditorButton.setEnabled(True)
        self.copyEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png"))
        self.copyEditorButton.setMenuRole(QAction.PreferencesRole)
        self.copyEditorButton.setIconVisibleInMenu(True)
        self.copyEditorButton.setToolTip(copyEditorBt)
        self.copyEditorButton.setText(copyEditorBt)
        ## Action Paste
        pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste")
        self.pasteEditorButton = QAction(self)
        self.pasteEditorButton.setCheckable(False)
        self.pasteEditorButton.setEnabled(True)
        self.pasteEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png"))
        self.pasteEditorButton.setMenuRole(QAction.PreferencesRole)
        self.pasteEditorButton.setIconVisibleInMenu(True)
        self.pasteEditorButton.setToolTip(pasteEditorBt)
        self.pasteEditorButton.setText(pasteEditorBt)
        ## Action Run Script (subprocess)
        runScriptEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Run script")
        self.runScriptEditorButton = QAction(self)
        self.runScriptEditorButton.setCheckable(False)
        self.runScriptEditorButton.setEnabled(True)
        self.runScriptEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunScriptConsole.png"))
        self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole)
        self.runScriptEditorButton.setIconVisibleInMenu(True)
        self.runScriptEditorButton.setToolTip(runScriptEditorBt)
        self.runScriptEditorButton.setText(runScriptEditorBt)
        ## Action Run Script (subprocess)
        commentEditorBt = QCoreApplication.translate("PythonConsole",
                                                     "Comment")
        self.commentEditorButton = QAction(self)
        self.commentEditorButton.setCheckable(False)
        self.commentEditorButton.setEnabled(True)
        self.commentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconCommentEditorConsole.png"))
        self.commentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.commentEditorButton.setIconVisibleInMenu(True)
        self.commentEditorButton.setToolTip(commentEditorBt)
        self.commentEditorButton.setText(commentEditorBt)
        ## Action Run Script (subprocess)
        uncommentEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Uncomment")
        self.uncommentEditorButton = QAction(self)
        self.uncommentEditorButton.setCheckable(False)
        self.uncommentEditorButton.setEnabled(True)
        self.uncommentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconUncommentEditorConsole.png"))
        self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.uncommentEditorButton.setIconVisibleInMenu(True)
        self.uncommentEditorButton.setToolTip(uncommentEditorBt)
        self.uncommentEditorButton.setText(uncommentEditorBt)
        ## Action for Object browser
        objList = QCoreApplication.translate("PythonConsole",
                                             "Object Inspector")
        self.objectListButton = QAction(self)
        self.objectListButton.setCheckable(True)
        self.objectListButton.setEnabled(
            self.settings.value("pythonConsole/enableObjectInsp",
                                False,
                                type=bool))
        self.objectListButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png"))
        self.objectListButton.setMenuRole(QAction.PreferencesRole)
        self.objectListButton.setIconVisibleInMenu(True)
        self.objectListButton.setToolTip(objList)
        self.objectListButton.setText(objList)
        ## Action for Find text
        findText = QCoreApplication.translate("PythonConsole", "Find Text")
        self.findTextButton = QAction(self)
        self.findTextButton.setCheckable(True)
        self.findTextButton.setEnabled(True)
        self.findTextButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png"))
        self.findTextButton.setMenuRole(QAction.PreferencesRole)
        self.findTextButton.setIconVisibleInMenu(True)
        self.findTextButton.setToolTip(findText)
        self.findTextButton.setText(findText)

        ##----------------Toolbar Console-------------------------------------

        ## Action Show Editor
        showEditor = QCoreApplication.translate("PythonConsole", "Show editor")
        self.showEditorButton = QAction(self)
        self.showEditorButton.setEnabled(True)
        self.showEditorButton.setCheckable(True)
        self.showEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.showEditorButton.setMenuRole(QAction.PreferencesRole)
        self.showEditorButton.setIconVisibleInMenu(True)
        self.showEditorButton.setToolTip(showEditor)
        self.showEditorButton.setText(showEditor)
        ## Action for Clear button
        clearBt = QCoreApplication.translate("PythonConsole", "Clear console")
        self.clearButton = QAction(self)
        self.clearButton.setCheckable(False)
        self.clearButton.setEnabled(True)
        self.clearButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClearConsole.png"))
        self.clearButton.setMenuRole(QAction.PreferencesRole)
        self.clearButton.setIconVisibleInMenu(True)
        self.clearButton.setToolTip(clearBt)
        self.clearButton.setText(clearBt)
        ## Action for settings
        optionsBt = QCoreApplication.translate("PythonConsole", "Settings")
        self.optionsButton = QAction(self)
        self.optionsButton.setCheckable(False)
        self.optionsButton.setEnabled(True)
        self.optionsButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSettingsConsole.png"))
        self.optionsButton.setMenuRole(QAction.PreferencesRole)
        self.optionsButton.setIconVisibleInMenu(True)
        self.optionsButton.setToolTip(optionsBt)
        self.optionsButton.setText(optionsBt)
        ## Action menu for class
        actionClassBt = QCoreApplication.translate("PythonConsole",
                                                   "Import Class")
        self.actionClass = QAction(self)
        self.actionClass.setCheckable(False)
        self.actionClass.setEnabled(True)
        self.actionClass.setIcon(
            QgsApplication.getThemeIcon("console/iconClassConsole.png"))
        self.actionClass.setMenuRole(QAction.PreferencesRole)
        self.actionClass.setIconVisibleInMenu(True)
        self.actionClass.setToolTip(actionClassBt)
        self.actionClass.setText(actionClassBt)
        ## Import Processing class
        loadProcessingBt = QCoreApplication.translate(
            "PythonConsole", "Import Processing class")
        self.loadProcessingButton = QAction(self)
        self.loadProcessingButton.setCheckable(False)
        self.loadProcessingButton.setEnabled(True)
        self.loadProcessingButton.setIcon(
            QgsApplication.getThemeIcon("console/iconProcessingConsole.png"))
        self.loadProcessingButton.setMenuRole(QAction.PreferencesRole)
        self.loadProcessingButton.setIconVisibleInMenu(True)
        self.loadProcessingButton.setToolTip(loadProcessingBt)
        self.loadProcessingButton.setText(loadProcessingBt)
        ## Import QtCore class
        loadQtCoreBt = QCoreApplication.translate("PythonConsole",
                                                  "Import PyQt.QtCore class")
        self.loadQtCoreButton = QAction(self)
        self.loadQtCoreButton.setCheckable(False)
        self.loadQtCoreButton.setEnabled(True)
        self.loadQtCoreButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtCoreConsole.png"))
        self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtCoreButton.setIconVisibleInMenu(True)
        self.loadQtCoreButton.setToolTip(loadQtCoreBt)
        self.loadQtCoreButton.setText(loadQtCoreBt)
        ## Import QtGui class
        loadQtGuiBt = QCoreApplication.translate("PythonConsole",
                                                 "Import PyQt.QtGui class")
        self.loadQtGuiButton = QAction(self)
        self.loadQtGuiButton.setCheckable(False)
        self.loadQtGuiButton.setEnabled(True)
        self.loadQtGuiButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtGuiConsole.png"))
        self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtGuiButton.setIconVisibleInMenu(True)
        self.loadQtGuiButton.setToolTip(loadQtGuiBt)
        self.loadQtGuiButton.setText(loadQtGuiBt)
        ## Action for Run script
        runBt = QCoreApplication.translate("PythonConsole", "Run command")
        self.runButton = QAction(self)
        self.runButton.setCheckable(False)
        self.runButton.setEnabled(True)
        self.runButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunConsole.png"))
        self.runButton.setMenuRole(QAction.PreferencesRole)
        self.runButton.setIconVisibleInMenu(True)
        self.runButton.setToolTip(runBt)
        self.runButton.setText(runBt)
        ## Help action
        helpBt = QCoreApplication.translate("PythonConsole", "Help")
        self.helpButton = QAction(self)
        self.helpButton.setCheckable(False)
        self.helpButton.setEnabled(True)
        self.helpButton.setIcon(
            QgsApplication.getThemeIcon("console/iconHelpConsole.png"))
        self.helpButton.setMenuRole(QAction.PreferencesRole)
        self.helpButton.setIconVisibleInMenu(True)
        self.helpButton.setToolTip(helpBt)
        self.helpButton.setText(helpBt)

        self.toolBar = QToolBar()
        self.toolBar.setEnabled(True)
        self.toolBar.setFocusPolicy(Qt.NoFocus)
        self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBar.setLayoutDirection(Qt.LeftToRight)
        self.toolBar.setIconSize(QSize(24, 24))
        self.toolBar.setOrientation(Qt.Vertical)
        self.toolBar.setMovable(True)
        self.toolBar.setFloatable(True)
        self.toolBar.addAction(self.clearButton)
        self.toolBar.addAction(self.actionClass)
        self.toolBar.addAction(self.runButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.showEditorButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.optionsButton)
        self.toolBar.addAction(self.helpButton)

        self.toolBarEditor = QToolBar()
        # self.toolBarEditor.setStyleSheet('QToolBar{background-color: rgb(%s, %s, %s' % tuple(bkgrcolor) + ');\
        #                                   border-right: 1px solid rgb(%s, %s, %s' % tuple(bordercl) + ');}')
        self.toolBarEditor.setEnabled(False)
        self.toolBarEditor.setFocusPolicy(Qt.NoFocus)
        self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBarEditor.setLayoutDirection(Qt.LeftToRight)
        self.toolBarEditor.setIconSize(QSize(18, 18))
        self.toolBarEditor.setOrientation(Qt.Vertical)
        self.toolBarEditor.setMovable(True)
        self.toolBarEditor.setFloatable(True)
        self.toolBarEditor.addAction(self.openFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.saveFileButton)
        self.toolBarEditor.addAction(self.saveAsFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.findTextButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.cutEditorButton)
        self.toolBarEditor.addAction(self.copyEditorButton)
        self.toolBarEditor.addAction(self.pasteEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.commentEditorButton)
        self.toolBarEditor.addAction(self.uncommentEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.objectListButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.runScriptEditorButton)

        ## Menu Import Class
        self.classMenu = QMenu()
        self.classMenu.addAction(self.loadProcessingButton)
        self.classMenu.addAction(self.loadQtCoreButton)
        self.classMenu.addAction(self.loadQtGuiButton)
        cM = self.toolBar.widgetForAction(self.actionClass)
        cM.setMenu(self.classMenu)
        cM.setPopupMode(QToolButton.InstantPopup)

        self.widgetButton = QWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButton.sizePolicy().hasHeightForWidth())
        self.widgetButton.setSizePolicy(sizePolicy)

        self.widgetButtonEditor = QWidget(self.widgetEditor)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButtonEditor.sizePolicy().hasHeightForWidth())
        self.widgetButtonEditor.setSizePolicy(sizePolicy)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.shellOut.sizePolicy().hasHeightForWidth())
        self.shellOut.setSizePolicy(sizePolicy)

        self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        ##------------ Layout -------------------------------

        self.mainLayout = QGridLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1)
        self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1)

        self.layoutEditor = QGridLayout(self.widgetEditor)
        self.layoutEditor.setMargin(0)
        self.layoutEditor.setSpacing(0)
        self.layoutEditor.addWidget(self.widgetButtonEditor, 0, 0, 2, 1)
        self.layoutEditor.addWidget(self.tabEditorWidget, 0, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetFind, 1, 1, 1, 1)

        self.toolBarLayout = QGridLayout(self.widgetButton)
        self.toolBarLayout.setMargin(0)
        self.toolBarLayout.setSpacing(0)
        self.toolBarLayout.addWidget(self.toolBar)
        self.toolBarEditorLayout = QGridLayout(self.widgetButtonEditor)
        self.toolBarEditorLayout.setMargin(0)
        self.toolBarEditorLayout.setSpacing(0)
        self.toolBarEditorLayout.addWidget(self.toolBarEditor)

        ## Layout for the find widget
        self.layoutFind = QGridLayout(self.widgetFind)
        self.layoutFind.setContentsMargins(0, 0, 0, 0)
        self.lineEditFind = QgsFilterLineEdit()
        placeHolderTxt = QCoreApplication.translate("PythonConsole",
                                                    "Enter text to find...")

        if pyqtconfig.Configuration().qt_version >= 0x40700:
            self.lineEditFind.setPlaceholderText(placeHolderTxt)
        else:
            self.lineEditFind.setToolTip(placeHolderTxt)
        self.findNextButton = QToolButton()
        self.findNextButton.setEnabled(False)
        toolTipfindNext = QCoreApplication.translate("PythonConsole",
                                                     "Find Next")
        self.findNextButton.setToolTip(toolTipfindNext)
        self.findNextButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchNextEditorConsole.png"))
        self.findNextButton.setIconSize(QSize(24, 24))
        self.findNextButton.setAutoRaise(True)
        self.findPrevButton = QToolButton()
        self.findPrevButton.setEnabled(False)
        toolTipfindPrev = QCoreApplication.translate("PythonConsole",
                                                     "Find Previous")
        self.findPrevButton.setToolTip(toolTipfindPrev)
        self.findPrevButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchPrevEditorConsole.png"))
        self.findPrevButton.setIconSize(QSize(24, 24))
        self.findPrevButton.setAutoRaise(True)
        self.caseSensitive = QCheckBox()
        caseSensTr = QCoreApplication.translate("PythonConsole",
                                                "Case Sensitive")
        self.caseSensitive.setText(caseSensTr)
        self.wholeWord = QCheckBox()
        wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word")
        self.wholeWord.setText(wholeWordTr)
        self.wrapAround = QCheckBox()
        self.wrapAround.setChecked(True)
        wrapAroundTr = QCoreApplication.translate("PythonConsole",
                                                  "Wrap Around")
        self.wrapAround.setText(wrapAroundTr)
        self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1)
        self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1)
        self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1)
        self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1)
        self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1)
        self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1)

        ##------------ Add first Tab in Editor -------------------------------

        #self.tabEditorWidget.newTabEditor(tabName='first', filename=None)

        ##------------ Signal -------------------------------

        self.findTextButton.toggled.connect(self.findTextEditor)
        self.objectListButton.toggled.connect(self.toggleObjectListWidget)
        self.commentEditorButton.triggered.connect(self.commentCode)
        self.uncommentEditorButton.triggered.connect(self.uncommentCode)
        self.runScriptEditorButton.triggered.connect(self.runScriptEditor)
        self.cutEditorButton.triggered.connect(self.cutEditor)
        self.copyEditorButton.triggered.connect(self.copyEditor)
        self.pasteEditorButton.triggered.connect(self.pasteEditor)
        self.showEditorButton.toggled.connect(self.toggleEditor)
        self.clearButton.triggered.connect(self.shellOut.clearConsole)
        self.optionsButton.triggered.connect(self.openSettings)
        self.loadProcessingButton.triggered.connect(self.processing)
        self.loadQtCoreButton.triggered.connect(self.qtCore)
        self.loadQtGuiButton.triggered.connect(self.qtGui)
        self.runButton.triggered.connect(self.shell.entered)
        self.openFileButton.triggered.connect(self.openScriptFile)
        self.saveFileButton.triggered.connect(self.saveScriptFile)
        self.saveAsFileButton.triggered.connect(self.saveAsScriptFile)
        self.helpButton.triggered.connect(self.openHelp)
        self.connect(self.listClassMethod,
                     SIGNAL('itemClicked(QTreeWidgetItem*, int)'),
                     self.onClickGoToLine)
        self.lineEditFind.returnPressed.connect(self._findText)
        self.findNextButton.clicked.connect(self._findNext)
        self.findPrevButton.clicked.connect(self._findPrev)
        self.lineEditFind.textChanged.connect(self._textFindChanged)

    def _findText(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(True)

    def _findNext(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(True)

    def _findPrev(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(False)

    def _textFindChanged(self):
        if self.lineEditFind.text():
            self.findNextButton.setEnabled(True)
            self.findPrevButton.setEnabled(True)
        else:
            self.lineEditFind.setStyleSheet('')
            self.findNextButton.setEnabled(False)
            self.findPrevButton.setEnabled(False)

    def onClickGoToLine(self, item, column):
        tabEditor = self.tabEditorWidget.currentWidget().newEditor
        if item.text(1) == 'syntaxError':
            check = tabEditor.syntaxCheck(fromContextMenu=False)
            if check and not tabEditor.isReadOnly():
                self.tabEditorWidget.currentWidget().save()
            return
        linenr = int(item.text(1))
        itemName = str(item.text(0))
        charPos = itemName.find(' ')
        if charPos != -1:
            objName = itemName[0:charPos]
        else:
            objName = itemName
        tabEditor.goToLine(objName, linenr)

    def processing(self):
        self.shell.commandConsole('processing')

    def qtCore(self):
        self.shell.commandConsole('qtCore')

    def qtGui(self):
        self.shell.commandConsole('qtGui')

    def toggleEditor(self, checked):
        self.splitterObj.show() if checked else self.splitterObj.hide()
        if not self.tabEditorWidget:
            self.tabEditorWidget.enableToolBarEditor(checked)
            self.tabEditorWidget.restoreTabsOrAddNew()

    def toggleObjectListWidget(self, checked):
        self.listClassMethod.show() if checked else self.listClassMethod.hide()

    def findTextEditor(self, checked):
        self.widgetFind.show() if checked else self.widgetFind.hide()

    def pasteEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.paste()

    def cutEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.cut()

    def copyEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.copy()

    def runScriptEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.runScriptCode()

    def commentCode(self):
        self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(True)

    def uncommentCode(self):
        self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(False)

    def openScriptFile(self):
        lastDirPath = self.settings.value("pythonConsole/lastDirPath", "")
        openFileTr = QCoreApplication.translate("PythonConsole", "Open File")
        fileList = QFileDialog.getOpenFileNames(self, openFileTr, lastDirPath,
                                                "Script file (*.py)")
        if fileList:
            for pyFile in fileList:
                for i in range(self.tabEditorWidget.count()):
                    tabWidget = self.tabEditorWidget.widget(i)
                    if tabWidget.path == pyFile:
                        self.tabEditorWidget.setCurrentWidget(tabWidget)
                        break
                else:
                    tabName = QFileInfo(pyFile).fileName()
                    self.tabEditorWidget.newTabEditor(tabName, pyFile)

                    lastDirPath = QFileInfo(pyFile).path()
                    self.settings.setValue("pythonConsole/lastDirPath", pyFile)
                    self.updateTabListScript(pyFile, action='append')

    def saveScriptFile(self):
        tabWidget = self.tabEditorWidget.currentWidget()
        try:
            tabWidget.save()
        except (IOError, OSError), error:
            msgText = QCoreApplication.translate(
                'PythonConsole',
                'The file <b>{0}</b> could not be saved. Error: {1}').format(
                    tabWidget.path, error.strerror)
            self.callWidgetMessageBarEditor(msgText, 2, False)
Example #40
0
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        #self.prm = prm

        self.pchs = [
            "o", "s", "v", "p", "h", "8", "*", "x", "+", "d", ",", "^", "<",
            ">", "1", "2", "3", "4", "H", "D", ".", "|", "_"
        ]

        mpl.rcParams['xtick.major.size'] = 6
        mpl.rcParams['xtick.minor.size'] = 4
        mpl.rcParams['xtick.major.width'] = 1
        mpl.rcParams['xtick.minor.width'] = 1
        mpl.rcParams['ytick.major.size'] = 9
        mpl.rcParams['ytick.minor.size'] = 5
        mpl.rcParams['ytick.major.width'] = 0.8
        mpl.rcParams['ytick.minor.width'] = 0.8
        mpl.rcParams['xtick.direction'] = 'out'
        mpl.rcParams['ytick.direction'] = 'out'
        mpl.rcParams['font.size'] = 14
        mpl.rcParams['figure.facecolor'] = 'white'
        mpl.rcParams['lines.color'] = 'black'
        mpl.rcParams['axes.prop_cycle'] = cycler('color', [
            "#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2",
            "#D55E00", "#CC79A7"
        ])  #['k', 'b', 'g', 'r', 'c', 'm', 'y']

        self.mw = QWidget(self)
        self.vbl = QVBoxLayout(self.mw)
        self.fig = Figure(
            figsize=(8, 8))  #facecolor=self.canvasColor, dpi=self.dpi)
        self.ax1 = self.fig.add_subplot(221)
        self.ax2 = self.fig.add_subplot(222)
        self.ax3 = self.fig.add_subplot(223)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mw)
        self.ntb = NavigationToolbar(self.canvas, self.mw)

        self.logAxisMidpoint = QCheckBox(self.tr("Midpoint Log Axis"))
        self.logAxisMidpoint.stateChanged[int].connect(
            self.toggleMidpointLogAxis)

        self.logAxisSlope = QCheckBox(self.tr("Slope Log Axis"))
        self.logAxisSlope.stateChanged[int].connect(self.toggleSlopeLogAxis)

        self.logAxisLapse = QCheckBox(self.tr("Lapse Log Axis"))
        self.logAxisLapse.stateChanged[int].connect(self.toggleLapseLogAxis)

        self.updateButton = QPushButton(self.tr("Update"), self)
        self.updateButton.setIcon(
            QIcon.fromTheme("view-refresh", QIcon(":/view-refresh")))
        self.updateButton.clicked.connect(self.onClickUpdateButton)

        self.ntbBox = QHBoxLayout()
        self.ntbBox.addWidget(self.ntb)
        self.ntbBox.addWidget(self.logAxisMidpoint)
        self.ntbBox.addWidget(self.logAxisSlope)
        self.ntbBox.addWidget(self.logAxisLapse)
        self.ntbBox.addWidget(self.updateButton)
        self.vbl.addWidget(self.canvas)
        self.vbl.addLayout(self.ntbBox)
        self.mw.setFocus()
        self.setCentralWidget(self.mw)

        self.getUMLPars()
        if self.stimScaling == "Linear":
            self.logAxisMidpoint.setChecked(False)
            self.plotDataMidpoint()
        elif self.stimScaling == "Logarithmic":
            self.logAxisMidpoint.setChecked(True)
            self.plotDataMidpointLogAxis()

        if self.slopeSpacing == "Linear":
            self.logAxisSlope.setChecked(False)
            self.plotDataSlope()
        elif self.slopeSpacing == "Logarithmic":
            self.logAxisSlope.setChecked(True)
            self.plotDataSlopeLogAxis()

        if self.lapseSpacing == "Linear":
            self.logAxisLapse.setChecked(False)
            self.plotDataLapse()
        elif self.lapseSpacing == "Logarithmic":
            self.logAxisLapse.setChecked(True)
            self.plotDataLapseLogAxis()

        self.fig.suptitle(self.tr("UML Parameter Space"))
        self.show()
        self.canvas.draw()
Example #41
0
class UMLParSpacePlot(QMainWindow):
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        #self.prm = prm

        self.pchs = [
            "o", "s", "v", "p", "h", "8", "*", "x", "+", "d", ",", "^", "<",
            ">", "1", "2", "3", "4", "H", "D", ".", "|", "_"
        ]

        mpl.rcParams['xtick.major.size'] = 6
        mpl.rcParams['xtick.minor.size'] = 4
        mpl.rcParams['xtick.major.width'] = 1
        mpl.rcParams['xtick.minor.width'] = 1
        mpl.rcParams['ytick.major.size'] = 9
        mpl.rcParams['ytick.minor.size'] = 5
        mpl.rcParams['ytick.major.width'] = 0.8
        mpl.rcParams['ytick.minor.width'] = 0.8
        mpl.rcParams['xtick.direction'] = 'out'
        mpl.rcParams['ytick.direction'] = 'out'
        mpl.rcParams['font.size'] = 14
        mpl.rcParams['figure.facecolor'] = 'white'
        mpl.rcParams['lines.color'] = 'black'
        mpl.rcParams['axes.prop_cycle'] = cycler('color', [
            "#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2",
            "#D55E00", "#CC79A7"
        ])  #['k', 'b', 'g', 'r', 'c', 'm', 'y']

        self.mw = QWidget(self)
        self.vbl = QVBoxLayout(self.mw)
        self.fig = Figure(
            figsize=(8, 8))  #facecolor=self.canvasColor, dpi=self.dpi)
        self.ax1 = self.fig.add_subplot(221)
        self.ax2 = self.fig.add_subplot(222)
        self.ax3 = self.fig.add_subplot(223)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mw)
        self.ntb = NavigationToolbar(self.canvas, self.mw)

        self.logAxisMidpoint = QCheckBox(self.tr("Midpoint Log Axis"))
        self.logAxisMidpoint.stateChanged[int].connect(
            self.toggleMidpointLogAxis)

        self.logAxisSlope = QCheckBox(self.tr("Slope Log Axis"))
        self.logAxisSlope.stateChanged[int].connect(self.toggleSlopeLogAxis)

        self.logAxisLapse = QCheckBox(self.tr("Lapse Log Axis"))
        self.logAxisLapse.stateChanged[int].connect(self.toggleLapseLogAxis)

        self.updateButton = QPushButton(self.tr("Update"), self)
        self.updateButton.setIcon(
            QIcon.fromTheme("view-refresh", QIcon(":/view-refresh")))
        self.updateButton.clicked.connect(self.onClickUpdateButton)

        self.ntbBox = QHBoxLayout()
        self.ntbBox.addWidget(self.ntb)
        self.ntbBox.addWidget(self.logAxisMidpoint)
        self.ntbBox.addWidget(self.logAxisSlope)
        self.ntbBox.addWidget(self.logAxisLapse)
        self.ntbBox.addWidget(self.updateButton)
        self.vbl.addWidget(self.canvas)
        self.vbl.addLayout(self.ntbBox)
        self.mw.setFocus()
        self.setCentralWidget(self.mw)

        self.getUMLPars()
        if self.stimScaling == "Linear":
            self.logAxisMidpoint.setChecked(False)
            self.plotDataMidpoint()
        elif self.stimScaling == "Logarithmic":
            self.logAxisMidpoint.setChecked(True)
            self.plotDataMidpointLogAxis()

        if self.slopeSpacing == "Linear":
            self.logAxisSlope.setChecked(False)
            self.plotDataSlope()
        elif self.slopeSpacing == "Logarithmic":
            self.logAxisSlope.setChecked(True)
            self.plotDataSlopeLogAxis()

        if self.lapseSpacing == "Linear":
            self.logAxisLapse.setChecked(False)
            self.plotDataLapse()
        elif self.lapseSpacing == "Logarithmic":
            self.logAxisLapse.setChecked(True)
            self.plotDataLapseLogAxis()

        self.fig.suptitle(self.tr("UML Parameter Space"))
        self.show()
        self.canvas.draw()

    def getUMLPars(self):
        self.psyFun = self.parent().psyFunChooser.currentText()
        self.loStim = self.parent().currLocale.toDouble(
            self.parent().loStim.text())[0]
        self.hiStim = self.parent().currLocale.toDouble(
            self.parent().hiStim.text())[0]
        self.stimScaling = self.parent().stimScalingChooser.currentText()
        self.loMidPoint = self.parent().currLocale.toDouble(
            self.parent().loMidPoint.text())[0]
        self.hiMidPoint = self.parent().currLocale.toDouble(
            self.parent().hiMidPoint.text())[0]
        self.threshGridStep = self.parent().currLocale.toDouble(
            self.parent().threshGridStep.text())[0]
        self.threshPrior = self.parent().threshPriorChooser.currentText()
        self.threshPriorMu = self.parent().currLocale.toDouble(
            self.parent().threshPriorMu.text())[0]
        self.threshPriorSTD = self.parent().currLocale.toDouble(
            self.parent().threshPriorSTD.text())[0]
        self.loSlope = self.parent().currLocale.toDouble(
            self.parent().loSlope.text())[0]
        self.hiSlope = self.parent().currLocale.toDouble(
            self.parent().hiSlope.text())[0]
        self.slopeGridStep = self.parent().currLocale.toDouble(
            self.parent().slopeGridStep.text())[0]
        self.slopeSpacing = self.parent().slopeSpacingChooser.currentText()
        self.slopePrior = self.parent().slopePriorChooser.currentText()
        self.slopePriorMu = self.parent().currLocale.toDouble(
            self.parent().slopePriorMu.text())[0]
        self.slopePriorSTD = self.parent().currLocale.toDouble(
            self.parent().slopePriorSTD.text())[0]
        self.loLapse = self.parent().currLocale.toDouble(
            self.parent().loLapse.text())[0]
        self.hiLapse = self.parent().currLocale.toDouble(
            self.parent().hiLapse.text())[0]
        self.lapseGridStep = self.parent().currLocale.toDouble(
            self.parent().lapseGridStep.text())[0]
        self.lapseSpacing = self.parent().lapseSpacingChooser.currentText()
        self.lapsePrior = self.parent().lapsePriorChooser.currentText()
        self.lapsePriorMu = self.parent().currLocale.toDouble(
            self.parent().lapsePriorMu.text())[0]
        self.lapsePriorSTD = self.parent().currLocale.toDouble(
            self.parent().lapsePriorSTD.text())[0]
        try:
            self.nAlternatives = int(
                self.parent().nAlternativesChooser.currentText())
        except:
            ## this currently works for CRM and DTT tasks that have fixed nAlternatives
            self.nAlternatives = self.parent().prm[
                self.parent().currExp]['defaultNAlternatives']

        if self.stimScaling == "Linear":
            self.UML = setupUML(model=self.psyFun,
                                swptRule="Up-Down",
                                nDown=2,
                                centTend="Mean",
                                stimScale=self.stimScaling,
                                x0=1,
                                xLim=(self.loStim, self.hiStim),
                                alphaLim=(self.loMidPoint, self.hiMidPoint),
                                alphaStep=self.threshGridStep,
                                alphaSpacing="Linear",
                                alphaDist=self.threshPrior,
                                alphaMu=self.threshPriorMu,
                                alphaSTD=self.threshPriorSTD,
                                betaLim=(self.loSlope, self.hiSlope),
                                betaStep=self.slopeGridStep,
                                betaSpacing=self.slopeSpacing,
                                betaDist=self.slopePrior,
                                betaMu=self.slopePriorMu,
                                betaSTD=self.slopePriorSTD,
                                gamma=1 / self.nAlternatives,
                                lambdaLim=(self.loLapse, self.hiLapse),
                                lambdaStep=self.lapseGridStep,
                                lambdaSpacing=self.lapseSpacing,
                                lambdaDist=self.lapsePrior,
                                lambdaMu=self.lapsePriorMu,
                                lambdaSTD=self.lapsePriorSTD)
        elif self.stimScaling == "Logarithmic":
            self.UML = setupUML(model=self.psyFun,
                                swptRule="Up-Down",
                                nDown=2,
                                centTend="Mean",
                                stimScale=self.stimScaling,
                                x0=1,
                                xLim=(abs(self.loStim), abs(self.hiStim)),
                                alphaLim=(abs(self.loMidPoint),
                                          abs(self.hiMidPoint)),
                                alphaStep=self.threshGridStep,
                                alphaSpacing="Linear",
                                alphaDist=self.threshPrior,
                                alphaMu=abs(self.threshPriorMu),
                                alphaSTD=self.threshPriorSTD,
                                betaLim=(self.loSlope, self.hiSlope),
                                betaStep=self.slopeGridStep,
                                betaSpacing=self.slopeSpacing,
                                betaDist=self.slopePrior,
                                betaMu=self.slopePriorMu,
                                betaSTD=self.slopePriorSTD,
                                gamma=1 / self.nAlternatives,
                                lambdaLim=(self.loLapse, self.hiLapse),
                                lambdaStep=self.lapseGridStep,
                                lambdaSpacing=self.lapseSpacing,
                                lambdaDist=self.lapsePrior,
                                lambdaMu=self.lapsePriorMu,
                                lambdaSTD=self.lapsePriorSTD)

    def plotDataMidpoint(self):
        self.ax1.clear()
        self.A = setPrior(self.UML["a"], self.UML["par"]["alpha"])

        if self.stimScaling == "Linear":
            markerline, stemlines, baseline = self.ax1.stem(
                self.UML["alpha"], self.A[:, 0, 0], 'k')
        elif self.stimScaling == "Logarithmic":  #logarithmic spaced plotted on linear coords
            markerline, stemlines, baseline = self.ax1.stem(
                exp(self.UML["alpha"]),
                self.A[:, 0, 0] / exp(self.UML["alpha"]), 'k')
            if self.loStim < 0:
                self.ax1.set_xticklabels(list(map(str,
                                                  -self.ax1.get_xticks())))

        plt.setp(markerline, 'markerfacecolor', 'k')
        nAlpha = len(self.A[:, 0, 0])
        self.ax1.set_title("Midpoint, #Points " + str(nAlpha))

    def plotDataSlope(self):
        self.ax2.clear()
        self.B = setPrior(self.UML["b"], self.UML["par"]["beta"])
        if self.UML["par"]["beta"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax2.stem(
                self.UML["beta"], self.B[0, :, 0], 'k')
        elif self.UML["par"]["beta"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax2.stem(
                self.UML["beta"], self.B[0, :, 0] / self.UML["beta"], 'k')
        plt.setp(markerline, 'markerfacecolor', 'k')
        nBeta = len(self.B[0, :, 0])
        self.ax2.set_title("Slope, #Points " + str(nBeta))

    def plotDataLapse(self):
        self.ax3.clear()
        L = setPrior(self.UML["l"], self.UML["par"]["lambda"])
        if self.UML["par"]["lambda"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax3.stem(
                self.UML["lambda"], L[0, 0, :], 'k')
        elif self.UML["par"]["lambda"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax3.stem(
                self.UML["lambda"], L[0, 0, :] / self.UML["lambda"], 'k')
        plt.setp(markerline, 'markerfacecolor', 'k')
        nLambda = len(L[0, 0, :])
        self.ax3.set_title("Lapse, #Points " + str(nLambda))

    def plotDataMidpointLogAxis(self):
        self.ax1.clear()
        self.A = setPrior(self.UML["a"], self.UML["par"]["alpha"])

        if self.stimScaling == "Logarithmic":
            x = self.UML["alpha"]
            markerline, stemlines, baseline = self.ax1.stem(
                x, self.A[:, 0, 0], 'k')
        elif self.stimScaling == "Linear":
            x = log(self.UML["alpha"])
            markerline, stemlines, baseline = self.ax1.stem(
                x, self.A[:, 0, 0] * self.UML["alpha"], 'k')

        setLogTicks(self.ax1, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')
        nAlpha = len(self.A[:, 0, 0])
        self.ax1.set_title("Midpoint, #Points " + str(nAlpha))

    def plotDataSlopeLogAxis(self):
        self.ax2.clear()
        self.B = setPrior(self.UML["b"], self.UML["par"]["beta"])
        if self.UML["par"]["beta"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax2.stem(
                log(self.UML["beta"]), self.B[0, :, 0], 'k')
        elif self.UML["par"]["beta"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax2.stem(
                log(self.UML["beta"]), self.B[0, :, 0] * self.UML["beta"], 'k')

        setLogTicks(self.ax2, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')

        nBeta = len(self.B[0, :, 0])
        self.ax2.set_title("Slope, #Points " + str(nBeta))

    def plotDataLapseLogAxis(self):
        self.ax3.clear()
        L = setPrior(self.UML["l"], self.UML["par"]["lambda"])
        if self.UML["par"]["lambda"]["spacing"] == "Logarithmic":
            markerline, stemlines, baseline = self.ax3.stem(
                log(self.UML["lambda"]), L[0, 0, :], 'k')
        elif self.UML["par"]["lambda"]["spacing"] == "Linear":
            markerline, stemlines, baseline = self.ax3.stem(
                log(self.UML["lambda"]), L[0, 0, :] * self.UML["lambda"], 'k')
        setLogTicks(self.ax3, exp(1))
        plt.setp(markerline, 'markerfacecolor', 'k')

        nLambda = len(L[0, 0, :])
        self.ax3.set_title("Lapse, #Points " + str(nLambda))

    def onClickUpdateButton(self):
        self.getUMLPars()

        if self.logAxisMidpoint.isChecked() == False:
            self.plotDataMidpoint()
        else:
            self.plotDataMidpointLogAxis()

        if self.logAxisSlope.isChecked() == False:
            self.plotDataSlope()
        else:
            self.plotDataSlopeLogAxis()

        if self.logAxisLapse.isChecked() == False:
            self.plotDataLapse()
        else:
            self.plotDataLapseLogAxis()

        self.canvas.draw()

    def toggleMidpointLogAxis(self):
        if self.logAxisMidpoint.isChecked() == True:
            self.plotDataMidpointLogAxis()
        else:
            self.plotDataMidpoint()
        self.canvas.draw()

    def toggleSlopeLogAxis(self):
        if self.logAxisSlope.isChecked() == True:
            self.plotDataSlopeLogAxis()
        else:
            self.plotDataSlope()
        self.canvas.draw()

    def toggleLapseLogAxis(self):
        if self.logAxisLapse.isChecked() == True:
            self.plotDataLapseLogAxis()
        else:
            self.plotDataLapse()
        self.canvas.draw()
Example #42
0
    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"),
                                       translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(
            QCompleter([
                "*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS
            ]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(translations.TR_TEXT_FOR_REPLACE +
                                             "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)
Example #43
0
 def setup(self):
     for label, value in self.data:
         if DEBUG:
             print("value:", value)
         if label is None and value is None:
             # Separator: (None, None)
             self.formlayout.addRow(QLabel(" "), QLabel(" "))
             self.widgets.append(None)
             continue
         elif label is None:
             # Comment
             self.formlayout.addRow(QLabel(value))
             self.widgets.append(None)
             continue
         elif tuple_to_qfont(value) is not None:
             field = FontLayout(value, self)
         elif text_to_qcolor(value).isValid():
             field = ColorLayout(QColor(value), self)
         elif isinstance(value, (str, unicode)):
             field = QLineEdit(value, self)
         elif isinstance(value, (list, tuple)):
             value = list(value)  # in case this is a tuple
             selindex = value.pop(0)
             field = QComboBox(self)
             if isinstance(value[0], (list, tuple)):
                 keys = [key for key, _val in value]
                 value = [val for _key, val in value]
             else:
                 keys = value
             field.addItems(value)
             if selindex in value:
                 selindex = value.index(selindex)
             elif selindex in keys:
                 selindex = keys.index(selindex)
             elif not isinstance(selindex, int):
                 print("Warning: '%s' index is invalid (label: "\
                       "%s, value: %s)" % (selindex, label, value),
                       file=STDERR)
                 selindex = 0
             field.setCurrentIndex(selindex)
         elif isinstance(value, bool):
             field = QCheckBox(self)
             field.setCheckState(Qt.Checked if value else Qt.Unchecked)
         elif isinstance(value, float):
             field = QLineEdit(repr(value), self)
             field.setValidator(QDoubleValidator(field))
             dialog = self.get_dialog()
             dialog.register_float_field(field)
             self.connect(field, SIGNAL('textChanged(QString)'),
                          lambda text: dialog.update_buttons())
         elif isinstance(value, int):
             field = QSpinBox(self)
             field.setRange(-1e9, 1e9)
             field.setValue(value)
         elif isinstance(value, datetime.datetime):
             field = QDateTimeEdit(self)
             field.setDateTime(value)
         elif isinstance(value, datetime.date):
             field = QDateEdit(self)
             field.setDate(value)
         else:
             field = QLineEdit(repr(value), self)
         self.formlayout.addRow(label, field)
         self.widgets.append(field)
Example #44
0
    def createWidgets(self):
        """
        Create qt widgets
        """
        # prepare menu
        self.toolbar = QToolBar(self)
        self.toolbar.setStyleSheet(
            "QToolBar { border: 0px }")  # remove 3D border
        self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        self.toolbarPlugins = QToolBar(self)
        self.toolbarPlugins.setStyleSheet(
            "QToolBar { border: 0px }")  # remove 3D border
        self.toolbarPlugins.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        self.pluginsBox = QGroupBox("Plugins")
        self.pluginsBox.setStyleSheet("""
                                           QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } 
                                           QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } 
                                           QGroupBox::title { subcontrol-position: bottom center;}
                                       """)
        layoutPlugins = QHBoxLayout()
        layoutPlugins.addWidget(self.toolbarPlugins)
        layoutPlugins.setContentsMargins(0, 0, 0, 0)
        self.pluginsBox.setLayout(layoutPlugins)
        self.pluginsBox.hide()

        self.exportBox = QGroupBox("Exports")
        self.exportBox.setStyleSheet("""
                                           QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } 
                                           QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } 
                                           QGroupBox::title { subcontrol-position: bottom center;}
                                       """)
        layoutExports = QHBoxLayout()
        layoutExports.addWidget(self.toolbar)
        layoutExports.setContentsMargins(0, 0, 0, 0)
        self.exportBox.setLayout(layoutExports)

        layout = QVBoxLayout()

        if self.toXml:
            self.txtEdit = QtHelper.RawXmlEditor(parent=self)
            self.txtEdit.setText(self.__data)
            # self.txtEdit.setUtf8(True)
            self.txtEdit.setFont(QFont("Courier", 9))
        else:
            self.txtEdit = QtHelper.RawEditor(parent=self)
            self.txtEdit.setTabStopWidth(10)
            self.txtEdit.setText(self.__data)
            self.txtEdit.setFont(QFont("Courier", 9))

        self.txtEdit.setMinimumWidth(650)
        self.txtEdit.setMinimumHeight(400)

        self.delGroup = QGroupBox("Remove line")
        self.delTG = QCheckBox("TESTGLOBAL")
        self.delTP = QCheckBox("TESTPLAN")
        self.delTS = QCheckBox("TESTSUITE")
        self.delTU = QCheckBox("TESTUNIT")
        self.delTA = QCheckBox("TESTABSTRACT")
        self.delTC = QCheckBox("TESTCASE")
        self.delSTP = QCheckBox("STEP")

        layoutDel = QHBoxLayout()
        layoutDel.addWidget(self.delTG)
        layoutDel.addWidget(self.delTP)
        layoutDel.addWidget(self.delTS)
        layoutDel.addWidget(self.delTU)
        layoutDel.addWidget(self.delTA)
        layoutDel.addWidget(self.delTC)
        layoutDel.addWidget(self.delSTP)
        self.delGroup.setLayout(layoutDel)

        if self.toXml: self.delGroup.setEnabled(False)

        layoutToolbars = QHBoxLayout()
        layoutToolbars.addWidget(self.exportBox)
        layoutToolbars.addWidget(self.pluginsBox)
        layoutToolbars.addStretch(1)
        layoutToolbars.setContentsMargins(5, 0, 0, 0)

        layout.addLayout(layoutToolbars)
        layout.addWidget(self.delGroup)
        layout.addWidget(self.txtEdit)
        if not self.toXml:
            self.rawFind = QtHelper.RawFind(parent=self,
                                            editor=self.txtEdit,
                                            buttonNext=True)
            layout.addWidget(self.rawFind)

        self.setLayout(layout)
    def __init__(self, situations, differences, names, points):
        """
        Constructor
        :param situations: situations, when point and vertex elevations are different
        :param differences: when lines vertex elevations are different on position connection
        :param names: layers names
        :param points: vertices positions
        """
        QDialog.__init__(self)
        self.__situations = situations
        self.__differences = differences
        self.__names = names
        num_lines = len(points[0]['z']) - len(names) + 1
        self.__points = points
        self.setWindowTitle(QCoreApplication.translate("VDLTools","Elevations situations"))
        self.resize(300, 100)
        self.__layout = QGridLayout()

        self.__msgLabels = []
        self.__msgChecks = []
        self.__difLabels = []

        for i in xrange(len(self.__situations)):
            line = self.__situations[i]
            ptz = self.__points[line['point']]['z']
            msg = "- point " + str(line['point']) + QCoreApplication.translate("VDLTools"," in layer '") + \
                  self.__names[line['layer']] + "' (point: " + str(ptz[line['layer']+num_lines-1]) + "m |" + \
                  QCoreApplication.translate("VDLTools","line vertex: ") + str(line['vertex']) + "m) \n"

            msgLabel = QLabel(msg)
            self.__msgLabels.append(msgLabel)
            self.__layout.addWidget(self.__msgLabels[i], i+1, 0, 1, 2)
            msgCheck = QCheckBox()
            msgCheck.setChecked(True)
            self.__msgChecks.append(msgCheck)
            self.__layout.addWidget(self.__msgChecks[i], i+1, 2)

        for i in xrange(len(self.__differences)):
            line = self.__differences[i]
            msg = "- point " + str(line['point']) + \
                  QCoreApplication.translate("VDLTools"," in layer : different elevations on same position ") + "(" +\
                  str(line['v1']) + "m and" + str(line['v2']) + "m) \n"
            difLabel = QLabel(msg)
            self.__difLabels.append(difLabel)
            self.__layout.addWidget(self.__difLabels[i], len(self.__situations) + (i+1), 0, 1, 2)

        self.__passButton = QPushButton(QCoreApplication.translate("VDLTools","Pass"))
        self.__passButton.setMinimumHeight(20)
        self.__passButton.setMinimumWidth(100)

        pos = len(self.__situations) + len(self.__differences) + 1
        self.__layout.addWidget(self.__passButton, pos, 0)

        self.__onPointsButton = QPushButton(QCoreApplication.translate("VDLTools", "Apply line elevations to points"))
        self.__onPointsButton.setMinimumHeight(20)
        self.__onPointsButton.setMinimumWidth(200)

        self.__onLineButton = QPushButton(QCoreApplication.translate("VDLTools", "Apply points elevations to line"))
        self.__onLineButton.setMinimumHeight(20)
        self.__onLineButton.setMinimumWidth(200)

        if len(self.__situations) > 0:
            self.__layout.addWidget(self.__onLineButton, pos, 1)
            self.__layout.addWidget(self.__onPointsButton, pos, 2)

        self.setLayout(self.__layout)
Example #46
0
class Color(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletColor, *args)

        self.color = self.device

        self.cbe_color = CallbackEmulator(self.color.get_color,
                                          self.cb_color_get,
                                          self.increase_error_count)
        self.cbe_illuminance = CallbackEmulator(self.color.get_illuminance,
                                                self.cb_illuminance_get,
                                                self.increase_error_count)
        self.cbe_color_temperature = CallbackEmulator(
            self.color.get_color_temperature, self.cb_color_temperature_get,
            self.increase_error_count)

        self.color_label = ColorLabel()
        self.illuminance_label = IlluminanceLabel()
        self.color_temperature_label = ColorTemperatureLabel()
        self.color_frame = ColorFrame()
        self.color_temperature_frame = ColorFrame()
        self.illuminance_frame = ColorFrame()

        self.current_color = (0, 0, 0, 0)
        self.current_illuminance = 0
        self.current_color_temperature = 0

        self.clear_graphs_button = QPushButton("Clear Graphs")

        plot_list = [['R', Qt.red, self.get_current_r],
                     ['G', Qt.darkGreen, self.get_current_g],
                     ['B', Qt.blue, self.get_current_b],
                     ['C', Qt.black, self.get_current_c]]
        self.plot_widget = PlotWidget('Color Value', plot_list,
                                      self.clear_graphs_button)
        self.plot_widget.setMinimumSize(250, 200)

        plot_list_illuminance = [[
            '', Qt.red, self.get_current_illuminance_value
        ]]
        self.plot_widget_illuminance = PlotWidget('Illuminance [Lux]',
                                                  plot_list_illuminance,
                                                  self.clear_graphs_button)
        self.plot_widget_illuminance.setMinimumSize(250, 200)

        plot_list_color_temperature = [[
            '', Qt.red, self.get_current_color_temperature_value
        ]]
        self.plot_widget_color_temperature = PlotWidget(
            'Color Temperature [K]', plot_list_color_temperature,
            self.clear_graphs_button)
        self.plot_widget_color_temperature.setMinimumSize(250, 200)

        self.gain_label = QLabel('Gain: ')
        self.gain_combo = QComboBox()
        self.gain_combo.addItem("1x")
        self.gain_combo.addItem("4x")
        self.gain_combo.addItem("16x")
        self.gain_combo.addItem("60x")

        self.gain_combo.currentIndexChanged.connect(self.gain_changed)

        self.current_gain_factor = 60

        self.conversion_label = QLabel('Integration Time: ')
        self.conversion_combo = QComboBox()
        self.conversion_combo.addItem("2.4ms")
        self.conversion_combo.addItem("24ms")
        self.conversion_combo.addItem("101ms")
        self.conversion_combo.addItem("154ms")
        self.conversion_combo.addItem("700ms")

        self.current_conversion_time = 154

        self.conversion_combo.currentIndexChanged.connect(
            self.conversion_changed)

        self.light_checkbox = QCheckBox("Enable Light")

        self.light_checkbox.stateChanged.connect(self.light_state_changed)

        layout_config = QHBoxLayout()
        layout_config.addWidget(self.gain_label)
        layout_config.addWidget(self.gain_combo)
        layout_config.addWidget(self.conversion_label)
        layout_config.addWidget(self.conversion_combo)
        layout_config.addWidget(self.clear_graphs_button, 1)
        layout_config.addWidget(self.light_checkbox)

        layout_ht1 = QHBoxLayout()
        layout_ht1.addStretch()
        layout_ht1.addWidget(self.illuminance_label)
        layout_ht1.addWidget(self.illuminance_frame)
        layout_ht1.addStretch()

        layout_ht2 = QHBoxLayout()
        layout_ht2.addStretch()
        layout_ht2.addWidget(self.color_temperature_label)
        layout_ht2.addWidget(self.color_temperature_frame)
        layout_ht2.addStretch()

        layout_v1 = QVBoxLayout()
        layout_v1.addLayout(layout_ht1)
        layout_v1.addWidget(self.plot_widget_illuminance)

        layout_v2 = QVBoxLayout()
        layout_v2.addLayout(layout_ht2)
        layout_v2.addWidget(self.plot_widget_color_temperature)

        layout_h2 = QHBoxLayout()
        layout_h2.addLayout(layout_v1)
        layout_h2.addLayout(layout_v2)

        layout_h = QHBoxLayout()
        layout_h.addStretch()
        layout_h.addWidget(self.color_label)
        layout_h.addWidget(self.color_frame)
        layout_h.addStretch()

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

        self.k_to_rgb = {
            1000: (255, 56, 0),
            1100: (255, 71, 0),
            1200: (255, 83, 0),
            1300: (255, 93, 0),
            1400: (255, 101, 0),
            1500: (255, 109, 0),
            1600: (255, 115, 0),
            1700: (255, 121, 0),
            1800: (255, 126, 0),
            1900: (255, 131, 0),
            2000: (255, 137, 18),
            2100: (255, 142, 33),
            2200: (255, 147, 44),
            2300: (255, 152, 54),
            2400: (255, 157, 63),
            2500: (255, 161, 72),
            2600: (255, 165, 79),
            2700: (255, 169, 87),
            2800: (255, 173, 94),
            2900: (255, 177, 101),
            3000: (255, 180, 107),
            3100: (255, 184, 114),
            3200: (255, 187, 120),
            3300: (255, 190, 126),
            3400: (255, 193, 132),
            3500: (255, 196, 137),
            3600: (255, 199, 143),
            3700: (255, 201, 148),
            3800: (255, 204, 153),
            3900: (255, 206, 159),
            4000: (255, 209, 163),
            4100: (255, 211, 168),
            4200: (255, 213, 173),
            4300: (255, 215, 177),
            4400: (255, 217, 182),
            4500: (255, 219, 186),
            4600: (255, 221, 190),
            4700: (255, 223, 194),
            4800: (255, 225, 198),
            4900: (255, 227, 202),
            5000: (255, 228, 206),
            5100: (255, 230, 210),
            5200: (255, 232, 213),
            5300: (255, 233, 217),
            5400: (255, 235, 220),
            5500: (255, 236, 224),
            5600: (255, 238, 227),
            5700: (255, 239, 230),
            5800: (255, 240, 233),
            5900: (255, 242, 236),
            6000: (255, 243, 239),
            6100: (255, 244, 242),
            6200: (255, 245, 245),
            6300: (255, 246, 248),
            6400: (255, 248, 251),
            6500: (255, 249, 253),
            6600: (254, 249, 255),
            6700: (252, 247, 255),
            6800: (249, 246, 255),
            6900: (247, 245, 255),
            7000: (245, 243, 255),
            7100: (243, 242, 255),
            7200: (240, 241, 255),
            7300: (239, 240, 255),
            7400: (237, 239, 255),
            7500: (235, 238, 255),
            7600: (233, 237, 255),
            7700: (231, 236, 255),
            7800: (230, 235, 255),
            7900: (228, 234, 255),
            8000: (227, 233, 255),
            8100: (225, 232, 255),
            8200: (224, 231, 255),
            8300: (222, 230, 255),
            8400: (221, 230, 255),
            8500: (220, 229, 255),
            8600: (218, 228, 255),
            8700: (217, 227, 255),
            8800: (216, 227, 255),
            8900: (215, 226, 255),
            9000: (214, 225, 255),
            9100: (212, 225, 255),
            9200: (211, 224, 255),
            9300: (210, 223, 255),
            9400: (209, 223, 255),
            9500: (208, 222, 255),
            9600: (207, 221, 255),
            9700: (207, 221, 255),
            9800: (206, 220, 255),
            9900: (205, 220, 255),
            10000: (204, 219, 255),
            10100: (203, 219, 255),
            10200: (202, 218, 255),
            10300: (201, 218, 255),
            10400: (201, 217, 255),
            10500: (200, 217, 255),
            10600: (199, 216, 255),
            10700: (199, 216, 255),
            10800: (198, 216, 255),
            10900: (197, 215, 255),
            11000: (196, 215, 255),
            11100: (196, 214, 255),
            11200: (195, 214, 255),
            11300: (195, 214, 255),
            11400: (194, 213, 255),
            11500: (193, 213, 255),
            11600: (193, 212, 255),
            11700: (192, 212, 255),
            11800: (192, 212, 255),
            11900: (191, 211, 255),
            12000: (191, 211, 255),
            12100: (190, 211, 255),
            12200: (190, 210, 255),
            12300: (189, 210, 255),
            12400: (189, 210, 255),
            12500: (188, 210, 255),
            12600: (188, 209, 255),
            12700: (187, 209, 255),
            12800: (187, 209, 255),
            12900: (186, 208, 255),
            13000: (186, 208, 255),
            13100: (185, 208, 255),
            13200: (185, 208, 255),
            13300: (185, 207, 255),
            13400: (184, 207, 255),
            13500: (184, 207, 255),
            13600: (183, 207, 255),
            13700: (183, 206, 255),
            13800: (183, 206, 255),
            13900: (182, 206, 255),
            14000: (182, 206, 255),
            14100: (182, 205, 255),
            14200: (181, 205, 255),
            14300: (181, 205, 255),
            14400: (181, 205, 255),
            14500: (180, 205, 255),
            14600: (180, 204, 255),
            14700: (180, 204, 255),
            14800: (179, 204, 255),
            14900: (179, 204, 255),
            15000: (179, 204, 255),
            15100: (178, 203, 255),
            15200: (178, 203, 255),
            15300: (178, 203, 255),
            15400: (178, 203, 255),
            15500: (177, 203, 255),
            15600: (177, 202, 255),
            15700: (177, 202, 255),
            15800: (177, 202, 255),
            15900: (176, 202, 255),
            16000: (176, 202, 255),
            16100: (176, 202, 255),
            16200: (175, 201, 255),
            16300: (175, 201, 255),
            16400: (175, 201, 255),
            16500: (175, 201, 255),
            16600: (175, 201, 255),
            16700: (174, 201, 255),
            16800: (174, 201, 255),
            16900: (174, 200, 255),
            17000: (174, 200, 255),
            17100: (173, 200, 255),
            17200: (173, 200, 255),
            17300: (173, 200, 255),
            17400: (173, 200, 255),
            17500: (173, 200, 255),
            17600: (172, 199, 255),
            17700: (172, 199, 255),
            17800: (172, 199, 255),
            17900: (172, 199, 255),
            18000: (172, 199, 255),
            18100: (171, 199, 255),
            18200: (171, 199, 255),
            18300: (171, 199, 255),
            18400: (171, 198, 255),
            18500: (171, 198, 255),
            18600: (170, 198, 255),
            18700: (170, 198, 255),
            18800: (170, 198, 255),
            18900: (170, 198, 255),
            19000: (170, 198, 255),
            19100: (170, 198, 255),
            19200: (169, 198, 255),
            19300: (169, 197, 255),
            19400: (169, 197, 255),
            19500: (169, 197, 255),
            19600: (169, 197, 255),
            19700: (169, 197, 255),
            19800: (169, 197, 255),
            19900: (168, 197, 255),
            20000: (168, 197, 255),
            20100: (168, 197, 255),
            20200: (168, 197, 255),
            20300: (168, 196, 255),
            20400: (168, 196, 255),
            20500: (168, 196, 255),
            20600: (167, 196, 255),
            20700: (167, 196, 255),
            20800: (167, 196, 255),
            20900: (167, 196, 255),
            21000: (167, 196, 255),
            21100: (167, 196, 255),
            21200: (167, 196, 255),
            21300: (166, 196, 255),
            21400: (166, 195, 255),
            21500: (166, 195, 255),
            21600: (166, 195, 255),
            21700: (166, 195, 255),
            21800: (166, 195, 255),
            21900: (166, 195, 255),
            22000: (166, 195, 255),
            22100: (165, 195, 255),
            22200: (165, 195, 255),
            22300: (165, 195, 255),
            22400: (165, 195, 255),
            22500: (165, 195, 255),
            22600: (165, 195, 255),
            22700: (165, 194, 255),
            22800: (165, 194, 255),
            22900: (165, 194, 255),
            23000: (164, 194, 255),
            23100: (164, 194, 255),
            23200: (164, 194, 255),
            23300: (164, 194, 255),
            23400: (164, 194, 255),
            23500: (164, 194, 255),
            23600: (164, 194, 255),
            23700: (164, 194, 255),
            23800: (164, 194, 255),
            23900: (164, 194, 255),
            24000: (163, 194, 255),
            24100: (163, 194, 255),
            24200: (163, 193, 255),
            24300: (163, 193, 255),
            24400: (163, 193, 255),
            24500: (163, 193, 255),
            24600: (163, 193, 255),
            24700: (163, 193, 255),
            24800: (163, 193, 255),
            24900: (163, 193, 255),
            25000: (163, 193, 255),
            25100: (162, 193, 255),
            25200: (162, 193, 255),
            25300: (162, 193, 255),
            25400: (162, 193, 255),
            25500: (162, 193, 255),
            25600: (162, 193, 255),
            25700: (162, 193, 255),
            25800: (162, 193, 255),
            25900: (162, 192, 255),
            26000: (162, 192, 255),
            26100: (162, 192, 255),
            26200: (162, 192, 255),
            26300: (162, 192, 255),
            26400: (161, 192, 255),
            26500: (161, 192, 255),
            26600: (161, 192, 255),
            26700: (161, 192, 255),
            26800: (161, 192, 255),
            26900: (161, 192, 255),
            27000: (161, 192, 255),
            27100: (161, 192, 255),
            27200: (161, 192, 255),
            27300: (161, 192, 255),
            27400: (161, 192, 255),
            27500: (161, 192, 255),
            27600: (161, 192, 255),
            27700: (161, 192, 255),
            27800: (160, 192, 255),
            27900: (160, 192, 255),
            28000: (160, 191, 255),
            28100: (160, 191, 255),
            28200: (160, 191, 255),
            28300: (160, 191, 255),
            28400: (160, 191, 255),
            28500: (160, 191, 255),
            28600: (160, 191, 255),
            28700: (160, 191, 255),
            28800: (160, 191, 255),
            28900: (160, 191, 255),
            29000: (160, 191, 255),
            29100: (160, 191, 255),
            29200: (160, 191, 255),
            29300: (159, 191, 255),
            29400: (159, 191, 255),
            29500: (159, 191, 255),
            29600: (159, 191, 255),
            29700: (159, 191, 255),
            29800: (159, 191, 255),
            29900: (159, 191, 255),
            30000: (159, 191, 255),
            30100: (159, 191, 255),
            30200: (159, 191, 255),
            30300: (159, 191, 255),
            30400: (159, 190, 255),
            30500: (159, 190, 255),
            30600: (159, 190, 255),
            30700: (159, 190, 255),
            30800: (159, 190, 255),
            30900: (159, 190, 255),
            31000: (159, 190, 255),
            31100: (158, 190, 255),
            31200: (158, 190, 255),
            31300: (158, 190, 255),
            31400: (158, 190, 255),
            31500: (158, 190, 255),
            31600: (158, 190, 255),
            31700: (158, 190, 255),
            31800: (158, 190, 255),
            31900: (158, 190, 255),
            32000: (158, 190, 255),
            32100: (158, 190, 255),
            32200: (158, 190, 255),
            32300: (158, 190, 255),
            32400: (158, 190, 255),
            32500: (158, 190, 255),
            32600: (158, 190, 255),
            32700: (158, 190, 255),
            32800: (158, 190, 255),
            32900: (158, 190, 255),
            33000: (158, 190, 255),
            33100: (158, 190, 255),
            33200: (157, 190, 255),
            33300: (157, 190, 255),
            33400: (157, 189, 255),
            33500: (157, 189, 255),
            33600: (157, 189, 255),
            33700: (157, 189, 255),
            33800: (157, 189, 255),
            33900: (157, 189, 255),
            34000: (157, 189, 255),
            34100: (157, 189, 255),
            34200: (157, 189, 255),
            34300: (157, 189, 255),
            34400: (157, 189, 255),
            34500: (157, 189, 255),
            34600: (157, 189, 255),
            34700: (157, 189, 255),
            34800: (157, 189, 255),
            34900: (157, 189, 255),
            35000: (157, 189, 255),
            35100: (157, 189, 255),
            35200: (157, 189, 255),
            35300: (157, 189, 255),
            35400: (157, 189, 255),
            35500: (157, 189, 255),
            35600: (156, 189, 255),
            35700: (156, 189, 255),
            35800: (156, 189, 255),
            35900: (156, 189, 255),
            36000: (156, 189, 255),
            36100: (156, 189, 255),
            36200: (156, 189, 255),
            36300: (156, 189, 255),
            36400: (156, 189, 255),
            36500: (156, 189, 255),
            36600: (156, 189, 255),
            36700: (156, 189, 255),
            36800: (156, 189, 255),
            36900: (156, 189, 255),
            37000: (156, 189, 255),
            37100: (156, 189, 255),
            37200: (156, 188, 255),
            37300: (156, 188, 255),
            37400: (156, 188, 255),
            37500: (156, 188, 255),
            37600: (156, 188, 255),
            37700: (156, 188, 255),
            37800: (156, 188, 255),
            37900: (156, 188, 255),
            38000: (156, 188, 255),
            38100: (156, 188, 255),
            38200: (156, 188, 255),
            38300: (156, 188, 255),
            38400: (155, 188, 255),
            38500: (155, 188, 255),
            38600: (155, 188, 255),
            38700: (155, 188, 255),
            38800: (155, 188, 255),
            38900: (155, 188, 255),
            39000: (155, 188, 255),
            39100: (155, 188, 255),
            39200: (155, 188, 255),
            39300: (155, 188, 255),
            39400: (155, 188, 255),
            39500: (155, 188, 255),
            39600: (155, 188, 255),
            39700: (155, 188, 255),
            39800: (155, 188, 255),
            39900: (155, 188, 255),
            40000: (155, 188, 255)
        }

    def start(self):
        async_call(self.color.get_color, None, self.cb_color_get,
                   self.increase_error_count)
        async_call(self.color.get_illuminance, None, self.cb_illuminance_get,
                   self.increase_error_count)
        async_call(self.color.get_color_temperature, None,
                   self.cb_color_temperature_get, self.increase_error_count)
        self.cbe_color.set_period(50)
        self.cbe_illuminance.set_period(100)
        self.cbe_color_temperature.set_period(100)
        async_call(self.color.get_config, None, self.cb_config,
                   self.increase_error_count)
        async_call(self.color.is_light_on, None, self.cb_light_on,
                   self.increase_error_count)

        self.plot_widget.stop = False
        self.plot_widget_illuminance.stop = False
        self.plot_widget_color_temperature.stop = False

    def stop(self):
        self.cbe_color.set_period(0)
        self.cbe_illuminance.set_period(0)
        self.cbe_color_temperature.set_period(0)

        self.plot_widget.stop = True
        self.plot_widget_illuminance.stop = True
        self.plot_widget_color_temperature.stop = True

    def destroy(self):
        pass

    def get_url_part(self):
        return 'color'

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

    def cb_color(self, r, g, b, c):
        self.current_color = (r, g, b, c)
        self.color_label.setText(r, g, b, c)

        rgb_at_limit = r >= 65535 or g >= 65535 or b >= 65535
        self.illuminance_label.mark_as_invalid(rgb_at_limit)
        self.color_temperature_label.mark_as_invalid(rgb_at_limit)

        #        normalize = r+g+b
        normalize = 0xFFFF
        self.color_frame.set_color(r * 255.0 / normalize,
                                   g * 255.0 / normalize,
                                   b * 255.0 / normalize)

    def cb_illuminance(self, illuminance):
        self.current_illuminance = round(
            illuminance * 700.0 / float(self.current_gain_factor) /
            float(self.current_conversion_time), 1)
        self.illuminance_label.setText(self.current_illuminance)

        i = self.current_illuminance * 255 / 20000
        if i > 255:
            i = 255

        self.illuminance_frame.set_color(i, i, i)

    def cb_color_temperature(self, color_temperature):
        self.current_color_temperature = color_temperature
        self.color_temperature_label.setText(self.current_color_temperature)

        m = color_temperature % 100
        color_temperature -= m
        if m > 50:
            color_temperature += 100

        if color_temperature < 1000:
            color_temperature = 1000
        if color_temperature > 40000:
            color_temperature = 40000

        r, g, b = self.k_to_rgb[color_temperature]

        self.color_temperature_frame.set_color(r, g, b)

    def cb_light_on(self, light):
        self.light_checkbox.setChecked(light == BrickletColor.LIGHT_ON)

    def light_state_changed(self, state):
        if state == Qt.Checked:
            self.color.light_on()
        else:
            self.color.light_off()

    def cb_config(self, config):
        gain, gain_factor, conv, conv_time = self.gain_conv_to_combo(
            config.gain, config.integration_time)

        self.gain_combo.setCurrentIndex(gain)
        self.conversion_combo.setCurrentIndex(conv)

        self.current_gain_factor = gain_factor
        self.current_conversion_time = conv_time

    def gain_conv_to_combo(self, gain, conv):
        if gain == BrickletColor.GAIN_1X:
            gain = 0
            gain_factor = 1
        elif gain == BrickletColor.GAIN_4X:
            gain = 1
            gain_factor = 4
        elif gain == BrickletColor.GAIN_16X:
            gain = 2
            gain_factor = 16
        elif gain == BrickletColor.GAIN_60X:
            gain = 3
            gain_factor = 60

        if conv == BrickletColor.INTEGRATION_TIME_2MS:
            conv = 0
            conv_time = 2.4
        elif conv == BrickletColor.INTEGRATION_TIME_24MS:
            conv = 1
            conv_time = 24
        elif conv == BrickletColor.INTEGRATION_TIME_101MS:
            conv = 2
            conv_time = 101
        elif conv == BrickletColor.INTEGRATION_TIME_154MS:
            conv = 3
            conv_time = 154
        elif conv == BrickletColor.INTEGRATION_TIME_700MS:
            conv = 4
            conv_time = 700

        return gain, gain_factor, conv, conv_time

    def combo_to_gain_conv(self, gain, conv):
        if gain == 0:
            gain = BrickletColor.GAIN_1X
            gain_factor = 1
        elif gain == 1:
            gain = BrickletColor.GAIN_4X
            gain_factor = 4
        elif gain == 2:
            gain = BrickletColor.GAIN_16X
            gain_factor = 16
        elif gain == 3:
            gain = BrickletColor.GAIN_60X
            gain_factor = 60

        if conv == 0:
            conv = BrickletColor.INTEGRATION_TIME_2MS
            conv_time = 2.4
        elif conv == 1:
            conv = BrickletColor.INTEGRATION_TIME_24MS
            conv_time = 24
        elif conv == 2:
            conv = BrickletColor.INTEGRATION_TIME_101MS
            conv_time = 101
        elif conv == 3:
            conv = BrickletColor.INTEGRATION_TIME_154MS
            conv_time = 154
        elif conv == 4:
            conv = BrickletColor.INTEGRATION_TIME_700MS
            conv_time = 700

        return gain, gain_factor, conv, conv_time

    def gain_changed(self, gain):
        conversion = self.conversion_combo.currentIndex()

        g, gf, c, ct = self.combo_to_gain_conv(gain, conversion)

        self.current_gain_factor = gf
        self.current_conversion_time = ct

        self.color.set_config(g, c)

    def conversion_changed(self, conversion):
        gain = self.gain_combo.currentIndex()

        g, gf, c, ct = self.combo_to_gain_conv(gain, conversion)

        self.current_gain_factor = gf
        self.current_conversion_time = ct

        self.color.set_config(g, c)

    def cb_color_get(self, color):
        self.cb_color(color.r, color.g, color.b, color.c)

    def cb_illuminance_get(self, illuminance):
        self.cb_illuminance(illuminance)

    def cb_color_temperature_get(self, color_temperature):
        self.cb_color_temperature(color_temperature)

    def get_current_r(self):
        return self.current_color[0]

    def get_current_g(self):
        return self.current_color[1]

    def get_current_b(self):
        return self.current_color[2]

    def get_current_c(self):
        return self.current_color[3]

    def get_current_illuminance_value(self):
        return self.current_illuminance

    def get_current_color_temperature_value(self):
        return self.current_color_temperature
Example #47
0
class DesignPage(QWidget):
    """
    Design Export Page
    """
    ExportTests = pyqtSignal(list, dict) 
    def __init__(self, parent, core, debugMode=False):
        """
        Constructor
        @param parent:
        """
        QWidget.__init__(self, parent)
        self.__core = core
        self.__debugMode = debugMode
        self.__rawXml = ""
        self.__listCsv = []
        
        self.createWidgets()
        self.creationConnections()
        
        if self.__debugMode: self.readXml(rawXml=DESIGN_EXAMPLE)
    
    def core(self):
        """
        """
        return self.__core

    def creationConnections (self):
        """
        QtSignals connection:
        """
        self.exportButton.clicked.connect( self.exportClicked )
        self.loadCsvButton.clicked.connect( self.loadCsv )
        self.testsTable.LoadSteps.connect( self.onLoadSteps )
        
        self.mergeCheckBox.toggled.connect( self.onOptionToggled )
        self.showTcNameCheckBox.toggled.connect( self.onOptionToggled )
        self.mergeStepsCheckBox.toggled.connect( self.onOptionToggled )
        self.replaceTcCheckBox.toggled.connect( self.onOptionToggled )
        
    def createWidgets(self):
        """
        """
        # options
        self.mergeCheckBox = QCheckBox(self.tr("Merge all tests in one"))
        if self.core().settings().cfg()["export-tests"]["merge-all-tests"]:
            self.mergeCheckBox.setCheckState(Qt.Checked) 
            
        self.showTcNameCheckBox = QCheckBox(self.tr("Load with original test name"))
        if self.core().settings().cfg()["export-tests"]["original-test"]:
            self.showTcNameCheckBox.setCheckState(Qt.Checked) 
            
        self.replaceTcCheckBox = QCheckBox(self.tr("Replace testcase with testname"))
        if self.core().settings().cfg()["export-tests"]["replace-testcase"]:
            self.replaceTcCheckBox.setCheckState(Qt.Checked) 
            
        self.mergeStepsCheckBox = QCheckBox(self.tr("Merge all steps in one"))
        if self.core().settings().cfg()["export-tests"]["merge-all-steps"]:
            self.mergeStepsCheckBox.setCheckState(Qt.Checked) 
            
        self.addMissingFoldersCheckBox = QCheckBox(self.tr("Create missing folders"))
        if self.core().settings().cfg()["export-tests"]["add-folders"]:
            self.addMissingFoldersCheckBox.setCheckState(Qt.Checked) 
            
        self.overwriteTcCheckBox = QCheckBox(self.tr("Overwrite testcase(s)"))
        if self.core().settings().cfg()["export-tests"]["overwrite-tests"]:
            self.overwriteTcCheckBox.setCheckState(Qt.Checked) 
            
        # actions to export
        self.loadCsvButton = QPushButton(self.tr("Load CSV"), self)
        
        self.exportButton = QPushButton(self.tr("Export Test"), self)
        self.exportButton.setMinimumWidth(300)
        self.exportStatusLabel = QLabel( "Status: Disconnected", self)

        # tables definition
        self.testsTable = TestsTableView(self, core=self.core())
        self.stepsTable = StepsTableView(self, core=self.core())
        
        # options layout
        optionsTpLayout = QHBoxLayout()
        optionsTpLayout.addWidget(self.addMissingFoldersCheckBox)
        optionsTpLayout.addWidget(self.overwriteTcCheckBox)
        optionsTpLayout.addStretch(1)
        
        optionsLayout = QHBoxLayout()
        optionsLayout.addWidget(self.mergeCheckBox)
        optionsLayout.addWidget(self.showTcNameCheckBox)
        optionsLayout.addWidget(self.replaceTcCheckBox)
        optionsLayout.addStretch(1)
        
        layoutGrid = QGridLayout()
        layoutGrid.addWidget(QLabel("Remote TestPlan:"), 0, 0)
        layoutGrid.addLayout(optionsTpLayout, 0, 1)
        layoutGrid.addWidget(QLabel("Local Test:"), 1, 0)
        layoutGrid.addLayout(optionsLayout, 1, 1)
        layoutGrid.addWidget(QLabel("Tests Listing:"), 2, 0)
        layoutGrid.addWidget(self.testsTable, 2, 1)
        layoutGrid.addWidget(self.mergeStepsCheckBox, 3, 1)
        layoutGrid.addWidget(QLabel("Steps Listing:"), 4, 0)
        layoutGrid.addWidget(self.stepsTable, 4, 1)
        
        layoutRight = QHBoxLayout()
        layoutRight.addWidget(self.exportButton)
        layoutRight.addWidget(self.loadCsvButton)
        layoutRight.addWidget(self.exportStatusLabel)
        layoutRight.addStretch(1)
        
        layoutGrid.addWidget(QLabel("Controls:"), 5, 0)
        layoutGrid.addLayout(layoutRight, 5, 1)
        
        layoutMain = QVBoxLayout()
        layoutMain.addLayout(layoutGrid)
    
        self.setLayout(layoutMain)

    def resetBuffers(self):
        """
        """
        self.__rawXml = ""
        self.__listCsv = []
        
    def loadCsv(self):
        """
        """
        self.resetBuffers()
        
        fileName = QFileDialog.getOpenFileName(self,
              self.tr("Open File"), "", "CSV (*.csv)")
        if not len(fileName):
            return

        csv.register_dialect('coma', delimiter=';')

        tests = []
            
        with open(fileName, encoding='iso-8859-1') as f:
            reader = csv.DictReader(f, dialect="coma")
            prev = None
            for row in reader:
                if prev is not None:
                    if prev["testpath"] == row["testpath"] and prev["testcase"] == row["testcase"]:
                        prev["steps"].append( { 
                                            "summary": row["step description"],
                                            "action": row["step description"],         
                                            "expected": row["step expected"] 
                                        } )
                        continue

                test = {
                            "testpath": row["testpath"], 
                            "requirement": "", 
                            "testname": "",
                            "testcase": row["testcase"], 
                            "purpose": row["purpose"], 
                            "steps": [ 
                                        { 
                                            "summary": row["step description"],
                                            "action": row["step description"],         
                                            "expected": row["step expected"] 
                                        }
                                    ]
                        }
                tests.append(test)
                prev = test

        self.readListCsv(listCsv=tests)
        
    def exportClicked (self):
        """
        Called on accept button
        """
        indexes = self.testsTable.selectionModel().selectedRows()
        if not len(indexes):
            QMessageBox.warning(self, self.tr("Export Test") , 
                                self.tr("Please to select a testcase!") )
            return
        
        testcases = []
        
        error = False
        for index in indexes:
            selectedIndex = index.row()
            row = self.testsTable.model.getData()[selectedIndex]
            if not len(row["testcase"]): error = True
            testcases.append(row)
        
        if error: 
            QMessageBox.warning(self, self.tr("Export Test") , 
                                self.tr("Please to set a testcase name!") )
            return

        config = {}
        for cfg in self.core().settings().cfg()["custom-test-fields"]:
            config.update( {cfg["key"]: cfg["value"] } )
            
        self.disableExport()
        
        config["Add_Folders"] = self.addMissingFoldersCheckBox.isChecked()
        config["Overwrite_Tests"] = self.overwriteTcCheckBox.isChecked()
                    
        self.ExportTests.emit(testcases, config)
        
    def onOptionToggled (self, toggled):
        """
        Called on accept button
        """
        # reload from initial dict
        if len(self.__listCsv):
            self.readListCsv(listCsv=self.__listCsv)
        
        # reload from initial xml, default       
        else:
            self.readXml(rawXml=self.__rawXml)

    def logStatus(self, status):
        """
        """
        self.exportStatusLabel.setText(status)
        
    def enableExport(self):
        """
        """
        self.exportButton.setEnabled(True)
        
    def disableExport(self):
        """
        """
        self.exportButton.setEnabled(False)
 
    def onLoadSteps(self, steps):
        """
        """
        self.stepsTable.loadTable(data=steps)

    def onLoadTests(self, data):
        """
        """
        self.stepsTable.clear()
        self.testsTable.loadTable(data=data)

    def readListCsv(self, listCsv):
        """
        """
        self.resetBuffers()
        
        self.__listCsv = listCsv
        
        testcases = copy.deepcopy(listCsv)

        if self.mergeCheckBox.isChecked(): testcases = self.mergeTests(testcases=testcases)
            
        for tc in testcases:
            # read and merge all tests in one ?
            if self.mergeStepsCheckBox.isChecked(): tc["steps"] = self.mergeCsvSteps(steps=tc["steps"])

        # finally loading all tests in table model
        self.core().debug().addLogSuccess("Tests detected in csv: %s"  % len(testcases) )
        if len(testcases):  self.onLoadTests(data=testcases)
        
    def mergeTests(self, testcases):
        """
        """
        tc = {
                    "testpath": testcases[0]["testpath"], 
                    "requirement": testcases[0]["requirement"], 
                    "testname": testcases[0]["testname"], 
                    "testcase": testcases[0]["testcase"], 
                    "purpose": testcases[0]["purpose"],  
                    "steps": []
                }
        for t in testcases:  tc["steps"].extend(t["steps"]) 
        return [ tc ]
        
    def mergeCsvSteps(self, steps):
        """
        """
        summaries = []
        actions = []
        expecteds = []
        i = 0
        for stp in steps:
            i += 1
            summaries.append( "%s. %s" %  (i, stp["summary"]) )
            actions.append( "%s. %s" %  (i, stp["action"]) )
            expecteds.append( "%s. %s" % (i, stp["expected"]) )
            
        ret = {
                 'summary': "\n".join(summaries),
                 'action': "\n".join(actions),
                 'expected': "\n".join(expecteds)
                }
        return [ ret ]
        
    def readXml(self, rawXml):
        """
        """
        self.resetBuffers()
        
        # init and save the xml provided
        self.__rawXml = rawXml
        testcases = []
        
        # load the xml provided
        try:
            root = ET.fromstring(rawXml)
        except Exception as e:
            self.core().debug().addLogError("Unable to read xml: %s"  % e )
        else: 
            designs = root.find(".")

            # read and merge all tests in one ?
            if self.mergeCheckBox.isChecked(): testcases = self.mergeXmlTests(designsXml=designs)
                
            # otherwise read all tests
            else: testcases = self.readXmlTests(designsXml=designs)
             
            # finally loading all tests in table model
            self.core().debug().addLogSuccess("Export tests detected: %s"  % len(testcases) )
            if len(testcases):  self.onLoadTests(data=testcases)

    def mergeXmlTests(self, designsXml):
        """
        """
        testcases = []
        tc = { "steps": [] }
        summaries = []
        actions = []
        expecteds = []
        delta = 0
        for i in range(len(designsXml)):
            if i == 0:
                tc["requirement"] = designsXml[i].find("requirement").text
                tc["purpose"] = designsXml[i].find("purpose").text
                if self.showTcNameCheckBox.isChecked():
                    tc["testpath"] = designsXml[i].find("testpath").text
                    tc["testname"] = designsXml[i].find("testname").text
                    tc["testcase"] = designsXml[i].find("testcase").text
                else:
                    tc["testpath"] = designsXml[i].find("filepath").text
                    tc["testname"] = designsXml[i].find("filename").text
                    tc["testcase"] = designsXml[i].find("testname").text
                    
                if self.replaceTcCheckBox.isChecked():
                    tc["testpath"] = designsXml[i].find("filepath").text
                    tc["testname"] = ""
                    tc["testcase"] = designsXml[i].find("filename").text
                    
            stepsDesigns = designsXml[i].findall("steps/step")

            steps, nb_steps = self.readXmlSteps(stepsXml=stepsDesigns, delta=delta)
            delta += nb_steps
            if self.mergeStepsCheckBox.isChecked() and len(steps):
                summaries.append(steps[0]["summary"])
                actions.append(steps[0]["action"])
                expecteds.append(steps[0]["expected"])
            else:
                tc["steps"].extend(steps) 

        testcases.append(tc)
        if self.mergeStepsCheckBox.isChecked():
            stp = {
                     'summary': "\n".join(summaries),
                     'action': "\n".join(actions),
                     'expected': "\n".join(expecteds)
                    }
            tc["steps"].extend( [ stp ] )
        return testcases
        
    def readXmlTests(self, designsXml):
        """
        """
        testcases = []
        for design in designsXml:
            tc = { 
                    "requirement": design.find("requirement").text,
                    "purpose": design.find("purpose").text,
                 }
            
            # replace testcase name ?
            if not self.showTcNameCheckBox.isChecked():
                tc.update( {
                            "testpath": design.find("filepath").text,
                            "testname": design.find("filename").text,
                            "testcase": design.find("testname").text
                            } )
            else:
                tc.update( {
                            "testpath": design.find("testpath").text,
                            "testname": design.find("testname").text,
                            "testcase": design.find("testcase").text
                            } )
                            
            if self.replaceTcCheckBox.isChecked():
                tc.update( {
                            "testpath": design.find("testpath").text,
                            "testname": "",
                            "testcase": design.find("testname").text
                            } )
                
            # read steps
            stepsDesigns = design.findall("steps/step")
            steps, nb_steps = self.readXmlSteps(stepsXml=stepsDesigns)
            tc.update( {"steps": steps} )
            
            testcases.append(tc)
        return testcases
        
    def readXmlSteps(self, stepsXml, delta=0):
        """
        """
        steps = []
        summaries = []
        actions = []
        expecteds = []
        i = 0
        for stp in stepsXml:
            i += 1
            summary = stp.find("summary").text
            action = stp.find("action").text
            expected = stp.find("expected").text
            if self.mergeStepsCheckBox.isChecked():
                summaries.append( "%s. %s" % (i + delta, summary) )
                actions.append( "%s. %s" % (i + delta, action) )
                expecteds.append( "%s. %s" % (i + delta, expected) )
            else:
                stp = {
                         'summary': summary,
                         'action': action,
                         'expected': expected
                        }
                steps.append(stp)
                
        if self.mergeStepsCheckBox.isChecked():
            stp = {
                     'summary': "\n".join(summaries),
                     'action': "\n".join(actions),
                     'expected': "\n".join(expecteds)
                    }
            steps.append(stp)
        return (steps, i)
Example #48
0
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletColor, *args)

        self.color = self.device

        self.cbe_color = CallbackEmulator(self.color.get_color,
                                          self.cb_color_get,
                                          self.increase_error_count)
        self.cbe_illuminance = CallbackEmulator(self.color.get_illuminance,
                                                self.cb_illuminance_get,
                                                self.increase_error_count)
        self.cbe_color_temperature = CallbackEmulator(
            self.color.get_color_temperature, self.cb_color_temperature_get,
            self.increase_error_count)

        self.color_label = ColorLabel()
        self.illuminance_label = IlluminanceLabel()
        self.color_temperature_label = ColorTemperatureLabel()
        self.color_frame = ColorFrame()
        self.color_temperature_frame = ColorFrame()
        self.illuminance_frame = ColorFrame()

        self.current_color = (0, 0, 0, 0)
        self.current_illuminance = 0
        self.current_color_temperature = 0

        self.clear_graphs_button = QPushButton("Clear Graphs")

        plot_list = [['R', Qt.red, self.get_current_r],
                     ['G', Qt.darkGreen, self.get_current_g],
                     ['B', Qt.blue, self.get_current_b],
                     ['C', Qt.black, self.get_current_c]]
        self.plot_widget = PlotWidget('Color Value', plot_list,
                                      self.clear_graphs_button)
        self.plot_widget.setMinimumSize(250, 200)

        plot_list_illuminance = [[
            '', Qt.red, self.get_current_illuminance_value
        ]]
        self.plot_widget_illuminance = PlotWidget('Illuminance [Lux]',
                                                  plot_list_illuminance,
                                                  self.clear_graphs_button)
        self.plot_widget_illuminance.setMinimumSize(250, 200)

        plot_list_color_temperature = [[
            '', Qt.red, self.get_current_color_temperature_value
        ]]
        self.plot_widget_color_temperature = PlotWidget(
            'Color Temperature [K]', plot_list_color_temperature,
            self.clear_graphs_button)
        self.plot_widget_color_temperature.setMinimumSize(250, 200)

        self.gain_label = QLabel('Gain: ')
        self.gain_combo = QComboBox()
        self.gain_combo.addItem("1x")
        self.gain_combo.addItem("4x")
        self.gain_combo.addItem("16x")
        self.gain_combo.addItem("60x")

        self.gain_combo.currentIndexChanged.connect(self.gain_changed)

        self.current_gain_factor = 60

        self.conversion_label = QLabel('Integration Time: ')
        self.conversion_combo = QComboBox()
        self.conversion_combo.addItem("2.4ms")
        self.conversion_combo.addItem("24ms")
        self.conversion_combo.addItem("101ms")
        self.conversion_combo.addItem("154ms")
        self.conversion_combo.addItem("700ms")

        self.current_conversion_time = 154

        self.conversion_combo.currentIndexChanged.connect(
            self.conversion_changed)

        self.light_checkbox = QCheckBox("Enable Light")

        self.light_checkbox.stateChanged.connect(self.light_state_changed)

        layout_config = QHBoxLayout()
        layout_config.addWidget(self.gain_label)
        layout_config.addWidget(self.gain_combo)
        layout_config.addWidget(self.conversion_label)
        layout_config.addWidget(self.conversion_combo)
        layout_config.addWidget(self.clear_graphs_button, 1)
        layout_config.addWidget(self.light_checkbox)

        layout_ht1 = QHBoxLayout()
        layout_ht1.addStretch()
        layout_ht1.addWidget(self.illuminance_label)
        layout_ht1.addWidget(self.illuminance_frame)
        layout_ht1.addStretch()

        layout_ht2 = QHBoxLayout()
        layout_ht2.addStretch()
        layout_ht2.addWidget(self.color_temperature_label)
        layout_ht2.addWidget(self.color_temperature_frame)
        layout_ht2.addStretch()

        layout_v1 = QVBoxLayout()
        layout_v1.addLayout(layout_ht1)
        layout_v1.addWidget(self.plot_widget_illuminance)

        layout_v2 = QVBoxLayout()
        layout_v2.addLayout(layout_ht2)
        layout_v2.addWidget(self.plot_widget_color_temperature)

        layout_h2 = QHBoxLayout()
        layout_h2.addLayout(layout_v1)
        layout_h2.addLayout(layout_v2)

        layout_h = QHBoxLayout()
        layout_h.addStretch()
        layout_h.addWidget(self.color_label)
        layout_h.addWidget(self.color_frame)
        layout_h.addStretch()

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

        self.k_to_rgb = {
            1000: (255, 56, 0),
            1100: (255, 71, 0),
            1200: (255, 83, 0),
            1300: (255, 93, 0),
            1400: (255, 101, 0),
            1500: (255, 109, 0),
            1600: (255, 115, 0),
            1700: (255, 121, 0),
            1800: (255, 126, 0),
            1900: (255, 131, 0),
            2000: (255, 137, 18),
            2100: (255, 142, 33),
            2200: (255, 147, 44),
            2300: (255, 152, 54),
            2400: (255, 157, 63),
            2500: (255, 161, 72),
            2600: (255, 165, 79),
            2700: (255, 169, 87),
            2800: (255, 173, 94),
            2900: (255, 177, 101),
            3000: (255, 180, 107),
            3100: (255, 184, 114),
            3200: (255, 187, 120),
            3300: (255, 190, 126),
            3400: (255, 193, 132),
            3500: (255, 196, 137),
            3600: (255, 199, 143),
            3700: (255, 201, 148),
            3800: (255, 204, 153),
            3900: (255, 206, 159),
            4000: (255, 209, 163),
            4100: (255, 211, 168),
            4200: (255, 213, 173),
            4300: (255, 215, 177),
            4400: (255, 217, 182),
            4500: (255, 219, 186),
            4600: (255, 221, 190),
            4700: (255, 223, 194),
            4800: (255, 225, 198),
            4900: (255, 227, 202),
            5000: (255, 228, 206),
            5100: (255, 230, 210),
            5200: (255, 232, 213),
            5300: (255, 233, 217),
            5400: (255, 235, 220),
            5500: (255, 236, 224),
            5600: (255, 238, 227),
            5700: (255, 239, 230),
            5800: (255, 240, 233),
            5900: (255, 242, 236),
            6000: (255, 243, 239),
            6100: (255, 244, 242),
            6200: (255, 245, 245),
            6300: (255, 246, 248),
            6400: (255, 248, 251),
            6500: (255, 249, 253),
            6600: (254, 249, 255),
            6700: (252, 247, 255),
            6800: (249, 246, 255),
            6900: (247, 245, 255),
            7000: (245, 243, 255),
            7100: (243, 242, 255),
            7200: (240, 241, 255),
            7300: (239, 240, 255),
            7400: (237, 239, 255),
            7500: (235, 238, 255),
            7600: (233, 237, 255),
            7700: (231, 236, 255),
            7800: (230, 235, 255),
            7900: (228, 234, 255),
            8000: (227, 233, 255),
            8100: (225, 232, 255),
            8200: (224, 231, 255),
            8300: (222, 230, 255),
            8400: (221, 230, 255),
            8500: (220, 229, 255),
            8600: (218, 228, 255),
            8700: (217, 227, 255),
            8800: (216, 227, 255),
            8900: (215, 226, 255),
            9000: (214, 225, 255),
            9100: (212, 225, 255),
            9200: (211, 224, 255),
            9300: (210, 223, 255),
            9400: (209, 223, 255),
            9500: (208, 222, 255),
            9600: (207, 221, 255),
            9700: (207, 221, 255),
            9800: (206, 220, 255),
            9900: (205, 220, 255),
            10000: (204, 219, 255),
            10100: (203, 219, 255),
            10200: (202, 218, 255),
            10300: (201, 218, 255),
            10400: (201, 217, 255),
            10500: (200, 217, 255),
            10600: (199, 216, 255),
            10700: (199, 216, 255),
            10800: (198, 216, 255),
            10900: (197, 215, 255),
            11000: (196, 215, 255),
            11100: (196, 214, 255),
            11200: (195, 214, 255),
            11300: (195, 214, 255),
            11400: (194, 213, 255),
            11500: (193, 213, 255),
            11600: (193, 212, 255),
            11700: (192, 212, 255),
            11800: (192, 212, 255),
            11900: (191, 211, 255),
            12000: (191, 211, 255),
            12100: (190, 211, 255),
            12200: (190, 210, 255),
            12300: (189, 210, 255),
            12400: (189, 210, 255),
            12500: (188, 210, 255),
            12600: (188, 209, 255),
            12700: (187, 209, 255),
            12800: (187, 209, 255),
            12900: (186, 208, 255),
            13000: (186, 208, 255),
            13100: (185, 208, 255),
            13200: (185, 208, 255),
            13300: (185, 207, 255),
            13400: (184, 207, 255),
            13500: (184, 207, 255),
            13600: (183, 207, 255),
            13700: (183, 206, 255),
            13800: (183, 206, 255),
            13900: (182, 206, 255),
            14000: (182, 206, 255),
            14100: (182, 205, 255),
            14200: (181, 205, 255),
            14300: (181, 205, 255),
            14400: (181, 205, 255),
            14500: (180, 205, 255),
            14600: (180, 204, 255),
            14700: (180, 204, 255),
            14800: (179, 204, 255),
            14900: (179, 204, 255),
            15000: (179, 204, 255),
            15100: (178, 203, 255),
            15200: (178, 203, 255),
            15300: (178, 203, 255),
            15400: (178, 203, 255),
            15500: (177, 203, 255),
            15600: (177, 202, 255),
            15700: (177, 202, 255),
            15800: (177, 202, 255),
            15900: (176, 202, 255),
            16000: (176, 202, 255),
            16100: (176, 202, 255),
            16200: (175, 201, 255),
            16300: (175, 201, 255),
            16400: (175, 201, 255),
            16500: (175, 201, 255),
            16600: (175, 201, 255),
            16700: (174, 201, 255),
            16800: (174, 201, 255),
            16900: (174, 200, 255),
            17000: (174, 200, 255),
            17100: (173, 200, 255),
            17200: (173, 200, 255),
            17300: (173, 200, 255),
            17400: (173, 200, 255),
            17500: (173, 200, 255),
            17600: (172, 199, 255),
            17700: (172, 199, 255),
            17800: (172, 199, 255),
            17900: (172, 199, 255),
            18000: (172, 199, 255),
            18100: (171, 199, 255),
            18200: (171, 199, 255),
            18300: (171, 199, 255),
            18400: (171, 198, 255),
            18500: (171, 198, 255),
            18600: (170, 198, 255),
            18700: (170, 198, 255),
            18800: (170, 198, 255),
            18900: (170, 198, 255),
            19000: (170, 198, 255),
            19100: (170, 198, 255),
            19200: (169, 198, 255),
            19300: (169, 197, 255),
            19400: (169, 197, 255),
            19500: (169, 197, 255),
            19600: (169, 197, 255),
            19700: (169, 197, 255),
            19800: (169, 197, 255),
            19900: (168, 197, 255),
            20000: (168, 197, 255),
            20100: (168, 197, 255),
            20200: (168, 197, 255),
            20300: (168, 196, 255),
            20400: (168, 196, 255),
            20500: (168, 196, 255),
            20600: (167, 196, 255),
            20700: (167, 196, 255),
            20800: (167, 196, 255),
            20900: (167, 196, 255),
            21000: (167, 196, 255),
            21100: (167, 196, 255),
            21200: (167, 196, 255),
            21300: (166, 196, 255),
            21400: (166, 195, 255),
            21500: (166, 195, 255),
            21600: (166, 195, 255),
            21700: (166, 195, 255),
            21800: (166, 195, 255),
            21900: (166, 195, 255),
            22000: (166, 195, 255),
            22100: (165, 195, 255),
            22200: (165, 195, 255),
            22300: (165, 195, 255),
            22400: (165, 195, 255),
            22500: (165, 195, 255),
            22600: (165, 195, 255),
            22700: (165, 194, 255),
            22800: (165, 194, 255),
            22900: (165, 194, 255),
            23000: (164, 194, 255),
            23100: (164, 194, 255),
            23200: (164, 194, 255),
            23300: (164, 194, 255),
            23400: (164, 194, 255),
            23500: (164, 194, 255),
            23600: (164, 194, 255),
            23700: (164, 194, 255),
            23800: (164, 194, 255),
            23900: (164, 194, 255),
            24000: (163, 194, 255),
            24100: (163, 194, 255),
            24200: (163, 193, 255),
            24300: (163, 193, 255),
            24400: (163, 193, 255),
            24500: (163, 193, 255),
            24600: (163, 193, 255),
            24700: (163, 193, 255),
            24800: (163, 193, 255),
            24900: (163, 193, 255),
            25000: (163, 193, 255),
            25100: (162, 193, 255),
            25200: (162, 193, 255),
            25300: (162, 193, 255),
            25400: (162, 193, 255),
            25500: (162, 193, 255),
            25600: (162, 193, 255),
            25700: (162, 193, 255),
            25800: (162, 193, 255),
            25900: (162, 192, 255),
            26000: (162, 192, 255),
            26100: (162, 192, 255),
            26200: (162, 192, 255),
            26300: (162, 192, 255),
            26400: (161, 192, 255),
            26500: (161, 192, 255),
            26600: (161, 192, 255),
            26700: (161, 192, 255),
            26800: (161, 192, 255),
            26900: (161, 192, 255),
            27000: (161, 192, 255),
            27100: (161, 192, 255),
            27200: (161, 192, 255),
            27300: (161, 192, 255),
            27400: (161, 192, 255),
            27500: (161, 192, 255),
            27600: (161, 192, 255),
            27700: (161, 192, 255),
            27800: (160, 192, 255),
            27900: (160, 192, 255),
            28000: (160, 191, 255),
            28100: (160, 191, 255),
            28200: (160, 191, 255),
            28300: (160, 191, 255),
            28400: (160, 191, 255),
            28500: (160, 191, 255),
            28600: (160, 191, 255),
            28700: (160, 191, 255),
            28800: (160, 191, 255),
            28900: (160, 191, 255),
            29000: (160, 191, 255),
            29100: (160, 191, 255),
            29200: (160, 191, 255),
            29300: (159, 191, 255),
            29400: (159, 191, 255),
            29500: (159, 191, 255),
            29600: (159, 191, 255),
            29700: (159, 191, 255),
            29800: (159, 191, 255),
            29900: (159, 191, 255),
            30000: (159, 191, 255),
            30100: (159, 191, 255),
            30200: (159, 191, 255),
            30300: (159, 191, 255),
            30400: (159, 190, 255),
            30500: (159, 190, 255),
            30600: (159, 190, 255),
            30700: (159, 190, 255),
            30800: (159, 190, 255),
            30900: (159, 190, 255),
            31000: (159, 190, 255),
            31100: (158, 190, 255),
            31200: (158, 190, 255),
            31300: (158, 190, 255),
            31400: (158, 190, 255),
            31500: (158, 190, 255),
            31600: (158, 190, 255),
            31700: (158, 190, 255),
            31800: (158, 190, 255),
            31900: (158, 190, 255),
            32000: (158, 190, 255),
            32100: (158, 190, 255),
            32200: (158, 190, 255),
            32300: (158, 190, 255),
            32400: (158, 190, 255),
            32500: (158, 190, 255),
            32600: (158, 190, 255),
            32700: (158, 190, 255),
            32800: (158, 190, 255),
            32900: (158, 190, 255),
            33000: (158, 190, 255),
            33100: (158, 190, 255),
            33200: (157, 190, 255),
            33300: (157, 190, 255),
            33400: (157, 189, 255),
            33500: (157, 189, 255),
            33600: (157, 189, 255),
            33700: (157, 189, 255),
            33800: (157, 189, 255),
            33900: (157, 189, 255),
            34000: (157, 189, 255),
            34100: (157, 189, 255),
            34200: (157, 189, 255),
            34300: (157, 189, 255),
            34400: (157, 189, 255),
            34500: (157, 189, 255),
            34600: (157, 189, 255),
            34700: (157, 189, 255),
            34800: (157, 189, 255),
            34900: (157, 189, 255),
            35000: (157, 189, 255),
            35100: (157, 189, 255),
            35200: (157, 189, 255),
            35300: (157, 189, 255),
            35400: (157, 189, 255),
            35500: (157, 189, 255),
            35600: (156, 189, 255),
            35700: (156, 189, 255),
            35800: (156, 189, 255),
            35900: (156, 189, 255),
            36000: (156, 189, 255),
            36100: (156, 189, 255),
            36200: (156, 189, 255),
            36300: (156, 189, 255),
            36400: (156, 189, 255),
            36500: (156, 189, 255),
            36600: (156, 189, 255),
            36700: (156, 189, 255),
            36800: (156, 189, 255),
            36900: (156, 189, 255),
            37000: (156, 189, 255),
            37100: (156, 189, 255),
            37200: (156, 188, 255),
            37300: (156, 188, 255),
            37400: (156, 188, 255),
            37500: (156, 188, 255),
            37600: (156, 188, 255),
            37700: (156, 188, 255),
            37800: (156, 188, 255),
            37900: (156, 188, 255),
            38000: (156, 188, 255),
            38100: (156, 188, 255),
            38200: (156, 188, 255),
            38300: (156, 188, 255),
            38400: (155, 188, 255),
            38500: (155, 188, 255),
            38600: (155, 188, 255),
            38700: (155, 188, 255),
            38800: (155, 188, 255),
            38900: (155, 188, 255),
            39000: (155, 188, 255),
            39100: (155, 188, 255),
            39200: (155, 188, 255),
            39300: (155, 188, 255),
            39400: (155, 188, 255),
            39500: (155, 188, 255),
            39600: (155, 188, 255),
            39700: (155, 188, 255),
            39800: (155, 188, 255),
            39900: (155, 188, 255),
            40000: (155, 188, 255)
        }
Example #49
0
class LogTool(preferences.Group):
    def __init__(self, page):
        super(LogTool, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QDoubleSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)

        box = QHBoxLayout()
        box.addWidget(self.fontLabel)
        box.addWidget(self.fontChooser, 1)
        box.addWidget(self.fontSize)
        layout.addLayout(box)

        self.showlog = QCheckBox(toggled=self.changed)
        layout.addWidget(self.showlog)

        self.rawview = QCheckBox(toggled=self.changed)
        layout.addWidget(self.rawview)

        self.hideauto = QCheckBox(toggled=self.changed)
        layout.addWidget(self.hideauto)

        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("LilyPond Log"))
        self.fontLabel.setText(_("Font:"))
        self.showlog.setText(_("Show log when a job is started"))
        self.rawview.setText(_("Display plain log output"))
        self.rawview.setToolTip(
            _("If checked, Frescobaldi will not shorten filenames in the log output."
              ""))
        self.hideauto.setText(_("Hide automatic engraving jobs"))
        self.hideauto.setToolTip(
            _("If checked, Frescobaldi will not show the log for automatically\n"
              "started engraving jobs (LilyPond->Auto-engrave)."))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("log")
        font = QFont(s.value("fontfamily", "monospace", type("")))
        font.setPointSizeF(s.value("fontsize", 9.0, float))
        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(font)
            self.fontSize.setValue(font.pointSizeF())
        self.showlog.setChecked(s.value("show_on_start", True, bool))
        self.rawview.setChecked(s.value("rawview", True, bool))
        self.hideauto.setChecked(s.value("hide_auto_engrave", False, bool))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("log")
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
        s.setValue("show_on_start", self.showlog.isChecked())
        s.setValue("rawview", self.rawview.isChecked())
        s.setValue("hide_auto_engrave", self.hideauto.isChecked())
Example #50
0
    def __init__(self, parent):
        super(GeneralPreferences, self).__init__(parent)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.typq = QCheckBox()
        self.tagl = QCheckBox()
        self.barnum = QCheckBox()
        self.neutdir = QCheckBox()
        self.midi = QCheckBox()
        self.metro = QCheckBox()
        self.paperSizeLabel = QLabel()
        self.paper = QComboBox()
        self.paper.addItems(paperSizes)
        self.paperLandscape = QCheckBox(enabled=False)
        self.paper.activated.connect(self.slotPaperChanged)

        layout.addWidget(self.typq)
        layout.addWidget(self.tagl)
        layout.addWidget(self.barnum)
        layout.addWidget(self.neutdir)
        layout.addWidget(self.midi)
        layout.addWidget(self.metro)

        box = QHBoxLayout(spacing=2)
        box.addWidget(self.paperSizeLabel)
        box.addWidget(self.paper)
        box.addWidget(self.paperLandscape)
        layout.addLayout(box)
        app.translateUI(self)

        self.loadSettings()
        self.window().finished.connect(self.saveSettings)
Example #51
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None

        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.lilyChooser = lilychooser.LilyChooser()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(
            checked=QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()

        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')

        self.buttons = QDialogButtonBox(QDialogButtonBox.Reset
                                        | QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)

        layout = QVBoxLayout()
        self.setLayout(layout)

        grid = QGridLayout()
        grid.addWidget(self.fromVersionLabel, 0, 0)
        grid.addWidget(self.fromVersion, 0, 1)
        grid.addWidget(self.reason, 0, 2, 1, 3)
        grid.addWidget(self.toVersionLabel, 1, 0)
        grid.addWidget(self.toVersion, 1, 1)
        grid.addWidget(self.lilyChooser, 1, 3, 1, 2)

        layout.addLayout(grid)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        self.lilyChooser.currentIndexChanged.connect(
            self.slotLilyPondVersionChanged)
        self.slotLilyPondVersionChanged()

    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(
            _("If checked, the messages of convert-ly are appended as a "
              "comment to the end of the document."))
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.setCaption()

    def saveCopyCheckSetting(self):
        QSettings().setValue('convert_ly/copy_messages',
                             self.copyCheck.isChecked())

    def readSettings(self):
        font = textformats.formatData('editor').font
        self.diff.setFont(font)

    def slotLilyPondVersionChanged(self):
        self.setLilyPondInfo(self.lilyChooser.lilyPondInfo())

    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()
        self.messages.clear()

    def setConvertedText(self, text=''):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(
                htmldiff.htmldiff(self._text,
                                  text,
                                  _("Current Document"),
                                  _("Converted Document"),
                                  wrapcolumn=100))
        else:
            self.diff.clear()

    def convertedText(self):
        return self._convertedtext or ''

    def setDocument(self, doc):
        v = documentinfo.docinfo(doc).version_string()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or 'UTF-8'
        self.setConvertedText()

    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(
                _("Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        command = info.toolcommand(info.convert_ly)
        command += ['-f', fromVersion, '-t', toVersion, '-']

        # if the user wants english messages, do it also here: LANGUAGE=C
        env = None
        if QSettings().value("lilypond_settings/no_translation", False, bool):
            if os.name == "nt":
                # Python 2.7 subprocess on Windows chokes on unicode in env
                env = util.bytes_environ()
                env[b'LANGUAGE'] = b'C'
            else:
                env = dict(os.environ)
                env['LANGUAGE'] = 'C'

        with qutil.busyCursor():
            try:
                proc = subprocess.Popen(command,
                                        universal_newlines=True,
                                        env=env,
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
                out, err = proc.communicate(self._text.encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(
                    _("Could not start {convert_ly}:\n\n"
                      "{message}\n").format(convert_ly=convert_ly, message=e))
                return
            self.messages.setPlainText(err.decode('UTF-8'))
            self.setConvertedText(out.decode('UTF-8'))
            if not out or self._convertedtext == self._text:
                self.messages.append('\n' +
                                     _("The document has not been changed."))
Example #52
0
 def __init__(self, iface, layer, tree, dlg):
     QTreeWidgetItem.__init__(self)
     self.iface = iface
     self.layer = layer
     self.setText(0, layer.name())
     self.setIcon(0, self.layerIcon)
     project = QgsProject.instance()
     if project.layerTreeRoot().findLayer(layer.id()).isVisible():
         self.setCheckState(0, Qt.Checked)
     else:
         self.setCheckState(0, Qt.Unchecked)
     self.visibleItem = QTreeWidgetItem(self)
     self.visibleCheck = QCheckBox()
     vis = layer.customProperty("qgis2web/Visible", True)
     if (vis == 0 or unicode(vis).lower() == "false"):
         self.visibleCheck.setChecked(False)
     else:
         self.visibleCheck.setChecked(True)
     self.visibleItem.setText(0, "Visible")
     self.addChild(self.visibleItem)
     tree.setItemWidget(self.visibleItem, 1, self.visibleCheck)
     if layer.type() == layer.VectorLayer:
         if layer.providerType() == 'WFS':
             self.jsonItem = QTreeWidgetItem(self)
             self.jsonCheck = QCheckBox()
             if layer.customProperty("qgis2web/Encode to JSON") == 2:
                 self.jsonCheck.setChecked(True)
             self.jsonItem.setText(0, "Encode to JSON")
             self.jsonCheck.stateChanged.connect(self.changeJSON)
             self.addChild(self.jsonItem)
             tree.setItemWidget(self.jsonItem, 1, self.jsonCheck)
         if layer.geometryType() == QGis.Point:
             self.clusterItem = QTreeWidgetItem(self)
             self.clusterCheck = QCheckBox()
             if layer.customProperty("qgis2web/Cluster") == 2:
                 self.clusterCheck.setChecked(True)
             self.clusterItem.setText(0, "Cluster")
             self.clusterCheck.stateChanged.connect(self.changeCluster)
             self.addChild(self.clusterItem)
             tree.setItemWidget(self.clusterItem, 1, self.clusterCheck)
         self.popupItem = QTreeWidgetItem(self)
         self.popupItem.setText(0, "Popup fields")
         options = []
         fields = self.layer.pendingFields()
         for f in fields:
             fieldIndex = fields.indexFromName(unicode(f.name()))
             try:
                 formCnf = layer.editFormConfig()
                 editorWidget = formCnf.widgetType(fieldIndex)
             except:
                 editorWidget = layer.editorWidgetV2(fieldIndex)
             if editorWidget == QgsVectorLayer.Hidden or \
                editorWidget == 'Hidden':
                 continue
             options.append(f.name())
         for option in options:
             self.attr = QTreeWidgetItem(self)
             self.attrWidget = QComboBox()
             self.attrWidget.addItem("no label")
             self.attrWidget.addItem("inline label")
             self.attrWidget.addItem("header label")
             custProp = layer.customProperty("qgis2web/popup/" + option)
             if (custProp != "" and custProp is not None):
                 self.attrWidget.setCurrentIndex(
                     self.attrWidget.findText(
                         layer.customProperty("qgis2web/popup/" + option)))
             self.attr.setText(1, option)
             self.popupItem.addChild(self.attr)
             tree.setItemWidget(self.attr, 2, self.attrWidget)
         self.addChild(self.popupItem)
Example #53
0
class GeneralPreferences(QGroupBox):
    def __init__(self, parent):
        super(GeneralPreferences, self).__init__(parent)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.typq = QCheckBox()
        self.tagl = QCheckBox()
        self.barnum = QCheckBox()
        self.neutdir = QCheckBox()
        self.midi = QCheckBox()
        self.metro = QCheckBox()
        self.paperSizeLabel = QLabel()
        self.paper = QComboBox()
        self.paper.addItems(paperSizes)
        self.paperLandscape = QCheckBox(enabled=False)
        self.paper.activated.connect(self.slotPaperChanged)

        layout.addWidget(self.typq)
        layout.addWidget(self.tagl)
        layout.addWidget(self.barnum)
        layout.addWidget(self.neutdir)
        layout.addWidget(self.midi)
        layout.addWidget(self.metro)

        box = QHBoxLayout(spacing=2)
        box.addWidget(self.paperSizeLabel)
        box.addWidget(self.paper)
        box.addWidget(self.paperLandscape)
        layout.addLayout(box)
        app.translateUI(self)

        self.loadSettings()
        self.window().finished.connect(self.saveSettings)

    def translateUI(self):
        self.setTitle(_("General preferences"))
        self.typq.setText(_("Use typographical quotes"))
        self.typq.setToolTip(
            _("Replace normal quotes in titles with nice typographical quotes."
              ))
        self.tagl.setText(_("Remove default tagline"))
        self.tagl.setToolTip(
            _("Suppress the default tagline output by LilyPond."))
        self.barnum.setText(_("Remove bar numbers"))
        self.barnum.setToolTip(
            _("Suppress the display of measure numbers at the beginning of "
              "every system."))
        self.neutdir.setText(_("Smart neutral stem direction"))
        self.neutdir.setToolTip(
            _("Use a logical direction (up or down) for stems on the middle "
              "line of a staff."))
        self.midi.setText(_("Create MIDI output"))
        self.midi.setToolTip(
            _("Create a MIDI file in addition to the PDF file."))
        self.metro.setText(_("Show metronome mark"))
        self.metro.setToolTip(
            _("If checked, show the metronome mark at the beginning of the "
              "score. The MIDI output also uses the metronome setting."))
        # paper size:
        self.paperSizeLabel.setText(_("Paper size:"))
        self.paper.setItemText(0, _("Default"))
        self.paperLandscape.setText(_("Landscape"))

    def slotPaperChanged(self, index):
        self.paperLandscape.setEnabled(bool(index))

    def getPaperSize(self):
        """Returns the configured papersize or the empty string for default."""
        return paperSizes[self.paper.currentIndex()]

    def loadSettings(self):
        s = QSettings()
        s.beginGroup('scorewiz/preferences')
        self.typq.setChecked(s.value('typographical_quotes', True, bool))
        self.tagl.setChecked(s.value('remove_tagline', False, bool))
        self.barnum.setChecked(s.value('remove_barnumbers', False, bool))
        self.neutdir.setChecked(s.value('smart_neutral_direction', False,
                                        bool))
        self.midi.setChecked(s.value('midi', True, bool))
        self.metro.setChecked(s.value('metronome_mark', False, bool))
        psize = s.value('paper_size', '', type(""))
        enable = bool(psize and psize in paperSizes)
        self.paper.setCurrentIndex(paperSizes.index(psize) if enable else 0)
        self.paperLandscape.setChecked(s.value('paper_landscape', False, bool))
        self.paperLandscape.setEnabled(enable)

    def saveSettings(self):
        s = QSettings()
        s.beginGroup('scorewiz/preferences')
        s.setValue('typographical_quotes', self.typq.isChecked())
        s.setValue('remove_tagline', self.tagl.isChecked())
        s.setValue('remove_barnumbers', self.barnum.isChecked())
        s.setValue('smart_neutral_direction', self.neutdir.isChecked())
        s.setValue('midi', self.midi.isChecked())
        s.setValue('metronome_mark', self.metro.isChecked())
        s.setValue('paper_size', paperSizes[self.paper.currentIndex()])
        s.setValue('paper_landscape', self.paperLandscape.isChecked())
Example #54
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()
Example #55
0
class OptionsWidget(QWidget):

    progress = pyqtSignal(int)

    def __init__(self, conf, parent=None):
        QWidget.__init__(self, parent)
        self._conf = conf
        self._projects = []
        for project in self._conf.projects:
            self._projects += [ProjectWidgets(project)]

        gLayout = QGridLayout()
        column = 0
        for iproject in range(len(self._projects)):
            column += self._projects[iproject].addToLayout(column, gLayout)
        toolsGroup = QGroupBox('Projects && Tools')
        toolsGroup.setLayout(gLayout)

        scrollToolsGroup = QScrollArea()
        scrollToolsGroup.setMinimumHeight(350)
        #scrollToolsGroup.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOn )
        scrollToolsGroup.setWidget(toolsGroup)

        self._buildMode = QComboBox()
        self._buildMode.addItems(('Release', 'Debug'))
        #self._svnUpdate   = QCheckBox( 'SVN Update' )
        #self._svnStatus   = QCheckBox( 'SVN Status' )
        self._make = QCheckBox('Build')
        self._enableDoc = QCheckBox('Build Documentation')
        self._devtoolset2 = QCheckBox('Build with devtoolset 2')
        self._qt5 = QCheckBox('Build with Qt 5 (Qt 4 default)')
        self._noCache = QCheckBox('Remove previous CMake cache')
        self._rmBuild = QCheckBox('Cleanup Build Directory')
        self._verbose = QCheckBox('Display Compiler Commands')
        self._threads = QComboBox()
        for j in range(16):
            self._threads.addItem('-j%d' % (j + 1), j + 1)

        self._commandGroup = QButtonGroup()
        self._commandGroup.setExclusive(True)
        #self._commandGroup.addButton( self._svnUpdate )
        #self._commandGroup.addButton( self._svnStatus )
        self._commandGroup.addButton(self._make)

        vLayout = QVBoxLayout()
        #vLayout.addWidget( self._svnUpdate )
        #vLayout.addWidget( self._svnStatus )
        vLayout.addWidget(self._make)
        vLayout.addStretch()
        commandGroup = QGroupBox('Command')
        commandGroup.setLayout(vLayout)

        vLayout = QVBoxLayout()
        vLayout.addWidget(self._buildMode)
        vLayout.addWidget(self._enableDoc)
        vLayout.addWidget(self._devtoolset2)
        vLayout.addWidget(self._qt5)
        vLayout.addWidget(self._noCache)
        vLayout.addWidget(self._rmBuild)
        vLayout.addStretch()
        optionsGroup = QGroupBox('Command Options')
        optionsGroup.setLayout(vLayout)

        vLayout = QVBoxLayout()
        vLayout.addWidget(self._threads)
        vLayout.addWidget(self._verbose)
        vLayout.addStretch()
        miscGroup = QGroupBox('Misc. Options')
        miscGroup.setLayout(vLayout)

        hLayout = QHBoxLayout()
        hLayout.addWidget(commandGroup)
        hLayout.addWidget(optionsGroup)
        hLayout.addWidget(miscGroup)
        commands = QWidget()
        commands.setLayout(hLayout)

        vLayout = QVBoxLayout()
        vLayout.addWidget(commands)
        vLayout.addWidget(scrollToolsGroup)
        vLayout.addStretch()
        self.setLayout(vLayout)

        self.readSettings()
        return

    def _getProjects(self):
        return self._projects

    def _getBuildMode(self):
        return self._buildMode.currentText()

    def _getThreads(self):
        return self._threads.currentText()

    #def _getSvnUpdate   ( self ): return self._svnUpdate.isChecked()
    #def _getSvnStatus   ( self ): return self._svnStatus.isChecked()
    def _getMake(self):
        return self._make.isChecked()

    def _getEnableDoc(self):
        return self._enableDoc.isChecked()

    def _getDevtoolset2(self):
        return self._devtoolset2.isChecked()

    def _getQt5(self):
        return self._qt5.isChecked()

    def _getNoCache(self):
        return self._noCache.isChecked()

    def _getRmBuild(self):
        return self._rmBuild.isChecked()

    def _getVerbose(self):
        return self._verbose.isChecked()

    projects = property(_getProjects)
    buildMode = property(_getBuildMode)
    threads = property(_getThreads)
    #svnUpdate   = property( _getSvnUpdate )
    #svnStatus   = property( _getSvnStatus )
    make = property(_getMake)
    enableDoc = property(_getEnableDoc)
    devtoolset2 = property(_getDevtoolset2)
    qt5 = property(_getQt5)
    noCache = property(_getNoCache)
    rmBuild = property(_getRmBuild)
    verbose = property(_getVerbose)

    def readSettings(self):
        settings = QSettings()
        #self._svnUpdate  .setChecked( settings.value('builder/svnUpdate').toBool() )
        #self._svnStatus  .setChecked( settings.value('builder/svnStatus').toBool() )
        self._make.setChecked(settings.value('builder/make').toBool())
        self._enableDoc.setChecked(
            settings.value('builder/enableDoc').toBool())
        self._devtoolset2.setChecked(
            settings.value('builder/devtoolset2').toBool())
        self._qt5.setChecked(settings.value('builder/qt5').toBool())
        self._noCache.setChecked(settings.value('builder/noCache').toBool())
        self._rmBuild.setChecked(settings.value('builder/rmBuild').toBool())
        self._verbose.setChecked(settings.value('builder/verbose').toBool())

        buildModeName = settings.value('builder/buildMode').toString()
        index = self._buildMode.findText(buildModeName)
        if index >= 0: self._buildMode.setCurrentIndex(index)

        threads = settings.value('builder/threads').toString()
        index = self._threads.findText(threads)
        if index >= 0: self._threads.setCurrentIndex(index)

        for project in self._projects:
            project.readFromSettings()
        return

    def saveSettings(self):
        settings = QSettings()
        #settings.setValue('builder/svnUpdate'  , self._svnUpdate  .isChecked() )
        #settings.setValue('builder/svnStatus'  , self._svnStatus  .isChecked() )
        settings.setValue('builder/make', self._make.isChecked())
        settings.setValue('builder/enableDoc', self._enableDoc.isChecked())
        settings.setValue('builder/devtoolset2', self._devtoolset2.isChecked())
        settings.setValue('builder/qt5', self._qt5.isChecked())
        settings.setValue('builder/buildMode', self._buildMode.currentText())
        settings.setValue('builder/noCache', self._noCache.isChecked())
        settings.setValue('builder/rmBuild', self._rmBuild.isChecked())
        settings.setValue('builder/verbose', self._verbose.isChecked())
        settings.setValue('builder/threads', self._threads.currentText())

        for project in self._projects:
            project.saveToSettings()
        return
Example #56
0
class TreeLayerItem(QTreeWidgetItem):
    layerIcon = QIcon(os.path.join(os.path.dirname(__file__), "icons",
                                   "layer.png"))

    def __init__(self, iface, layer, tree, dlg):
        QTreeWidgetItem.__init__(self)
        self.iface = iface
        self.layer = layer
        self.setText(0, layer.name())
        self.setIcon(0, self.layerIcon)
        project = QgsProject.instance()
        if project.layerTreeRoot().findLayer(layer.id()).isVisible():
            self.setCheckState(0, Qt.Checked)
        else:
            self.setCheckState(0, Qt.Unchecked)
        self.visibleItem = QTreeWidgetItem(self)
        self.visibleCheck = QCheckBox()
        vis = layer.customProperty("qgis2web/Visible", True)
        if (vis == 0 or unicode(vis).lower() == "false"):
            self.visibleCheck.setChecked(False)
        else:
            self.visibleCheck.setChecked(True)
        self.visibleItem.setText(0, "Visible")
        self.addChild(self.visibleItem)
        tree.setItemWidget(self.visibleItem, 1, self.visibleCheck)
        if layer.type() == layer.VectorLayer:
            if layer.providerType() == 'WFS':
                self.jsonItem = QTreeWidgetItem(self)
                self.jsonCheck = QCheckBox()
                if layer.customProperty("qgis2web/Encode to JSON") == 2:
                    self.jsonCheck.setChecked(True)
                self.jsonItem.setText(0, "Encode to JSON")
                self.jsonCheck.stateChanged.connect(self.changeJSON)
                self.addChild(self.jsonItem)
                tree.setItemWidget(self.jsonItem, 1, self.jsonCheck)
            if layer.geometryType() == QGis.Point:
                self.clusterItem = QTreeWidgetItem(self)
                self.clusterCheck = QCheckBox()
                if layer.customProperty("qgis2web/Cluster") == 2:
                    self.clusterCheck.setChecked(True)
                self.clusterItem.setText(0, "Cluster")
                self.clusterCheck.stateChanged.connect(self.changeCluster)
                self.addChild(self.clusterItem)
                tree.setItemWidget(self.clusterItem, 1, self.clusterCheck)
            self.popupItem = QTreeWidgetItem(self)
            self.popupItem.setText(0, "Popup fields")
            options = []
            fields = self.layer.pendingFields()
            for f in fields:
                fieldIndex = fields.indexFromName(unicode(f.name()))
                try:
                    formCnf = layer.editFormConfig()
                    editorWidget = formCnf.widgetType(fieldIndex)
                except:
                    editorWidget = layer.editorWidgetV2(fieldIndex)
                if editorWidget == QgsVectorLayer.Hidden or \
                   editorWidget == 'Hidden':
                    continue
                options.append(f.name())
            for option in options:
                self.attr = QTreeWidgetItem(self)
                self.attrWidget = QComboBox()
                self.attrWidget.addItem("no label")
                self.attrWidget.addItem("inline label")
                self.attrWidget.addItem("header label")
                custProp = layer.customProperty("qgis2web/popup/" + option)
                if (custProp != "" and custProp is not None):
                    self.attrWidget.setCurrentIndex(
                        self.attrWidget.findText(
                            layer.customProperty("qgis2web/popup/" + option)))
                self.attr.setText(1, option)
                self.popupItem.addChild(self.attr)
                tree.setItemWidget(self.attr, 2, self.attrWidget)
            self.addChild(self.popupItem)

    @property
    def popup(self):
        popup = []
        self.tree = self.treeWidget()
        for p in xrange(self.childCount()):
            item = self.child(p).text(1)
            if item != "":
                popupVal = self.tree.itemWidget(self.child(p), 2).currentText()
                pair = (item, popupVal)
                popup.append(pair)
        popup = OrderedDict(popup)
        return popup

    @property
    def visible(self):
        return self.visibleCheck.isChecked()

    @property
    def json(self):
        try:
            return self.jsonCheck.isChecked()
        except:
            return False

    @property
    def cluster(self):
        try:
            return self.clusterCheck.isChecked()
        except:
            return False

    def changeJSON(self, isJSON):
        self.layer.setCustomProperty("qgis2web/Encode to JSON", isJSON)

    def changeCluster(self, isCluster):
        self.layer.setCustomProperty("qgis2web/Cluster", isCluster)
Example #57
0
    def __init__(self, conf, parent=None):
        QWidget.__init__(self, parent)
        self._conf = conf
        self._projects = []
        for project in self._conf.projects:
            self._projects += [ProjectWidgets(project)]

        gLayout = QGridLayout()
        column = 0
        for iproject in range(len(self._projects)):
            column += self._projects[iproject].addToLayout(column, gLayout)
        toolsGroup = QGroupBox('Projects && Tools')
        toolsGroup.setLayout(gLayout)

        scrollToolsGroup = QScrollArea()
        scrollToolsGroup.setMinimumHeight(350)
        #scrollToolsGroup.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOn )
        scrollToolsGroup.setWidget(toolsGroup)

        self._buildMode = QComboBox()
        self._buildMode.addItems(('Release', 'Debug'))
        #self._svnUpdate   = QCheckBox( 'SVN Update' )
        #self._svnStatus   = QCheckBox( 'SVN Status' )
        self._make = QCheckBox('Build')
        self._enableDoc = QCheckBox('Build Documentation')
        self._devtoolset2 = QCheckBox('Build with devtoolset 2')
        self._qt5 = QCheckBox('Build with Qt 5 (Qt 4 default)')
        self._noCache = QCheckBox('Remove previous CMake cache')
        self._rmBuild = QCheckBox('Cleanup Build Directory')
        self._verbose = QCheckBox('Display Compiler Commands')
        self._threads = QComboBox()
        for j in range(16):
            self._threads.addItem('-j%d' % (j + 1), j + 1)

        self._commandGroup = QButtonGroup()
        self._commandGroup.setExclusive(True)
        #self._commandGroup.addButton( self._svnUpdate )
        #self._commandGroup.addButton( self._svnStatus )
        self._commandGroup.addButton(self._make)

        vLayout = QVBoxLayout()
        #vLayout.addWidget( self._svnUpdate )
        #vLayout.addWidget( self._svnStatus )
        vLayout.addWidget(self._make)
        vLayout.addStretch()
        commandGroup = QGroupBox('Command')
        commandGroup.setLayout(vLayout)

        vLayout = QVBoxLayout()
        vLayout.addWidget(self._buildMode)
        vLayout.addWidget(self._enableDoc)
        vLayout.addWidget(self._devtoolset2)
        vLayout.addWidget(self._qt5)
        vLayout.addWidget(self._noCache)
        vLayout.addWidget(self._rmBuild)
        vLayout.addStretch()
        optionsGroup = QGroupBox('Command Options')
        optionsGroup.setLayout(vLayout)

        vLayout = QVBoxLayout()
        vLayout.addWidget(self._threads)
        vLayout.addWidget(self._verbose)
        vLayout.addStretch()
        miscGroup = QGroupBox('Misc. Options')
        miscGroup.setLayout(vLayout)

        hLayout = QHBoxLayout()
        hLayout.addWidget(commandGroup)
        hLayout.addWidget(optionsGroup)
        hLayout.addWidget(miscGroup)
        commands = QWidget()
        commands.setLayout(hLayout)

        vLayout = QVBoxLayout()
        vLayout.addWidget(commands)
        vLayout.addWidget(scrollToolsGroup)
        vLayout.addStretch()
        self.setLayout(vLayout)

        self.readSettings()
        return
Example #58
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)
Example #59
0
class FindInFilesDialog(QDialog):
    """Dialog to configure and trigger the search in the files."""
    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"),
                                       translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(
            QCompleter([
                "*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS
            ]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(translations.TR_TEXT_FOR_REPLACE +
                                             "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(
            self, translations.TR_OPEN, self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
Example #60
0
    def getWidgetFromParameter(self, param):
        # TODO Create Parameter widget class that holds the logic
        # for creating a widget that belongs to the parameter.
        if isinstance(param, ParameterRaster):
            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterVector):
            if self.somethingDependsOnThisParameter(
                    param) or self.alg.allowOnlyOpenedLayers:
                item = QComboBox()
                layers = dataobjects.getVectorLayers(param.shapetype)
                layers.sort(key=lambda lay: lay.name())
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(self.getExtendedLayerName(layer), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getVectorLayers(param.shapetype)
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((self.getExtendedLayerName(layer), layer))
                # if already set, put first in list
                for i, (name, layer) in enumerate(items):
                    if layer and layer.source() == param.value:
                        items.insert(0, items.pop(i))
                item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterTable):
            if self.somethingDependsOnThisParameter(param):
                item = QComboBox()
                layers = dataobjects.getTables()
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(layer.name(), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getTables()
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((layer.name(), layer))
                # if already set, put first in list
                for i, (name, layer) in enumerate(items):
                    if layer and layer.source() == param.value:
                        items.insert(0, items.pop(i))
                item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterBoolean):
            item = QCheckBox()
            if param.default:
                item.setChecked(True)
            else:
                item.setChecked(False)
        elif isinstance(param, ParameterTableField):
            item = QComboBox()
            if param.parent in self.dependentItems:
                items = self.dependentItems[param.parent]
            else:
                items = []
                self.dependentItems[param.parent] = items
            items.append(param.name)
            parent = self.alg.getParameterFromName(param.parent)
            if isinstance(parent, ParameterVector):
                layers = dataobjects.getVectorLayers(parent.shapetype)
            else:
                layers = dataobjects.getTables()
            if len(layers) > 0:
                if param.optional:
                    item.addItem(self.tr('[not set]'))
                item.addItems(self.getFields(layers[0], param.datatype))
        elif isinstance(param, ParameterSelection):
            item = QComboBox()
            item.addItems(param.options)
            if param.default:
                item.setCurrentIndex(param.default)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterFile):
            item = FileSelectionPanel(param.isFolder, param.ext)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_FILE:
                item = MultipleInputPanel(
                    datatype=ParameterMultipleInput.TYPE_FILE)
            else:
                if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                    options = dataobjects.getRasterLayers(sorting=False)
                elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                    options = dataobjects.getVectorLayers(sorting=False)
                else:
                    options = dataobjects.getVectorLayers([param.datatype],
                                                          sorting=False)
                opts = [self.getExtendedLayerName(opt) for opt in options]
                item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterNumber):
            item = NumberInputPanel(param.default, param.min, param.max,
                                    param.isInteger)
        elif isinstance(param, ParameterExtent):
            item = ExtentSelectionPanel(self.parent, self.alg, param.default)
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterString):
            if param.multiline:
                verticalLayout = QVBoxLayout()
                verticalLayout.setSizeConstraint(QLayout.SetDefaultConstraint)
                textEdit = QPlainTextEdit()
                if param.default:
                    textEdit.setPlainText(param.default)
                verticalLayout.addWidget(textEdit)
                item = textEdit
            else:
                item = QLineEdit()
                if param.default:
                    item.setText(unicode(param.default))
        elif isinstance(param, ParameterGeometryPredicate):
            item = GeometryPredicateSelectionPanel(param.enabledPredicates)
            if param.left:
                widget = self.valueItems[param.left]
                if isinstance(widget, InputLayerSelectorPanel):
                    widget = widget.cmbText
                widget.currentIndexChanged.connect(item.onLeftLayerChange)
                item.leftLayer = widget.itemData(widget.currentIndex())
            if param.right:
                widget = self.valueItems[param.right]
                if isinstance(widget, InputLayerSelectorPanel):
                    widget = widget.cmbText
                widget.currentIndexChanged.connect(item.onRightLayerChange)
                item.rightLayer = widget.itemData(widget.currentIndex())
            item.updatePredicates()
            if param.default:
                item.setValue(param.default)
        else:
            item = QLineEdit()
            if param.default:
                item.setText(unicode(param.default))

        return item