def createEditor( self, parent, option, index ):
     if index.column() == CANTIDAD:
         spinbox = QSpinBox( parent )
         spinbox.setRange( 0, index.model().lines[index.row()].maxquantity )
         spinbox.setSingleStep( 1 )
         return spinbox
     else:
         QStyledItemDelegate.createEditor( self, parent, option, index )
    def createEditor( self, parent, option, index ):
        if index.column() == CANTIDAD:
            max_items = index.model().lines[index.row()].existencia
            if max_items < 1 :
                return None
            spinbox = QSpinBox( parent )
            spinbox.setRange( 0, max_items )
            spinbox.setSingleStep( 1 )
            spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter )
            return spinbox
        elif index.column() == DESCRIPCION :
            if self.articles.rowCount() > 0:
                self.proxymodel.setSourceModel( self.articles )
                model = index.model()

                current = model.index( index.row(), IDARTICULOEX ).data()
                self.proxymodel.setFilterRegExp( self.filter( model , current ) )
                sp = super( FacturaDelegate, self ).createEditor( parent, option, index )
                #sp.setColumnHidden( IDBODEGAEX )
                #sp.setColumnHidden( IDARTICULOEX )
                return sp
        elif index.column() == TOTALPROD:
            return None
        elif index.column() == PRECIO:
            spinbox = QDoubleSpinBox( parent )
            spinbox.setRange( 0.0001, 10000 )
            spinbox.setDecimals( 4 )
            spinbox.setSingleStep( 1 )
            spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter )
            return spinbox
        else:
            super( FacturaDelegate, self ).createEditor( parent, option, index )
Beispiel #3
0
 def _populateFormCB(self, config):
     cfg = json.loads(config)
     cfg = Helpers.makeDictKeysInt(cfg)
     if 'Inputsignals' not in cfg:
         pass
     else:
         signalsin = cfg['Inputsignals']
         it = {}
         for k, item in signalsin.iteritems():
             it[item['name']] = k
         self.addComboBox('InputSignal', 'input signal', it)
         self.addLineEdit('Duration', 'Duration of one run in milliseconds')
         self.settings['Duration'].setText(str(100))
         spin = QSpinBox()
         spin.setRange(2**8, 2**16)
         spin.setSingleStep(2**8)
         spin.setValue(2**11)
         self.addSetting('Samples', 'Number of bytes to be read.', spin)
         sampling = QLabel()
         sampling.setText(str(2**11 / 100.0) + ' kS/s')
         self.addSetting('Sampling', 'Resulting sampling rate', sampling)
         self.addCheckBox('Loop', 'Run infinitely')
         self.settings['Loop'].setChecked(True)
         spin.valueChanged.connect(self.spinValueChangedCB)
         self.settings['Duration'].textChanged.connect(
             self.durationValueChangedCB)
Beispiel #4
0
 def createEditor(
     self,
     parent,
     options,
     index,
 ):
     setting = index.model().data(index, Qt.UserRole)
     if setting.valuetype == Setting.FOLDER:
         return FileDirectorySelector(parent)
     elif setting.valuetype == Setting.FILE:
         return FileDirectorySelector(parent, True)
     elif setting.valuetype == Setting.SELECTION:
         combo = QComboBox(parent)
         combo.addItems(setting.options)
         return combo
     else:
         value = self.convertValue(index.model().data(index, Qt.EditRole))
         if isinstance(value, (int, long)):
             spnBox = QSpinBox(parent)
             spnBox.setRange(-999999999, 999999999)
             return spnBox
         elif isinstance(value, float):
             spnBox = QDoubleSpinBox(parent)
             spnBox.setRange(-999999999.999999, 999999999.999999)
             spnBox.setDecimals(6)
             return spnBox
         elif isinstance(value, (str, unicode)):
             return QLineEdit(parent)
Beispiel #5
0
 def createEditor(self, parent, option, index):
     if index.column() == TEU:
         spinbox = QSpinBox(parent)
         spinbox.setRange(0, 200000)
         spinbox.setSingleStep(1000)
         spinbox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
         return spinbox
     elif index.column() == OWNER:
         combobox = QComboBox(parent)
         combobox.addItems(sorted(index.model().owners))
         combobox.setEditable(True)
         return combobox
     elif index.column() == COUNTRY:
         combobox = QComboBox(parent)
         combobox.addItems(sorted(index.model().countries))
         combobox.setEditable(True)
         return combobox
     elif index.column() == NAME:
         editor = QLineEdit(parent)
         self.connect(editor, SIGNAL("returnPressed()"),
                      self.commitAndCloseEditor)
         return editor
     elif index.column() == DESCRIPTION:
         editor = richtextlineedit.RichTextLineEdit(parent)
         self.connect(editor, SIGNAL("returnPressed()"),
                      self.commitAndCloseEditor)
         return editor
     else:
         return QStyledItemDelegate.createEditor(self, parent, option,
                                                 index)
Beispiel #6
0
class ResizeDlg(QDialog):
    def __init__(self, width, height, parent=None):
        super(ResizeDlg, self).__init__(parent)

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

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

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

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

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

    def result(self):
        return self.widthSpinBox.value(), self.heightSpinBox.value()
Beispiel #7
0
 def createEditor(
     self,
     parent,
     options,
     index,
 ):
     setting = index.model().data(index, Qt.UserRole)
     if setting.valuetype == Setting.FOLDER:
         return FileDirectorySelector(parent)
     elif setting.valuetype == Setting.FILE:
         return FileDirectorySelector(parent, True)
     elif setting.valuetype == Setting.SELECTION:
         combo = QComboBox(parent)
         combo.addItems(setting.options)
         return combo
     else:
         value = self.convertValue(index.model().data(index, Qt.EditRole))
         if isinstance(value, (int, long)):
             spnBox = QSpinBox(parent)
             spnBox.setRange(-999999999, 999999999)
             return spnBox
         elif isinstance(value, float):
             spnBox = QDoubleSpinBox(parent)
             spnBox.setRange(-999999999.999999, 999999999.999999)
             spnBox.setDecimals(6)
             return spnBox
         elif isinstance(value, (str, unicode)):
             return QLineEdit(parent)
Beispiel #8
0
 def createEditor(self, parent, option, index):
     if index.column() == TEU:
         spinbox = QSpinBox(parent)
         spinbox.setRange(0, 200000)
         spinbox.setSingleStep(1000)
         spinbox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
         return spinbox
     elif index.column() == OWNER:
         combobox = QComboBox(parent)
         combobox.addItems(sorted(index.model().owners))
         combobox.setEditable(True)
         return combobox
     elif index.column() == COUNTRY:
         combobox = QComboBox(parent)
         combobox.addItems(sorted(index.model().countries))
         combobox.setEditable(True)
         return combobox
     elif index.column() == NAME:
         editor = QLineEdit(parent)
         editor.returnPressed.connect(self.commitAndCloseEditor)
         return editor
     elif index.column() == DESCRIPTION:
         editor = richtextlineedit.RichTextLineEdit(parent)
         editor.returnPressed.connect(self.commitAndCloseEditor)
         return editor
     else:
         return QStyledItemDelegate.createEditor(self, parent, option,
                                                 index)
    def createEditor( self, parent, option, index ):
        if index.column() == CANTIDAD:
            spinbox = QSpinBox( parent )
            spinbox.setRange( 1, 1000 )
            spinbox.setSingleStep( 1 )
            spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter )
            return spinbox
        elif index .column() == COSTOUNIT:
            spinbox = QDoubleSpinBox( parent )
            spinbox.setRange( 0.0001, 100000 )
            spinbox.setDecimals( 4 )
            spinbox.setSingleStep( 1 )
            spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter )
            return spinbox
        elif index.column() in ( IDARTICULO, ARTICULO ):

            self.proxymodel.setSourceModel( self.prods )
            current = index.model().data( index.model().index( index.row(), IDARTICULO ) )
            self.proxymodel.setFilterRegExp( self.filter( index.model(), current ) )

            sp = super( LiquidacionDelegate, self ).createEditor( parent, option, index )
            sp.setColumnHidden( IDARTICULO )
            sp.setMinimumWidth( 600 )
            return sp

        else:
            super( LiquidacionDelegate, self ).createEditor( parent, option, index )
Beispiel #10
0
    def __get_widget_for_primitive_types(self, key, value):

        """
        return right widget and connect the value with config_manager
        :param key:
        :param value:
        :return:
        """

        if key in self.dropdownboxes.keys():
            atomic_widget = self._create_dropdownbox(key,value)
            self.config.add_handler(key, atomic_widget)
        elif key in self.radiobuttons.keys():
            atomic_widget = self._create_radiobutton(key,value)
            self.config.add_handler(key, atomic_widget)
        elif type(value) is int:
            atomic_widget = QSpinBox()
            atomic_widget.setRange(-100000, 100000)
            self.config.add_handler(key, atomic_widget)
        elif type(value) is float:
            atomic_widget = QDoubleSpinBox()
            atomic_widget.setDecimals(6)
            atomic_widget.setMaximum(1000000000)
            self.config.add_handler(key, atomic_widget)
        elif type(value) is str:
            atomic_widget = QLineEdit()
            self.config.add_handler(key, atomic_widget)
        elif type(value) is bool:
            atomic_widget = QCheckBox()
            self.config.add_handler(key, atomic_widget)
        else:
            return None
        return atomic_widget
    def createEditor( self, parent, option, index ):
        """
        Aca se crean los widgets para edición
        """
        if index.column() == CANTIDAD:
            spinbox = QSpinBox( parent )
            spinbox.setRange( 1, 1000 )
            spinbox.setSingleStep( 1 )
            spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter )
            return spinbox
        elif index.column() == DESCRIPCION :
#            if index.data() != "":
#                self.prods.items.append( [ index.model().data( index.model().index( index.row(), 0 ) ) , index.data().toString()] )
            self.proxymodel.setSourceModel( self.prods )
            model = index.model()

            current = model.index( index.row(), IDARTICULO ).data()

            self.proxymodel.setFilterRegExp( self.filter( model, current ) )

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

        elif index.column() == TOTALPROD:
            return None

        elif index.column() in ( PRECIO, PRECIOD ):
            spinbox = QDoubleSpinBox( parent )
            spinbox.setRange( 0, 10000 )
            spinbox.setDecimals( 4 )
            spinbox.setSingleStep( 1 )
            spinbox.setAlignment( Qt.AlignRight | Qt.AlignVCenter )
            return spinbox
        else:
            return super( EntradaCompraDelegate, self ).createEditor( parent, option, index )
Beispiel #12
0
class Prefs(preferences.Group):
    def __init__(self, page):
        super(Prefs, self).__init__(page)

        self._closeOutputs = QCheckBox(clicked=self.changed)
        self._pollingLabel = QLabel()
        self._pollingTime = QSpinBox()
        self._pollingTime.setRange(0, 1000)
        self._pollingTime.setSuffix(" ms")
        self._pollingTime.valueChanged.connect(self.changed)

        layout = QVBoxLayout()
        self.setLayout(layout)

        layout.addWidget(self._closeOutputs)
        app.translateUI(self)

        hbox = QHBoxLayout()
        layout.addLayout(hbox)

        hbox.addWidget(self._pollingLabel)
        hbox.addWidget(self._pollingTime)

    def translateUI(self):
        self.setTitle(_("Preferences"))
        self._closeOutputs.setText(_("Close unused MIDI output"))
        self._closeOutputs.setToolTip(
            _("Closes unused MIDI ports after one minute. " 'See "What\'s This" for more information.')
        )
        self._closeOutputs.setWhatsThis(
            _(
                "<p>If checked, Frescobaldi will close MIDI output ports that are not "
                "used for one minute.</p>\n"
                "<p>This could free up system resources that a software MIDI synthesizer "
                "might be using, thus saving battery power.</p>\n"
                "<p>A side effect is that if you pause a MIDI file for a long time "
                "the instruments are reset to the default piano (instrument 0). "
                "In that case, playing the file from the beginning sets up the "
                "instruments again.</p>\n"
            )
        )
        self._pollingLabel.setText(_("Polling time for input:"))
        self._pollingTime.setToolTip(_("Polling time for MIDI input. " 'See "What\'s This" for more information.'))
        self._pollingTime.setWhatsThis(
            _(
                "Sets the time between the polling of the MIDI input port in milliseconds. "
                "Small values lead to faster recognition of incoming MIDI events, but stress "
                "the CPU. 10 ms should be a good value."
            )
        )

    def loadSettings(self):
        s = QSettings()
        self._closeOutputs.setChecked(s.value("midi/close_outputs", False, bool))
        self._pollingTime.setValue(s.value("midi/polling_time", 10, int))

    def saveSettings(self):
        s = QSettings()
        s.setValue("midi/close_outputs", self._closeOutputs.isChecked())
        s.setValue("midi/polling_time", self._pollingTime.value())
Beispiel #13
0
    def createEditor(self, parent, option, index):
        if index.column() == CANTIDAD:
            spinbox = QSpinBox(parent)
            spinbox.setRange(0, 1000)
            spinbox.setSingleStep(1)
            return spinbox
        elif index.column() == DENOMINACION:

            model = index.model()

            self.proxymodel.setSourceModel(self.denominationsmodel)

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

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

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

            return sp

        else:
            return super(ArqueoDelegate, self).createEditor(parent, option, index)
        def changeTileWidth():
            '''Change tile width (tile block size) and reset image-scene'''
            dlg = QDialog(self)
            dlg.setWindowTitle("Viewer Tile Width")
            dlg.setModal(True)
            
            spinBox = QSpinBox( parent=dlg )
            spinBox.setRange( 128, 10*1024 )
            spinBox.setValue( self.editor.imageScenes[0].tileWidth() )
                
            ctrl_layout = QHBoxLayout()
            ctrl_layout.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding))
            ctrl_layout.addWidget( QLabel("Tile Width:") )
            ctrl_layout.addWidget( spinBox )

            button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, parent=dlg)
            button_box.accepted.connect( dlg.accept )
            button_box.rejected.connect( dlg.reject )
            
            dlg_layout = QVBoxLayout()
            dlg_layout.addLayout( ctrl_layout )
            dlg_layout.addWidget( QLabel("Setting will apply current view immediately,\n"
                                         "and all other views upon restart.") )
            dlg_layout.addWidget( button_box )

            dlg.setLayout( dlg_layout )
            
            if dlg.exec_() == QDialog.Accepted:
                for s in self.editor.imageScenes:
                    if s.tileWidth != spinBox.value():
                        s.setTileWidth( spinBox.value() )
                        s.reset()
Beispiel #15
0
        def changeTileWidth():
            '''Change tile width (tile block size) and reset image-scene'''
            dlg = QDialog(self)
            layout = QHBoxLayout()
            layout.addWidget(QLabel("Tile Width:"))

            spinBox = QSpinBox(parent=dlg)
            spinBox.setRange(128, 10 * 1024)
            spinBox.setValue(512)

            if self.editor.imageScenes[0].tileWidth:
                spinBox.setValue(self.editor.imageScenes[0].tileWidth)

            layout.addWidget(spinBox)
            okButton = QPushButton("OK", parent=dlg)
            okButton.clicked.connect(dlg.accept)
            layout.addWidget(okButton)
            dlg.setLayout(layout)
            dlg.setModal(True)

            if dlg.exec_() == QDialog.Accepted:
                for s in self.editor.imageScenes:
                    if s.tileWidth != spinBox.value():
                        s.tileWidth = spinBox.value()
                        s.reset()
Beispiel #16
0
    def __init__(self, parent=None):
        super(Options, self).__init__(parent)
        self.setWindowIcon(QIcon('res/opciones4.png'))
        self.setWindowTitle('Opciones')

        self.options = load_data()['options']

        self.chk_mask = QCheckBox(u'Máscara por defecto.')
        self.line_mask = LineEdit(u'máscara', ['required', 'ms'])
        self.line_mask.focusInEvent = lambda _: self.block_focus_event()

        if self.options[0]:
            self.chk_mask.setChecked(True)
            self.line_mask.setText(self.options[1])

        self.chk_dns = QCheckBox('Servidor dns por defecto.')
        self.line_dns = LineEdit('Servidor dns', ['required', 'ip'])
        self.line_dns.focusInEvent = lambda _: self.block_focus_event()
        self.line_mask.setCursor(QCursor(Qt.ForbiddenCursor))

        if self.options[2]:
            self.chk_dns.setChecked(True)
            self.line_dns.setText(self.options[3])

        self.status(self.chk_mask.isChecked(), self.line_mask)
        self.status(self.chk_dns.isChecked(), self.line_dns)

        lbl = QLabel('Cantidad de Configuraciones permitidas.')
        spin = QSpinBox()
        spin.setRange(1, 8)
        spin.setValue(self.options[4])
        spin.setMaximumWidth(50)
        lbl.setBuddy(spin)

        btn_ok = QPushButton('OK')
        btn_ok.setMaximumWidth(200)
        btn_ok.setObjectName('btn_ok')

        btn_cancel = QPushButton('Cancel')
        btn_cancel.setMaximumWidth(200)
        btn_cancel.setObjectName('btn_cancel')

        layout = QGridLayout()
        layout.addWidget(self.chk_mask, 0, 0, 1, 3)
        layout.addWidget(self.line_mask, 1, 0, 1, 3)
        layout.addWidget(self.chk_dns, 2, 0, 1, 3)
        layout.addWidget(self.line_dns, 3, 0, 1, 3)
        layout.addWidget(lbl, 4, 0)
        layout.addWidget(spin, 4, 1)
        layout.addWidget(QLabel(''), 5, 0)
        layout.addWidget(btn_cancel, 6, 1)
        layout.addWidget(btn_ok, 6, 2)
        self.setLayout(layout)

        self.connect(self.chk_mask, SIGNAL('clicked(bool)'), self.set_disable_mask)
        self.connect(self.chk_dns, SIGNAL('clicked(bool)'), self.set_disable_dns)
        self.connect(btn_ok, SIGNAL('clicked()'), self.save_and_exit)
        self.connect(btn_ok, SIGNAL('returnPressed()'), self.save_and_exit)
        self.connect(spin, SIGNAL('valueChanged(int)'), self.spin_value)
        self.connect(btn_cancel, SIGNAL("clicked()"), self.reject)
Beispiel #17
0
    def createEditor(self, parent, option, index):
        if index.column() == CANTIDAD:
            max_items = index.model().lines[index.row()].existencia
            if max_items < 1:
                return None
            spinbox = QSpinBox(parent)
            spinbox.setRange(1, max_items)
            spinbox.setSingleStep(1)
            spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            return spinbox
        elif index.column() == DESCRIPCION:
            if self.articles.rowCount() > 0:
                self.proxymodel.setSourceModel(self.articles)
                model = index.model()

                current = model.index(index.row(), IDARTICULOEX).data()
                self.proxymodel.setFilterRegExp(self.filter(model, current))
                sp = super(FacturaDelegate, self).createEditor(parent, option, index)
                # sp.setColumnHidden( IDBODEGAEX )
                # sp.setColumnHidden( IDARTICULOEX )
                return sp
        elif index.column() == TOTALPROD:
            return None
        elif index.column() == PRECIO:
            spinbox = QDoubleSpinBox(parent)
            spinbox.setRange(0.0001, 10000)
            spinbox.setDecimals(4)
            spinbox.setSingleStep(1)
            spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            return spinbox
        else:
            super(FacturaDelegate, self).createEditor(parent, option, index)
Beispiel #18
0
class IntegerProperty(Property, QWidget):
    """ Property which hold editable integer numbers.
    
    A Spinbox is provided when the property is editable.
    """

    USER_INFO = "Integer field"

    def __init__(self, name, value, categoryName=None):
        """ Constructor
        """
        Property.__init__(self, name, categoryName)
        QWidget.__init__(self)
        self.setLayout(QHBoxLayout())
        self.layout().setSpacing(0)
        self.layout().setContentsMargins(0, 0, 0, 0)

        self._spinbox = QSpinBox()
        #self.maxint = sys.maxint     # does not work on Mac OS X (Snow Leopard 10.6.2), confusion between 32 and 64 bit limits
        self.maxint = 2**31
        self._spinbox.setRange(-self.maxint + 1, self.maxint - 1)
        self._spinbox.setFrame(False)
        self.layout().addWidget(self._spinbox)
        self.setFocusProxy(self._spinbox)
        self._lineedit = QLineEdit()
        self._lineedit.setReadOnly(True)
        self._lineedit.setFrame(False)
        self._lineedit.setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self._lineedit)
        self._lineedit.hide()

        self.setValue(value)
        self.connect(self._spinbox, SIGNAL('valueChanged(int)'),
                     self.valueChanged)

    def setReadOnly(self, readOnly):
        """ Switches between lineedit and spinbox.
        """
        if readOnly:
            self._spinbox.hide()
            self._lineedit.show()
            self.setFocusProxy(self._lineedit)
        else:
            self._spinbox.show()
            self._lineedit.hide()
            self.setFocusProxy(self._spinbox)

    def value(self):
        """ Returns integer value.
        """
        return self._spinbox.value()

    def setValue(self, value):
        self.disconnect(self._spinbox, SIGNAL('valueChanged(int)'),
                        self.valueChanged)
        self._spinbox.setValue(value % self.maxint)
        self.connect(self._spinbox, SIGNAL('valueChanged(int)'),
                     self.valueChanged)
        self._lineedit.setText(str(value))
Beispiel #19
0
 def createEditor(self, parent, option, index):
     if index.column() == NUMAJUSTE:
         spinbox = QSpinBox(parent)
         spinbox.setRange(-1000, 1000)
         spinbox.setSingleStep(1)
         return spinbox
     else:
         QStyledItemDelegate.createEditor(self, parent, option, index)
Beispiel #20
0
 def int_widget(self, start_val, min_val=-100, max_val=100, step=1):
     """ Returns an int widget with the given values.
     """
     box = QSpinBox()
     box.setRange(min_val, max_val)
     box.setValue(start_val)
     box.setSingleStep(step)
     return box
class ProjectData(QWidget):

    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0)
        self.name = QLineEdit()
        if not len(self._parent.project.name):
            self.name.setText(file_manager.get_basename(
                self._parent.project.path))
        else:
            self.name.setText(self._parent.project.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0)
        self.txtPath = QLineEdit()
        self.txtPath.setReadOnly(True)
        self.txtPath.setText(self._parent.project.path)
        grid.addWidget(self.txtPath, 1, 1)
        grid.addWidget(QLabel(translations.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.project.project_type)
        grid.addWidget(self.txtType, 2, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent.project.description)
        grid.addWidget(self.description, 3, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent.project.url)
        self.url.setPlaceholderText('https://www.{}.com'.format(getuser()))
        grid.addWidget(self.url, 4, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItems(LICENCES)
        self.cboLicense.setCurrentIndex(12)
        index = self.cboLicense.findText(self._parent.project.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 5, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent.project.extensions))
        grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0)
        grid.addWidget(self.txtExtensions, 6, 1)

        grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent.project.indentation)
        self.spinIndentation.setRange(2, 10)
        self.spinIndentation.setValue(4)
        self.spinIndentation.setSingleStep(2)
        grid.addWidget(self.spinIndentation, 7, 1)
        self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS)
        self.checkUseTabs.setChecked(self._parent.project.use_tabs)
        grid.addWidget(self.checkUseTabs, 7, 2)
 def __init__(self, reaction, window):
     super(BalanceWindow, self).__init__()
     self.setWindowTitle("Balance Equation")
     self._grid = QGridLayout()
     self._numbermenus = []
     self._reactants = []
     self._products = []
     self._boxes = []
     self._formulae = []
     self._symbols = []
     self._themainwindow = window
     # Ensures only valid reactants and products are used
     for x in range(Reaction.REACTING_SPECIES_LIMIT):
         species = reaction.GetReactants()[x]
         if species.GetUsed():
             self._reactants.append(species)
         species = reaction.GetProducts()[x]
         if species.GetUsed():
             self._products.append(species)
     for x in range(len(self._reactants)):
         box = QSpinBox()
         box.setRange(1, 9)
         box.valueChanged.connect(self.update)
         self._boxes.append(box)
         formula = ""
         if self._reactants[x].GetSRatio() > 1:
             formula = self._reactants[x].GetFormulaForLabels()[1:]
         else:
             formula = self._reactants[x].GetFormulaForLabels()
         self._formulae.append(formula)
         self._symbols.append(QLabel())
     for x in range(len(self._products)):
         box = QSpinBox()
         box.setRange(1, 9)
         box.valueChanged.connect(self.update)
         self._boxes.append(box)
         formula = ""
         if self._products[x].GetSRatio() > 1:
             formula = self._products[x].GetFormulaForLabels()[1:]
         else:
             formula = self._products[x].GetFormulaForLabels()
         self._formulae.append(formula)
         self._symbols.append(QLabel())
     for x in range(len(self._reactants)):
         self._grid.addWidget(self._boxes[x], x, 0)
         self._grid.addWidget(QLabel(self._formulae[x]), x, 1)
         self._grid.addWidget(self._symbols[x], x, 2)
     arrows = QLabel()
     arrows.setPixmap(QPixmap("assets/double arrow v.png"))
     self._grid.addWidget(arrows, len(self._reactants), 1)
     for x in range(len(self._products)):
         self._grid.addWidget(self._boxes[x + len(self._reactants)], x + 1 + len(self._reactants), 0)
         self._grid.addWidget(QLabel(self._formulae[x + len(self._reactants)]), x + 1 + len(self._reactants), 1)
         self._grid.addWidget(self._symbols[x + len(self._reactants)], x + 1 + len(self._reactants), 2)
     self._okbtn = QPushButton("OK")
     self._okbtn.clicked.connect(self.close)
     self._grid.addWidget(self._okbtn, len(self._reactants)+len(self._products)+2, 1)
     self.setLayout(self._grid)
Beispiel #23
0
class Prefs(preferences.Group):
    def __init__(self, page):
        super(Prefs, self).__init__(page)

        self._closeOutputs = QCheckBox(clicked=self.changed)
        self._pollingLabel = QLabel()
        self._pollingTime = QSpinBox()
        self._pollingTime.setRange(0, 1000)
        self._pollingTime.setSuffix(" ms")
        self._pollingTime.valueChanged.connect(self.changed)

        layout = QVBoxLayout()
        self.setLayout(layout)

        layout.addWidget(self._closeOutputs)
        app.translateUI(self)

        hbox = QHBoxLayout()
        layout.addLayout(hbox)

        hbox.addWidget(self._pollingLabel)
        hbox.addWidget(self._pollingTime)

    def translateUI(self):
        self.setTitle(_("Preferences"))
        self._closeOutputs.setText(_("Close unused MIDI output"))
        self._closeOutputs.setToolTip(
            _("Closes unused MIDI ports after one minute. "
              "See \"What's This\" for more information."))
        self._closeOutputs.setWhatsThis(
            _("<p>If checked, Frescobaldi will close MIDI output ports that are not "
              "used for one minute.</p>\n"
              "<p>This could free up system resources that a software MIDI synthesizer "
              "might be using, thus saving battery power.</p>\n"
              "<p>A side effect is that if you pause a MIDI file for a long time "
              "the instruments are reset to the default piano (instrument 0). "
              "In that case, playing the file from the beginning sets up the "
              "instruments again.</p>\n"))
        self._pollingLabel.setText(_("Polling time for input:"))
        self._pollingTime.setToolTip(
            _("Polling time for MIDI input. "
              "See \"What's This\" for more information."))
        self._pollingTime.setWhatsThis(
            _("Sets the time between the polling of the MIDI input port in milliseconds. "
              "Small values lead to faster recognition of incoming MIDI events, but stress "
              "the CPU. 10 ms should be a good value."))

    def loadSettings(self):
        s = QSettings()
        self._closeOutputs.setChecked(
            s.value("midi/close_outputs", False, bool))
        self._pollingTime.setValue(s.value("midi/polling_time", 10, int))

    def saveSettings(self):
        s = QSettings()
        s.setValue("midi/close_outputs", self._closeOutputs.isChecked())
        s.setValue("midi/polling_time", self._pollingTime.value())
Beispiel #24
0
class ProjectData(QWidget):
    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0)
        self.name = QLineEdit()
        if not len(self._parent.project.name):
            self.name.setText(
                file_manager.get_basename(self._parent.project.path))
        else:
            self.name.setText(self._parent.project.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0)
        self.txtPath = QLineEdit()
        self.txtPath.setReadOnly(True)
        self.txtPath.setText(self._parent.project.path)
        grid.addWidget(self.txtPath, 1, 1)
        grid.addWidget(QLabel(translations.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.project.project_type)
        grid.addWidget(self.txtType, 2, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent.project.description)
        grid.addWidget(self.description, 3, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent.project.url)
        self.url.setPlaceholderText('https://www.{}.com'.format(getuser()))
        grid.addWidget(self.url, 4, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItems(LICENCES)
        self.cboLicense.setCurrentIndex(12)
        index = self.cboLicense.findText(self._parent.project.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 5, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent.project.extensions))
        grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0)
        grid.addWidget(self.txtExtensions, 6, 1)

        grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent.project.indentation)
        self.spinIndentation.setRange(2, 10)
        self.spinIndentation.setValue(4)
        self.spinIndentation.setSingleStep(2)
        grid.addWidget(self.spinIndentation, 7, 1)
        self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS)
        self.checkUseTabs.setChecked(self._parent.project.use_tabs)
        grid.addWidget(self.checkUseTabs, 7, 2)
Beispiel #25
0
class IntegerProperty(Property,QWidget):
    """ Property which hold editable integer numbers.
    
    A Spinbox is provided when the property is editable.
    """
    
    USER_INFO = "Integer field"
    
    def __init__(self, name, value, categoryName=None):
        """ Constructor
        """
        Property.__init__(self, name, categoryName)
        QWidget.__init__(self)
        self.setLayout(QHBoxLayout())
        self.layout().setSpacing(0)
        self.layout().setContentsMargins(0, 0, 0, 0)
        
        self._spinbox=QSpinBox()
        #self.maxint = sys.maxint     # does not work on Mac OS X (Snow Leopard 10.6.2), confusion between 32 and 64 bit limits
        self.maxint = 2**31
        self._spinbox.setRange(-self.maxint+1, self.maxint-1)
        self._spinbox.setFrame(False)
        self.layout().addWidget(self._spinbox)
        self.setFocusProxy(self._spinbox)
        self._lineedit=QLineEdit()
        self._lineedit.setReadOnly(True)
        self._lineedit.setFrame(False)
        self._lineedit.setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self._lineedit)
        self._lineedit.hide()

        self.setValue(value)
        self.connect(self._spinbox, SIGNAL('valueChanged(int)'), self.valueChanged)
        
    def setReadOnly(self, readOnly):
        """ Switches between lineedit and spinbox.
        """
        if readOnly:
            self._spinbox.hide()
            self._lineedit.show()
            self.setFocusProxy(self._lineedit)
        else:
            self._spinbox.show()
            self._lineedit.hide()
            self.setFocusProxy(self._spinbox)
        
    def value(self):
        """ Returns integer value.
        """
        return self._spinbox.value()
    
    def setValue(self,value):
        self.disconnect(self._spinbox, SIGNAL('valueChanged(int)'), self.valueChanged)
        self._spinbox.setValue(value % self.maxint)
        self.connect(self._spinbox, SIGNAL('valueChanged(int)'), self.valueChanged)
        self._lineedit.setText(str(value))
Beispiel #26
0
    def createIntegerSpinner(self, minimum, maximum):
        spinner = QSpinBox()
        spinner.setMinimumWidth(75)
        spinner.setRange(minimum, maximum)
        spinner.setKeyboardTracking(False)

        spinner.editingFinished.connect(self.plotScaleChanged)
        spinner.valueChanged.connect(self.plotScaleChanged)

        return spinner
Beispiel #27
0
    def createIntegerSpinner(self, minimum, maximum):
        spinner = QSpinBox()
        spinner.setMinimumWidth(75)
        spinner.setRange(minimum, maximum)
        spinner.setKeyboardTracking(False)

        spinner.editingFinished.connect(self.plotScaleChanged)
        spinner.valueChanged.connect(self.plotScaleChanged)

        return spinner
Beispiel #28
0
class MusicView(preferences.Group):
    def __init__(self, page):
        super(MusicView, self).__init__(page)
        
        layout = QGridLayout()
        self.setLayout(layout)

        self.magnifierSizeLabel = QLabel()
        self.magnifierSizeSlider = QSlider(Qt.Horizontal, valueChanged=self.changed)
        self.magnifierSizeSlider.setSingleStep(50)
        self.magnifierSizeSlider.setRange(*popplerview.MagnifierSettings.sizeRange)
        self.magnifierSizeSpinBox = QSpinBox()
        self.magnifierSizeSpinBox.setRange(*popplerview.MagnifierSettings.sizeRange)
        self.magnifierSizeSpinBox.valueChanged.connect(self.magnifierSizeSlider.setValue)
        self.magnifierSizeSlider.valueChanged.connect(self.magnifierSizeSpinBox.setValue)
        layout.addWidget(self.magnifierSizeLabel, 0, 0)
        layout.addWidget(self.magnifierSizeSlider, 0, 1)
        layout.addWidget(self.magnifierSizeSpinBox, 0, 2)
        
        self.magnifierScaleLabel = QLabel()
        self.magnifierScaleSlider = QSlider(Qt.Horizontal, valueChanged=self.changed)
        self.magnifierScaleSlider.setSingleStep(50)
        self.magnifierScaleSlider.setRange(*popplerview.MagnifierSettings.scaleRange)
        self.magnifierScaleSpinBox = QSpinBox()
        self.magnifierScaleSpinBox.setRange(*popplerview.MagnifierSettings.scaleRange)
        self.magnifierScaleSpinBox.valueChanged.connect(self.magnifierScaleSlider.setValue)
        self.magnifierScaleSlider.valueChanged.connect(self.magnifierScaleSpinBox.setValue)
        layout.addWidget(self.magnifierScaleLabel, 1, 0)
        layout.addWidget(self.magnifierScaleSlider, 1, 1)
        layout.addWidget(self.magnifierScaleSpinBox, 1, 2)
        
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Music View"))
        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", "%"))
            
    def loadSettings(self):
        s = popplerview.MagnifierSettings.load()
        self.magnifierSizeSlider.setValue(s.size)
        self.magnifierScaleSlider.setValue(s.scale)
    
    def saveSettings(self):
        s = popplerview.MagnifierSettings()
        s.size = self.magnifierSizeSlider.value()
        s.scale = self.magnifierScaleSlider.value()
        s.save()
Beispiel #29
0
class Updates(QWidget):
    
    def __init__(self, pref):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)

        vbox.addWidget(QLabel('Set the interval for updates:'))
        self.spin = QSpinBox()
        self.spin.setRange(1, 60)
        self.spin.setSuffix(' minutes')
        self.spin.setValue(pref.get('time', 10))
        vbox.addWidget(self.spin)
Beispiel #30
0
class SpinSlider(QWidget):
	"Boite de spin + curseur avec sauvegarde de la dernière valeur sélectionnée"
	def __init__(self, debut, fin, defaut, optionConfig=None, parent=None):
		QWidget.__init__(self)

		self.spin = QSpinBox()
		self.slider = QSlider(Qt.Horizontal)
		self.spin.setRange(debut, fin)
		self.slider.setRange(debut, fin)

		valeur = None
		if optionConfig:
			self.config = parent.config
			self.idSection = parent.idSection
			self.optionConfig = optionConfig
			try :
				valeur = self.config.get(self.idSection, self.optionConfig)
			except:
				valeur = defaut
				self.config.set(self.idSection, self.optionConfig, valeur)
		erreur = False
		if valeur:
			try: valeur = int(valeur)
			except ValueError: erreur = True
		if not erreur and debut <= valeur <= fin:
			self.spin.setValue(valeur)
			self.slider.setValue(valeur)
		else:
			self.spin.setValue(defaut)
			self.slider.setValue(defaut)
		if optionConfig: self.connect(self.spin, SIGNAL("valueChanged(int)"), self.sauveConfig)
		self.connect(self.spin, SIGNAL("valueChanged(int)"), self.slider,
						SLOT("setValue(int)"))
		self.connect(self.slider, SIGNAL("valueChanged(int)"), self.spin,
						SLOT("setValue(int)"))
		self.connect(self.spin, SIGNAL("valueChanged(int)"), self.changed)
		hbox = QHBoxLayout(self)
		hbox.addWidget(self.spin)
		hbox.addWidget(self.slider)
		hbox.setMargin(0) # pour un meilleur alignement dans un grid

	def changed(self, i):
		self.emit(SIGNAL("valueChanged(int)"), i)

	def sauveConfig(self, i):
		self.config.set(self.idSection, self.optionConfig, str(i))

	def value(self):
		return self.spin.value()

	def setValue(self, i):
		self.spin.setValue(i)
		self.slider.setValue(i)
Beispiel #31
0
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.label_amount = QLabel('Amount')
        self.spin_amount = QDoubleSpinBox()
        self.spin_amount.setRange(0, 10000000000)
        self.spin_amount.setPrefix('Rp. ')
        self.spin_amount.setSingleStep(100000)

        self.label_rate = QLabel('Rate')
        self.spin_rate = QDoubleSpinBox()
        self.spin_rate.setSuffix(' %')
        self.spin_rate.setSingleStep(0.1)
        self.spin_rate.setRange(0, 100)

        self.label_year = QLabel('Years')
        self.spin_year = QSpinBox()
        self.spin_year.setSuffix(' year')
        self.spin_year.setSingleStep(1)
        self.spin_year.setRange(0, 1000)
        self.spin_year.setValue(1)

        self.label_total_ = QLabel('Total')
        self.label_total = QLabel('Rp. 0.00')

        grid = QGridLayout()
        grid.addWidget(self.label_amount, 0, 0)
        grid.addWidget(self.spin_amount, 0, 1)
        grid.addWidget(self.label_rate, 1, 0)
        grid.addWidget(self.spin_rate, 1, 1)
        grid.addWidget(self.label_year, 2, 0)
        grid.addWidget(self.spin_year, 2, 1)
        grid.addWidget(self.label_total_, 3, 0)
        grid.addWidget(self.label_total, 3, 1)
        self.setLayout(grid)

        self.connect(self.spin_amount, SIGNAL('valueChanged(double)'),
                     self.update_ui)
        self.connect(self.spin_rate, SIGNAL('valueChanged(double)'),
                     self.update_ui)
        self.connect(self.spin_year, SIGNAL('valueChanged(int)'),
                     self.update_ui)
        self.setWindowTitle('Interest')

    def update_ui(self):
        amount = self.spin_amount.value()
        rate = self.spin_rate.value()
        year = self.spin_year.value()
        total = amount * (1 + rate / 100.0)**year

        self.label_total.setText('Rp. %.2f' % total)
Beispiel #32
0
 def createEditor(self, parent, option, index):
     col = index.column()
     if col == 2:
         sbox = QSpinBox(parent)
         sbox.setRange(1,100) # 100 is a magic number
         return sbox
     elif col == 1:
         editor = QLineEdit(parent)
         regExp = QtCore.QRegExp("[tri]")
         editor.setValidator(QtGui.QRegExpValidator(regExp, parent))
         return editor
     else:
         return QLineEdit(parent)
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        
        self.label_amount = QLabel('Amount')
        self.spin_amount = QDoubleSpinBox()
        self.spin_amount.setRange(0, 10000000000)
        self.spin_amount.setPrefix('Rp. ')
        self.spin_amount.setSingleStep(100000)
        
        self.label_rate = QLabel('Rate')
        self.spin_rate = QDoubleSpinBox()
        self.spin_rate.setSuffix(' %')
        self.spin_rate.setSingleStep(0.1)
        self.spin_rate.setRange(0, 100)
        
        self.label_year = QLabel('Years')
        self.spin_year = QSpinBox()
        self.spin_year.setSuffix(' year')
        self.spin_year.setSingleStep(1)
        self.spin_year.setRange(0, 1000)
        self.spin_year.setValue(1)
        
        
        self.label_total_ = QLabel('Total')
        self.label_total = QLabel('Rp. 0.00')
        
        grid = QGridLayout()
        grid.addWidget(self.label_amount, 0, 0)
        grid.addWidget(self.spin_amount, 0, 1)
        grid.addWidget(self.label_rate, 1, 0)
        grid.addWidget(self.spin_rate, 1, 1)
        grid.addWidget(self.label_year, 2, 0)
        grid.addWidget(self.spin_year, 2, 1)
        grid.addWidget(self.label_total_, 3, 0)
        grid.addWidget(self.label_total, 3, 1)
        self.setLayout(grid)
        
        self.connect(self.spin_amount, SIGNAL('valueChanged(double)'), self.update_ui)
        self.connect(self.spin_rate, SIGNAL('valueChanged(double)'), self.update_ui)
        self.connect(self.spin_year, SIGNAL('valueChanged(int)'), self.update_ui)
        self.setWindowTitle('Interest')
    
    def update_ui(self):        
        amount = self.spin_amount.value()
        rate = self.spin_rate.value()
        year = self.spin_year.value()
        total = amount * (1 + rate / 100.0) ** year
        
        self.label_total.setText('Rp. %.2f' % total)
Beispiel #34
0
    def __init__(self):
        super(TestWindow, self).__init__()
        self.setWindowTitle("LivePlot Example Runner")
        layout = QHBoxLayout(self)
        button_layout = QVBoxLayout()
        time_layout = QHBoxLayout()
        time_spin = QSpinBox()
        self.timer = QTimer()
        time_spin.valueChanged.connect(self.timer.setInterval)
        self.timer.timeout.connect(self.iterate)
        self.progress_bar = QProgressBar()
        time_spin.setValue(50)
        time_spin.setRange(0, 1000)
        time_layout.addWidget(QLabel("Sleep Time (ms)"))
        time_layout.addWidget(time_spin)
        button_layout.addLayout(time_layout)

        tests = {
            'plot y': test_plot_y,
            'plot xy': test_plot_xy,
            'plot parametric': test_plot_xy_parametric,
            'plot z': test_plot_z,
            'plot huge': test_plot_huge,
            'append y': test_append_y,
            'append xy': test_append_xy,
            'append z': test_append_z,
            'label': test_label,
        }
        fn_text_widget = QPlainTextEdit()
        fn_text_widget.setMinimumWidth(500)

        def make_set_iterator(iter):
            def set_iterator():
                fn_text_widget.setPlainText(inspect.getsource(iter))
                QApplication.instance().processEvents()
                self.iterator = iter()
                self.timer.start()
            return set_iterator

        for name, iter in tests.items():
            button = QPushButton(name)
            button.clicked.connect(make_set_iterator(iter))
            button_layout.addWidget(button)

        layout.addLayout(button_layout)
        text_layout = QVBoxLayout()
        text_layout.addWidget(fn_text_widget)
        text_layout.addWidget(self.progress_bar)
        layout.addLayout(text_layout)
Beispiel #35
0
    def __init__(self):
        super(TestWindow, self).__init__()
        self.setWindowTitle("LivePlot Example Runner")
        layout = QHBoxLayout(self)
        button_layout = QVBoxLayout()
        time_layout = QHBoxLayout()
        time_spin = QSpinBox()
        self.timer = QTimer()
        time_spin.valueChanged.connect(self.timer.setInterval)
        self.timer.timeout.connect(self.iterate)
        self.progress_bar = QProgressBar()
        time_spin.setValue(50)
        time_spin.setRange(0, 1000)
        time_layout.addWidget(QLabel("Sleep Time (ms)"))
        time_layout.addWidget(time_spin)
        button_layout.addLayout(time_layout)

        tests = {
            'plot y': test_plot_y,
            'plot xy': test_plot_xy,
            'plot parametric': test_plot_xy_parametric,
            'plot z': test_plot_z,
            'plot huge': test_plot_huge,
            'append y': test_append_y,
            'append xy': test_append_xy,
            'append z': test_append_z,
        }
        fn_text_widget = QPlainTextEdit()
        fn_text_widget.setMinimumWidth(500)

        def make_set_iterator(iter):
            def set_iterator():
                fn_text_widget.setPlainText(inspect.getsource(iter))
                QApplication.instance().processEvents()
                self.iterator = iter()
                self.timer.start()

            return set_iterator

        for name, iter in tests.items():
            button = QPushButton(name)
            button.clicked.connect(make_set_iterator(iter))
            button_layout.addWidget(button)

        layout.addLayout(button_layout)
        text_layout = QVBoxLayout()
        text_layout.addWidget(fn_text_widget)
        text_layout.addWidget(self.progress_bar)
        layout.addLayout(text_layout)
Beispiel #36
0
        def setCacheSize( cache_size ):
            dlg = QDialog(self)
            layout = QHBoxLayout()
            layout.addWidget( QLabel("Cached Slices Per View:") )

            spinBox = QSpinBox( parent=dlg )
            spinBox.setRange( 0, 1000 )
            spinBox.setValue( self.editor.cacheSize )
            layout.addWidget( spinBox )
            okButton = QPushButton( "OK", parent=dlg )
            okButton.clicked.connect( dlg.accept )
            layout.addWidget( okButton )
            dlg.setLayout( layout )
            dlg.setModal(True)
            if dlg.exec_() == QDialog.Accepted:
                self.editor.cacheSize = spinBox.value()
Beispiel #37
0
class ConnectDialog(QDialog):
    def __init__(self, parent = None):
        QDialog.__init__(self, parent)
        self.setWindowTitle("Connect To Game")
        self.hostEdit = QLineEdit()
        self.hostEdit.setText("127.0.0.1")
        self.portEdit = QSpinBox()
        self.portEdit.setRange(0, 2 ** 16)
        self.portEdit.setValue(9002)
        connect = QPushButton("Connect")
        connect.released.connect(self.accept)
        layout = QFormLayout()
        layout.addRow("Host", self.hostEdit)
        layout.addRow("Port", self.portEdit)
        layout.addRow(connect)
        self.setLayout(layout)
Beispiel #38
0
class StaffBase(QWidget):
    def __init__(self, dialog):
        QWidget.__init__(self, dialog)
        self.dialog = dialog
        self.setLayout(QGridLayout())
        self.systems = QSpinBox()
        self.systems.setRange(1, 64)
        self.layout().setColumnStretch(0, 1)
        self.layout().setColumnStretch(3, 1)

    def systemCount(self):
        return self.systems.value()
    
    def music(self, layout):
        """ add lines to layout contexts and returns the music, also in lines """
        return []
        def setCacheSize(cache_size):
            dlg = QDialog(self)
            layout = QHBoxLayout()
            layout.addWidget(QLabel("Cached Slices Per View:"))

            spinBox = QSpinBox(parent=dlg)
            spinBox.setRange(0, 1000)
            spinBox.setValue(self.editor.cacheSize)
            layout.addWidget(spinBox)
            okButton = QPushButton("OK", parent=dlg)
            okButton.clicked.connect(dlg.accept)
            layout.addWidget(okButton)
            dlg.setLayout(layout)
            dlg.setModal(True)
            if dlg.exec_() == QDialog.Accepted:
                self.editor.cacheSize = spinBox.value()
class ResizeDlg(QDialog):

    def __init__(self, width, height, parent=None):
        super(ResizeDlg, self).__init__(parent)
        self.create_widgets(width, height)
        self.layout_widgets()
        self.create_connections()


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

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


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


    def create_connections(self):
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.setWindowTitle("Image Changer - Resize")


    def result(self):
        return self.widthSpinBox.value(), self.heightSpinBox.value()
Beispiel #41
0
class QxtSpanSliderWidget(QWidget):
    def __init__(self, low, upp, parent=None):
        QWidget.__init__(self, parent)
        self.layout = QHBoxLayout(self)
        self._spin_start = QSpinBox(self)
        self._spin_end = QSpinBox(self)
        self.layout.addWidget(self._spin_start)

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

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

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

        self.setRange(low, upp)
        self.setSpan(low, upp)

    @property
    def lowerValue(self):
        return self._slider.lowerValue

    @property
    def upperValue(self):
        return self._slider.upperValue

    def setRange(self, low, upp):
        self._slider.setRange(low, upp)
        self._spin_start.setRange(low, upp)
        self._spin_end.setRange(low, upp)

    def setSpan(self, low, upp):
        self._spin_start.setValue(low)
        self._spin_end.setValue(upp)
        self._slider.setSpan(low, upp)
    def createEditor( self, parent, option, index ):
        if index.column() == CANTIDAD:
            spinbox = QSpinBox( parent )
            spinbox.setRange( -500, 500 )
            spinbox.setSingleStep( 1 )
            spinbox.setAlignment( Qt.AlignLeft | Qt.AlignVCenter )
            return spinbox
        elif index.column() in ( DESCRIPCION, IDARTICULO ):
            current = index.model().data( index.model().index( index.row(), IDARTICULO ) )
            self.proxymodel.setFilterRegExp( self.filter( index.model(), current ) )

            sp = super( KardexOtherDelegate, self ).createEditor( parent, option, index )
            sp.setColumnHidden( IDARTICULO )
            sp.setColumnHidden( COSTO )
            return sp
        else:
            super( KardexOtherDelegate, self ).createEditor( parent, option, index )
Beispiel #43
0
class QxtSpanSliderWidget(QWidget):
    def __init__(self, low, upp, parent=None):
        QWidget.__init__(self, parent)
        self.layout = QHBoxLayout(self)
        self._spin_start = QSpinBox(self)
        self._spin_end = QSpinBox(self)
        self.layout.addWidget(self._spin_start)

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

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

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

        self.setRange(low, upp)
        self.setSpan(low, upp)

    @property
    def lowerValue(self):
        return self._slider.lowerValue

    @property
    def upperValue(self):
        return self._slider.upperValue

    def setRange(self, low, upp):
        self._slider.setRange(low, upp)
        self._spin_start.setRange(low, upp)
        self._spin_end.setRange(low, upp)

    def setSpan(self, low, upp):
        self._spin_start.setValue(low)
        self._spin_end.setValue(upp)
        self._slider.setSpan(low, upp)
Beispiel #44
0
class NewProjectDialog(QDialog):
    def __init__(self, parent=None):
        super(NewProjectDialog,self).__init__(parent)
        self.setSizeGripEnabled(True)
        self.create_layout()
        
    def create_layout(self):
        # select directory containing images
        # configure the skip-frames
        # cancel or create project
        self.project_name_ = QLineEdit()
        self.filefield_ = QFileField(msg="Select Image Directory...", select_dir=True)
        self.skip_ = QSpinBox()
        self.skip_.setRange(0,50)
        self.skip_.setValue(5)
        layout = QFormLayout(self)
        layout.setLabelAlignment(Qt.AlignVCenter)
        layout.addRow("Project Name:", self.project_name_)
        layout.addRow("Image Directory:", self.filefield_)
        layout.addRow("Skip images:", self.skip_)
        
        dbb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        dbb.accepted.connect(self.on_accept)
        dbb.rejected.connect(self.on_reject)
        layout.addRow(dbb)
        self.setLayout(layout)
    
    @property
    def name(self):
        return self.project_name_.text()
        
    @property
    def path(self):
        return self.filefield_.path
    
    @property
    def skip(self):
        return self.skip_.value()

    def on_accept(self):
        # todo: check file validity
        self.accept()
        
    def on_reject(self):
        self.reject()    
Beispiel #45
0
 def createEditor(self, parent, options, index):
     value = self.convertValue(index.model().data(index, Qt.EditRole))
     if isinstance(value, (int, long)):
         spnBox = QSpinBox(parent)
         spnBox.setRange(-999999999, 999999999)
         return spnBox
     elif isinstance(value, float):
         spnBox = QDoubleSpinBox(parent)
         spnBox.setRange(-999999999.999999, 999999999.999999)
         spnBox.setDecimals(6)
         return spnBox
     elif isinstance(value, (str, unicode)):
         if os.path.isdir(value):
             return FileDirectorySelector(parent)
         elif os.path.isfile(value):
             return FileDirectorySelector(parent, True)
         else:
             return FileDirectorySelector(parent, True)
Beispiel #46
0
 def add_spin_box(self, name='Number', n_min=1, n_max=99, init_val=1,
                    advance_n=True, fulldesc='Number of Engines', 
                    text_align='right', text_font=ARIAL_10, col=0, width=120,
                    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)
     
     lbl = QLabel("    %s "%fulldesc, parent)
     lbl.setFont( text_font )
     
     spin_box =  QSpinBox(parent)    
     spin_box.setFont( text_font )
     spin_box.setFixedWidth( width )
     spin_box.setRange( n_min, n_max)
     spin_box.setValue( init_val )
     
     if layout is None:
         parent.grid.addWidget(lbl,      NRow, col)
     else:
         layout.addWidget( lbl )
         
     hbox = QHBoxLayout()
     hbox.addWidget(spin_box)
     hbox.addStretch(1)
     widget = QWidget()
     widget.setLayout(hbox)
     if layout is None:
         parent.grid.addWidget(widget , NRow, col+1)
         if text_align=='right':
             parent.grid.setAlignment(lbl, Qt.AlignRight )
     else:
         layout.addWidget( widget )
     
     
     self.objectD['%s_spin_box'%name] = spin_box 
     self.input_widget_by_nameD[name] = (spin_box , 'spin_box')
         
     spin_box.valueChanged.connect( lambda: self.spin_box_changed( '%s_spin_box'%name ) )   
Beispiel #47
0
 def createEditor(self, parent, option, index):
     model = index.model()
     if model.isColumn("name", index):
         textedit = QLineEdit(parent)
         return textedit
     elif model.isColumn("rating", index):
         spinbox = QSpinBox(parent)
         spinbox.setRange(0, 200)
         spinbox.setSingleStep(1)
         spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
         return spinbox
     elif model.isColumn("adjust", index):
         spinbox = QSpinBox(parent)
         spinbox.setRange(-10, 10)
         spinbox.setSingleStep(1)
         spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
         return spinbox
     else:
         return QItemDelegate.createEditor(self, parent, option, index)
Beispiel #48
0
 def create_fontgroup(self, option=None, text=None,
                      tip=None, fontfilters=None):
     """Option=None -> setting plugin font"""
     fontlabel = QLabel(_("Font: "))
     fontbox = QFontComboBox()
     if fontfilters is not None:
         fontbox.setFontFilters(fontfilters)
     sizelabel = QLabel("  "+_("Size: "))
     sizebox = QSpinBox()
     sizebox.setRange(7, 100)
     self.fontboxes[(fontbox, sizebox)] = option
     layout = QHBoxLayout()
     for subwidget in (fontlabel, fontbox, sizelabel, sizebox):
         layout.addWidget(subwidget)
     layout.addStretch(1)
     if text is None:
         text = _("Font style")
     group = QGroupBox(text)
     group.setLayout(layout)
     if tip is not None:
         group.setToolTip(tip)
     return group
Beispiel #49
0
 def createEditor(
     self,
     parent,
     options,
     index,
 ):
     value = self.convertValue(index.model().data(index, Qt.EditRole))
     if isinstance(value, (int, long)):
         spnBox = QSpinBox(parent)
         spnBox.setRange(-999999999, 999999999)
         return spnBox
     elif isinstance(value, float):
         spnBox = QDoubleSpinBox(parent)
         spnBox.setRange(-999999999.999999, 999999999.999999)
         spnBox.setDecimals(6)
         return spnBox
     elif isinstance(value, (str, unicode)):
         valuetype = self.convertValue(index.model().data(index, Qt.UserRole))
         if valuetype == Setting.FOLDER:
             return FileDirectorySelector(parent)
         else:
             return FileDirectorySelector(parent, True)
Beispiel #50
0
class IntervalWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QHBoxLayout(self)
        layout.setContentsMargins(0,0,0,0)

        self.spinbox = QSpinBox(self)
        self.combo = QComboBox(self)

        sp = self.spinbox.sizePolicy()
        sp.setHorizontalStretch(1)
        self.spinbox.setSizePolicy(sp)

        self.spinbox.setRange(0, (1 << 31) - 1)
        self.spinbox.setSingleStep(1)

        self.combo.addItem('Seconds')
        self.combo.addItem('Milliseconds')

        layout.addWidget(self.spinbox)
        layout.addWidget(self.combo)

    def set_interval(self, interval):
        if ('%.03f' % interval).endswith('.000'):
            self.spinbox.setValue(int(interval))
            self.combo.setCurrentIndex(0)
        else:
            self.spinbox.setValue(round(interval * 1000.0))
            self.combo.setCurrentIndex(1)

    def get_interval(self):
        if self.combo.currentIndex() == 0:
            return self.spinbox.value()
        else:
            return self.spinbox.value() / 1000.0
Beispiel #51
0
class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.main_layout = QGridLayout()

        self.steps_spin = QSpinBox()
        self.steps_spin.setRange(1, 12)
        self.steps_label = QLabel("steps:")
        self.steps_slider = QSlider(1)  #horizontal
        self.steps_slider.setRange(1, 12)

        self.smooth_spin = QSpinBox()
        self.smooth_spin.setRange(1, 100)
        self.smooth_label = QLabel("smoothness:")
        self.smooth_slider = QSlider(1)  #horizontal
        self.smooth_slider.setRange(0, 100)
        self.smooth_slider.setSingleStep(1)

        self.dampen_spin = QSpinBox()
        self.dampen_spin.setRange(1, 100)
        self.dampen_label = QLabel("dampening:")
        self.dampen_slider = QSlider(1)  #horizontal
        self.dampen_slider.setRange(0, 100)
        self.dampen_slider.setSingleStep(1)

        self.update_button = QPushButton("update")

        self.view = QGraphicsView()

        self.main_layout.addWidget(self.steps_spin, 0, 0)
        self.main_layout.addWidget(self.steps_label, 0, 1)
        self.main_layout.addWidget(self.steps_slider, 0, 2)

        self.main_layout.addWidget(self.smooth_spin, 1, 0)
        self.main_layout.addWidget(self.smooth_label, 1, 1)
        self.main_layout.addWidget(self.smooth_slider, 1, 2)

        self.main_layout.addWidget(self.dampen_spin, 2, 0)
        self.main_layout.addWidget(self.dampen_label, 2, 1)
        self.main_layout.addWidget(self.dampen_slider, 2, 2)

        self.main_layout.addWidget(self.update_button, 3, 0, 1, 3)

        self.main_layout.addWidget(
            self.view,
            4,
            0,
            1,  #rowSpan
            3)  #columnSpan

        self.setLayout(self.main_layout)
Beispiel #52
0
class EditorGeneral(QWidget):
    """EditorGeneral widget class."""

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

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

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

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

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

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

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

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

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

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

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

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

    def save(self):
        qsettings = IDE.ninja_settings()
        settings.FONT = self._font
        qsettings.setValue('preferences/editor/font', settings.FONT)
        settings.SHOW_MINIMAP = self._checkShowMinimap.isChecked()
        settings.MINIMAP_MAX_OPACITY = self._spinMaxOpacity.value() / 100.0
        settings.MINIMAP_MIN_OPACITY = self._spinMinOpacity.value() / 100.0
        settings.SIZE_PROPORTION = self._spinSize.value() / 100.0
        qsettings.setValue('preferences/editor/minimapMaxOpacity',
                           settings.MINIMAP_MAX_OPACITY)
        qsettings.setValue('preferences/editor/minimapMinOpacity',
                           settings.MINIMAP_MIN_OPACITY)
        qsettings.setValue('preferences/editor/minimapSizeProportion',
                           settings.SIZE_PROPORTION)
        qsettings.setValue('preferences/editor/minimapShow',
                           settings.SHOW_MINIMAP)
        scheme = self._listScheme.currentItem().text()
        resources.CUSTOM_SCHEME = self._schemes.get(scheme,
                                                    resources.COLOR_SCHEME)
        qsettings.setValue('preferences/editor/scheme', scheme)
Beispiel #53
0
    def __init__(self, config_in, ncols=2):
        super(DictGui, 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("Default", self)
        btn_reset_config.clicked.connect(self.btnResetConfig)
        gd.addWidget(btn_reset_config, 0, text_col)

        btn_save_config = QPushButton("Ok", 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)
Beispiel #54
0
class QKoordinaten(QWidget):

    'Methode __init__'

    def __init__(self, parent=None):

        'Vererbung aller Attribute und Methoden von QWidget'
        super(QKoordinaten, self).__init__(parent)

        'Schriftart und Schriftgröße festlegen'
        self.setFont(QFont('Arial', 12))

        'Methode grafikelemente_hinzufuegen aufrufen'
        self.grafikelemente_hinzufuegen()

    'Methode grafikelemente_hinzufuegen'

    def grafikelemente_hinzufuegen(self):

        'Textfelder für die Beschriftung instanziieren'
        self.textX = QLabel('X')
        self.textY = QLabel('Y')
        self.textZ = QLabel('Z')

        'QSpinBox-Objekt zur Anzeige der x-Koordinate instanziieren'
        self.x = QSpinBox()
        #Wert rechts ausrichten
        self.x.setAlignment(Qt.AlignRight)
        #Anzeigebereich erweitern
        self.x.setRange(-800, 800)
        #manuelle Eingaben deaktivieren
        self.x.setReadOnly(True)

        'QSpinBox-Objekt zur Anzeige der y-Koordinate instanziieren'
        self.y = QSpinBox()
        #Wert rechts ausrichten
        self.y.setAlignment(Qt.AlignRight)
        #Anzeigebereich erweitern
        self.y.setRange(-800, 800)
        #manuelle Eingaben deaktivieren
        self.y.setReadOnly(True)

        'QSpinBox-Objekt zur Anzeige der z-Koordinate instanziieren'
        self.z = QSpinBox()
        #Wert rechts ausrichten
        self.z.setAlignment(Qt.AlignRight)
        #Anzeigebereich erweitern
        self.z.setRange(-800, 800)
        #manuelle Eingaben deaktivieren
        self.z.setReadOnly(True)

        'Grafikelemente untereinander anordnen'
        layout = QFormLayout(self)
        layout.addRow(self.textX, self.x)
        layout.addRow(self.textY, self.y)
        layout.addRow(self.textZ, self.z)

    'Methode groesse_festlegen'

    def groesse_festlegen(self, breite, hoehe):

        'Breite und Höhe festlegen'
        self.breite = breite
        self.hoehe = hoehe

        'Abmessungen ändern'
        self.textX.setFixedHeight(self.hoehe)
        self.x.setFixedSize(QSize(self.breite, self.hoehe))
        self.textY.setFixedHeight(self.hoehe)
        self.y.setFixedSize(QSize(self.breite, self.hoehe))
        self.textZ.setFixedHeight(self.hoehe)
        self.z.setFixedSize(QSize(self.breite, self.hoehe))

    'Methode koordinaten_aktualisieren'

    def koordinaten_aktualisieren(self, x, y, z):

        'Werte eintragen'
        self.x.setValue(x)
        self.y.setValue(y)
        self.z.setValue(z)
Beispiel #55
0
class EditorConfiguration(QWidget):
    """EditorConfiguration widget class"""

    def __init__(self, parent):
        super(EditorConfiguration, self).__init__()
        self._preferences, vbox = parent, QVBoxLayout(self)

        # groups
        group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_INDENT)
        group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_MARGIN)
        group3 = QGroupBox(translations.TR_LINT_DIRTY_TEXT)
        group4 = QGroupBox(translations.TR_PEP8_DIRTY_TEXT)
        group5 = QGroupBox(translations.TR_HIGHLIGHTER_EXTRAS)
        group6 = QGroupBox(translations.TR_TYPING_ASSISTANCE)
        group7 = QGroupBox(translations.TR_DISPLAY_ERRORS)

        # groups container
        container_widget_with_all_preferences = QWidget()
        formFeatures = QGridLayout(container_widget_with_all_preferences)

        # Indentation
        hboxg1 = QHBoxLayout(group1)
        hboxg1.setContentsMargins(5, 15, 5, 5)
        self._spin, self._checkUseTabs = QSpinBox(), QComboBox()
        self._spin.setRange(1, 10)
        self._spin.setValue(settings.INDENT)
        hboxg1.addWidget(self._spin)
        self._checkUseTabs.addItems([
            translations.TR_PREFERENCES_EDITOR_CONFIG_SPACES.capitalize(),
            translations.TR_PREFERENCES_EDITOR_CONFIG_TABS.capitalize()])
        self._checkUseTabs.setCurrentIndex(int(settings.USE_TABS))
        hboxg1.addWidget(self._checkUseTabs)
        formFeatures.addWidget(group1, 0, 0)

        # Margin Line
        hboxg2 = QHBoxLayout(group2)
        hboxg2.setContentsMargins(5, 15, 5, 5)
        self._checkShowMargin = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MARGIN_LINE)
        self._checkShowMargin.setChecked(settings.SHOW_MARGIN_LINE)
        hboxg2.addWidget(self._checkShowMargin)
        self._spinMargin = QSpinBox()
        self._spinMargin.setRange(50, 100)
        self._spinMargin.setSingleStep(2)
        self._spinMargin.setValue(settings.MARGIN_LINE)
        hboxg2.addWidget(self._spinMargin)
        hboxg2.addWidget(QLabel(translations.TR_CHARACTERS))
        formFeatures.addWidget(group2, 0, 1)

        # Display Errors
        hboxDisplay = QHBoxLayout(group7)
        hboxDisplay.setContentsMargins(5, 15, 5, 5)
        self._checkHighlightLine = QComboBox()
        self._checkHighlightLine.addItems([
            translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_BACKGROUND,
            translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_UNDERLINE])
        self._checkHighlightLine.setCurrentIndex(
            int(settings.UNDERLINE_NOT_BACKGROUND))
        hboxDisplay.addWidget(self._checkHighlightLine)
        formFeatures.addWidget(group7, 1, 0, 1, 0)

        # Find Lint Errors (highlighter)
        vboxg3 = QVBoxLayout(group3)
        self._checkErrors = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS)
        self._checkErrors.setChecked(settings.FIND_ERRORS)
        self.connect(self._checkErrors, SIGNAL("stateChanged(int)"),
                     self._disable_show_errors)
        self._showErrorsOnLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS)
        self._showErrorsOnLine.setChecked(settings.ERRORS_HIGHLIGHT_LINE)
        self.connect(self._showErrorsOnLine, SIGNAL("stateChanged(int)"),
                     self._enable_errors_inline)
        vboxg3.addWidget(self._checkErrors)
        vboxg3.addWidget(self._showErrorsOnLine)
        formFeatures.addWidget(group3, 2, 0)

        # Find PEP8 Errors (highlighter)
        vboxg4 = QVBoxLayout(group4)
        vboxg4.setContentsMargins(5, 15, 5, 5)
        self._checkStyle = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8)
        self._checkStyle.setChecked(settings.CHECK_STYLE)
        self.connect(self._checkStyle, SIGNAL("stateChanged(int)"),
                     self._disable_check_style)
        vboxg4.addWidget(self._checkStyle)
        self._checkStyleOnLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8)
        self._checkStyleOnLine.setChecked(settings.CHECK_HIGHLIGHT_LINE)
        self.connect(self._checkStyleOnLine, SIGNAL("stateChanged(int)"),
                     self._enable_check_inline)
        vboxg4.addWidget(self._checkStyleOnLine)
        formFeatures.addWidget(group4, 2, 1)

        # Show Python3 Migration, DocStrings and Spaces (highlighter)
        vboxg5 = QVBoxLayout(group5)
        vboxg5.setContentsMargins(5, 15, 5, 5)
        self._showMigrationTips = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MIGRATION)
        self._showMigrationTips.setChecked(settings.SHOW_MIGRATION_TIPS)
        vboxg5.addWidget(self._showMigrationTips)
        self._checkForDocstrings = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_CHECK_FOR_DOCSTRINGS)
        self._checkForDocstrings.setChecked(settings.CHECK_FOR_DOCSTRINGS)
        vboxg5.addWidget(self._checkForDocstrings)
        self._checkShowSpaces = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES)
        self._checkShowSpaces.setChecked(settings.SHOW_TABS_AND_SPACES)
        vboxg5.addWidget(self._checkShowSpaces)
        self._checkIndentationGuide = QCheckBox(
            translations.TR_SHOW_INDENTATION_GUIDE)
        self._checkIndentationGuide.setChecked(settings.SHOW_INDENTATION_GUIDE)
        vboxg5.addWidget(self._checkIndentationGuide)
        formFeatures.addWidget(group5, 3, 0)

        # End of line, Center On Scroll, Trailing space, Word wrap
        vboxg6 = QVBoxLayout(group6)
        vboxg6.setContentsMargins(5, 15, 5, 5)
        self._checkEndOfLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE)
        self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE)
        vboxg6.addWidget(self._checkEndOfLine)
        self._checkCenterScroll = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_CENTER_SCROLL)
        self._checkCenterScroll.setChecked(settings.CENTER_ON_SCROLL)
        vboxg6.addWidget(self._checkCenterScroll)
        self._checkTrailing = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING)
        self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES)
        vboxg6.addWidget(self._checkTrailing)
        self._allowWordWrap = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP)
        self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP)
        vboxg6.addWidget(self._allowWordWrap)
        formFeatures.addWidget(group6, 3, 1)

        # pack all the groups
        vbox.addWidget(container_widget_with_all_preferences)
        vbox.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding,
                     QSizePolicy.Expanding))

        self.connect(self._preferences, SIGNAL("savePreferences()"), self.save)

    def _enable_check_inline(self, val):
        """Method that takes a value to enable the inline style checking"""
        if val == Qt.Checked:
            self._checkStyle.setChecked(True)

    def _enable_errors_inline(self, val):
        """Method that takes a value to enable the inline errors checking"""
        if val == Qt.Checked:
            self._checkErrors.setChecked(True)

    def _disable_check_style(self, val):
        """Method that takes a value to disable the inline style checking"""
        if val == Qt.Unchecked:
            self._checkStyleOnLine.setChecked(False)

    def _disable_show_errors(self, val):
        """Method that takes a value to disable the inline errors checking"""
        if val == Qt.Unchecked:
            self._showErrorsOnLine.setChecked(False)

    def save(self):
        """Method to save settings"""
        qsettings = IDE.ninja_settings()
        settings.USE_TABS = bool(self._checkUseTabs.currentIndex())
        qsettings.setValue('preferences/editor/useTabs',
                           settings.USE_TABS)
        margin_line = self._spinMargin.value()
        settings.MARGIN_LINE = margin_line
        settings.pep8mod_update_margin_line_length(margin_line)
        qsettings.setValue('preferences/editor/marginLine', margin_line)
        settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked()
        qsettings.setValue('preferences/editor/showMarginLine',
                           settings.SHOW_MARGIN_LINE)
        settings.INDENT = self._spin.value()
        qsettings.setValue('preferences/editor/indent', settings.INDENT)
        endOfLine = self._checkEndOfLine.isChecked()
        settings.USE_PLATFORM_END_OF_LINE = endOfLine
        qsettings.setValue('preferences/editor/platformEndOfLine', endOfLine)
        settings.UNDERLINE_NOT_BACKGROUND = \
            bool(self._checkHighlightLine.currentIndex())
        qsettings.setValue('preferences/editor/errorsUnderlineBackground',
                           settings.UNDERLINE_NOT_BACKGROUND)
        settings.FIND_ERRORS = self._checkErrors.isChecked()
        qsettings.setValue('preferences/editor/errors', settings.FIND_ERRORS)
        settings.ERRORS_HIGHLIGHT_LINE = self._showErrorsOnLine.isChecked()
        qsettings.setValue('preferences/editor/errorsInLine',
                           settings.ERRORS_HIGHLIGHT_LINE)
        settings.CHECK_STYLE = self._checkStyle.isChecked()
        qsettings.setValue('preferences/editor/checkStyle',
                           settings.CHECK_STYLE)
        settings.SHOW_MIGRATION_TIPS = self._showMigrationTips.isChecked()
        qsettings.setValue('preferences/editor/showMigrationTips',
                           settings.SHOW_MIGRATION_TIPS)
        settings.CHECK_HIGHLIGHT_LINE = self._checkStyleOnLine.isChecked()
        qsettings.setValue('preferences/editor/checkStyleInline',
                           settings.CHECK_HIGHLIGHT_LINE)
        settings.CENTER_ON_SCROLL = self._checkCenterScroll.isChecked()
        qsettings.setValue('preferences/editor/centerOnScroll',
                           settings.CENTER_ON_SCROLL)
        settings.REMOVE_TRAILING_SPACES = self._checkTrailing.isChecked()
        qsettings.setValue('preferences/editor/removeTrailingSpaces',
                           settings.REMOVE_TRAILING_SPACES)
        settings.ALLOW_WORD_WRAP = self._allowWordWrap.isChecked()
        qsettings.setValue('preferences/editor/allowWordWrap',
                           settings.ALLOW_WORD_WRAP)
        settings.SHOW_TABS_AND_SPACES = self._checkShowSpaces.isChecked()
        qsettings.setValue('preferences/editor/showTabsAndSpaces',
                           settings.SHOW_TABS_AND_SPACES)
        settings.SHOW_INDENTATION_GUIDE = (
            self._checkIndentationGuide.isChecked())
        qsettings.setValue('preferences/editor/showIndentationGuide',
                           settings.SHOW_INDENTATION_GUIDE)
        settings.CHECK_FOR_DOCSTRINGS = self._checkForDocstrings.isChecked()
        qsettings.setValue('preferences/editor/checkForDocstrings',
                           settings.CHECK_FOR_DOCSTRINGS)

        if settings.USE_TABS:
            settings.pep8mod_add_ignore("W191")
        else:
            settings.pep8mod_remove_ignore("W191")
        settings.pep8mod_refresh_checks()
Beispiel #56
0
class YPipeWidget(QWidget):
    def __init__(self, leftFlow=0, rightFlow=0, maxFlow=100, parent=None):
        super(YPipeWidget, self).__init__(parent)

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

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

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

        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.setMinimumSize(self.minimumSizeHint())
        self.valueChanged()

    def valueChanged(self):
        a = self.leftSpinBox.value()
        b = self.rightSpinBox.value()
        self.label.setText("{0} l/s".format(a + b))
        self.emit(SIGNAL("valueChanged"), a, b)
        self.update()

    def values(self):
        return self.leftSpinBox.value(), self.rightSpinBox.value()

    def minimumSizeHint(self):
        return QSize(self.leftSpinBox.width() * 3,
                     self.leftSpinBox.height() * 5)

    def resizeEvent(self, event=None):
        fm = QFontMetricsF(self.font())
        x = (self.width() - self.label.width()) / 2
        y = self.height() - (fm.height() * 1.5)
        self.label.move(x, y)
        y = self.height() / 60.0
        x = (self.width() / 4.0) - self.leftSpinBox.width()
        self.leftSpinBox.move(x, y)
        x = self.width() - (self.width() / 4.0)
        self.rightSpinBox.move(x, y)

    def paintEvent(self, event=None):
        LogicalSize = 100.0

        def logicalFromPhysical(length, side):
            return (length / side) * LogicalSize

        fm = QFontMetricsF(self.font())
        ymargin = (
            (LogicalSize / 30.0) +
            logicalFromPhysical(self.leftSpinBox.height(), self.height()))
        ymax = (LogicalSize -
                logicalFromPhysical(fm.height() * 2, self.height()))
        width = LogicalSize / 4.0
        cx, cy = LogicalSize / 2.0, LogicalSize / 3.0
        ax, ay = cx - (2 * width), ymargin
        bx, by = cx - width, ay
        dx, dy = cx + width, ay
        ex, ey = cx + (2 * width), ymargin
        fx, fy = cx + (width / 2), cx + (LogicalSize / 24.0)
        gx, gy = fx, ymax
        hx, hy = cx - (width / 2), ymax
        ix, iy = hx, fy

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        side = min(self.width(), self.height())
        painter.setViewport((self.width() - side) / 2,
                            (self.height() - side) / 2, side, side)
        painter.setWindow(0, 0, LogicalSize, LogicalSize)

        painter.setPen(Qt.NoPen)

        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        a = self.leftSpinBox.value()
        gradient.setColorAt(1, (Qt.red if a != 0 else Qt.white))
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([ax, ay, bx, by, cx, cy, ix, iy]))

        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        b = self.rightSpinBox.value()
        gradient.setColorAt(1, (Qt.blue if b != 0 else Qt.white))
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([cx, cy, dx, dy, ex, ey, fx, fy]))

        if (a + b) == 0:
            color = QColor(Qt.white)
        else:
            ashare = (a / (a + b)) * 255.0
            bshare = 255.0 - ashare
            color = QColor(ashare, 0, bshare)
        gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100))
        gradient.setColorAt(0, Qt.white)
        gradient.setColorAt(1, color)
        painter.setBrush(QBrush(gradient))
        painter.drawPolygon(QPolygon([cx, cy, fx, fy, gx, gy, hx, hy, ix, iy]))

        painter.setPen(Qt.black)
        painter.drawPolyline(QPolygon([ax, ay, ix, iy, hx, hy]))
        painter.drawPolyline(QPolygon([gx, gy, fx, fy, ex, ey]))
        painter.drawPolyline(QPolygon([bx, by, cx, cy, dx, dy]))
Beispiel #57
0
class Window(QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.image = QImage()
        self.dirty = False
        self.filename = None
        self.mirroredvertically = False
        self.mirroredhorizontally = False
        self.printer = None
        self.create_widgets()
        self.create_actions()
        self.load_settings()
        self.setWindowTitle("Image Changer")
        self.updateFileMenu()
        QTimer.singleShot(0, self.loadInitialFile)

    def create_widgets(self):
        self.imageLabel = QLabel()
        self.imageLabel.setMinimumSize(200, 200)
        self.imageLabel.setAlignment(Qt.AlignCenter)
        self.imageLabel.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.setCentralWidget(self.imageLabel)

        logDockWidget = QDockWidget("Log", self)
        logDockWidget.setObjectName("LogDockWidget")
        logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea
                                      | Qt.RightDockWidgetArea)
        self.listWidget = QListWidget()
        logDockWidget.setWidget(self.listWidget)
        self.addDockWidget(Qt.RightDockWidgetArea, logDockWidget)

        self.sizeLabel = QLabel()
        self.sizeLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        status = self.statusBar()
        status.setSizeGripEnabled(False)
        status.addPermanentWidget(self.sizeLabel)
        status.showMessage("Ready", 5000)

    def create_actions(self):
        fileNewAction = self.createAction("&New...", self.fileNew,
                                          QKeySequence.New, "filenew",
                                          "Create an image file")
        fileOpenAction = self.createAction("&Open...", self.fileOpen,
                                           QKeySequence.Open, "fileopen",
                                           "Open an existing image file")
        fileSaveAction = self.createAction("&Save", self.fileSave,
                                           QKeySequence.Save, "filesave",
                                           "Save the image")
        fileSaveAsAction = self.createAction(
            "Save &As...",
            self.fileSaveAs,
            icon="filesaveas",
            tip="Save the image using a new name")
        filePrintAction = self.createAction("&Print", self.filePrint,
                                            QKeySequence.Print, "fileprint",
                                            "Print the image")
        fileQuitAction = self.createAction("&Quit", self.close, "Ctrl+Q",
                                           "filequit", "Close the application")
        editInvertAction = self.createAction("&Invert", None, "Ctrl+I",
                                             "editinvert",
                                             "Invert the image's colors", True)
        editInvertAction.toggled.connect(self.editInvert)
        editSwapRedAndBlueAction = self.createAction(
            "Sw&ap Red and Blue", None, "Ctrl+A", "editswap",
            "Swap the image's red and blue color components", True)
        editSwapRedAndBlueAction.toggled.connect(self.editSwapRedAndBlue)
        editZoomAction = self.createAction("&Zoom...", self.editZoom, "Alt+Z",
                                           "editzoom", "Zoom the image")
        mirrorGroup = QActionGroup(self)
        editUnMirrorAction = self.createAction("&Unmirror", None, "Ctrl+U",
                                               "editunmirror",
                                               "Unmirror the image", True)
        editUnMirrorAction.toggled.connect(self.editUnMirror)
        mirrorGroup.addAction(editUnMirrorAction)
        editMirrorHorizontalAction = self.createAction(
            "Mirror &Horizontally", None, "Ctrl+H", "editmirrorhoriz",
            "Horizontally mirror the image", True)
        editMirrorHorizontalAction.toggled.connect(self.editMirrorHorizontal)
        mirrorGroup.addAction(editMirrorHorizontalAction)
        editMirrorVerticalAction = self.createAction(
            "Mirror &Vertically", None, "Ctrl+V", "editmirrorvert",
            "Vertically mirror the image", True)
        editMirrorVerticalAction.toggled.connect(self.editMirrorVertical)
        mirrorGroup.addAction(editMirrorVerticalAction)
        editUnMirrorAction.setChecked(True)
        helpAboutAction = self.createAction("&About Image Changer",
                                            self.helpAbout)
        helpHelpAction = self.createAction("&Help", self.helpHelp,
                                           QKeySequence.HelpContents)

        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenuActions = (fileNewAction, fileOpenAction, fileSaveAction,
                                fileSaveAsAction, None, filePrintAction,
                                fileQuitAction)
        self.fileMenu.aboutToShow.connect(self.updateFileMenu)
        editMenu = self.menuBar().addMenu("&Edit")
        self.addActions(
            editMenu,
            (editInvertAction, editSwapRedAndBlueAction, editZoomAction))
        mirrorMenu = editMenu.addMenu(QIcon(":/editmirror.png"), "&Mirror")
        self.addActions(mirrorMenu,
                        (editUnMirrorAction, editMirrorHorizontalAction,
                         editMirrorVerticalAction))
        helpMenu = self.menuBar().addMenu("&Help")
        self.addActions(helpMenu, (helpAboutAction, helpHelpAction))

        fileToolbar = self.addToolBar("File")
        fileToolbar.setObjectName("FileToolBar")
        self.addActions(fileToolbar,
                        (fileNewAction, fileOpenAction, fileSaveAsAction))
        editToolbar = self.addToolBar("Edit")
        editToolbar.setObjectName("EditToolBar")
        self.addActions(
            editToolbar,
            (editInvertAction, editSwapRedAndBlueAction, editUnMirrorAction,
             editMirrorVerticalAction, editMirrorHorizontalAction))
        self.zoomSpinBox = QSpinBox()
        self.zoomSpinBox.setRange(1, 400)
        self.zoomSpinBox.setSuffix(" %")
        self.zoomSpinBox.setValue(100)
        self.zoomSpinBox.setToolTip("Zoom the image")
        self.zoomSpinBox.setStatusTip(self.zoomSpinBox.toolTip())
        self.zoomSpinBox.setFocusPolicy(Qt.NoFocus)
        self.zoomSpinBox.valueChanged.connect(self.showImage)
        editToolbar.addWidget(self.zoomSpinBox)

        self.addActions(
            self.imageLabel,
            (editInvertAction, editSwapRedAndBlueAction, editUnMirrorAction,
             editMirrorVerticalAction, editMirrorHorizontalAction))

        self.resetableActions = ((editInvertAction,
                                  False), (editSwapRedAndBlueAction, False),
                                 (editUnMirrorAction, True))

    def load_settings(self):
        settings = QSettings()
        self.recentFiles = settings.value("RecentFiles").toStringList()
        self.restoreGeometry(
            settings.value("MainWindow/Geometry").toByteArray())
        self.restoreState(settings.value("MainWindow/State").toByteArray())

    def createAction(self,
                     text,
                     slot=None,
                     shortcut=None,
                     icon=None,
                     tip=None,
                     checkable=False):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/{0}.png".format(icon)))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)
        if checkable:
            action.setCheckable(True)
        return action

    def addActions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def closeEvent(self, event):
        if self.okToContinue():
            settings = QSettings()
            filename = (QVariant(QString(self.filename))
                        if self.filename is not None else QVariant())
            settings.setValue("LastFile", filename)
            recentFiles = (QVariant(self.recentFiles)
                           if self.recentFiles else QVariant())
            settings.setValue("RecentFiles", recentFiles)
            settings.setValue("MainWindow/Geometry",
                              QVariant(self.saveGeometry()))
            settings.setValue("MainWindow/State", QVariant(self.saveState()))
        else:
            event.ignore()

    def okToContinue(self):
        if self.dirty:
            reply = QMessageBox.question(
                self, "Image Changer - Unsaved Changes",
                "Save unsaved changes?",
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
            if reply == QMessageBox.Cancel:
                return False
            elif reply == QMessageBox.Yes:
                return self.fileSave()
        return True

    def loadInitialFile(self):
        settings = QSettings()
        fname = unicode(settings.value("LastFile").toString())
        if fname and QFile.exists(fname):
            self.loadFile(fname)

    def updateStatus(self, message):
        self.statusBar().showMessage(message, 5000)
        self.listWidget.addItem(message)
        if self.filename is not None:
            self.setWindowTitle("Image Changer - {0}[*]".format(
                os.path.basename(self.filename)))
        elif not self.image.isNull():
            self.setWindowTitle("Image Changer - Unnamed[*]")
        else:
            self.setWindowTitle("Image Changer[*]")
        self.setWindowModified(self.dirty)

    def updateFileMenu(self):
        self.fileMenu.clear()
        self.addActions(self.fileMenu, self.fileMenuActions[:-1])
        current = (QString(self.filename)
                   if self.filename is not None else None)
        recentFiles = []
        for fname in self.recentFiles:
            if fname != current and QFile.exists(fname):
                recentFiles.append(fname)
        if recentFiles:
            self.fileMenu.addSeparator()
            for i, fname in enumerate(recentFiles):
                action = QAction(
                    QIcon(":/icon.png"),
                    "&{0} {1}".format(i + 1,
                                      QFileInfo(fname).fileName()), self)
                action.setData(QVariant(fname))
                action.triggered.connect(self.loadFile)
                self.fileMenu.addAction(action)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.fileMenuActions[-1])

    def fileNew(self):
        if not self.okToContinue():
            return
        dialog = newimagedlg.NewImageDlg(self)
        if dialog.exec_():
            self.addRecentFile(self.filename)
            self.image = QImage()
            for action, check in self.resetableActions:
                action.setChecked(check)
            self.image = dialog.image()
            self.filename = None
            self.dirty = True
            self.showImage()
            self.sizeLabel.setText("{0} x {1}".format(self.image.width(),
                                                      self.image.height()))
            self.updateStatus("Created new image")

    def fileOpen(self):
        if not self.okToContinue():
            return
        dir = (os.path.dirname(self.filename)
               if self.filename is not None else ".")
        formats = ([
            "*.{0}".format(unicode(format).lower())
            for format in QImageReader.supportedImageFormats()
        ])
        fname = unicode(
            QFileDialog.getOpenFileName(
                self, "Image Changer - Choose Image", dir,
                "Image files ({0})".format(" ".join(formats))))
        if fname:
            self.loadFile(fname)

    def loadFile(self, fname=None):
        if fname is None:
            action = self.sender()
            if isinstance(action, QAction):
                fname = unicode(action.data().toString())
                if not self.okToContinue():
                    return
            else:
                return
        if fname:
            self.filename = None
            image = QImage(fname)
            if image.isNull():
                message = "Failed to read {0}".format(fname)
            else:
                self.addRecentFile(fname)
                self.image = QImage()
                for action, check in self.resetableActions:
                    action.setChecked(check)
                self.image = image
                self.filename = fname
                self.showImage()
                self.dirty = False
                self.sizeLabel.setText("{0} x {1}".format(
                    image.width(), image.height()))
                message = "Loaded {0}".format(os.path.basename(fname))
            self.updateStatus(message)

    def addRecentFile(self, fname):
        if fname is None:
            return
        if not self.recentFiles.contains(fname):
            self.recentFiles.prepend(QString(fname))
            while self.recentFiles.count() > 9:
                self.recentFiles.takeLast()

    def fileSave(self):
        if self.image.isNull():
            return True
        if self.filename is None:
            return self.fileSaveAs()
        else:
            if self.image.save(self.filename, None):
                self.updateStatus("Saved as {0}".format(self.filename))
                self.dirty = False
                return True
            else:
                self.updateStatus("Failed to save {0}".format(self.filename))
                return False

    def fileSaveAs(self):
        if self.image.isNull():
            return True
        fname = self.filename if self.filename is not None else "."
        formats = ([
            "*.{0}".format(unicode(format).lower())
            for format in QImageWriter.supportedImageFormats()
        ])
        fname = unicode(
            QFileDialog.getSaveFileName(
                self, "Image Changer - Save Image", fname,
                "Image files ({0})".format(" ".join(formats))))
        if fname:
            if "." not in fname:
                fname += ".png"
            self.addRecentFile(fname)
            self.filename = fname
            return self.fileSave()
        return False

    def filePrint(self):
        if self.image.isNull():
            return
        if self.printer is None:
            self.printer = QPrinter(QPrinter.HighResolution)
            self.printer.setPageSize(QPrinter.Letter)
        form = QPrintDialog(self.printer, self)
        if form.exec_():
            painter = QPainter(self.printer)
            rect = painter.viewport()
            size = self.image.size()
            size.scale(rect.size(), Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(),
                                size.height())
            painter.drawImage(0, 0, self.image)

    def editInvert(self, on):
        if self.image.isNull():
            return
        self.image.invertPixels()
        self.showImage()
        self.dirty = True
        self.updateStatus("Inverted" if on else "Uninverted")

    def editSwapRedAndBlue(self, on):
        if self.image.isNull():
            return
        self.image = self.image.rgbSwapped()
        self.showImage()
        self.dirty = True
        self.updateStatus(
            ("Swapped Red and Blue" if on else "Unswapped Red and Blue"))

    def editUnMirror(self, on):
        if self.image.isNull():
            return
        if self.mirroredhorizontally:
            self.editMirrorHorizontal(False)
        if self.mirroredvertically:
            self.editMirrorVertical(False)

    def editMirrorHorizontal(self, on):
        if self.image.isNull():
            return
        self.image = self.image.mirrored(True, False)
        self.showImage()
        self.mirroredhorizontally = not self.mirroredhorizontally
        self.dirty = True
        self.updateStatus(
            ("Mirrored Horizontally" if on else "Unmirrored Horizontally"))

    def editMirrorVertical(self, on):
        if self.image.isNull():
            return
        self.image = self.image.mirrored(False, True)
        self.showImage()
        self.mirroredvertically = not self.mirroredvertically
        self.dirty = True
        self.updateStatus(
            ("Mirrored Vertically" if on else "Unmirrored Vertically"))

    def editZoom(self):
        if self.image.isNull():
            return
        percent, ok = QInputDialog.getInteger(self, "Image Changer - Zoom",
                                              "Percent:",
                                              self.zoomSpinBox.value(), 1, 400)
        if ok:
            self.zoomSpinBox.setValue(percent)

    def showImage(self, percent=None):
        if self.image.isNull():
            return
        if percent is None:
            percent = self.zoomSpinBox.value()
        factor = percent / 100.0
        width = self.image.width() * factor
        height = self.image.height() * factor
        image = self.image.scaled(width, height, Qt.KeepAspectRatio)
        self.imageLabel.setPixmap(QPixmap.fromImage(image))

    def helpAbout(self):
        QMessageBox.about(
            self, "About Image Changer", """<b>Image Changer</b> v {0}
                <p>Copyright &copy; 2008-14 Qtrac Ltd. 
                All rights reserved.
                <p>This application can be used to perform
                simple image manipulations.
                <p>Python {1} - Qt {2} - PyQt {3} on {4}""".format(
                __version__, platform.python_version(), QT_VERSION_STR,
                PYQT_VERSION_STR, platform.system()))

    def helpHelp(self):
        form = helpform.HelpForm("index.html", self)
        form.show()
 def createEditor(self, parent, option, index):
     spinbox = QSpinBox(parent)
     spinbox.setRange(self.minimum, self.maximum)
     spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
     return spinbox