Exemplo n.º 1
1
    def setup_toolbar(self):
        color_widget = ColorWidget()
        color_widget.color_changed.connect(self.fourier.on_color_change)
        self.toolBar.addWidget(QLabel("Color:"))
        self.toolBar.addWidget(color_widget)

        self.toolBar.addWidget(QLabel("Shape:"))
        size_spin = QSpinBox(self.toolBar)
        size_spin.setValue(20)
        size_spin.valueChanged[int].connect(self.fourier.on_size_change)

        shape_combo = QComboBox(self.toolBar)
        shape_combo.activated[str].connect(self.fourier.on_shape_change)
        shape_combo.addItems(brush_shapes)

        self.toolBar.addWidget(shape_combo)
        self.toolBar.addWidget(size_spin)

        self.toolBar.addWidget(QLabel("Symmetry:"))
        x_sym = QCheckBox(self.toolBar)
        x_sym.toggled.connect(self.fourier.on_x_toggle)

        opp_sym = QCheckBox(self.toolBar)
        opp_sym.toggled.connect(self.fourier.on_opp_toggle)
        self.toolBar.addWidget(QLabel("X"))
        self.toolBar.addWidget(x_sym)

        y_sym = QCheckBox(self.toolBar)
        y_sym.toggled.connect(self.fourier.on_y_toggle)
        self.toolBar.addWidget(QLabel("Y"))
        self.toolBar.addWidget(y_sym)
        self.toolBar.addWidget(QLabel("Center"))
        self.toolBar.addWidget(opp_sym)
    def initUi(self):
        self.grid = QGridLayout()
        self.grid.addWidget(QLabel("Connection name"), 0, 0)
        self.grid.addWidget(QLabel("Username"), 2, 0)
        self.grid.addWidget(QLabel("Password"), 4, 0)
        self.grid.addWidget(QLabel("Hostname"), 6, 0)
        self.grid.addWidget(QLabel("Port"), 8, 0)
        self.connectionNameInput =  QLineEdit(self)
        self.grid.addWidget(self.connectionNameInput, 1, 0)
        self.userNameInput =  QLineEdit(self)
        self.grid.addWidget(self.userNameInput, 3, 0)
        self.passwordInput =  QLineEdit(self)
        self.grid.addWidget(self.passwordInput, 5, 0)
        self.hostnameInput =  QLineEdit(self)
        self.grid.addWidget(self.hostnameInput, 7, 0)
        self.portSpinBox =  QSpinBox(self)
        self.portSpinBox.setMinimum(1)
        self.portSpinBox.setMaximum(65535)
        self.portSpinBox.setValue(22)
        self.grid.addWidget(self.portSpinBox, 9, 0)
        self.addButton = QPushButton("Accept")
        self.grid.addWidget(self.addButton, 10, 0)
        self.setLayout(self.grid)

        self.addButton.clicked.connect(self.clickedAddButton)

        self.show()
Exemplo n.º 3
0
    def setup_toolbar(self):
        color_widget = ColorWidget()
        color_widget.color_changed.connect(self.fourier.on_color_change)
        self.toolBar.addWidget(QLabel("Color:"))
        self.toolBar.addWidget(color_widget)

        self.toolBar.addWidget(QLabel("Shape:"))
        size_spin = QSpinBox(self.toolBar)
        size_spin.setValue(20)
        size_spin.valueChanged[int].connect(self.fourier.on_size_change)

        shape_combo = QComboBox(self.toolBar)
        shape_combo.activated[str].connect(self.fourier.on_shape_change)
        shape_combo.addItems(brush_shapes)

        self.toolBar.addWidget(shape_combo)
        self.toolBar.addWidget(size_spin)

        self.toolBar.addWidget(QLabel("Symmetry:"))
        x_sym = QCheckBox(self.toolBar)
        x_sym.toggled.connect(self.fourier.on_x_toggle)

        opp_sym = QCheckBox(self.toolBar)
        opp_sym.toggled.connect(self.fourier.on_opp_toggle)
        self.toolBar.addWidget(QLabel("X"))
        self.toolBar.addWidget(x_sym)

        y_sym = QCheckBox(self.toolBar)
        y_sym.toggled.connect(self.fourier.on_y_toggle)
        self.toolBar.addWidget(QLabel("Y"))
        self.toolBar.addWidget(y_sym)
        self.toolBar.addWidget(QLabel("Center"))
        self.toolBar.addWidget(opp_sym)
Exemplo n.º 4
0
    def _initUI(self):
        # Widgets
        self._brw_pendbase = DirBrowseWidget()

        self._brw_exe = FileBrowseWidget()
        if os.name == 'nt':
            self._brw_exe.setNameFilter('Application files (*.exe)')
        else:
            self._brw_exe.setNameFilter('Application files (*)')

        self._spn_dumpp = QSpinBox()
        self._spn_dumpp.setMinimum(30)
        self._spn_dumpp.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        # Layouts
        layout = _ConfigurePanelWidget._initUI(self)
        layout.addRow("Path to pendbase directory", self._brw_pendbase)
        layout.addRow('Path to PENEPMA executable', self._brw_exe)
        layout.addRow('Interval between dump (s)', self._spn_dumpp)

        # Signals
        self._brw_pendbase.pathChanged.connect(self._onPathChanged)
        self._brw_exe.pathChanged.connect(self._onPathChanged)

        return layout
Exemplo n.º 5
0
    class SpinBoxPySlot(UsesQApplication, BasicPySlotCase):
        """Tests the connection of python slots to QSpinBox signals"""

        def setUp(self):
            super(SpinBoxPySlot, self).setUp()
            self.spin = QSpinBox()

        def tearDown(self):
            del self.spin
            super(SpinBoxPySlot, self).tearDown()

        def testSpinBoxValueChanged(self):
            """Connection of a python slot to QSpinBox.valueChanged(int)"""
            QObject.connect(self.spin, SIGNAL('valueChanged(int)'), self.cb)
            self.args = [3]
            self.spin.emit(SIGNAL('valueChanged(int)'), *self.args)
            self.assert_(self.called)

        def testSpinBoxValueChangedImplicit(self):
            """Indirect qt signal emission using QSpinBox.setValue(int)"""
            QObject.connect(self.spin, SIGNAL('valueChanged(int)'), self.cb)
            self.args = [42]
            self.spin.setValue(self.args[0])
            self.assert_(self.called)

        def atestSpinBoxValueChangedFewArgs(self):
            """Emission of signals with fewer arguments than needed"""
            # XXX: PyQt4 crashes on the assertRaises
            QObject.connect(self.spin, SIGNAL('valueChanged(int)'), self.cb)
            self.args = (554,)
            self.assertRaises(TypeError, self.spin.emit, SIGNAL('valueChanged(int)'))
Exemplo n.º 6
0
    class SpinBoxPySlot(UsesQApplication, BasicPySlotCase):
        """Tests the connection of python slots to QSpinBox signals"""

        def setUp(self):
            super(SpinBoxPySlot, self).setUp()
            self.spin = QSpinBox()

        def tearDown(self):
            del self.spin
            super(SpinBoxPySlot, self).tearDown()

        def testSpinBoxValueChanged(self):
            """Connection of a python slot to QSpinBox.valueChanged(int)"""
            QObject.connect(self.spin, SIGNAL('valueChanged(int)'), self.cb)
            self.args = [3]
            self.spin.emit(SIGNAL('valueChanged(int)'), *self.args)
            self.assert_(self.called)

        def testSpinBoxValueChangedImplicit(self):
            """Indirect qt signal emission using QSpinBox.setValue(int)"""
            QObject.connect(self.spin, SIGNAL('valueChanged(int)'), self.cb)
            self.args = [42]
            self.spin.setValue(self.args[0])
            self.assert_(self.called)

        def atestSpinBoxValueChangedFewArgs(self):
            """Emission of signals with fewer arguments than needed"""
            # XXX: PyQt4 crashes on the assertRaises
            QObject.connect(self.spin, SIGNAL('valueChanged(int)'), self.cb)
            self.args = (554,)
            self.assertRaises(TypeError, self.spin.emit, SIGNAL('valueChanged(int)'))
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent
        self.setWindowTitle("Calculate Salary")

        t = datetime.now()
        self.month = QComboBox()
        self.month.addItems([
            "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
            "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
        ])
        self.month.setCurrentIndex(t.month - 1)
        self.year = QSpinBox()
        self.year.setRange(1900, 3000)
        self.year.setValue(t.year)

        self.name = SearchBox(self)
        self.name.setPlaceholderText("Enter Name")

        self.name.returnPressed.connect(self.setIDList)
        self.nameList = []
        self.nameList = DatabaseManager.db.getEmployeeNameList()
        self.name.setList(self.nameList)
        self.name.setCurrentIndex(-1)

        self.id = QComboBox()
        self.id.currentIndexChanged.connect(
            lambda: self.loadInfo(self.id.currentText()))

        self.designation = QLineEdit()
        self.designation.setReadOnly(True)
        self.originalPay = QLineEdit()
        self.originalPay.setReadOnly(True)
        self.originalPayGrade = QLineEdit()
        self.originalPayGrade.setReadOnly(True)
        self.DOJ = QLineEdit()
        self.DOJ.setReadOnly(True)
        self.pan = QLineEdit()
        self.pan.setReadOnly(True)

        self.presentPay = QLineEdit()
        self.presentPay.setReadOnly(True)
        self.da_percent = ValueBox()
        self.hra_percent = ValueBox()
        self.ta_percent = ValueBox()
        self.it_percent = ValueBox()
        self.pt_percent = ValueBox()

        self.name.editTextChanged.connect(self.clearInfo)

        self.bttnCalculate = QPushButton("Calculate")
        self.bttnCalculate.clicked.connect(self.calculate)
        self.bttnCancel = QPushButton("Back")
        self.bttnCancel.clicked.connect(self.goBack)
        self.bttnCalculate.setObjectName("OkButton")
        self.bttnCancel.setObjectName("CancelButton")

        self.setupUI()
Exemplo n.º 8
0
	def __init__(self):
		self.plate			= QLineEdit()
		self.parents		= QSpinBox()
		self.samples		= QSpinBox()
		self.loadedBy		= QComboBox()
		self.parents.setMaximum(8)
		self.parents.setValue(2)
		self.samples.setMaximum(96)
		self.samples.setValue(94)
		self.loadedBy.addItems(['Column','Row'])
Exemplo n.º 9
0
 def testSpinButton(self):
     #Connecting a lambda to a QPushButton.clicked()
     obj = QSpinBox()
     ctr = Control()
     arg = 444
     func = lambda x: setattr(ctr, 'arg', 444)
     QObject.connect(obj, SIGNAL('valueChanged(int)'), func)
     obj.setValue(444)
     self.assertEqual(ctr.arg, arg)
     QObject.disconnect(obj, SIGNAL('valueChanged(int)'), func)
class StackSizeCompound(QGroupBox):
  def __init__(self, parent=None):
    super(StackSizeCompound, self).__init__(parent)
    self.setTitle("Stack size")
    self.spinbox_stacksize = QSpinBox()
    self.spinbox_stacksize.setMaximum(9999)
    self.spinbox_stacksize.setMinimumWidth(100)
    layout = QHBoxLayout()
    layout.addWidget(self.spinbox_stacksize)
    self.setLayout(layout)
Exemplo n.º 11
0
 def testSpinButton(self):
     #Connecting a lambda to a QPushButton.clicked()
     obj = QSpinBox()
     ctr = Control()
     arg = 444
     func = lambda x: setattr(ctr, 'arg', 444)
     QObject.connect(obj, SIGNAL('valueChanged(int)'), func)
     obj.setValue(444)
     self.assertEqual(ctr.arg, arg)
     QObject.disconnect(obj, SIGNAL('valueChanged(int)'), func)
Exemplo n.º 12
0
 def create_spinbox(self, prefix, suffix, option, default=NoDefault,
                    min_=None, max_=None, step=None, tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[option] = spinbox
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
Exemplo n.º 13
0
    def __init__(self, fixtures_folder, parent=None):
        QWidget.__init__(self, parent)
        self.current_fixture = None
        self.fixtures_folder = fixtures_folder
        self.setWindowTitle("Frangitron DMX program editor")

        self.text = QPlainTextEdit()
        font = QFont("Monospace")
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(16)
        self.text.setFont(font)
        self.text.setStyleSheet(
            "color: white; background-color: rgb(30, 30, 30)")

        self.combo_fixture = QComboBox()

        self.frame_programs = QWidget()
        self.checkboxes_programs = list()
        self.layout_programs = QGridLayout(self.frame_programs)

        self.spinner_offset = QSpinBox()
        self.spinner_offset.setMinimum(1)
        self.spinner_offset.setMaximum(512)
        self.spinner_offset.setValue(1)
        self.spinner_offset.valueChanged.connect(self.address_changed)

        self.doc = QPlainTextEdit()
        self.doc.setReadOnly(True)
        self.doc.setFont(font)

        self.status = QLabel()

        layout = QGridLayout(self)
        layout.addWidget(self.combo_fixture, 0, 1)
        layout.addWidget(self.spinner_offset, 0, 2)
        layout.addWidget(self.frame_programs, 1, 1)
        layout.addWidget(self.text, 0, 0, 3, 1)
        layout.addWidget(self.doc, 2, 1, 1, 2)
        layout.addWidget(self.status, 3, 0, 1, 3)
        layout.setColumnStretch(0, 60)
        layout.setColumnStretch(1, 40)

        self.resize(1280, 800)

        self.streamer = Streamer(self.fixtures_folder)

        self.combo_fixture.addItems(sorted(self.streamer.fixtures))
        self.combo_fixture.currentIndexChanged.connect(self.fixture_changed)

        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.timer.start(500.0 / FRAMERATE)
        self.should_reload = True

        self.fixture_changed()
Exemplo n.º 14
0
    def createBinaryOptions(self):
        """
        Binary Analysis Options
        """
        groupBox = QtGui.QGroupBox('Binary Analysis')

        # Elements
        cbs_unique_str = QCheckBox('Show unique strings', self)
        cbs_unique_com = QCheckBox('Show unique comments', self)
        cbs_unique_calls = QCheckBox('Show unique calls', self)
        cbs_entropy = QCheckBox('Calculate entropy', self)
        cutoff_label = QLabel('Connect BB cutoff')
        sb_cutoff = QSpinBox()
        sb_cutoff.setRange(1, 40)
        cutoff_func_label = QLabel('Connect functions cutoff')
        sbf_cutoff = QSpinBox()
        sbf_cutoff.setRange(1, 40)

        # Default states are read from the Config
        # class and reflected in the GUI
        cbs_unique_str.setCheckState(
            self.get_state(self.config.display_unique_strings))
        cbs_unique_com.setCheckState(
            self.get_state(self.config.display_unique_comments))
        cbs_unique_calls.setCheckState(
            self.get_state(self.config.display_unique_calls))
        cbs_entropy.setCheckState(
            self.get_state(self.config.calculate_entropy))
        sb_cutoff.setValue(self.config.connect_bb_cutoff)
        sbf_cutoff.setValue(self.config.connect_func_cutoff)

        # Connect elements and signals
        cbs_unique_str.stateChanged.connect(self.string_unique)
        cbs_unique_com.stateChanged.connect(self.comment_unique)
        cbs_unique_calls.stateChanged.connect(self.calls_unique)
        cbs_entropy.stateChanged.connect(self.string_entropy)
        sb_cutoff.valueChanged[int].connect(self.set_cutoff)
        sb_cutoff.valueChanged[int].connect(self.set_func_cutoff)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(cbs_unique_str)
        vbox.addWidget(cbs_unique_com)
        vbox.addWidget(cbs_unique_calls)
        vbox.addWidget(cbs_entropy)
        vbox.addWidget(cutoff_label)
        vbox.addWidget(sb_cutoff)
        vbox.addWidget(cutoff_func_label)
        vbox.addWidget(sbf_cutoff)
        vbox.addStretch(1)

        groupBox.setLayout(vbox)

        return groupBox
Exemplo n.º 15
0
class CreateSamplesRow():
	def __init__(self):
		self.plate			= QLineEdit()
		self.parents		= QSpinBox()
		self.samples		= QSpinBox()
		self.loadedBy		= QComboBox()
		self.parents.setMaximum(8)
		self.parents.setValue(2)
		self.samples.setMaximum(96)
		self.samples.setValue(94)
		self.loadedBy.addItems(['Column','Row'])
	def getPlate(self):			return self.plate.text()
	def getParents(self):		return self.parents.value()
	def getSamples(self):		return self.samples.value()
	def getLoadedBy(self):		return self.loadedBy.currentText()
Exemplo n.º 16
0
        def testSetValueIndirect(self):
            """Indirect signal emission: QSpinBox using valueChanged(int)/setValue(int)"""
            spinSend = QSpinBox()
            spinRec = QSpinBox()

            spinRec.setValue(5)

            QObject.connect(spinSend, SIGNAL('valueChanged(int)'), spinRec, SLOT('setValue(int)'))
            self.assertEqual(spinRec.value(), 5)
            spinSend.setValue(3)
            self.assertEqual(spinRec.value(), 3)
            self.assertEqual(spinSend.value(), 3)
 def testSpinBoxValueChanged(self):
     """Multiple connections to QSpinBox.valueChanged(int)"""
     sender = QSpinBox()
     #FIXME if number of receivers if higher than 50, segfaults
     receivers = [BasicPySlotCase() for x in range(10)]
     self.run_many(sender, 'valueChanged(int)', sender.setValue,
                   receivers, (1, ))
    def createEditor(self, parent, option, index):
        if not index.isValid():
            return QSqlRelationalDelegate.createEditor(self, parent, option,
                                                       index)

        if index.column() in self.__read_only:
            return None
        elif index.column() in self.__dates:
            return QDateEdit(QDate.currentDate(), parent)
        elif index.column() in self.__booleens:
            editor = QCheckBox("", parent)
            r = self.checkBoxRect(option, editor)
            rect = option.rect
            rect.moveTo(r.x(), r.y())
            rect.setWidth(r.width())
            rect.setHeight(r.height())
            editor.setGeometry(rect)
            editor.setAutoFillBackground(True)
            return editor
        elif index.column() in self.__numbers:
            editor = QSpinBox(parent)
            editor.setMinimum(0)
            editor.setMaximum(100)
            return editor
        return QSqlRelationalDelegate.createEditor(self, parent, option, index)
Exemplo n.º 19
0
    def insertRow(self, index, propertyName, label):
        propertyKey = self.resultSet.propertyKey(str(propertyName))

        propertyType = self.resultSet.propertyType(propertyKey)
        propertyAttributes = self.resultSet.propertyAttributes(propertyKey)

        widget = None

        if propertyAttributes & QGalleryProperty.CanWrite:
            if propertyType == str:
                widget = QLineEdit()
            elif propertyType == float:
                widget = QDoubleSpinBox()
            elif propertyType == int:
                widget = QSpinBox()
            elif propertyType == QDateTime:
                widget = QDateTimeEdit()
            else:
                widget = QLabel()
        elif propertyAttributes & QGalleryProperty.CanRead:
            widget = QLabel()

        self.propertyKeys.insert(index, propertyKey)
        self.widgets.insert(index, widget)

        self.layout().insertRow(index, label, widget)
Exemplo n.º 20
0
    def __init__(self):
        super(SliderWidget, self).__init__()

        self.label = QLabel()
        self.slider = QSlider(Qt.Horizontal)
        self.spinbox = QSpinBox()

        self.slider.valueChanged.connect(self.changedValue)
        self.spinbox.valueChanged.connect(self.changedValue)

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setVerticalSpacing(0)
        layout.addWidget(self.label, 0, 0)
        layout.addWidget(self.slider, 0, 1)
        layout.addWidget(self.spinbox, 0, 2)
        self.setLayout(layout)
Exemplo n.º 21
0
    def __init__(self,
                 parent,
                 North="Up",
                 East="Right",
                 South="Down",
                 West="Left",
                 BoxLabel='Power',
                 valueName='Position'):
        QWidget.__init__(self)
        self.North = North
        self.East = East
        self.South = South
        self.West = West
        self.boxLabel = BoxLabel
        buttonLayout = QGridLayout(self)
        northButton = QPushButton(self.North, self)
        #        northbutton.click(actionscript)

        eastButton = QPushButton(self.East, self)

        southButton = QPushButton(self.South, self)

        westButton = QPushButton(self.West, self)

        speedSlider = QSlider()
        speedSlider.setTickPosition(QSlider.TicksRight)
        speedSlider.setTickInterval(10)
        speedSlider.TicksRight
        sliderPosition = QSpinBox()
        sliderPosition.setRange(0, 101)
        sliderLabel = QLabel(self.boxLabel)
        speedSlider.valueChanged.connect(sliderPosition.setValue)
        sliderPosition.valueChanged.connect(speedSlider.setValue)
        SliderValue = speedSlider.value()
        speedSlider.valueChanged.connect(self.printValue)

        #Needs work to fix the layout issues......
        buttonLayout.addWidget(northButton, 1, 1)
        buttonLayout.addWidget(eastButton, 2, 2)
        buttonLayout.addWidget(westButton, 2, 0)
        buttonLayout.addWidget(southButton, 3, 1)
        buttonLayout.addWidget(sliderPosition, 1, 3)
        buttonLayout.addWidget(sliderLabel, 0, 3)
        buttonLayout.addWidget(speedSlider, 2, 3, 3, 3)

        self.setLayout(buttonLayout)
Exemplo n.º 22
0
    class SpinBoxPySignal(UsesQApplication):
        """Tests the connection of python signals to QSpinBox qt slots."""

        def setUp(self):
            super(SpinBoxPySignal, self).setUp()
            self.obj = Dummy()
            self.spin = QSpinBox()
            self.spin.setValue(0)

        def tearDown(self):
            super(SpinBoxPySignal, self).tearDown()
            del self.obj
            del self.spin

        def testValueChanged(self):
            """Emission of a python signal to QSpinBox setValue(int)"""
            QObject.connect(self.obj, SIGNAL('dummy(int)'), self.spin, SLOT('setValue(int)'))
            self.assertEqual(self.spin.value(), 0)

            self.obj.emit(SIGNAL('dummy(int)'), 4)
            self.assertEqual(self.spin.value(), 4)

        def testValueChangedMultiple(self):
            """Multiple emissions of a python signal to QSpinBox setValue(int)"""
            QObject.connect(self.obj, SIGNAL('dummy(int)'), self.spin, SLOT('setValue(int)'))
            self.assertEqual(self.spin.value(), 0)

            self.obj.emit(SIGNAL('dummy(int)'), 4)
            self.assertEqual(self.spin.value(), 4)

            self.obj.emit(SIGNAL('dummy(int)'), 77)
            self.assertEqual(self.spin.value(), 77)
Exemplo n.º 23
0
    def _create_age_view(self, read_only):
        if read_only:
            widget = QLabel(str(self._age))
        else:
            widget = QSpinBox()
            widget.setValue(self._age)
            widget.valueChanged.connect(self._update_age)

        return widget
    def _setup_ui(self):
        layout = QVBoxLayout()

        top_layout = QHBoxLayout()

        top_layout.addWidget(QLabel('Nodes:'))
        self.nodes_edit = QSpinBox(self)
        self.nodes_edit.setValue(50)
        top_layout.addWidget(self.nodes_edit)

        top_layout.addWidget(QLabel('Edges:'))
        self.edges_edit = QSpinBox(self)
        self.edges_edit.setValue(50)
        top_layout.addWidget(self.edges_edit)

        generate_button = QPushButton('Generate')
        generate_button.clicked.connect(self.generate)
        top_layout.addWidget(generate_button)

        top_layout.addWidget(QLabel('Start node:'))
        self.start_edit = QSpinBox(self)
        self.start_edit.setValue(0)
        top_layout.addWidget(self.start_edit)

        top_layout.addWidget(QLabel('Target:'))
        self.target_edit = QSpinBox(self)
        self.target_edit.setValue(25)
        top_layout.addWidget(self.target_edit)

        top_layout.addWidget(QLabel('Delta:'))
        self.delta_edit = QSpinBox(self)
        self.delta_edit.setValue(0)
        top_layout.addWidget(self.delta_edit)

        infect_button = QPushButton('Infect')
        infect_button.clicked.connect(self.infect)
        top_layout.addWidget(infect_button)

        layout.addLayout(top_layout)

        self.image_widget = QSvgWidget(self)
        layout.addWidget(self.image_widget)

        self.setLayout(layout)
Exemplo n.º 25
0
 def createGUI(self):
     self.series = QSpinBox()
     self.series.setMinimum(1)
     
     self.repetitions = QSpinBox()
     self.repetitions.setMaximum(512)
     
     self.avgHeartRateToggle = QCheckBox()
     self.avgHeartRateToggle.toggled.connect(self._toggleHeartRateSpinBox)
     
     self.avgHeartRate = QSpinBox()
     self.avgHeartRate.setMinimum(30)
     self.avgHeartRate.setMaximum(250)
     self.avgHeartRate.setValue(120)
     self.avgHeartRate.setDisabled(True)
     
     self.dateSelector_widget = QCalendarWidget()
     self.dateSelector_widget.setMaximumDate(QDate.currentDate())
     
     self.addButton = QPushButton("Add pushup")
     self.addButton.setMaximumWidth(90)
     self.addButton.clicked.connect(self._createPushup)
     
     self.cancelButton = QPushButton("Cancel")
     self.cancelButton.setMaximumWidth(90)
     self.cancelButton.clicked.connect(self.reject)
     
     self.pushupForm.addRow("Series", self.series)
     self.pushupForm.addRow("Repetitions", self.repetitions)
     self.pushupForm.addRow("Store average heart rate ? ", self.avgHeartRateToggle)
     self.pushupForm.addRow("Average Heart Rate", self.avgHeartRate)
     self.pushupForm.addRow("Exercise Date", self.dateSelector_widget)
     
     btnsLayout = QVBoxLayout()
     btnsLayout.addWidget(self.addButton)
     btnsLayout.addWidget(self.cancelButton)        
     btnsLayout.setAlignment(Qt.AlignRight)
     
     layoutWrapper = QVBoxLayout()
     layoutWrapper.addLayout(self.pushupForm)
     layoutWrapper.addLayout(btnsLayout)
     
     self.setLayout(layoutWrapper)        
 def __init__(self, parent=None):
   super(DoFPCompound, self).__init__(parent)
   self.setTitle("doFP")
   self.button_execute = QPushButton("Execute ...")
   self.spinbox_iterations = QSpinBox()
   self.spinbox_iterations.setMaximum(9999)
   self.spinbox_iterations.setValue(200)
   self.spinbox_iterations.setToolTip("No. iterations")
   layout = QHBoxLayout()
   layout.addWidget(self.spinbox_iterations)
   layout.addWidget(self.button_execute)
   self.setLayout(layout)
    def __init__(self, parent, North="Up", East="Right", South="Down", West="Left",BoxLabel='Power', valueName='Position'):
        QWidget.__init__(self)
        self.North = North
        self.East= East
        self.South = South
        self.West = West
        self.boxLabel = BoxLabel
        buttonLayout = QGridLayout(self)
        northButton = QPushButton(self.North, self)
#        northbutton.click(actionscript)
        
        eastButton = QPushButton(self.East, self)

        southButton = QPushButton(self.South, self)
        
        westButton = QPushButton(self.West, self)
        
        speedSlider = QSlider()
        speedSlider.setTickPosition(QSlider.TicksRight)
        speedSlider.setTickInterval(10)
        speedSlider.TicksRight
        sliderPosition = QSpinBox()
        sliderPosition.setRange(0,101)
        sliderLabel = QLabel(self.boxLabel)
        speedSlider.valueChanged.connect(sliderPosition.setValue)
        sliderPosition.valueChanged.connect(speedSlider.setValue)
        SliderValue = speedSlider.value()
        speedSlider.valueChanged.connect(self.printValue)
        
        #Needs work to fix the layout issues......
        buttonLayout.addWidget(northButton, 1, 1)
        buttonLayout.addWidget(eastButton, 2, 2)
        buttonLayout.addWidget(westButton, 2, 0)
        buttonLayout.addWidget(southButton, 3, 1)
        buttonLayout.addWidget(sliderPosition,1, 3)
        buttonLayout.addWidget(sliderLabel, 0, 3)
        buttonLayout.addWidget(speedSlider, 2, 3, 3,3)
        
        self.setLayout(buttonLayout)
Exemplo n.º 28
0
class AddWindow(QDialog):
    def __init__(self, parent=None):
        super(AddWindow, self).__init__(parent)
        self.setGeometry(QtCore.QRect(110, 40, 171, 160))

    def initUi(self):
        self.grid = QGridLayout()
        self.grid.addWidget(QLabel("Connection name"), 0, 0)
        self.grid.addWidget(QLabel("Username"), 2, 0)
        self.grid.addWidget(QLabel("Password"), 4, 0)
        self.grid.addWidget(QLabel("Hostname"), 6, 0)
        self.grid.addWidget(QLabel("Port"), 8, 0)
        self.connectionNameInput =  QLineEdit(self)
        self.grid.addWidget(self.connectionNameInput, 1, 0)
        self.userNameInput =  QLineEdit(self)
        self.grid.addWidget(self.userNameInput, 3, 0)
        self.passwordInput =  QLineEdit(self)
        self.grid.addWidget(self.passwordInput, 5, 0)
        self.hostnameInput =  QLineEdit(self)
        self.grid.addWidget(self.hostnameInput, 7, 0)
        self.portSpinBox =  QSpinBox(self)
        self.portSpinBox.setMinimum(1)
        self.portSpinBox.setMaximum(65535)
        self.portSpinBox.setValue(22)
        self.grid.addWidget(self.portSpinBox, 9, 0)
        self.addButton = QPushButton("Accept")
        self.grid.addWidget(self.addButton, 10, 0)
        self.setLayout(self.grid)

        self.addButton.clicked.connect(self.clickedAddButton)

        self.show()

    @Slot()
    def clickedAddButton(self):
        dataRep = DataRepository()
        host = self.hostnameInput.text()
        port = self.portSpinBox.value()
        pwd = self.passwordInput.text()
        login = self.userNameInput.text()
        name = self.connectionNameInput.text()
        dataRep.addConnection({
            'host':host,
            'port':port,
            'pwd':pwd,
            'login':login,
            'name':name
        })
        self.accept()
        self.close()

    def closeEvent(self, event):
            event.accept()
Exemplo n.º 29
0
    def __init__(self, state, parent=None, *, editableFontSize=False):
        super().__init__(parent)
        self.appState = state
        self.state = FormatState(self.appState, self)
        self.fontSizeSpinBox = None
        if editableFontSize:
            self.fontSizeSpinBox = QSpinBox()
            self.fontSizeSpinBox.setAlignment(Qt.AlignRight)
            self.fontSizeSpinBox.setFocusPolicy(Qt.NoFocus)
            self.fontSizeSpinBox.setRange(MIN_FONT_SIZE, MAX_FONT_SIZE)
            self.fontSizeSpinBox.setSuffix(" pt")
            self.fontSizeSpinBox.setValue(self.appState.stdFontSize)
            self.fontSizeSpinBox.setToolTip("""<p><b>Font Size</b></p>
<p>Set the font size in points.</p>""")
        self.formatActions = Actions.Format.Actions(
            self, self.fontSizeSpinBox)
        for action in self.formatActions.forToolbar():
            if action is not None:
                self.addAction(action)
            else:
                self.addSeparator()
        if editableFontSize:
            self.addWidget(self.fontSizeSpinBox)
Exemplo n.º 30
0
class NewMarkerDialog(QDialog):
	def __init__(self):
		super(NewMarkerDialog, self).__init__()
		self.setWindowTitle('Add new marker...')
		newMarkerLabel		= QLabel('Marker:')
		self.newMarker		= QLineEdit()
		includeLabel		= QLabel('Include all samples:')
		self.includeAll		= QCheckBox()
		controlsLabel		= QLabel('Control wells:')
		self.controls		= QSpinBox()
		self.controls.setRange(0,8)
		self.controls.setValue(2)
		layout				= QGridLayout()
		layout.addWidget(newMarkerLabel,0,0)
		layout.addWidget(self.newMarker,0,1)
		layout.addWidget(includeLabel,1,0)
		layout.addWidget(self.includeAll,1,1)
		layout.addWidget(controlsLabel,2,0)
		layout.addWidget(self.controls,2,1)
		self.buttons		= QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)	
		self.buttons.accepted.connect(self.accept)
		self.buttons.rejected.connect(self.reject)
		layout.addWidget(self.buttons,100,0,1,2)
		self.setLayout(layout)
	def getMarker(self):		return self.newMarker.text()
	def getIncludeAll(self):	return self.includeAll.isChecked()
	def getControls(self):		return self.controls.value()
 
	@staticmethod
	def run(parent = None):
		dialog				= NewMarkerDialog()
		result				= dialog.exec_()
		newMarker			= dialog.getMarker()
		includeAll			= dialog.getIncludeAll()
		controls			= dialog.getControls()
		return (newMarker,includeAll,controls,result == QDialog.Accepted)
Exemplo n.º 31
0
    def initUI(self):
        mainlay = QVBoxLayout()
        btns = QHBoxLayout()
        mainui = QGridLayout()

        mainlay.addLayout(mainui)
        mainlay.addLayout(btns)

        ok = QPushButton('OK')
        ok.clicked.connect(self.ok)
        cancel = QPushButton('Cancel')
        cancel.clicked.connect(self.close)

        btns.addStretch()
        btns.addWidget(ok)
        btns.addWidget(cancel)

        text1 = QLabel(self.tl)
        text2 = QLabel(self.tr)
        self.int1 = QSpinBox()
        self.int1.setMaximum(2048)
        self.int1.setMinimum(128)
        self.int1.setValue(self.default1)
        self.int2 = QSpinBox()
        self.int2.setMaximum(2048)
        self.int2.setMinimum(128)
        self.int2.setValue(self.default2)
        mainui.addWidget(text1, 0, 0)
        mainui.addWidget(text2, 0, 1)
        mainui.addWidget(self.int1, 1, 0)
        mainui.addWidget(self.int2, 1, 1)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 200, 100)
        self.setWindowTitle('MSH Suite - Double Integer')
        self.show()
Exemplo n.º 32
0
 def create_spinbox(self,
                    prefix,
                    suffix,
                    option,
                    default=NoDefault,
                    min_=None,
                    max_=None,
                    step=None,
                    tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[option] = spinbox
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
    def _add_my_ships(self):
        """ Adds shipyards from a dict to the table.

        *Must* be called after (or by) add_shipyards_for(), since that's what 
        sets self.shipyards which this method depends on.
        """
        row = 0
        delete_buttons = {}
        for ship in sorted( self.ships, key=operator.attrgetter('type') ):
            ### Image
            lbl_icon = QLabel()
            img_bldg = QPixmap(":/" + ship.type + ".png").scaled(self.img_w, self.img_w, Qt.KeepAspectRatio)
            lbl_icon.setPixmap(img_bldg)
            ### Type
            itm_type    = QTableWidgetItem(ship.type)
            ### Num to build
            build_spinner = QSpinBox()
            build_spinner.setMinimum(0)
            build_spinner.valueChanged.connect( self._spinner_updated )
            self.widget.insertRow(row)
            self.widget.setCellWidget(row, 0, lbl_icon)
            self.widget.setItem(row, 1, itm_type)
            self.widget.setCellWidget(row, 2, build_spinner)
            row +=1
Exemplo n.º 34
0
    def createRotableGroupBox(self):
        self.rotableGroupBox = QGroupBox("Rotable Widgets")
        
        self.rotableWidgets.append(QSpinBox())
        self.rotableWidgets.append(QSlider())
        self.rotableWidgets.append(QDial())
        self.rotableWidgets.append(QProgressBar())
        count = len(self.rotableWidgets)
        for i in range(count):
            self.rotableWidgets[i].valueChanged[int].\
                connect(self.rotableWidgets[(i+1) % count].setValue)

        self.rotableLayout = QGridLayout()    
        self.rotableGroupBox.setLayout(self.rotableLayout)

        self.rotateWidgets()
	def __init__(self):
		super(SliderWidget, self).__init__()

		self.label = QLabel()
		self.slider = QSlider(Qt.Horizontal)
		self.spinbox = QSpinBox()

		self.slider.valueChanged.connect(self.changedValue)
		self.spinbox.valueChanged.connect(self.changedValue)

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setVerticalSpacing(0)
		layout.addWidget(self.label, 0, 0)
		layout.addWidget(self.slider, 0, 1)
		layout.addWidget(self.spinbox, 0, 2)
		self.setLayout(layout)
Exemplo n.º 36
0
class SliderWidget(QWidget):
    """
	SliderWidget
	"""
    valueChanged = Signal(int)

    def __init__(self):
        super(SliderWidget, self).__init__()

        self.label = QLabel()
        self.slider = QSlider(Qt.Horizontal)
        self.spinbox = QSpinBox()

        self.slider.valueChanged.connect(self.changedValue)
        self.spinbox.valueChanged.connect(self.changedValue)

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setVerticalSpacing(0)
        layout.addWidget(self.label, 0, 0)
        layout.addWidget(self.slider, 0, 1)
        layout.addWidget(self.spinbox, 0, 2)
        self.setLayout(layout)

    def setName(self, name):
        """
		Set the name for the slider
		"""
        self.label.setText(name)

    def setRange(self, range):
        """
		Set the range for the value
		"""
        self.slider.setMinimum(range[0])
        self.spinbox.setMinimum(range[0])
        self.slider.setMaximum(range[1])
        self.spinbox.setMaximum(range[1])

    def setValue(self, value):
        """
		Set the value for the slider and the spinbox
		"""
        self.slider.setValue(value)
        self.spinbox.setValue(value)

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

    @Slot(int)
    def changedValue(self, value):
        self.setValue(value)
        self.valueChanged.emit(value)
class SliderWidget(QWidget):
	"""
	SliderWidget
	"""
	valueChanged = Signal(int)

	def __init__(self):
		super(SliderWidget, self).__init__()

		self.label = QLabel()
		self.slider = QSlider(Qt.Horizontal)
		self.spinbox = QSpinBox()

		self.slider.valueChanged.connect(self.changedValue)
		self.spinbox.valueChanged.connect(self.changedValue)

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setVerticalSpacing(0)
		layout.addWidget(self.label, 0, 0)
		layout.addWidget(self.slider, 0, 1)
		layout.addWidget(self.spinbox, 0, 2)
		self.setLayout(layout)

	def setName(self, name):
		"""
		Set the name for the slider
		"""
		self.label.setText(name)

	def setRange(self, range):
		"""
		Set the range for the value
		"""
		self.slider.setMinimum(range[0])
		self.spinbox.setMinimum(range[0])
		self.slider.setMaximum(range[1])
		self.spinbox.setMaximum(range[1])

	def setValue(self, value):
		"""
		Set the value for the slider and the spinbox
		"""
		self.slider.setValue(value)
		self.spinbox.setValue(value)

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

	@Slot(int)
	def changedValue(self, value):
		self.setValue(value)
		self.valueChanged.emit(value)
Exemplo n.º 38
0
    def __init__(self, current_tab_text=None, parent=None):
        """
        Constructor
        """
        super(DialogGetConfigNumber, self).__init__(parent)
        ok_button = QPushButton("&OK")
        cancel_button = QPushButton("Cancel")
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(ok_button)
        button_layout.addWidget(cancel_button)

        layout = QGridLayout()

        current_row = 0
        label_start = QLabel("config number :")
        self.hsb_start = QSpinBox()
        self.hsb_start.setMinimum(1)
        self.hsb_start.setMaximum(4)
        self.hsb_start.setValue(1)
        layout.addWidget(label_start, current_row, 0)
        layout.addWidget(self.hsb_start, current_row, 1, 1, 1)

        # current_row += 1
        # label_finish = QLabel("ending address :")
        # self.hsb_finish = HexSpinBox()
        # self.hsb_finish.setMinimum(0x00)
        # self.hsb_finish.setMaximum(0x7F)
        # self.hsb_finish.setValue(0x7F)
        # layout.addWidget(label_finish, current_row, 0)
        # layout.addWidget(self.hsb_finish, current_row, 1, 1, 1)
        #
        # current_row += 1
        # label_bank = QLabel("otp bank :")
        # self.spin_box_bank_sel = QSpinBox()
        # self.spin_box_bank_sel.setMinimum(0)
        # self.spin_box_bank_sel.setMaximum(1)
        # layout.addWidget(label_bank, current_row, 0)
        # layout.addWidget(self.spin_box_bank_sel, current_row, 1, 1, 1)
        current_row += 1
        layout.addLayout(button_layout, current_row, 0, 1, 2)
        self.setLayout(layout)
        self.connect(ok_button, SIGNAL("clicked()"), self, SLOT("accept()"))
        self.connect(cancel_button, SIGNAL("clicked()"), self, SLOT("reject()"))
        self.setWindowTitle("set OTP write range / bank")
Exemplo n.º 39
0
    def setupButtonMenu(self):
        self.button1         = QPushButton("previous" )
        self.button2         = QPushButton("next" )
        self.label1          = QLabel("font")
        self.fontsizeSpinBox = QSpinBox()
        
        self.button1.hide()
        self.button2.hide()
        self.label1.hide()
        self.fontsizeSpinBox.hide()

        self.button1.clicked.connect(self.fire_search_backward)
        self.button2.clicked.connect(self.fire_search_foreward)
         
        self.fontsizeSpinBox.setRange(4, 30)
        self.fontsizeSpinBox.setSingleStep(1)
        self.fontsizeSpinBox.setSuffix('pt')
        self.fontsizeSpinBox.setValue(10)        
        self.fontsizeSpinBox.valueChanged.connect(self.setfontsize)         
 def __init__(self, rangeConstructor=1.0,  boardCombo=None, title="Enter first range arguments", parent=None):
   super(DoFPParametersDialog, self).__init__(parent)
   self._after_method = 2
   self._board_combo = boardCombo
   label_constructor = QLabel("Constructor argument <b>(initFrac)</b>")
   self._spinbox_constructor = QSpinBox()
   self._spinbox_constructor.setMaximum(9999)
   self._spinbox_constructor.setValue(rangeConstructor)
   label_after_construction = QLabel("After construction method")
   self._radiogroup_methods = HorizontalRadioGroup(["setRangeString()", "setAllFracs()", "setToTop()"])
   self._radiogroup_methods.radio_checked.connect(self._updateLayout)
   self._radiogroup_methods._radios[0].setChecked(True) # dunno why it's not checked by default
   label_method_args = QLabel("Method arguments")
   self._widget_method_args = SetRangeStringCompound()
   button_ok = QPushButton("Ok")
   button_ok.clicked.connect(self.accept)
   button_cancel = QPushButton("Cancel")
   button_cancel.clicked.connect(self.reject)
   layout = QGridLayout()
   row = 0; col = 0;
   layout.addWidget(label_constructor, row, col)
   col += 1
   layout.addWidget(self._spinbox_constructor, row, col)
   row += 1; col = 0;
   layout.addWidget(label_after_construction, row, col)
   col += 1
   layout.addWidget(self._radiogroup_methods)
   row += 1; col = 0;
   layout.addWidget(label_method_args, row, col)
   col += 1
   self._update_pos = (row, col)
   layout.addWidget(self._widget_method_args, row, col)
   row += 1; col = 0
   layout.addWidget(button_ok, row, col)
   col += 1
   layout.addWidget(button_cancel, row, col)
   self.setLayout(layout)
   self.setWindowTitle(title)
Exemplo n.º 41
0
    def initUI(self):
        mainlay = QVBoxLayout()
        scn = QGraphicsScene(0, 0, self.w, self.h)

        self.view = QGraphicsView()
        self.view.setScene(scn)
        self.view.setSceneRect(QRectF(0, 0, self.w, self.h))
        self.view.setMaximumWidth(self.w)
        self.view.setMaximumHeight(self.h)

        mainlay.addWidget(self.view)

        btns = QHBoxLayout()
        btns.addStretch()

        self.pen_w = QSpinBox()
        self.pen_w.setValue(self.pen_width)
        redraw = QPushButton('Redraw')
        redraw.clicked.connect(self.draw_uvs)
        save = QPushButton('Save')
        save.clicked.connect(self.save)
        close = QPushButton('Close')
        close.clicked.connect(self.close)

        btns.addWidget(QLabel('Stroke Width'))
        btns.addWidget(self.pen_w)
        btns.addWidget(redraw)
        btns.addWidget(save)
        btns.addWidget(close)

        mainlay.addLayout(btns)

        self.draw_uvs()

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 512, 560)
        self.setWindowTitle('MSH Suite UV Viewer')
        self.show()
Exemplo n.º 42
0
	def __init__(self):
		super(NewMarkerDialog, self).__init__()
		self.setWindowTitle('Add new marker...')
		newMarkerLabel		= QLabel('Marker:')
		self.newMarker		= QLineEdit()
		includeLabel		= QLabel('Include all samples:')
		self.includeAll		= QCheckBox()
		controlsLabel		= QLabel('Control wells:')
		self.controls		= QSpinBox()
		self.controls.setRange(0,8)
		self.controls.setValue(2)
		layout				= QGridLayout()
		layout.addWidget(newMarkerLabel,0,0)
		layout.addWidget(self.newMarker,0,1)
		layout.addWidget(includeLabel,1,0)
		layout.addWidget(self.includeAll,1,1)
		layout.addWidget(controlsLabel,2,0)
		layout.addWidget(self.controls,2,1)
		self.buttons		= QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)	
		self.buttons.accepted.connect(self.accept)
		self.buttons.rejected.connect(self.reject)
		layout.addWidget(self.buttons,100,0,1,2)
		self.setLayout(layout)
Exemplo n.º 43
0
    def createGUI(self):
        self.series = QSpinBox()
        self.series.setMinimum(1)

        self.repetitions = QSpinBox()
        self.repetitions.setMaximum(512)

        self.avgHeartRateToggle = QCheckBox()
        self.avgHeartRateToggle.toggled.connect(self._toggleHeartRateSpinBox)

        self.avgHeartRate = QSpinBox()
        self.avgHeartRate.setMinimum(30)
        self.avgHeartRate.setMaximum(250)
        self.avgHeartRate.setValue(120)
        self.avgHeartRate.setDisabled(True)

        self.dateSelector_widget = QCalendarWidget()
        self.dateSelector_widget.setMaximumDate(QDate.currentDate())

        self.addButton = QPushButton("Add pushup")
        self.addButton.setMaximumWidth(90)
        self.addButton.clicked.connect(self._createPushup)

        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.setMaximumWidth(90)
        self.cancelButton.clicked.connect(self.reject)

        self.pushupForm.addRow("Series", self.series)
        self.pushupForm.addRow("Repetitions", self.repetitions)
        self.pushupForm.addRow("Store average heart rate ? ",
                               self.avgHeartRateToggle)
        self.pushupForm.addRow("Average Heart Rate", self.avgHeartRate)
        self.pushupForm.addRow("Exercise Date", self.dateSelector_widget)

        btnsLayout = QVBoxLayout()
        btnsLayout.addWidget(self.addButton)
        btnsLayout.addWidget(self.cancelButton)
        btnsLayout.setAlignment(Qt.AlignRight)

        layoutWrapper = QVBoxLayout()
        layoutWrapper.addLayout(self.pushupForm)
        layoutWrapper.addLayout(btnsLayout)

        self.setLayout(layoutWrapper)
Exemplo n.º 44
0
    def add_ships(self, ships: dict):
        """ Adds ships from a dict to the table.

        Arguments:
            ships (dict): ``ship type (str) => quantity``

        This does *not* clear any existing entries before adding more ships. 
        If you want to pass an exhaustive dict, be sure to call ``reset`` first.

        You generally want ``add_ships_for`` instead of this.
        """
        row = 0
        delete_buttons = {}
        for type in sorted(ships.keys()):
            ### Image
            lbl_icon = QLabel()
            img_ship = QPixmap(":/" + type + ".png").scaled(
                self.img_w, self.img_w, Qt.KeepAspectRatio)
            lbl_icon.setPixmap(img_ship)
            ### Type and Quantity
            itm_type = QTableWidgetItem(type)
            itm_num_avail = QTableWidgetItem("{:,}".format(ships[type]))
            ### Num to delete spinner
            del_spinner = QSpinBox()
            del_spinner.setMinimum(0)
            del_spinner.setMaximum(ships[type])
            ### Do Eet button
            btn_go = QPushButton("Go")

            ### functools.partial locks the arg's current value to the method.
            ### A regular Python lambda would be late-binding, so all button
            ### clicks would indicate the same (last) row.
            btn_go.clicked.connect(functools.partial(self.scuttle, row))

            self.widget.insertRow(row)
            self.widget.setCellWidget(row, 0, lbl_icon)
            self.widget.setItem(row, 1, itm_type)
            self.widget.setItem(row, 2, itm_num_avail)
            self.widget.setCellWidget(row, 3, del_spinner)
            self.widget.setCellWidget(row, 4, btn_go)
            row += 1
        self.resize()
Exemplo n.º 45
0
    def __init__(self, filename=None, name=None, parent=None):
        super(ImageViewer, self).__init__(parent)
        self.imageRaw = np.zeros((200, 200, 200))
        self.imageRGB = np.zeros((200, 200, 200, 3))
        self.viewRange = [[100, 100], [100, 100], [100, 100]]
        self.zoomFactors = [3.0, 3.0, 3.0]
        self.iMin = 0
        self.iMax = 1000
        self.ijk = [0, 0, 0]

        self.name = 'untitled'
        self.initHbRL()
        self.mouseCursorCross = False

        ## Upper buttons
        self.upperRow = QHBoxLayout()
        self.drawRightHb = QPushButton('RightHb', self)
        self.drawLeftHb = QPushButton('LeftHb', self)
        self.drawRightHb.setCheckable(True)
        self.drawLeftHb.setCheckable(True)
        self.upperRow.addWidget(self.drawRightHb)
        self.upperRow.addWidget(self.drawLeftHb)
        QtCore.QObject.connect(self.drawRightHb, QtCore.SIGNAL('clicked()'),
                               self.clickRightHb)
        QtCore.QObject.connect(self.drawLeftHb, QtCore.SIGNAL('clicked()'),
                               self.clickLeftHb)

        ## View Layout
        self.scenes = [
            MyGraphicsScene(self, 0),
            MyGraphicsScene(self, 1),
            MyGraphicsScene(self, 2)
        ]
        self.views = [
            QGraphicsView(self.scenes[0]),
            QGraphicsView(self.scenes[1]),
            QGraphicsView(self.scenes[2])
        ]
        self.sceneItems = [None, None, None]

        #Scene 4
        view4 = QGridLayout()
        labelX = QLabel('X: ')
        labelY = QLabel('Y: ')
        labelZ = QLabel('Z: ')
        self.spin = [QSpinBox(), QSpinBox(), QSpinBox()]
        labelMinIntensity = QLabel('Min: ')
        labelMaxIntensity = QLabel('Max: ')
        labelZoom = QLabel('Zoom: ')
        self.spinMin = QSpinBox()
        self.spinMax = QSpinBox()
        self.spinZoom = QSpinBox()
        self.spinMin.setMaximum(10000)
        self.spinMax.setMaximum(10000)
        self.spinMin.setValue(self.iMin)
        self.spinMax.setValue(self.iMax)
        self.spinZoom.setValue(self.zoomFactors[0])
        self.spinMin.setKeyboardTracking(False)
        self.spinMin.valueChanged.connect(self.setIntensity)
        self.spinMax.setKeyboardTracking(False)
        self.spinMax.valueChanged.connect(self.setIntensityMax)
        self.spinZoom.valueChanged.connect(self.setZoomFactor)
        self.spinZoom.setKeyboardTracking(False)
        labelAreaR = QLabel('Right: ')
        labelAreaL = QLabel('Left: ')
        self.labelAreaValueR = QLabel()
        self.labelAreaValueL = QLabel()

        view4.addWidget(labelX, 0, 0, 2, 1)
        view4.addWidget(labelY, 1, 0, 2, 1)
        view4.addWidget(labelZ, 2, 0, 2, 1)
        view4.addWidget(labelMinIntensity, 4, 0, 2, 1)
        view4.addWidget(labelMaxIntensity, 5, 0, 2, 1)
        view4.addWidget(labelZoom, 6, 0, 2, 1)
        view4.addWidget(labelAreaR, 7, 0)
        view4.addWidget(labelAreaL, 7, 2)
        view4.addWidget(self.spin[0], 0, 2, 2, 1)
        view4.addWidget(self.spin[1], 1, 2, 2, 1)
        view4.addWidget(self.spin[2], 2, 2, 2, 1)
        view4.addWidget(self.spinMin, 4, 2, 2, 1)
        view4.addWidget(self.spinMax, 5, 2, 2, 1)
        view4.addWidget(self.spinZoom, 6, 2, 2, 1)
        view4.addWidget(self.labelAreaValueR, 7, 1)
        view4.addWidget(self.labelAreaValueL, 7, 3)

        self.viewLayout = QGridLayout()
        self.viewLayout.addWidget(self.views[0], 0, 0)
        self.viewLayout.addWidget(self.views[1], 0, 1)
        self.viewLayout.addWidget(self.views[2], 1, 0)
        self.viewLayout.addLayout(view4, 1, 1)

        ## Lower
        self.lowerRow = QHBoxLayout()
        calculateButtonDown = QPushButton('calculateVolume', self)
        saveButtonDown = QPushButton('SaveHb', self)
        loadButtonDown = QPushButton('loadHb', self)
        savepngButtonDown = QPushButton('Save PNG', self)
        self.lowerRow.addWidget(calculateButtonDown)
        self.lowerRow.addWidget(saveButtonDown)
        self.lowerRow.addWidget(loadButtonDown)
        self.lowerRow.addWidget(savepngButtonDown)
        QtCore.QObject.connect(calculateButtonDown, QtCore.SIGNAL('clicked()'),
                               self.getHbAreas)
        QtCore.QObject.connect(saveButtonDown, QtCore.SIGNAL('clicked()'),
                               self.saveHb)
        QtCore.QObject.connect(loadButtonDown, QtCore.SIGNAL('clicked()'),
                               self.loadHb)
        QtCore.QObject.connect(savepngButtonDown, QtCore.SIGNAL('clicked()'),
                               self.saveCoronalSlice)

        ## Layout
        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.upperRow)
        self.mainLayout.addLayout(self.viewLayout)
        self.mainLayout.addLayout(self.lowerRow)

        self.setLayout(self.mainLayout)
        self.setWindowTitle("Image Viewer")
        self.resize(600, 700)
        self.show()

        if filename:
            self.loadNifti1(filename, name=name)
class CalculateSalaryWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent
        self.setWindowTitle("Calculate Salary")

        t = datetime.now()
        self.month = QComboBox()
        self.month.addItems([
            "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
            "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
        ])
        self.month.setCurrentIndex(t.month - 1)
        self.year = QSpinBox()
        self.year.setRange(1900, 3000)
        self.year.setValue(t.year)

        self.name = SearchBox(self)
        self.name.setPlaceholderText("Enter Name")

        self.name.returnPressed.connect(self.setIDList)
        self.nameList = []
        self.nameList = DatabaseManager.db.getEmployeeNameList()
        self.name.setList(self.nameList)
        self.name.setCurrentIndex(-1)

        self.id = QComboBox()
        self.id.currentIndexChanged.connect(
            lambda: self.loadInfo(self.id.currentText()))

        self.designation = QLineEdit()
        self.designation.setReadOnly(True)
        self.originalPay = QLineEdit()
        self.originalPay.setReadOnly(True)
        self.originalPayGrade = QLineEdit()
        self.originalPayGrade.setReadOnly(True)
        self.DOJ = QLineEdit()
        self.DOJ.setReadOnly(True)
        self.pan = QLineEdit()
        self.pan.setReadOnly(True)

        self.presentPay = QLineEdit()
        self.presentPay.setReadOnly(True)
        self.da_percent = ValueBox()
        self.hra_percent = ValueBox()
        self.ta_percent = ValueBox()
        self.it_percent = ValueBox()
        self.pt_percent = ValueBox()

        self.name.editTextChanged.connect(self.clearInfo)

        self.bttnCalculate = QPushButton("Calculate")
        self.bttnCalculate.clicked.connect(self.calculate)
        self.bttnCancel = QPushButton("Back")
        self.bttnCancel.clicked.connect(self.goBack)
        self.bttnCalculate.setObjectName("OkButton")
        self.bttnCancel.setObjectName("CancelButton")

        self.setupUI()

    def calculate(self):
        if "" in (self.id.currentText(), self.name.text(),
                  self.designation.text(), self.originalPay.text(),
                  self.originalPayGrade.text(), self.DOJ.text(),
                  self.pan.text(), self.da_percent.text(),
                  self.hra_percent.text(), self.ta_percent.text(),
                  self.it_percent.text(), self.pt_percent.text()):
            msg = QMessageBox(QMessageBox.Information,
                              "Error",
                              "Please enter all the information!",
                              parent=self)
            msg.exec_()
        else:
            if self.__parent is not None:
                self.__parent.gotoPage(
                    "Result",
                    (self.id.currentText(), self.name.text(),
                     self.designation.text(), self.originalPay.text(),
                     self.originalPayGrade.text(), self.DOJ.text(),
                     self.pan.text(), self.da_percent.text(),
                     self.hra_percent.text(), self.ta_percent.text(),
                     self.it_percent.text(), self.pt_percent.text(),
                     self.month.currentText(), self.year.text()))

    def clearInfo(self):
        self.id.setCurrentIndex(-1)
        self.designation.clear()
        self.originalPay.clear()
        self.originalPayGrade.clear()
        self.DOJ.clear()
        self.pan.clear()
        self.da_percent.clear()
        self.hra_percent.clear()
        self.ta_percent.clear()
        self.it_percent.clear()
        self.pt_percent.clear()

    def loadInfo(self, id):
        print "id =", id, "...", len(id)
        if id != '':
            info = DatabaseManager.db.getEmployeeInfo(id)
            _, _, designation, originalPay, originalPayGrade, doj, pan = info
            self.designation.setText(str(designation))
            self.originalPay.setText(str(originalPay))
            self.originalPayGrade.setText(str(originalPayGrade))
            self.DOJ.setText("%02d/%02d/%4d" % (doj.day, doj.month, doj.year))
            self.pan.setText(str(pan))

            _, da, hra, ta, it, pt = DatabaseManager.db.getDesignationInfo(
                designation)

            self.da_percent.setText(str(da))
            self.hra_percent.setText(str(hra))
            self.ta_percent.setText(str(ta))
            self.it_percent.setText(str(it))
            self.pt_percent.setText(str(pt))

    def setIDList(self, name):
        self.id.clear()
        self.id.addItems(DatabaseManager.db.getIdListForName(name))

    def goBack(self):
        if self.__parent is not None:
            self.__parent.goBack()

    def setupUI(self):

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)

        datelayout = QHBoxLayout()
        datelayout.addWidget(QLabel("Salary for month of "))
        datelayout.addWidget(self.month)
        datelayout.addWidget(self.year)
        datelayout.addStretch()
        layout.addLayout(datelayout)

        form = QFormLayout()
        form.setSpacing(10)
        form.addRow(QLabel("Name"), self.name)
        form.addRow(QLabel("ID No."), self.id)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)

        infoGroup = QGroupBox("Basic Info")
        infoGroup.setLayout(form)
        layout.addWidget(infoGroup)

        leftForm = QFormLayout()
        leftForm.addRow(QLabel("Dearness Allowance"), self.da_percent)
        leftForm.addRow(QLabel("Housing Rent Allowance"), self.hra_percent)
        leftForm.addRow(QLabel("Transport Allowance"), self.ta_percent)

        leftGroup = QGroupBox("Allowances")
        leftGroup.setLayout(leftForm)

        rightForm = QFormLayout()
        rightForm.addRow(QLabel("Income Tax"), self.it_percent)
        rightForm.addRow(QLabel("Profession Tax"), self.pt_percent)

        rightGroup = QGroupBox("Deductions")
        rightGroup.setLayout(rightForm)

        table = QHBoxLayout()
        table.addWidget(leftGroup)
        table.addWidget(rightGroup)

        layout.addLayout(table)

        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnCalculate)

        layout.addLayout(bttnLayout)
        self.setLayout(layout)
Exemplo n.º 47
0
    def get_frame(self):
        # Info stuff.
        self.infos = {}
        infogrp = QGroupBox('Scene Info')
        grdlay = QGridLayout()
        grdlay.addWidget(QLabel('<b>Name</b>'), 0, 0)
        namebox = QLineEdit()
        self.infos['name'] = namebox
        namebox.setText(self.info.name)

        rangebox1 = QSpinBox()
        rangebox1.setMinimum(0)
        rangebox1.setMaximum(1000)
        self.infos['rangestart'] = rangebox1
        rangebox1.setValue(self.info.frame_range[0])

        rangebox2 = QSpinBox()
        rangebox2.setMinimum(0)
        rangebox2.setMaximum(1000)
        self.infos['rangeend'] = rangebox2
        rangebox2.setValue(self.info.frame_range[1])

        fpsbox = QDoubleSpinBox()
        self.infos['fps'] = fpsbox
        fpsbox.setValue(self.info.fps)

        bbox_btn = QPushButton('Bounding Box')
        bbox_btn.clicked.connect(self.edit_bbox)
        grdlay.addWidget(namebox, 0, 1)
        grdlay.addWidget(QLabel('<b>StartFrame</b>'), 1, 0)
        grdlay.addWidget(rangebox1, 1, 1)
        grdlay.addWidget(QLabel('<b>EndFrame</b>'), 1, 2)
        grdlay.addWidget(fpsbox, 0, 3)
        grdlay.addWidget(rangebox2, 1, 3)
        grdlay.addWidget(QLabel('<b>FPS</b>'), 0, 2)

        grdlay.addWidget(bbox_btn, 2, 0)

        grplay = QVBoxLayout()
        grplay.addLayout(grdlay)
        #grplay.addStretch()
        infogrp.setLayout(grplay)

        return infogrp
Exemplo n.º 48
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # Set window Icon
        self.setWindowTitle(__appname__)
        iconImage = QImage(iconByteArray)
        iconPixmap = QPixmap(iconImage)
        self.setWindowIcon(QIcon(iconPixmap))

        # Set up private key format widgets
        privateKeyFormatLayout = QHBoxLayout()
        privateKeyFormatLabel = QLabel('Select Key Format: ')
        self.privateKeyTypeCombobox = QComboBox()
        self.privateKeyTypeCombobox.addItems(privateKeyFormats)
        self.privateKeyLengthLabel = QLabel('0')
        privateKeyFormatLayout.addWidget(privateKeyFormatLabel)
        privateKeyFormatLayout.addWidget(self.privateKeyTypeCombobox)
        privateKeyFormatLayout.addWidget(self.privateKeyLengthLabel)

        # Set up private key text widgets
        privateKeyLayout = QVBoxLayout()
        privateKeyButtonsLayout = QHBoxLayout()
        generatePrivateKeyButton = QPushButton('Generate Key')
        generatePrivateKeyButton.clicked.connect(self.get_private_key)
        self.copyPrivateKeyButton = QPushButton('Copy Key')
        self.copyPrivateKeyButton.setDisabled(True)
        self.copyPrivateKeyButton.clicked.connect(self.copy_private_key)
        privateKeyButtonsLayout.addWidget(generatePrivateKeyButton)
        privateKeyButtonsLayout.addWidget(self.copyPrivateKeyButton)
        self.privateKeyEdit = GrowingTextEdit()
        self.privateKeyEdit.setFont(QFont('Courier'))
        self.privateKeyEdit.textChanged.connect(
            self.private_key_or_code_changed)
        privateKeyLayout.addLayout(privateKeyButtonsLayout)
        privateKeyLayout.addWidget(self.privateKeyEdit)

        # Set up cypher code widgets
        codeLayout = QHBoxLayout()
        codeLabel = QLabel('Select Cypher Code: ')
        self.codeSelect = QSpinBox()
        self.codeSelect.setValue(10)
        self.codeSelect.setMinimum(2)
        self.codeSelect.setDisabled(True)
        self.codeSelect.valueChanged.connect(self.private_key_or_code_changed)
        codeLayout.addWidget(codeLabel)
        codeLayout.addWidget(self.codeSelect)

        # Set up cypher text widgets
        cypherLayout = QVBoxLayout()
        cypherButtonsLayout = QHBoxLayout()
        cardButtonsLayout = QHBoxLayout()
        self.generateCypherButton = QPushButton('Generate Cypher')
        self.generateCypherButton.clicked.connect(self.get_cypher)
        self.generateCypherButton.setDisabled(True)
        self.copyCypherButton = QPushButton('Copy Cypher')
        self.copyCypherButton.setDisabled(True)
        self.copyCypherButton.clicked.connect(self.copy_cypher)
        cypherButtonsLayout.addWidget(self.generateCypherButton)
        cypherButtonsLayout.addWidget(self.copyCypherButton)
        self.cypherEdit = GrowingTextEdit()
        self.cypherEdit.setFont(QFont('Courier'))
        self.cypherEdit.setReadOnly(True)
        self.cypherEdit.setVisible(False)
        self.cypherEdit.textChanged.connect(self.resize_window)
        self.cypherPreviewLabel = QLabel('-CYPHER PREVIEW-')
        self.cypherPreviewLabel.setAlignment(Qt.AlignCenter)
        self.cypherPreviewLabel.setVisible(False)
        self.cypherPreview = GrowingTextEdit()
        self.cypherPreview.setFont(QFont('Courier'))
        self.cypherPreview.setAlignment(Qt.AlignHCenter)
        self.cypherPreview.setWordWrapMode(QTextOption.NoWrap)
        self.cypherPreview.setReadOnly(True)
        self.cypherPreview.setVisible(False)
        self.cypherCardsPrintButton = QPushButton('Print Cypher Cards')
        self.cypherCardsPrintButton.setVisible(False)
        self.cypherCardsPrintButton.clicked.connect(partial(self.cards, True))
        self.cypherCardsCopyButton = QPushButton('Copy Cypher Cards')
        self.cypherCardsCopyButton.setVisible(False)
        self.cypherCardsCopyButton.clicked.connect(partial(self.cards, False))
        cardButtonsLayout.addWidget(self.cypherCardsPrintButton)
        cardButtonsLayout.addWidget(self.cypherCardsCopyButton)
        cypherLayout.addLayout(cypherButtonsLayout)
        cypherLayout.addWidget(self.cypherEdit)
        cypherLayout.addWidget(self.cypherPreviewLabel)
        cypherLayout.addWidget(self.cypherPreview)
        cypherLayout.addLayout(cardButtonsLayout)

        # Set up donation widgets
        donationsLayout = QVBoxLayout()
        separater = QFrame()
        separater.setFrameShape(QFrame.HLine)
        self.donationButton = QPushButton('Donate')
        self.donationButton.setVisible(False)
        self.donationButton.clicked.connect(self.donate)
        self.copyEthAddressButton = QPushButton('ETH: Copy Address')
        self.copyEthAddressButton.clicked.connect(
            self.copy_eth_donation_address)
        self.copyEthAddressButton.setVisible(False)
        self.copyBtcAddressButton = QPushButton('BTC: Copy Address')
        self.copyBtcAddressButton.clicked.connect(
            self.copy_btc_donation_address)
        self.copyBtcAddressButton.setVisible(False)
        donationsLayout.addWidget(separater)
        donationsLayout.addWidget(self.donationButton)
        donationsLayout.addWidget(self.copyEthAddressButton)
        donationsLayout.addWidget(self.copyBtcAddressButton)

        # Add all widgets and sub-layouts to the master layout
        self.master_layout = QVBoxLayout()
        self.master_layout.addLayout(privateKeyFormatLayout)
        self.master_layout.addLayout(privateKeyLayout)
        self.master_layout.addLayout(codeLayout)
        self.master_layout.addLayout(cypherLayout)
        self.master_layout.addLayout(donationsLayout)
        self.master_widget = QWidget()
        self.master_widget.setLayout(self.master_layout)
        self.setCentralWidget(self.master_widget)

        # Start and connect the window resizing thread
        self.worker = Worker()
        self.worker.updateWindowSize.connect(self.resize_window)
Exemplo n.º 49
0
 def setUp(self):
     super(SpinBoxPySignal, self).setUp()
     self.obj = Dummy()
     self.spin = QSpinBox()
     self.spin.setValue(0)
Exemplo n.º 50
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle('Runner')
        self.setMinimumWidth(750)

        # Runner
        self._runner = None

        self._running_timer = QTimer()
        self._running_timer.setInterval(500)

        # Widgets
        self._dlg_progress = QProgressDialog()
        self._dlg_progress.setRange(0, 100)
        self._dlg_progress.setModal(True)
        self._dlg_progress.hide()

        lbl_outputdir = QLabel("Output directory")
        self._txt_outputdir = DirBrowseWidget()

        max_workers = cpu_count() #@UndefinedVariable
        lbl_workers = QLabel('Number of workers')
        self._spn_workers = QSpinBox()
        self._spn_workers.setRange(1, max_workers)
        self._spn_workers.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        lbl_max_workers = QLabel('(max: %i)' % max_workers)

        self._chk_overwrite = QCheckBox("Overwrite existing results in output directory")
        self._chk_overwrite.setChecked(True)

        self._lbl_available = QLabel('Available')
        self._lst_available = QListView()
        self._lst_available.setModel(_AvailableOptionsListModel())
        self._lst_available.setSelectionMode(QListView.SelectionMode.MultiSelection)

        tlb_available = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        tlb_available.addWidget(spacer)
        act_open = tlb_available.addAction(getIcon("document-open"), "Open")
        act_open.setShortcut(QKeySequence.Open)
        tlb_available.addSeparator()
        act_remove = tlb_available.addAction(getIcon("list-remove"), "Remove")
        act_clear = tlb_available.addAction(getIcon("edit-clear"), "Clear")

        self._btn_addtoqueue = QPushButton(getIcon("go-next"), "")
        self._btn_addtoqueue.setToolTip("Add to queue")
        self._btn_addtoqueue.setEnabled(False)

        self._btn_addalltoqueue = QPushButton(getIcon("go-last"), "")
        self._btn_addalltoqueue.setToolTip("Add all to queue")
        self._btn_addalltoqueue.setEnabled(False)

        self._lbl_options = QLabel('Queued/Running/Completed')
        self._tbl_options = QTableView()
        self._tbl_options.setModel(_StateOptionsTableModel())
        self._tbl_options.setItemDelegate(_StateOptionsItemDelegate())
        self._tbl_options.setSelectionMode(QListView.SelectionMode.NoSelection)
        self._tbl_options.setColumnWidth(1, 60)
        self._tbl_options.setColumnWidth(2, 80)
        header = self._tbl_options.horizontalHeader()
        header.setResizeMode(0, QHeaderView.Interactive)
        header.setResizeMode(1, QHeaderView.Fixed)
        header.setResizeMode(2, QHeaderView.Fixed)
        header.setResizeMode(3, QHeaderView.Stretch)

        self._btn_start = QPushButton(getIcon("media-playback-start"), "Start")

        self._btn_cancel = QPushButton("Cancel")
        self._btn_cancel.setEnabled(False)

        self._btn_close = QPushButton("Close")

        self._btn_import = QPushButton("Import")
        self._btn_import.setEnabled(False)

        # Layouts
        layout = QVBoxLayout()

        sublayout = QGridLayout()
        sublayout.addWidget(lbl_outputdir, 0, 0)
        sublayout.addWidget(self._txt_outputdir, 0, 1)
        sublayout.addWidget(lbl_workers, 1, 0)

        subsublayout = QHBoxLayout()
        subsublayout.addWidget(self._spn_workers)
        subsublayout.addWidget(lbl_max_workers)
        sublayout.addLayout(subsublayout, 1, 1)
        layout.addLayout(sublayout)

        sublayout.addWidget(self._chk_overwrite, 2, 0, 1, 3)

        sublayout = QGridLayout()
        sublayout.setColumnStretch(0, 1)
        sublayout.setColumnStretch(2, 3)
        sublayout.addWidget(self._lbl_available, 0, 0)
        sublayout.addWidget(self._lst_available, 1, 0)
        sublayout.addWidget(tlb_available, 2, 0)

        subsublayout = QVBoxLayout()
        subsublayout.addStretch()
        subsublayout.addWidget(self._btn_addtoqueue)
        subsublayout.addWidget(self._btn_addalltoqueue)
        subsublayout.addStretch()
        sublayout.addLayout(subsublayout, 1, 1)

        sublayout.addWidget(self._lbl_options, 0, 2)
        sublayout.addWidget(self._tbl_options, 1, 2)
        layout.addLayout(sublayout)

        sublayout = QHBoxLayout()
        sublayout.addStretch()
        sublayout.addWidget(self._btn_import)
        sublayout.addWidget(self._btn_start)
        sublayout.addWidget(self._btn_cancel)
        sublayout.addWidget(self._btn_close)
        layout.addLayout(sublayout)

        self.setLayout(layout)

        # Signal
        self._running_timer.timeout.connect(self._onRunningTimer)

        act_open.triggered.connect(self._onOpen)
        act_remove.triggered.connect(self._onRemove)
        act_clear.triggered.connect(self._onClear)

        self._btn_addtoqueue.released.connect(self._onAddToQueue)
        self._btn_addalltoqueue.released.connect(self._onAddAllToQueue)
        self._btn_start.released.connect(self._onStart)
        self._btn_cancel.released.connect(self._onCancel)
        self._btn_close.released.connect(self._onClose)
        self._btn_import.released.connect(self._onImport)

        self.options_added.connect(self._onOptionsAdded)
        self.options_running.connect(self._onOptionsRunning)
        self.options_simulated.connect(self._onOptionsSimulated)
        self.options_error.connect(self._onOptionsError)
        self.results_error.connect(self._onResultsError)

        # Defaults
        settings = get_settings()
        section = settings.add_section('gui')
        if hasattr(section, 'outputdir'):
            self._txt_outputdir.setPath(section.outputdir)
        if hasattr(section, 'maxworkers'):
            self._spn_workers.setValue(int(section.maxworkers))
        if hasattr(section, 'overwrite'):
            state = True if section.overwrite.lower() == 'true' else False
            self._chk_overwrite.setChecked(state)
Exemplo n.º 51
0
class RunnerDialog(QDialog):

    options_added = Signal(Options)
    options_running = Signal(Options)
    options_simulated = Signal(Options)
    options_error = Signal(Options, Exception)
    results_saved = Signal(Results, str)
    results_error = Signal(Results, Exception)

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle('Runner')
        self.setMinimumWidth(750)

        # Runner
        self._runner = None

        self._running_timer = QTimer()
        self._running_timer.setInterval(500)

        # Widgets
        self._dlg_progress = QProgressDialog()
        self._dlg_progress.setRange(0, 100)
        self._dlg_progress.setModal(True)
        self._dlg_progress.hide()

        lbl_outputdir = QLabel("Output directory")
        self._txt_outputdir = DirBrowseWidget()

        max_workers = cpu_count() #@UndefinedVariable
        lbl_workers = QLabel('Number of workers')
        self._spn_workers = QSpinBox()
        self._spn_workers.setRange(1, max_workers)
        self._spn_workers.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        lbl_max_workers = QLabel('(max: %i)' % max_workers)

        self._chk_overwrite = QCheckBox("Overwrite existing results in output directory")
        self._chk_overwrite.setChecked(True)

        self._lbl_available = QLabel('Available')
        self._lst_available = QListView()
        self._lst_available.setModel(_AvailableOptionsListModel())
        self._lst_available.setSelectionMode(QListView.SelectionMode.MultiSelection)

        tlb_available = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        tlb_available.addWidget(spacer)
        act_open = tlb_available.addAction(getIcon("document-open"), "Open")
        act_open.setShortcut(QKeySequence.Open)
        tlb_available.addSeparator()
        act_remove = tlb_available.addAction(getIcon("list-remove"), "Remove")
        act_clear = tlb_available.addAction(getIcon("edit-clear"), "Clear")

        self._btn_addtoqueue = QPushButton(getIcon("go-next"), "")
        self._btn_addtoqueue.setToolTip("Add to queue")
        self._btn_addtoqueue.setEnabled(False)

        self._btn_addalltoqueue = QPushButton(getIcon("go-last"), "")
        self._btn_addalltoqueue.setToolTip("Add all to queue")
        self._btn_addalltoqueue.setEnabled(False)

        self._lbl_options = QLabel('Queued/Running/Completed')
        self._tbl_options = QTableView()
        self._tbl_options.setModel(_StateOptionsTableModel())
        self._tbl_options.setItemDelegate(_StateOptionsItemDelegate())
        self._tbl_options.setSelectionMode(QListView.SelectionMode.NoSelection)
        self._tbl_options.setColumnWidth(1, 60)
        self._tbl_options.setColumnWidth(2, 80)
        header = self._tbl_options.horizontalHeader()
        header.setResizeMode(0, QHeaderView.Interactive)
        header.setResizeMode(1, QHeaderView.Fixed)
        header.setResizeMode(2, QHeaderView.Fixed)
        header.setResizeMode(3, QHeaderView.Stretch)

        self._btn_start = QPushButton(getIcon("media-playback-start"), "Start")

        self._btn_cancel = QPushButton("Cancel")
        self._btn_cancel.setEnabled(False)

        self._btn_close = QPushButton("Close")

        self._btn_import = QPushButton("Import")
        self._btn_import.setEnabled(False)

        # Layouts
        layout = QVBoxLayout()

        sublayout = QGridLayout()
        sublayout.addWidget(lbl_outputdir, 0, 0)
        sublayout.addWidget(self._txt_outputdir, 0, 1)
        sublayout.addWidget(lbl_workers, 1, 0)

        subsublayout = QHBoxLayout()
        subsublayout.addWidget(self._spn_workers)
        subsublayout.addWidget(lbl_max_workers)
        sublayout.addLayout(subsublayout, 1, 1)
        layout.addLayout(sublayout)

        sublayout.addWidget(self._chk_overwrite, 2, 0, 1, 3)

        sublayout = QGridLayout()
        sublayout.setColumnStretch(0, 1)
        sublayout.setColumnStretch(2, 3)
        sublayout.addWidget(self._lbl_available, 0, 0)
        sublayout.addWidget(self._lst_available, 1, 0)
        sublayout.addWidget(tlb_available, 2, 0)

        subsublayout = QVBoxLayout()
        subsublayout.addStretch()
        subsublayout.addWidget(self._btn_addtoqueue)
        subsublayout.addWidget(self._btn_addalltoqueue)
        subsublayout.addStretch()
        sublayout.addLayout(subsublayout, 1, 1)

        sublayout.addWidget(self._lbl_options, 0, 2)
        sublayout.addWidget(self._tbl_options, 1, 2)
        layout.addLayout(sublayout)

        sublayout = QHBoxLayout()
        sublayout.addStretch()
        sublayout.addWidget(self._btn_import)
        sublayout.addWidget(self._btn_start)
        sublayout.addWidget(self._btn_cancel)
        sublayout.addWidget(self._btn_close)
        layout.addLayout(sublayout)

        self.setLayout(layout)

        # Signal
        self._running_timer.timeout.connect(self._onRunningTimer)

        act_open.triggered.connect(self._onOpen)
        act_remove.triggered.connect(self._onRemove)
        act_clear.triggered.connect(self._onClear)

        self._btn_addtoqueue.released.connect(self._onAddToQueue)
        self._btn_addalltoqueue.released.connect(self._onAddAllToQueue)
        self._btn_start.released.connect(self._onStart)
        self._btn_cancel.released.connect(self._onCancel)
        self._btn_close.released.connect(self._onClose)
        self._btn_import.released.connect(self._onImport)

        self.options_added.connect(self._onOptionsAdded)
        self.options_running.connect(self._onOptionsRunning)
        self.options_simulated.connect(self._onOptionsSimulated)
        self.options_error.connect(self._onOptionsError)
        self.results_error.connect(self._onResultsError)

        # Defaults
        settings = get_settings()
        section = settings.add_section('gui')
        if hasattr(section, 'outputdir'):
            self._txt_outputdir.setPath(section.outputdir)
        if hasattr(section, 'maxworkers'):
            self._spn_workers.setValue(int(section.maxworkers))
        if hasattr(section, 'overwrite'):
            state = True if section.overwrite.lower() == 'true' else False
            self._chk_overwrite.setChecked(state)

    def _onDialogProgressProgress(self, progress, status):
        self._dlg_progress.setValue(progress * 100)
        self._dlg_progress.setLabelText(status)

    def _onDialogProgressCancel(self):
        self._dlg_progress.hide()
        if self._options_reader_thread is None:
            return
        self._options_reader_thread.cancel()
        self._options_reader_thread.quit()
        self._options_reader_thread.wait()

    def _onDialogProgressException(self, ex):
        self._dlg_progress.hide()
        self._options_reader_thread.quit()
        self._options_reader_thread.wait()
        messagebox.exception(self, ex)

    def _onRunningTimer(self):
        self._tbl_options.model().reset()

    def _onOpen(self):
        settings = get_settings()
        curdir = getattr(settings.gui, 'opendir', os.getcwd())

        filepath, namefilter = \
            QFileDialog.getOpenFileName(self, "Open", curdir,
                                        'Options [*.xml] (*.xml)')

        if not filepath or not namefilter:
            return
        settings.gui.opendir = os.path.dirname(filepath)

        if not filepath.endswith('.xml'):
            filepath += '.xml'

        self._options_reader_thread = _OptionsReaderWrapperThread(filepath)
        self._dlg_progress.canceled.connect(self._onDialogProgressCancel)
        self._options_reader_thread.resultReady.connect(self._onOpened)
        self._options_reader_thread.progressUpdated.connect(self._onDialogProgressProgress)
        self._options_reader_thread.exceptionRaised.connect(self._onDialogProgressException)
        self._options_reader_thread.start()

        self._dlg_progress.reset()
        self._dlg_progress.show()

    def _onOpened(self, options):
        self._dlg_progress.hide()
        self._options_reader_thread.quit()
        self._options_reader_thread.wait()
        self._options_reader_thread = None

        try:
            self._lst_available.model().addOptions(options)
        except Exception as ex:
            messagebox.exception(self, ex)

    def _onRemove(self):
        selection = self._lst_available.selectionModel().selection().indexes()
        if len(selection) == 0:
            QMessageBox.warning(self, "Queue", "Select an options")
            return

        model = self._lst_available.model()
        for row in sorted(map(methodcaller('row'), selection), reverse=True):
            model.popOptions(row)

    def _onClear(self):
        self._lst_available.model().clearOptions()

    def _onAddToQueue(self):
        selection = self._lst_available.selectionModel().selection().indexes()
        if len(selection) == 0:
            QMessageBox.warning(self, "Queue", "Select an options")
            return

        model = self._lst_available.model()
        for row in sorted(map(methodcaller('row'), selection), reverse=True):
            options = model.options(row)
            try:
                self._runner.put(options)
            except Exception as ex:
                messagebox.exception(self, ex)
                return

    def _onAddAllToQueue(self):
        model = self._lst_available.model()
        for row in reversed(range(0, model.rowCount())):
            options = model.options(row)
            try:
                self._runner.put(options)
            except Exception as ex:
                messagebox.exception(self, ex)
                return

    def _onStart(self):
        outputdir = self._txt_outputdir.path()
        if not outputdir:
            QMessageBox.critical(self, 'Start', 'Missing output directory')
            return
        max_workers = self._spn_workers.value()
        overwrite = self._chk_overwrite.isChecked()
        self.start(outputdir, overwrite, max_workers)

    def _onCancel(self):
        self.cancel()

    def _onClose(self):
        if self._runner is not None:
            self._runner.close()
        self._running_timer.stop()
        self.close()

    def _onImport(self):
        list_options = self._lst_available.model().listOptions()
        if not list_options:
            return

        # Select options
        dialog = _OptionsSelector(list_options)
        if not dialog.exec_():
            return
        options = dialog.options()

        # Start importer
        outputdir = self._runner.outputdir
        max_workers = self._runner.max_workers
        importer = LocalImporter(outputdir, max_workers)

        importer.start()
        importer.put(options)

        self._dlg_progress.show()
        try:
            while importer.is_alive():
                if self._dlg_progress.wasCanceled():
                    importer.cancel()
                    break
                self._dlg_progress.setValue(importer.progress * 100)
        finally:
            self._dlg_progress.hide()

    def _onOptionsAdded(self, options):
        logging.debug('runner: optionsAdded')
        self._tbl_options.model().addOptions(options)

    def _onOptionsRunning(self, options):
        logging.debug('runner: optionsRunning')
        self._tbl_options.model().resetOptions(options)

    def _onOptionsSimulated(self, options):
        logging.debug('runner: optionsSimulated')
        self._tbl_options.model().resetOptions(options)

    def _onOptionsError(self, options, ex):
        logging.debug('runner: optionsError')
        self._tbl_options.model().resetOptions(options)

    def _onResultsError(self, results, ex):
        logging.debug('runner: resultsError')
        self._tbl_options.model().reset()

    def closeEvent(self, event):
        if self.is_running():
            message = 'Runner is running. Do you want to continue?'
            answer = QMessageBox.question(self, 'Runner', message,
                                          QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.No:
                event.ignore()
                return

        self.cancel()
        self._dlg_progress.close()

        settings = get_settings()
        section = settings.add_section('gui')

        path = self._txt_outputdir.path()
        if path:
            section.outputdir = path
        section.maxworkers = str(self._spn_workers.value())
        section.overwrite = str(self._chk_overwrite.isChecked())

        settings.write()

        event.accept()

    def addAvailableOptions(self, options):
        self._lst_available.model().addOptions(options)

    def removeAvailableOptions(self, options):
        self._lst_available.model().removeOptions(options)

    def clearAvailableOptions(self):
        self._lbl_available.model().clearOptions()

    def start(self, outputdir, overwrite, max_workers):
        self._runner = LocalRunner(outputdir=outputdir,
                                   overwrite=overwrite,
                                   max_workers=max_workers)

        self._tbl_options.setModel(_StateOptionsTableModel(self._runner))

        self._spn_workers.setEnabled(False)
        self._txt_outputdir.setEnabled(False)
        self._chk_overwrite.setEnabled(False)
        self._btn_addtoqueue.setEnabled(True)
        self._btn_addalltoqueue.setEnabled(True)
        self._btn_start.setEnabled(False)
        self._btn_cancel.setEnabled(True)
        self._btn_close.setEnabled(False)
        self._btn_import.setEnabled(True)

        self._runner.options_added.connect(self.options_added.emit)
        self._runner.options_running.connect(self.options_running.emit)
        self._runner.options_simulated.connect(self.options_simulated.emit)
        self._runner.options_error.connect(self.options_error.emit)
        self._runner.results_saved.connect(self.results_saved.emit)
        self._runner.results_error.connect(self.results_error.emit)

        self._running_timer.start()
        self._runner.start()

    def cancel(self):
        if self._runner is None:
            return
        self._runner.cancel()
        self._running_timer.stop()

        self._runner.options_added.disconnect(self.options_added.emit)
        self._runner.options_running.disconnect(self.options_running.emit)
        self._runner.options_simulated.disconnect(self.options_simulated.emit)
        self._runner.options_error.disconnect(self.options_error.emit)
        self._runner.results_saved.disconnect(self.results_saved.emit)
        self._runner.results_error.disconnect(self.results_error.emit)

        self._runner = None

        self._spn_workers.setEnabled(True)
        self._txt_outputdir.setEnabled(True)
        self._chk_overwrite.setEnabled(True)
        self._btn_addtoqueue.setEnabled(False)
        self._btn_addalltoqueue.setEnabled(False)
        self._btn_start.setEnabled(True)
        self._btn_cancel.setEnabled(False)
        self._btn_close.setEnabled(True)
        self._btn_import.setEnabled(False)

    def is_running(self):
        return self._runner is not None and self._runner.is_alive()
Exemplo n.º 52
0
 def __init__(self, parent=None):
     QSpinBox.__init__(self, parent)
Exemplo n.º 53
0
class ImageViewer(QWidget):
    def __init__(self, filename=None, name=None, parent=None):
        super(ImageViewer, self).__init__(parent)
        self.imageRaw = np.zeros((200, 200, 200))
        self.imageRGB = np.zeros((200, 200, 200, 3))
        self.viewRange = [[100, 100], [100, 100], [100, 100]]
        self.zoomFactors = [3.0, 3.0, 3.0]
        self.iMin = 0
        self.iMax = 1000
        self.ijk = [0, 0, 0]

        self.name = 'untitled'
        self.initHbRL()
        self.mouseCursorCross = False

        ## Upper buttons
        self.upperRow = QHBoxLayout()
        self.drawRightHb = QPushButton('RightHb', self)
        self.drawLeftHb = QPushButton('LeftHb', self)
        self.drawRightHb.setCheckable(True)
        self.drawLeftHb.setCheckable(True)
        self.upperRow.addWidget(self.drawRightHb)
        self.upperRow.addWidget(self.drawLeftHb)
        QtCore.QObject.connect(self.drawRightHb, QtCore.SIGNAL('clicked()'),
                               self.clickRightHb)
        QtCore.QObject.connect(self.drawLeftHb, QtCore.SIGNAL('clicked()'),
                               self.clickLeftHb)

        ## View Layout
        self.scenes = [
            MyGraphicsScene(self, 0),
            MyGraphicsScene(self, 1),
            MyGraphicsScene(self, 2)
        ]
        self.views = [
            QGraphicsView(self.scenes[0]),
            QGraphicsView(self.scenes[1]),
            QGraphicsView(self.scenes[2])
        ]
        self.sceneItems = [None, None, None]

        #Scene 4
        view4 = QGridLayout()
        labelX = QLabel('X: ')
        labelY = QLabel('Y: ')
        labelZ = QLabel('Z: ')
        self.spin = [QSpinBox(), QSpinBox(), QSpinBox()]
        labelMinIntensity = QLabel('Min: ')
        labelMaxIntensity = QLabel('Max: ')
        labelZoom = QLabel('Zoom: ')
        self.spinMin = QSpinBox()
        self.spinMax = QSpinBox()
        self.spinZoom = QSpinBox()
        self.spinMin.setMaximum(10000)
        self.spinMax.setMaximum(10000)
        self.spinMin.setValue(self.iMin)
        self.spinMax.setValue(self.iMax)
        self.spinZoom.setValue(self.zoomFactors[0])
        self.spinMin.setKeyboardTracking(False)
        self.spinMin.valueChanged.connect(self.setIntensity)
        self.spinMax.setKeyboardTracking(False)
        self.spinMax.valueChanged.connect(self.setIntensityMax)
        self.spinZoom.valueChanged.connect(self.setZoomFactor)
        self.spinZoom.setKeyboardTracking(False)
        labelAreaR = QLabel('Right: ')
        labelAreaL = QLabel('Left: ')
        self.labelAreaValueR = QLabel()
        self.labelAreaValueL = QLabel()

        view4.addWidget(labelX, 0, 0, 2, 1)
        view4.addWidget(labelY, 1, 0, 2, 1)
        view4.addWidget(labelZ, 2, 0, 2, 1)
        view4.addWidget(labelMinIntensity, 4, 0, 2, 1)
        view4.addWidget(labelMaxIntensity, 5, 0, 2, 1)
        view4.addWidget(labelZoom, 6, 0, 2, 1)
        view4.addWidget(labelAreaR, 7, 0)
        view4.addWidget(labelAreaL, 7, 2)
        view4.addWidget(self.spin[0], 0, 2, 2, 1)
        view4.addWidget(self.spin[1], 1, 2, 2, 1)
        view4.addWidget(self.spin[2], 2, 2, 2, 1)
        view4.addWidget(self.spinMin, 4, 2, 2, 1)
        view4.addWidget(self.spinMax, 5, 2, 2, 1)
        view4.addWidget(self.spinZoom, 6, 2, 2, 1)
        view4.addWidget(self.labelAreaValueR, 7, 1)
        view4.addWidget(self.labelAreaValueL, 7, 3)

        self.viewLayout = QGridLayout()
        self.viewLayout.addWidget(self.views[0], 0, 0)
        self.viewLayout.addWidget(self.views[1], 0, 1)
        self.viewLayout.addWidget(self.views[2], 1, 0)
        self.viewLayout.addLayout(view4, 1, 1)

        ## Lower
        self.lowerRow = QHBoxLayout()
        calculateButtonDown = QPushButton('calculateVolume', self)
        saveButtonDown = QPushButton('SaveHb', self)
        loadButtonDown = QPushButton('loadHb', self)
        savepngButtonDown = QPushButton('Save PNG', self)
        self.lowerRow.addWidget(calculateButtonDown)
        self.lowerRow.addWidget(saveButtonDown)
        self.lowerRow.addWidget(loadButtonDown)
        self.lowerRow.addWidget(savepngButtonDown)
        QtCore.QObject.connect(calculateButtonDown, QtCore.SIGNAL('clicked()'),
                               self.getHbAreas)
        QtCore.QObject.connect(saveButtonDown, QtCore.SIGNAL('clicked()'),
                               self.saveHb)
        QtCore.QObject.connect(loadButtonDown, QtCore.SIGNAL('clicked()'),
                               self.loadHb)
        QtCore.QObject.connect(savepngButtonDown, QtCore.SIGNAL('clicked()'),
                               self.saveCoronalSlice)

        ## Layout
        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.upperRow)
        self.mainLayout.addLayout(self.viewLayout)
        self.mainLayout.addLayout(self.lowerRow)

        self.setLayout(self.mainLayout)
        self.setWindowTitle("Image Viewer")
        self.resize(600, 700)
        self.show()

        if filename:
            self.loadNifti1(filename, name=name)

    def loadNifti1(self, filename, name=None):
        self.loadImage = LoadImage()
        self.loadImage.readNifti1(filename)
        if name is None:
            name = filename[:]
            if name[-7:] == '.nii.gz':
                name = name[:-7]
            elif name[-4:] == '.nii':
                name = name[:-4]

            for ch in ['/', '.', '~']:
                pos = name.find(ch)
                while pos > -1:
                    name = '%s_%s' % (name[:pos], name[pos + 1:])
                    pos = name.find(ch)

        self.name = name
        self.imageRaw = self.loadImage.data

        self.spinMin.setMaximum(int(self.imageRaw.max() * 1.2))
        self.spinMax.setMaximum(int(self.imageRaw.max() * 1.2))
        #self.iMin = int(max(0, self.imageRaw.min()*1.2))
        self.iMin = 0
        self.iMax = int(self.imageRaw.max() * 0.8)

        self.spinMin.setValue(self.iMin)
        self.spinMax.setValue(self.iMax)

        self.imageRGB = convertImageRGB(
            resetIntensity(self.imageRaw, iMin=self.iMin, iMax=self.iMax))
        self.setIJK()
        self.drawBaseImage()
        self.setSceneIJK()
        self.showSpinValue()

        self.setMouseCursor(True)

    def showSpinValue(self):
        self.spin[0].setMaximum(self.imageRaw.shape[0])
        self.spin[1].setMaximum(self.imageRaw.shape[1])
        self.spin[2].setMaximum(self.imageRaw.shape[2])
        self.spin[0].setKeyboardTracking(False)
        self.spin[1].setKeyboardTracking(False)
        self.spin[2].setKeyboardTracking(False)
        self.spin[0].setValue(self.ijk[0])
        self.spin[1].setValue(self.ijk[1])
        self.spin[2].setValue(self.ijk[2])
        self.spin[0].valueChanged.connect(self.resetI)
        self.spin[1].valueChanged.connect(self.resetJ)
        self.spin[2].valueChanged.connect(self.resetK)

    def resetI(self, i):
        self.ijk[0] = i
        self.drawBaseImage([0])

    def resetJ(self, j):
        self.ijk[1] = j
        self.drawBaseImage([1])
        self.labelAreaValueR.clear()
        self.labelAreaValueL.clear()

    def resetK(self, k):
        self.ijk[2] = k
        self.drawBaseImage([2])

    def initHbRL(self):
        self.hbRight = {
            'name': 'HbRight',
            'color': 'red',
            'images': [],
            'points': []
        }
        self.hbLeft = {
            'name': 'HbLeft',
            'color': 'blue',
            'images': [],
            'points': []
        }

    def clickRightHb(self):
        if self.drawLeftHb.isChecked():
            self.drawLeftHb.setChecked(False)

    def clickLeftHb(self):
        if self.drawRightHb.isChecked():
            self.drawRightHb.setChecked(False)

    def saveHb(self, filename=None):
        if filename is None:
            filename = '%s_lawson_hb.csv' % self.name
        writeHb(filename, self.hbRight, self.hbLeft)
        with open(filename, 'a') as fout:
            volumes = self.getHbAreas()
            fout.write('%s,%s\n' % (volumes[0], volumes[1]))

        png_filename = filename[:-4]

    def saveCoronalSlice(self, filename=None):
        viewIndex = 1
        if filename is None:
            filename = '%s_lawson_hb' % self.name
        filename += str('%03d.png' % self.ijk[viewIndex])
        self.scenes[viewIndex].savePng(filename, 'PNG')

    def loadHb(self, filename=None):
        if filename is None:
            filename = '%s_lawson_hb.csv' % self.name
        self.initHbRL()
        readHb(filename, self.hbRight, self.hbLeft)

    def setMouseCursor(self, cross=False):
        if cross != self.mouseCursorCross:
            self.mouseCursorCross = cross
            if cross:
                #self.setCursor(QCursor(QtCore.Qt.CrossCursor))
                self.setCursor(QtCore.Qt.CrossCursor)
            else:
                #self.setCursor(QCursor(QtCore.Qt.ArrowCursor))
                self.setCursor(QtCore.Qt.ArrowCursor)

    def getZoomFactors(self):
        return self.zoomFactors

    def magZoomFactors(self, ratio):
        self.setZoomFactors([value + ratio for value in self.zoomFactors])
        self.spinZoom.setValue(self.zoomFactors[0])

    def setZoomFactors(self, zoomFactors):
        sceneRects = self.saveScene()
        self.zoomFactors = zoomFactors
        self.drawBaseImage()
        self.restoreScene(sceneRects)

    def setZoomFactor(self, zoomFactor):
        self.setZoomFactors([zoomFactor, zoomFactor, zoomFactor])

    def getIntensity(self):
        return self.iMin, self.iMax

    def setIntensityMax(self, iMax):
        self.setIntensity(iMax=iMax)

    def setIntensity(self, iMin=None, iMax=None):
        if iMin:
            self.iMin = iMin
        if iMax:
            self.iMax = iMax
        self.imageRGB = convertImageRGB(
            resetIntensity(self.imageRaw, iMin=self.iMin, iMax=self.iMax))
        self.drawBaseImage()

    def mousePressEventLeft(self, viewIndex, x, y):
        if viewIndex == 1:
            if self.drawRightHb.isChecked():
                hbDict = self.hbRight
                labelAreaValue = self.labelAreaValueR
            elif self.drawLeftHb.isChecked():
                hbDict = self.hbLeft
                labelAreaValue = self.labelAreaValueL
            else:
                self.resetIJK(viewIndex, x, y)
                return

            if not hbDict.has_key(self.ijk[viewIndex]):
                hbDict[self.ijk[viewIndex]] = HbRegionDraw()

            if hbDict[self.ijk[viewIndex]].insert == 4:
                for item in hbDict['images']:  # lines
                    self.scenes[viewIndex].removeItem(item)
                hbDict['images'] = []
                item = hbDict['points'].pop(0)  # last point
                self.scenes[viewIndex].removeItem(item)

            i, j = self.point2fijk(viewIndex, x, y)
            if not hbDict[self.ijk[viewIndex]].push((i, j)):
                item = hbDict['points'].pop(0)  # last point
                self.scenes[viewIndex].removeItem(item)
                #self.scenes[viewIndex].removeItem(self.scenes[viewIndex].items()[0])

            x_round, y_round = self.ij2point(viewIndex, i, j)
            hbDict['points'].insert(
                0, self.scenes[viewIndex].addEllipse(
                    x_round - 1,
                    y_round - 1,
                    2,
                    2,
                    pen=QPen(QColor(hbDict['color']))))

            if hbDict[self.ijk[viewIndex]].insert >= 4:
                area = hbDict[self.ijk[viewIndex]].calculate_area(
                    hbDict['name'])
                print ' %s %s: %s' % (self.ijk[viewIndex], hbDict['name'],
                                      area)
                self.drawHb(hbDict)
                #labelAreaValue.setText('%s: %3.2f' % (self.ijk[viewIndex], area))
                labelAreaValue.setText('%3.2f' % (area))
        else:
            self.resetIJK(viewIndex, x, y)

    def mousePressEventRight(self, viewIndex, x, y):
        if viewIndex == 1:
            if self.drawRightHb.isChecked():
                hbDict = self.hbRight
            elif self.drawLeftHb.isChecked():
                hbDict = self.hbLeft
            else:
                return

            if not hbDict.has_key(self.ijk[viewIndex]):
                return

            if hbDict[self.ijk[viewIndex]].insert == 4:
                for item in hbDict['images']:  # lines
                    self.scenes[viewIndex].removeItem(item)
                hbDict['images'] = []
                #for item in self.scenes[viewIndex].items()[:3]:     # lines
                #    self.scenes[viewIndex].removeItem(item)

            if hbDict[self.ijk[viewIndex]].pop():
                item = hbDict['points'].pop(0)  # last point
                self.scenes[viewIndex].removeItem(item)
                #self.scenes[viewIndex].removeItem(self.scenes[viewIndex].items()[0])

    def moveIJK(self, viewIndex, dx):
        self.ijk[viewIndex] += dx
        self.spin[viewIndex].setValue(self.ijk[viewIndex])
        self.drawBaseImage([viewIndex])
        self.labelAreaValueR.clear()
        self.labelAreaValueL.clear()

    def point2fijk(self, viewIndex, x, y):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        ijkX = float(x) / self.zoomFactors[viewIndex]
        ijkY = self.imageRGB.shape[yIndex] - 1 - float(
            y) / self.zoomFactors[viewIndex]
        ijkX = np.round(ijkX * 2) / 2
        ijkY = np.round(ijkY * 2) / 2
        return (ijkX, ijkY)

    def point2fijk_flt(self, viewIndex, x, y):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        ijkX = float(x) / self.zoomFactors[viewIndex]
        ijkY = self.imageRGB.shape[yIndex] - 1 - float(
            y) / self.zoomFactors[viewIndex]
        return (ijkX, ijkY)

    def point2ijk(self, viewIndex, x, y):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        ijkX = int(x / self.zoomFactors[viewIndex])
        ijkY = self.imageRGB.shape[yIndex] - 1 - int(
            y / self.zoomFactors[viewIndex])
        return (ijkX, ijkY)

    def ij2point(self, viewIndex, i, j):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        pointX = i * self.zoomFactors[viewIndex]
        pointY = (self.imageRGB.shape[yIndex] - 1 -
                  j) * self.zoomFactors[viewIndex]
        return (pointX, pointY)

    def resetIJK(self, viewIndex, x, y):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        self.ijk[xIndex] = int(x / self.zoomFactors[viewIndex])
        self.ijk[yIndex] = self.imageRGB.shape[yIndex] - 1 - int(
            y / self.zoomFactors[viewIndex])
        self.spin[xIndex].setValue(self.ijk[xIndex])
        self.spin[yIndex].setValue(self.ijk[yIndex])
        self.drawBaseImage(indexTable[viewIndex])
        self.labelAreaValueR.clear()
        self.labelAreaValueL.clear()

    def saveScene(self):
        sceneRects = [0, 0, 0]
        for i in range(3):
            size = self.views[i].size().toTuple()
            x, y, _, _ = self.scenes[i].sceneRect().getRect()
            x += (size[0] - 10) / 2.0
            y += (size[1] - 10) / 2.0
            x /= self.zoomFactors[i]
            y /= self.zoomFactors[i]
            sceneRects[i] = [x, y]
        return sceneRects

    def restoreScene(self, sceneRects):
        for i in range(3):
            size = self.views[i].size().toTuple()
            x = sceneRects[i][0] * self.zoomFactors[i]
            y = sceneRects[i][1] * self.zoomFactors[i]
            self.scenes[i].setSceneRect(x - (size[0] - 10) / 2,
                                        y - (size[0] - 10) / 2, size[0] - 10,
                                        size[1] - 10)

    def setSceneIJK(self, viewIndex=(0, 1, 2)):
        for i in viewIndex:
            size = self.views[i].size().toTuple()

            xyCenter = [
                self.ijk[tmp] * self.zoomFactors[i] for tmp in range(3)
                if tmp is not i
            ]

            self.scenes[i].setSceneRect(xyCenter[0] - size[0] / 2.0,
                                        xyCenter[1] - size[1] / 2.0,
                                        size[0] - 10, size[1] - 10)

    def setIJK(self, ijk='center'):
        if ijk == 'center':
            self.ijk = [
                self.imageRGB.shape[0] / 2, self.imageRGB.shape[1] / 2,
                self.imageRGB.shape[2] / 2
            ]
        else:
            self.ijk = ijk
        self.spin[0].setValue(self.ijk[0])
        self.spin[1].setValue(self.ijk[1])
        self.spin[2].setValue(self.ijk[2])

    def get2D(self, plane):
        if plane == 0:
            return np.rot90(self.imageRGB[self.ijk[0], :, :, :])
        elif plane == 1:
            return np.rot90(self.imageRGB[:, self.ijk[1], :, :])
        elif plane == 2:
            return np.rot90(self.imageRGB[:, :, self.ijk[2], :])

    def drawBaseImage(self, viewIndex=(0, 1, 2), eraseOthers=True):
        for i in viewIndex:
            imageArray3d = self.get2D(i)
            height, width, bytesPerComponent = imageArray3d.shape
            imageArray = imageArray3d.flatten()
            bytesPerLine = bytesPerComponent * width
            image = QImage(imageArray, width, height, bytesPerLine,
                           QImage.Format_RGB888)
            #image = image.scaled( int(width*self.zoomFactors[i]), int(height*self.zoomFactors[i]), Qt.KeepAspectRatio, Qt.SmoothTransformation)
            image = image.scaled(int(width * self.zoomFactors[i]),
                                 int(height * self.zoomFactors[i]),
                                 QtCore.Qt.KeepAspectRatio)

            if self.sceneItems[i] is not None:
                #self.scenes[i].removeItem(self.sceneItems[i])
                self.sceneItems[i].setPixmap(QPixmap.fromImage(image))
                if False:
                    items = self.scenes[i].items()
                    for item in items:
                        self.scenes[i].removeItem(item)

                    self.sceneItems[i] = self.scenes[i].addPixmap(
                        QPixmap.fromImage(image))
                    for item in items[1:]:
                        self.scenes[i].additem(item)

                    del items

            else:
                self.sceneItems[i] = self.scenes[i].addPixmap(
                    QPixmap.fromImage(image))

            if eraseOthers:
                for item in self.scenes[i].items():
                    if item != self.sceneItems[i]:
                        self.scenes[i].removeItem(item)

            # TODO: where to put this
            self.drawHbPts(self.hbRight)
            self.drawHb(self.hbRight)
            self.drawHbPts(self.hbLeft)
            self.drawHb(self.hbLeft)

    def drawHbPts(self, hbDict):
        viewIndex = 1
        if not hbDict.has_key(self.ijk[viewIndex]):
            return
        pts = [
            self.ij2point(viewIndex, i, j)
            for (i, j) in hbDict[self.ijk[viewIndex]].get_points()
        ]
        for i in range(hbDict[self.ijk[viewIndex]].insert):
            hbDict['points'].insert(
                0, self.scenes[viewIndex].addEllipse(
                    pts[i][0] - 1,
                    pts[i][1] - 1,
                    2,
                    2,
                    pen=QPen(QColor(hbDict['color']))))

    def drawHb(self, hbDict):
        viewIndex = 1
        if not hbDict.has_key(self.ijk[viewIndex]):
            return
        if hbDict[self.ijk[viewIndex]].insert < 4:
            return

        a, b, c, d = [
            self.ij2point(viewIndex, i, j)
            for (i, j) in hbDict[self.ijk[viewIndex]].get_points()
        ]

        cp = hbDict[self.ijk[viewIndex]].cp
        cp = self.ij2point(viewIndex, cp[0], cp[1])

        vA = (a[0] - cp[0], a[1] - cp[1])
        vB = (b[0] - cp[0], b[1] - cp[1])
        vD = (d[0] - cp[0], d[1] - cp[1])

        arcAD = QPainterPath()
        arcDB = QPainterPath()

        if hbDict['name'] == 'HbRight':
            sign = 1
            startAngle = 0
        else:
            sign = -1
            startAngle = 180

        angleADlad = sign * angleBw2Vectors(vA, vD)
        angleAD = 180 / np.pi * angleADlad

        if vD[0] * vD[0] + vD[1] * vD[1] >= vA[0] * vA[0] + vA[1] * vA[1]:
            rotD = (np.sqrt(vD[0] * vD[0] + vD[1] * vD[1]), 0)
            coefA = rotD[0]

            rotA = rotateVector(vA, angleADlad)
            coefB = np.sqrt(coefA * coefA /
                            (coefA * coefA - rotA[0] * rotA[0]) * rotA[1] *
                            rotA[1])
            eccentricAnomalyAD = -180 / np.pi * np.arctan(
                coefA / coefB * np.tan(angleADlad))
            arcAD.moveTo(cp[0] + sign * coefA, cp[1])
            arcAD.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB,
                        startAngle, eccentricAnomalyAD)
        else:
            rotA = (np.sqrt(vA[0] * vA[0] + vA[1] * vA[1]), 0)
            coefA = rotA[0]

            angleDAlad = sign * angleBw2Vectors(vD, vA)
            angleDA = 180 / np.pi * angleDAlad

            rotD = vD
            coefB = np.sqrt(coefA * coefA /
                            (coefA * coefA - rotD[0] * rotD[0]) * rotD[1] *
                            rotD[1])
            eccentricAnomalyDA = 180 / np.pi * np.arctan(
                coefA / coefB * np.tan(angleDAlad))
            arcAD.moveTo(cp[0] + sign * coefA, cp[1])
            arcAD.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB,
                        startAngle, eccentricAnomalyDA)
            angleAD = 0.0

        if vD[0] * vD[0] + vD[1] * vD[1] >= vB[0] * vB[0] + vB[1] * vB[1]:
            rotD = (np.sqrt(vD[0] * vD[0] + vD[1] * vD[1]), 0)
            coefA = rotD[0]

            angleBDlad = sign * angleBw2Vectors(vD, vB)
            angleBD = 180 / np.pi * angleBDlad

            rotB = rotateVector(vB, angleADlad)
            coefB = np.sqrt(coefA * coefA /
                            (coefA * coefA - rotB[0] * rotB[0]) * rotB[1] *
                            rotB[1])
            eccentricAnomalyDB = 180 / np.pi * np.arctan(
                coefA / coefB * np.tan(angleBDlad))
            arcDB.moveTo(cp[0] + sign * coefA, cp[1])
            arcDB.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB,
                        startAngle, eccentricAnomalyDB)

            angleAB = 180 / np.pi * sign * angleBw2Vectors(vA, vD)
        else:
            rotB = (np.sqrt(vB[0] * vB[0] + vB[1] * vB[1]), 0)
            coefA = rotB[0]

            angleABlad = sign * angleBw2Vectors(vA, vB)
            angleAB = 180 / np.pi * angleABlad

            angleDBlad = sign * angleBw2Vectors(vD, vB)
            angleDB = 180 / np.pi * angleDBlad

            rotD = rotateVector(vD, angleABlad)
            coefB = np.sqrt(coefA * coefA /
                            (coefA * coefA - rotD[0] * rotD[0]) * rotD[1] *
                            rotD[1])
            eccentricAnomalyDB = -180 / np.pi * np.arctan(
                coefA / coefB * np.tan(angleDBlad))
            arcDB.moveTo(cp[0] + sign * coefA, cp[1])
            arcDB.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB,
                        startAngle, eccentricAnomalyDB)

        imgAC = self.scenes[viewIndex].addLine(a[0],
                                               a[1],
                                               cp[0],
                                               cp[1],
                                               pen=QPen(QColor(
                                                   hbDict['color'])))
        imgBC = self.scenes[viewIndex].addLine(b[0],
                                               b[1],
                                               c[0],
                                               c[1],
                                               pen=QPen(QColor(
                                                   hbDict['color'])))
        imgAD = self.scenes[viewIndex].addPath(arcAD,
                                               pen=QPen(QColor(
                                                   hbDict['color'])))
        imgAD.setTransform(QTransform().translate(
            cp[0], cp[1]).rotate(-angleAD).translate(-cp[0], -cp[1]))
        imgDB = self.scenes[viewIndex].addPath(arcDB,
                                               pen=QPen(QColor(
                                                   hbDict['color'])))
        imgDB.setTransform(QTransform().translate(
            cp[0], cp[1]).rotate(-angleAB).translate(-cp[0], -cp[1]))
        hbDict['images'] = [imgAD, imgDB, imgBC, imgAC]

    def getHbAreas(self):
        volumes = []
        for hbDict in [self.hbRight, self.hbLeft]:
            keys = hbDict.keys()
            if not keys:
                volumes.append(0.0)
                continue

            print 'Calculate %s Volume...' % hbDict['name']
            unit = self.loadImage.zooms[0] * self.loadImage.zooms[
                1] * self.loadImage.zooms[2]
            volume = 0.0
            keys.sort()
            for key in keys:
                if type(key) == type(''):
                    continue
                area = hbDict[key].area
                print ' %s: %s (voxel)' % (key, area)
                volume += area
            volume *= unit
            print 'volume = %s (mm^3)' % volume
            volumes.append(volume)
        return volumes
Exemplo n.º 54
0
        def testSetValue(self):
            """Direct signal emission: QSpinBox using valueChanged(int)/setValue(int)"""
            spinSend = QSpinBox()
            spinRec = QSpinBox()

            spinRec.setValue(5)
            spinSend.setValue(42)

            QObject.connect(spinSend, SIGNAL('valueChanged(int)'), spinRec, SLOT('setValue(int)'))
            self.assertEqual(spinRec.value(), 5)
            self.assertEqual(spinSend.value(), 42)
            spinSend.emit(SIGNAL('valueChanged(int)'), 3)

            self.assertEqual(spinRec.value(), 3)
            #Direct emission shouldn't change the value of the emitter
            self.assertEqual(spinSend.value(), 42)

            spinSend.emit(SIGNAL('valueChanged(int)'), 66)
            self.assertEqual(spinRec.value(), 66)
            self.assertEqual(spinSend.value(), 42)
Exemplo n.º 55
0
def createFontBoxesFor(parent,
                       name,
                       family,
                       size,
                       *,
                       mono=False,
                       tooltips=None,
                       which="Font"):
    font = QFont(family, size)
    fontComboBox = QFontComboBox(parent)
    if not mono:
        fontFilter = QFontComboBox.ScalableFonts
    else:
        fontFilter = (QFontComboBox.ScalableFonts
                      | QFontComboBox.MonospacedFonts)
    fontComboBox.setFontFilters(fontFilter)
    fontComboBox.setCurrentFont(font)
    fontSizeSpinBox = QSpinBox(parent)
    fontSizeSpinBox.setAlignment(Qt.AlignRight)
    fontSizeSpinBox.setRange(6, 36)
    fontSizeSpinBox.setSuffix(" pt")
    fontSizeSpinBox.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
    fontSizeSpinBox.setValue(font.pointSize())
    if tooltips is not None:
        tooltips.append((fontComboBox, """\
<p><b>{0} Font</b></p><p>The font family to use for the {0} Font.</p>""".
                         format(which)))
        tooltips.append((fontSizeSpinBox, """\
<p><b>{0} Font Size</b></p><p>The font point size to use for the {0}
Font.</p>""".format(which)))
    setattr(parent, "{}FontComboBox".format(name.lower()), fontComboBox)
    setattr(parent, "{}FontSizeSpinBox".format(name.lower()), fontSizeSpinBox)
Exemplo n.º 56
0
class MainWindow(QMainWindow):  # Sets up the main window
    def resize_window(self):  # Function for resizing the window
        self.resize(self.minimumSizeHint())

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

        # Set window Icon
        self.setWindowTitle(__appname__)
        iconImage = QImage(iconByteArray)
        iconPixmap = QPixmap(iconImage)
        self.setWindowIcon(QIcon(iconPixmap))

        # Set up private key format widgets
        privateKeyFormatLayout = QHBoxLayout()
        privateKeyFormatLabel = QLabel('Select Key Format: ')
        self.privateKeyTypeCombobox = QComboBox()
        self.privateKeyTypeCombobox.addItems(privateKeyFormats)
        self.privateKeyLengthLabel = QLabel('0')
        privateKeyFormatLayout.addWidget(privateKeyFormatLabel)
        privateKeyFormatLayout.addWidget(self.privateKeyTypeCombobox)
        privateKeyFormatLayout.addWidget(self.privateKeyLengthLabel)

        # Set up private key text widgets
        privateKeyLayout = QVBoxLayout()
        privateKeyButtonsLayout = QHBoxLayout()
        generatePrivateKeyButton = QPushButton('Generate Key')
        generatePrivateKeyButton.clicked.connect(self.get_private_key)
        self.copyPrivateKeyButton = QPushButton('Copy Key')
        self.copyPrivateKeyButton.setDisabled(True)
        self.copyPrivateKeyButton.clicked.connect(self.copy_private_key)
        privateKeyButtonsLayout.addWidget(generatePrivateKeyButton)
        privateKeyButtonsLayout.addWidget(self.copyPrivateKeyButton)
        self.privateKeyEdit = GrowingTextEdit()
        self.privateKeyEdit.setFont(QFont('Courier'))
        self.privateKeyEdit.textChanged.connect(
            self.private_key_or_code_changed)
        privateKeyLayout.addLayout(privateKeyButtonsLayout)
        privateKeyLayout.addWidget(self.privateKeyEdit)

        # Set up cypher code widgets
        codeLayout = QHBoxLayout()
        codeLabel = QLabel('Select Cypher Code: ')
        self.codeSelect = QSpinBox()
        self.codeSelect.setValue(10)
        self.codeSelect.setMinimum(2)
        self.codeSelect.setDisabled(True)
        self.codeSelect.valueChanged.connect(self.private_key_or_code_changed)
        codeLayout.addWidget(codeLabel)
        codeLayout.addWidget(self.codeSelect)

        # Set up cypher text widgets
        cypherLayout = QVBoxLayout()
        cypherButtonsLayout = QHBoxLayout()
        cardButtonsLayout = QHBoxLayout()
        self.generateCypherButton = QPushButton('Generate Cypher')
        self.generateCypherButton.clicked.connect(self.get_cypher)
        self.generateCypherButton.setDisabled(True)
        self.copyCypherButton = QPushButton('Copy Cypher')
        self.copyCypherButton.setDisabled(True)
        self.copyCypherButton.clicked.connect(self.copy_cypher)
        cypherButtonsLayout.addWidget(self.generateCypherButton)
        cypherButtonsLayout.addWidget(self.copyCypherButton)
        self.cypherEdit = GrowingTextEdit()
        self.cypherEdit.setFont(QFont('Courier'))
        self.cypherEdit.setReadOnly(True)
        self.cypherEdit.setVisible(False)
        self.cypherEdit.textChanged.connect(self.resize_window)
        self.cypherPreviewLabel = QLabel('-CYPHER PREVIEW-')
        self.cypherPreviewLabel.setAlignment(Qt.AlignCenter)
        self.cypherPreviewLabel.setVisible(False)
        self.cypherPreview = GrowingTextEdit()
        self.cypherPreview.setFont(QFont('Courier'))
        self.cypherPreview.setAlignment(Qt.AlignHCenter)
        self.cypherPreview.setWordWrapMode(QTextOption.NoWrap)
        self.cypherPreview.setReadOnly(True)
        self.cypherPreview.setVisible(False)
        self.cypherCardsPrintButton = QPushButton('Print Cypher Cards')
        self.cypherCardsPrintButton.setVisible(False)
        self.cypherCardsPrintButton.clicked.connect(partial(self.cards, True))
        self.cypherCardsCopyButton = QPushButton('Copy Cypher Cards')
        self.cypherCardsCopyButton.setVisible(False)
        self.cypherCardsCopyButton.clicked.connect(partial(self.cards, False))
        cardButtonsLayout.addWidget(self.cypherCardsPrintButton)
        cardButtonsLayout.addWidget(self.cypherCardsCopyButton)
        cypherLayout.addLayout(cypherButtonsLayout)
        cypherLayout.addWidget(self.cypherEdit)
        cypherLayout.addWidget(self.cypherPreviewLabel)
        cypherLayout.addWidget(self.cypherPreview)
        cypherLayout.addLayout(cardButtonsLayout)

        # Set up donation widgets
        donationsLayout = QVBoxLayout()
        separater = QFrame()
        separater.setFrameShape(QFrame.HLine)
        self.donationButton = QPushButton('Donate')
        self.donationButton.setVisible(False)
        self.donationButton.clicked.connect(self.donate)
        self.copyEthAddressButton = QPushButton('ETH: Copy Address')
        self.copyEthAddressButton.clicked.connect(
            self.copy_eth_donation_address)
        self.copyEthAddressButton.setVisible(False)
        self.copyBtcAddressButton = QPushButton('BTC: Copy Address')
        self.copyBtcAddressButton.clicked.connect(
            self.copy_btc_donation_address)
        self.copyBtcAddressButton.setVisible(False)
        donationsLayout.addWidget(separater)
        donationsLayout.addWidget(self.donationButton)
        donationsLayout.addWidget(self.copyEthAddressButton)
        donationsLayout.addWidget(self.copyBtcAddressButton)

        # Add all widgets and sub-layouts to the master layout
        self.master_layout = QVBoxLayout()
        self.master_layout.addLayout(privateKeyFormatLayout)
        self.master_layout.addLayout(privateKeyLayout)
        self.master_layout.addLayout(codeLayout)
        self.master_layout.addLayout(cypherLayout)
        self.master_layout.addLayout(donationsLayout)
        self.master_widget = QWidget()
        self.master_widget.setLayout(self.master_layout)
        self.setCentralWidget(self.master_widget)

        # Start and connect the window resizing thread
        self.worker = Worker()
        self.worker.updateWindowSize.connect(self.resize_window)

    def copy_private_key(
            self):  # Copies the private key text to the system clipboard
        clip.setText(self.privateKeyEdit.toPlainText())
        self.copyPrivateKeyButton.setText('Key Copied')
        app.processEvents()
        sleep(2)
        self.copyPrivateKeyButton.setText('Copy Key')

    def copy_cypher(self):  # Copies the cypher text to the system clipboard
        clip.setText(self.cypherEdit.toPlainText())
        self.copyCypherButton.setText('Cypher Copied')
        app.processEvents()
        sleep(2)
        self.copyCypherButton.setText('Copy Cypher')

    def copy_eth_donation_address(
            self):  # Copies the ETH donation address to the system clipboard
        clip.setText(ethDonationAddress)
        self.copyEthAddressButton.setText('ETH: Address Copied\nThanks!')
        app.processEvents()
        sleep(2)
        self.copyEthAddressButton.setText('ETH: Copy Address')

    def copy_btc_donation_address(
            self):  # Copies the BTC donation address to the system clipboard
        clip.setText(btcDonationAddress)
        self.copyBtcAddressButton.setText('BTC: Address Copied\nThanks!')
        app.processEvents()
        sleep(2)
        self.copyBtcAddressButton.setText('BTC: Copy Address')

    def get_private_key(
        self
    ):  # Generates a key of the desired format using two instances of the SystemRandom function
        privateKey = generate_private_key.start(
            self.privateKeyTypeCombobox.currentText())
        self.privateKeyEdit.setText(privateKey)
        self.private_key_or_code_changed()
        self.copyPrivateKeyButton.setDisabled(False)

    def private_key_or_code_changed(
        self
    ):  # Changes visibility and ability of some widgets based on user input
        self.privateKeyLengthLabel.setText(
            str(len(self.privateKeyEdit.toPlainText())))
        self.copyCypherButton.setDisabled(True)
        self.cypherEdit.setText('')
        self.cypherPreview.setText('')
        self.cypherEdit.setVisible(False)
        self.cypherPreviewLabel.setVisible(False)
        self.cypherPreview.setVisible(False)
        if len(self.privateKeyEdit.toPlainText()) <= 2:
            self.copyPrivateKeyButton.setDisabled(True)
            self.generateCypherButton.setDisabled(True)
            self.codeSelect.setDisabled(True)
        else:
            self.codeSelect.setMaximum(
                len(self.privateKeyEdit.toPlainText()) - 1)
            self.copyPrivateKeyButton.setDisabled(False)
            self.generateCypherButton.setDisabled(False)
            self.codeSelect.setDisabled(False)
        self.cypherCardsPrintButton.setDisabled(True)
        self.cypherCardsPrintButton.setVisible(False)
        self.cypherCardsCopyButton.setDisabled(True)
        self.cypherCardsCopyButton.setVisible(False)
        self.worker.start()

    def get_cypher(
        self
    ):  # Converts the raw key into a cypher based on the codeSelect value
        if not 1 >= len(self.privateKeyEdit.toPlainText()) >= int(
                self.privateKeyLengthLabel.text()):
            self.generateCypherButton.setDisabled(False)
            cypherRows, cypherSeed = create_cypher.start(
                self.privateKeyEdit.toPlainText(), self.codeSelect.value())
            self.copyCypherButton.setDisabled(False)
            self.cypherEdit.setVisible(True)
            self.cypherEdit.setText(cypherSeed)
            self.cypherPreviewLabel.setVisible(True)
            self.cypherPreview.setVisible(True)
            previewText = ''
            for i in cypherRows:
                previewText += i + '\n'
            self.cypherPreview.setText(previewText)
            self.worker.start()
            self.cypherCardsPrintButton.setDisabled(False)
            self.cypherCardsPrintButton.setVisible(True)
            self.cypherCardsCopyButton.setDisabled(False)
            self.cypherCardsCopyButton.setVisible(True)
            self.donationButton.setVisible(True)
        else:
            self.generateCypherButton.setDisabled(True)

    def cards(self, print):  # Creates and prints the output.txt file
        cardList = split_cypher_into_pairs.start(self.cypherEdit.toPlainText())
        printString = format_cards.start(cardList)
        if print:
            self.cypherCardsPrintButton.setText('Printing')
            app.processEvents()
            cards_output.start(printString)
            self.cypherCardsPrintButton.setText('Print Cypher Cards')
        else:
            clip.setText(printString)
            self.cypherCardsCopyButton.setText('Cards Copied')
            app.processEvents()
            sleep(2)
            self.cypherCardsCopyButton.setText('Copy Cypher Cards')

    def donate(self):  # Adjusts the visibility of the donation buttons
        if self.donationButton.text() == 'Donate':
            self.copyEthAddressButton.setVisible(True)
            self.copyBtcAddressButton.setVisible(True)
            self.donationButton.setText('Hide')
        elif self.donationButton.text() == 'Hide':
            self.copyEthAddressButton.setVisible(False)
            self.copyBtcAddressButton.setVisible(False)
            self.donationButton.setText('Donate')
        self.worker.start()

    def cleanup(self):  # Clears the clipboard of any copied text
        clip.setText('')
Exemplo n.º 57
0
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(598, 450)
        self.icon = QIcon(":/icons/uglytheme/48x48/polibeepsync.png")
        Form.setWindowIcon(self.icon)
        Form.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setObjectName("verticalLayout")

        self.tabWidget = QTabWidget(Form)
        self.tabWidget.setObjectName("tabWidget")

        # Tab General Settings
        self.tab = QWidget()
        self.tab.setObjectName("tab")
        self.horizontalLayout = QHBoxLayout(self.tab)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.label_2 = QLabel(self.tab)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1)
        self.label = QLabel(self.tab)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.password = QLineEdit(self.tab)
        self.password.setMaximumSize(QSize(139, 16777215))
        self.password.setEchoMode(QLineEdit.Password)
        self.password.setObjectName("password")
        self.gridLayout.addWidget(self.password, 3, 1, 1, 1)
        self.userCode = QLineEdit(self.tab)
        self.userCode.setMaximumSize(QSize(139, 16777215))
        self.userCode.setText("")
        self.userCode.setObjectName("userCode")
        self.gridLayout.addWidget(self.userCode, 1, 1, 1, 1)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem, 1, 2, 1, 1)
        self.verticalLayout_2.addLayout(self.gridLayout)
        self.trylogin = QPushButton(self.tab)
        self.trylogin.setMaximumSize(QSize(154, 16777215))
        self.trylogin.setObjectName("trylogin")
        self.verticalLayout_2.addWidget(self.trylogin)
        self.login_attempt = QLabel(self.tab)
        self.login_attempt.setText("Logging in, please wait.")
        self.login_attempt.setStyleSheet("color: rgba(0, 0, 0, 0);")
        self.login_attempt.setObjectName("login_attempt")
        self.verticalLayout_2.addWidget(self.login_attempt)
        spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem1)
        self.horizontalLayout_3 = QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_4 = QLabel(self.tab)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_3.addWidget(self.label_4)
        self.rootfolder = QLineEdit(self.tab)
        self.rootfolder.setMinimumSize(QSize(335, 0))
        self.rootfolder.setMaximumSize(QSize(335, 16777215))
        self.rootfolder.setInputMask("")
        self.rootfolder.setReadOnly(True)
        self.rootfolder.setObjectName("rootfolder")
        self.horizontalLayout_3.addWidget(self.rootfolder)
        self.changeRootFolder = QPushButton(self.tab)
        self.changeRootFolder.setObjectName("changeRootFolder")
        self.horizontalLayout_3.addWidget(self.changeRootFolder)
        spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem2)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_5 = QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_5 = QLabel(self.tab)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_5.addWidget(self.label_5)
        self.timerMinutes = QSpinBox(self.tab)
        self.timerMinutes.setObjectName("timerMinutes")
        self.horizontalLayout_5.addWidget(self.timerMinutes)
        self.label_6 = QLabel(self.tab)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_5.addWidget(self.label_6)
        self.syncNow = QPushButton(self.tab)
        self.syncNow.setObjectName("syncNow")
        self.horizontalLayout_5.addWidget(self.syncNow)
        spacerItem3 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem3)
        self.verticalLayout_2.addLayout(self.horizontalLayout_5)
        self.addSyncNewCourses = QCheckBox(self.tab)
        self.addSyncNewCourses.setObjectName("addSyncNewCourses")
        self.verticalLayout_2.addWidget(self.addSyncNewCourses)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.tab, "")

        # Tab Courses
        self.tab_2 = QWidget()
        self.tab_2.setObjectName("tab_2")
        self.horizontalLayout_2 = QHBoxLayout(self.tab_2)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_6 = QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.refreshCourses = QPushButton(self.tab_2)
        self.refreshCourses.setObjectName("refreshCourses")
        self.horizontalLayout_6.addWidget(self.refreshCourses)
        spacerItem4 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_6.addItem(spacerItem4)
        self.verticalLayout_3.addLayout(self.horizontalLayout_6)
        self.coursesView = CoursesListView(self.tab_2)
        self.coursesView.setObjectName("coursesView")
        self.verticalLayout_3.addWidget(self.coursesView)
        self.horizontalLayout_2.addLayout(self.verticalLayout_3)
        self.tabWidget.addTab(self.tab_2, "")

        # Tab Status
        self.tab_3 = QWidget()
        self.tab_3.setObjectName("tab_3")
        self.horizontalLayout_7 = QHBoxLayout(self.tab_3)
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.verticalLayout_4 = QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.horizontalLayout_8 = QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.about = QPushButton(self.tab_3)
        self.about.setObjectName("about")
        self.horizontalLayout_8.addWidget(self.about)
        spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_8.addItem(spacerItem5)
        self.verticalLayout_4.addLayout(self.horizontalLayout_8)
        self.status = QTextEdit(self.tab_3)
        self.status.setTextInteractionFlags(Qt.TextSelectableByKeyboard
                                            | Qt.TextSelectableByMouse)
        self.status.setObjectName("status")
        self.verticalLayout_4.addWidget(self.status)
        self.horizontalLayout_7.addLayout(self.verticalLayout_4)
        self.tabWidget.addTab(self.tab_3, "")

        self.tab_4 = QWidget()
        self.tab_4.setObjectName("tab_4")
        self.verticalLayout.addWidget(self.tabWidget)

        self.okButton = QDialogButtonBox(Form)
        self.okButton.setStandardButtons(QDialogButtonBox.Ok)
        self.okButton.setObjectName("okButton")
        self.okButton.clicked.connect(self.hide)
        self.verticalLayout.addWidget(self.okButton)

        self.statusLabel = QLabel(Form)
        self.statusLabel.setObjectName("statusLabel")
        self.verticalLayout.addWidget(self.statusLabel)

        self.retranslateUi(Form)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(Form)