Beispiel #1
0
    def __init__(self, parent=None):
        super(LocationFilterPage, self).__init__(parent)

        self.xSpinBox = QDoubleSpinBox()
        self.xSpinBox.setMinimum(float('-inf'))
        self.xSpinBox.setMaximum(float('inf'))
        self.xSpinBox.setDecimals(6)

        self.ySpinBox = QDoubleSpinBox()
        self.ySpinBox.setMinimum(float('-inf'))
        self.ySpinBox.setMaximum(float('inf'))
        self.ySpinBox.setDecimals(6)

        self.tolSpinBox = QDoubleSpinBox()
        self.tolSpinBox.setMinimum(0)
        self.tolSpinBox.setMaximum(float('inf'))
        self.tolSpinBox.setDecimals(6)

        groupLayout = QFormLayout()
        groupLayout.addRow("X:", self.xSpinBox)
        groupLayout.addRow("Y:", self.ySpinBox)
        groupLayout.addRow("Tolerance:", self.tolSpinBox)

        self.group = QGroupBox("Lokace")
        self.group.setCheckable(True)
        self.group.setChecked(False)
        self.group.setLayout(groupLayout)

        layout = QVBoxLayout()
        layout.addWidget(self.group)
        layout.addStretch(1)

        self.setLayout(layout)
Beispiel #2
0
    def __init__(self, size, Id, parent=None):
        super().__init__(size, parent)

        self.id = Id

        self.box = QWidget(self)
        self.box.setGeometry(0, 0, self.width(), 240)

        self.verticalLayout = QVBoxLayout(self.box)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)

        # FadeIn
        self.groupFadeIn = QGroupBox(self.box)
        self.fadeInLayout = QGridLayout(self.groupFadeIn)

        self.fadeInSpin = QDoubleSpinBox(self.groupFadeIn)
        self.fadeInSpin.setMaximum(3600)
        self.fadeInLayout.addWidget(self.fadeInSpin, 0, 0)

        self.fadeInLabel = QLabel(self.groupFadeIn)
        self.fadeInLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeInLayout.addWidget(self.fadeInLabel, 0, 1)

        self.fadeInCombo = QComboBox(self.groupFadeIn)
        self.fadeInCombo.setItemDelegate(QStyledItemDelegate())
        for key in sorted(self.FadeIn.keys()):
            self.fadeInCombo.addItem(self.FadeIn[key], key)
        self.fadeInLayout.addWidget(self.fadeInCombo, 1, 0)

        self.fadeInExpLabel = QLabel(self.groupFadeIn)
        self.fadeInExpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeInLayout.addWidget(self.fadeInExpLabel, 1, 1)

        self.verticalLayout.addWidget(self.groupFadeIn)

        # FadeOut
        self.groupFadeOut = QGroupBox(self.box)
        self.fadeOutLayout = QGridLayout(self.groupFadeOut)

        self.fadeOutSpin = QDoubleSpinBox(self.groupFadeOut)
        self.fadeOutSpin.setMaximum(3600)
        self.fadeOutLayout.addWidget(self.fadeOutSpin, 0, 0)

        self.fadeOutLabel = QLabel(self.groupFadeOut)
        self.fadeOutLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeOutLayout.addWidget(self.fadeOutLabel, 0, 1)

        self.fadeOutCombo = QComboBox(self.groupFadeOut)
        self.fadeOutCombo.setItemDelegate(QStyledItemDelegate())
        for key in sorted(self.FadeOut.keys()):
            self.fadeOutCombo.addItem(self.FadeOut[key], key)
        self.fadeOutLayout.addWidget(self.fadeOutCombo, 1, 0)

        self.fadeOutExpLabel = QLabel(self.groupFadeOut)
        self.fadeOutExpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeOutLayout.addWidget(self.fadeOutExpLabel, 1, 1)

        self.verticalLayout.addWidget(self.groupFadeOut)

        self.retranslateUi()
class PlantSpacingWidget(QWidget):

    calculated = pyqtSignal()

    def __init__(self):
        """The constructor initializes the class NewVariantDialog."""
        super().__init__()

        self.value = 0

        # create the input fields
        self.x = QDoubleSpinBox(decimals=1, maximum=99, singleStep=0.1, suffix=" m")
        self.y = QDoubleSpinBox(decimals=1, maximum=99, singleStep=0.1, suffix=" m")
        label = QLabel("x")

        # dialog main layout
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.x)
        layout.addWidget(label)
        layout.addWidget(self.y)

        # connect actions
        self.x.valueChanged.connect(self.calculate)
        self.y.valueChanged.connect(self.calculate)

    def calculate(self):
        try:
            self.value = 10000 / (self.x.value() * self.y.value())
        except ZeroDivisionError:
            self.value = 0

        self.calculated.emit()
class Window(QWidget):

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

        # Make widgets #################

        self.spinbox = QDoubleSpinBox()
        self.spinbox.setMinimum(-15)
        self.spinbox.setMaximum(15)

        self.btn = QPushButton("Print")

        # Set button slot ##############

        self.btn.clicked.connect(self.printText)

        # Set the layout ###############

        vbox = QVBoxLayout()

        vbox.addWidget(self.spinbox)
        vbox.addWidget(self.btn)

        self.setLayout(vbox)

    def printText(self):
        print(self.spinbox.value())
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.cue_id = -1
        self.setLayout(QVBoxLayout(self))

        cues = Application().cue_model.filter(MediaCue)
        self.cueDialog = CueListDialog(cues=cues, parent=self)

        self.cueGroup = QGroupBox(self)
        self.cueGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.cueGroup)

        self.cueButton = QPushButton(self.cueGroup)
        self.cueButton.clicked.connect(self.select_cue)
        self.cueGroup.layout().addWidget(self.cueButton)

        self.cueLabel = QLabel(self.cueGroup)
        self.cueLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.cueGroup.layout().addWidget(self.cueLabel)

        self.volumeGroup = QGroupBox(self)
        self.volumeGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.volumeGroup)

        self.volumeEdit = QDoubleSpinBox(self.volumeGroup)
        self.volumeEdit.setMaximum(10)
        self.volumeGroup.layout().addWidget(self.volumeEdit)

        self.volumeLabel = QLabel(self.volumeGroup)
        self.volumeLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.volumeGroup.layout().addWidget(self.volumeLabel)

        # Fade
        self.fadeGroup = QGroupBox(self)
        self.fadeGroup.setLayout(QGridLayout())
        self.layout().addWidget(self.fadeGroup)

        self.fadeSpin = QDoubleSpinBox(self.fadeGroup)
        self.fadeSpin.setMaximum(3600)
        self.fadeGroup.layout().addWidget(self.fadeSpin, 0, 0)

        self.fadeLabel = QLabel(self.fadeGroup)
        self.fadeLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeGroup.layout().addWidget(self.fadeLabel, 0, 1)

        self.fadeCurveCombo = QComboBox(self.fadeGroup)
        self.fadeCurveCombo.setItemDelegate(QStyledItemDelegate())
        for key in sorted(VolumeSettings.FadeIcons.keys()):
            self.fadeCurveCombo.addItem(VolumeSettings.FadeIcons[key], key)
        self.fadeGroup.layout().addWidget(self.fadeCurveCombo, 1, 0)

        self.fadeCurveLabel = QLabel(self.fadeGroup)
        self.fadeCurveLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeGroup.layout().addWidget(self.fadeCurveLabel, 1, 1)

        self.layout().addSpacing(50)

        self.retranslateUi()
Beispiel #6
0
Datei: app.py Projekt: ipapi/ipap
    def initoptionspanel(self):
        label = QLabel('Filter')

        filtertype = QComboBox()
        filtertype.addItem('None')
        filtertype.addItem('Lowpass')
        filtertype.addItem('Highpass')
        filtertype.addItem('Bandreject')
        filtertype.addItem('Bandpass')
        filtertype.currentIndexChanged.connect(self.filtertypelistener)

        self.filterfunction = QComboBox()
        self.filterfunction.addItem('Ideal')
        self.filterfunction.addItem('Butterworth')
        self.filterfunction.addItem('Gaussian')
        self.filterfunction.currentIndexChanged.connect(self.filterfunctionlistener)
        self.filterfunction.setEnabled(False)

        self.filtercutoff = QDoubleSpinBox()
        self.filtercutoff.setValue(0.0)
        self.filtercutoff.setRange(0.0, 10000.0)
        self.filtercutoff.valueChanged.connect(self.filtercutofflistener)
        self.filtercutoff.setEnabled(False)

        self.filterbandwidth = QDoubleSpinBox()
        self.filterbandwidth.setValue(1.0)
        self.filterbandwidth.setRange(0.0, 10000.0)
        self.filterbandwidth.valueChanged.connect(self.filterbandwidthlistener)
        self.filterbandwidth.setEnabled(False)

        self.filterorder = QDoubleSpinBox()
        self.filterorder.setValue(1.0)
        self.filterorder.setRange(0.0, 10000.0)
        self.filterorder.valueChanged.connect(self.filterorderlistener)
        self.filterorder.setEnabled(False)

        loader = QMovie('loader.gif')
        loader.start()
        self.loadercontainer = QLabel()
        self.loadercontainer.setMovie(loader)
        self.loadercontainer.setVisible(False)

        formlayout = QFormLayout()
        formlayout.addRow('Type', filtertype)
        formlayout.addRow('Function', self.filterfunction)
        formlayout.addRow('Cut off', self.filtercutoff)
        formlayout.addRow('Bandwidth', self.filterbandwidth)
        formlayout.addRow('Order', self.filterorder)
        formlayout.addRow('', self.loadercontainer)

        filterbox = QGroupBox('Filter')
        filterbox.setLayout(formlayout)

        options = QDockWidget('Options')
        options.setFeatures(QDockWidget.DockWidgetFloatable)
        options.setFeatures(QDockWidget.DockWidgetMovable)
        options.setWidget(filterbox)
        self.addDockWidget(Qt.RightDockWidgetArea, options)
    def createEditor(self, parent, option, index):
        editor = QDoubleSpinBox(parent=parent)

        # setFrame(): tell whether the line edit draws itself with a frame.
        # If enabled (the default) the line edit draws itself inside a frame, otherwise the line edit draws itself without any frame.
        editor.setFrame(False)

        editor.setRange(0, 3)

        return editor
Beispiel #8
0
    def __init__(self, element_id, **kwargs):
        super().__init__(element_id)
        self.setLayout(QVBoxLayout())
        self.layout().setAlignment(Qt.AlignTop)

        # FadeIn
        self.fadeInGroup = QGroupBox(self)
        self.fadeInGroup.setLayout(QGridLayout())
        self.layout().addWidget(self.fadeInGroup)

        self.fadeInSpin = QDoubleSpinBox(self.fadeInGroup)
        self.fadeInSpin.setMaximum(3600)
        self.fadeInGroup.layout().addWidget(self.fadeInSpin, 0, 0)

        self.fadeInLabel = QLabel(self.fadeInGroup)
        self.fadeInLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeInGroup.layout().addWidget(self.fadeInLabel, 0, 1)

        self.fadeInCombo = QComboBox(self.fadeInGroup)
        self.fadeInCombo.setItemDelegate(QStyledItemDelegate())
        for key in sorted(self.FadeInIcons.keys()):
            self.fadeInCombo.addItem(self.FadeInIcons[key], key)
        self.fadeInGroup.layout().addWidget(self.fadeInCombo, 1, 0)

        self.fadeInExpLabel = QLabel(self.fadeInGroup)
        self.fadeInExpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeInGroup.layout().addWidget(self.fadeInExpLabel, 1, 1)

        # FadeOut
        self.fadeOutGroup = QGroupBox(self)
        self.fadeOutGroup.setLayout(QGridLayout())
        self.layout().addWidget(self.fadeOutGroup)

        self.fadeOutSpin = QDoubleSpinBox(self.fadeOutGroup)
        self.fadeOutSpin.setMaximum(3600)
        self.fadeOutGroup.layout().addWidget(self.fadeOutSpin, 0, 0)

        self.fadeOutLabel = QLabel(self.fadeOutGroup)
        self.fadeOutLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeOutGroup.layout().addWidget(self.fadeOutLabel, 0, 1)

        self.fadeOutCombo = QComboBox(self.fadeOutGroup)
        self.fadeOutCombo.setItemDelegate(QStyledItemDelegate())
        for key in sorted(self.FadeOutIcons.keys()):
            self.fadeOutCombo.addItem(self.FadeOutIcons[key], key)
        self.fadeOutGroup.layout().addWidget(self.fadeOutCombo, 1, 0)

        self.fadeOutExpLabel = QLabel(self.fadeOutGroup)
        self.fadeOutExpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fadeOutGroup.layout().addWidget(self.fadeOutExpLabel, 1, 1)

        self.retranslateUi()
Beispiel #9
0
    def _setup_figure_layout_grpbox(self):
        """
        Setup a groupbox containing various widget to control the layout
        of the figure.
        """
        self.fwidth = QDoubleSpinBox()
        self.fwidth.setSingleStep(0.05)
        self.fwidth.setMinimum(5.)
        self.fwidth.setValue(self.pageSize[0])
        self.fwidth.setSuffix('  in')
        self.fwidth.setAlignment(Qt.AlignCenter)
        self.fwidth.label = "Figure Width"

        self.fheight = QDoubleSpinBox()
        self.fheight.setSingleStep(0.05)
        self.fheight.setMinimum(5.)
        self.fheight.setValue(self.pageSize[1])
        self.fheight.setSuffix('  in')
        self.fheight.setAlignment(Qt.AlignCenter)
        self.fheight.label = "Figure Heigh"

        self.va_ratio_spinBox = QDoubleSpinBox()
        self.va_ratio_spinBox.setSingleStep(0.01)
        self.va_ratio_spinBox.setMinimum(0.1)
        self.va_ratio_spinBox.setMaximum(0.95)
        self.va_ratio_spinBox.setValue(self.va_ratio)
        self.va_ratio_spinBox.setAlignment(Qt.AlignCenter)
        self.va_ratio_spinBox.label = "Top/Bottom Axes Ratio"

        self.fframe_lw_widg = QDoubleSpinBox()
        self.fframe_lw_widg.setSingleStep(0.1)
        self.fframe_lw_widg.setDecimals(1)
        self.fframe_lw_widg.setMinimum(0)
        self.fframe_lw_widg.setMaximum(99.9)
        self.fframe_lw_widg.setSuffix('  pt')
        self.fframe_lw_widg.setAlignment(Qt.AlignCenter)
        self.fframe_lw_widg.label = "Frame Thickness"
        self.fframe_lw_widg.setValue(self.figframe_lw)

        # Setup the layout of the groupbox.

        grpbox = QGroupBox("Figure Size :")
        layout = QGridLayout(grpbox)
        widgets = [self.fwidth, self.fheight, self.va_ratio_spinBox,
                   self.fframe_lw_widg]
        for row, widget in enumerate(widgets):
            layout.addWidget(QLabel("%s :" % widget.label), row, 0)
            layout.addWidget(widget, row, 2)

        layout.setColumnStretch(1, 100)
        layout.setContentsMargins(10, 10, 10, 10)
        return grpbox
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A FloatParameter object.
        :type parameter: FloatParameter

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

        self._input = QDoubleSpinBox()
        self._input.setDecimals(self._parameter.precision)
        self._input.setMinimum(self._parameter.minimum_allowed_value)
        self._input.setMaximum(self._parameter.maximum_allowed_value)
        self._input.setValue(self._parameter.value)
        self._input.setSingleStep(
            10 ** -self._parameter.precision)
        # is it possible to use dynamic precision ?
        string_min_value = '%.*f' % (
            self._parameter.precision, self._parameter.minimum_allowed_value)
        string_max_value = '%.*f' % (
            self._parameter.precision, self._parameter.maximum_allowed_value)
        tool_tip = 'Choose a number between %s and %s' % (
            string_min_value, string_max_value)
        self._input.setToolTip(tool_tip)

        self._input.setSizePolicy(self._spin_box_size_policy)

        self.inner_input_layout.addWidget(self._input)
        self.inner_input_layout.addWidget(self._unit_widget)
Beispiel #11
0
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle('Dash results')
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        self.scrollArea = QScrollArea()
        self.widget = QWidget()

        self.test_name_label = QLabel()
        grid = QGridLayout()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel('Control'), 1, 0)
        grid.addWidget(QLabel('Rendered'), 1, 1)
        grid.addWidget(QLabel('Difference'), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel('Current Mask'), 3, 0)
        grid.addWidget(QLabel('New Mask'), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        self.widget.setLayout(grid)
        self.scrollArea.setWidget(self.widget)
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.scrollArea, 1)

        next_image_button = QPushButton()
        next_image_button.setText('Skip')
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)
        self.overload_spin.valueChanged.connect(lambda: save_mask_button.setEnabled(False))

        preview_mask_button = QPushButton()
        preview_mask_button.setText('Preview New Mask')
        preview_mask_button.pressed.connect(self.preview_mask)
        preview_mask_button.pressed.connect(lambda: save_mask_button.setEnabled(True))

        save_mask_button = QPushButton()
        save_mask_button.setText('Save New Mask')
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel('Mask diff multiplier:'))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)
Beispiel #12
0
    def initUi(self):
        self.setWindowTitle('Конвертер валют')

        self.srcLabel = QLabel(' Сумма в рублях', self)
        self.resultLabel = QLabel('Сумма в долларах', self)

        self.srcAmmount = QDoubleSpinBox(self)
        self.srcAmmount.setMaximum(999999999)
        self.resultAmount = QDoubleSpinBox(self)
        self.resultAmount.setMaximum(999999999)
        #self.resultAmount.setReadOnly(True)
        #self.resultAmount.setDisabled(True)

        self.convertBtn = QPushButton('Перевести', self)

        self.resetBtn = QPushButton('Очистить', self)
Beispiel #13
0
    def __init__(self, page):
        super(LogTool, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

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

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

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

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

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

        app.translateUI(self)
Beispiel #14
0
    def __init__(self, parent=None):
        super().__init__(parent)

        date = self.getdata()
        rates = sorted(self.rates.keys(), key=str.lower)
     #   print(rates)

        dateLabel = QLabel(date)
        self.fromComboBox = QComboBox()
        self.fromComboBox.addItems(rates)
        self.fromSpinBox = QDoubleSpinBox()
        self.fromSpinBox.setRange(0.01, 10000000.00)
        self.fromSpinBox.setValue(1.00)
        self.toComboBox = QComboBox()
        self.toComboBox.addItems(rates)
        self.toLabel = QLabel("1.00")
        grid = QGridLayout()
        grid.addWidget(dateLabel, 0, 0)
        grid.addWidget(self.fromComboBox, 1, 0)
        grid.addWidget(self.fromSpinBox, 1, 1)
        grid.addWidget(self.toComboBox, 2, 0)
        grid.addWidget(self.toLabel, 2, 1)
        self.setLayout(grid)
        self.fromComboBox.currentIndexChanged.connect(self.updateUi)
        self.toComboBox.currentIndexChanged.connect(self.updateUi)
        self.fromSpinBox.valueChanged.connect(self.updateUi)
        self.setWindowTitle("Currency")
    def _refresh_widgets_from_axistags(self):
        axiskeys = [tag.key for tag in self.axistags]
        row_widgets = collections.OrderedDict()
        for key in axiskeys:
            tag_info = self.axistags[key]
            
            resolution_box = QDoubleSpinBox(parent=self)
            resolution_box.setRange(0.0, numpy.finfo(numpy.float32).max)
            resolution_box.setValue( tag_info.resolution )
            resolution_box.valueChanged.connect( self._update_axistags_from_widgets )
            resolution_box.installEventFilter(self)
            
            description_edit = QLineEdit(tag_info.description, parent=self)
            description_edit.textChanged.connect( self._update_axistags_from_widgets )
            description_edit.installEventFilter(self)            

            row_widgets[key] = RowWidgets( resolution_box, description_edit )

        # Clean up old widgets (if any)
        for row in range(self.rowCount()):
            for col in range(self.columnCount()):
                w = self.cellWidget( row, col )
                if w:
                    w.removeEventFilter(self)

        # Fill table with widgets
        self.setRowCount( len(row_widgets) )
        self.setVerticalHeaderLabels( list(row_widgets.keys()) )
        for row, widgets in enumerate(row_widgets.values()):
            self.setCellWidget( row, 0, widgets.resolution_box )
            self.setCellWidget( row, 1, widgets.description_edit )
Beispiel #16
0
 def createEditor(self, parent, option, index):  # residNum,residNum_color, residName, atomName, atomNum, X,Y,Z
     if index.column() == residNum:
         spinbox = QSpinBox(parent)
         spinbox.setRange(1, 200000)
         spinbox.setSingleStep(1)
         spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
         return spinbox
     elif index.column() == residName:
         combobox = QComboBox(parent)
         combobox.addItems(comboBoxList)
         combobox.insertSeparator(23)
         combobox.setEditable(True)
         return combobox
     elif index.column() == atomName:
         editor = QLineEdit(parent)
         editor.returnPressed.connect(self.commitAndCloseEditor)
         return editor
     elif index.column() == atomNum:
         spinbox = QSpinBox(parent)
         spinbox.setRange(1, 200000)
         spinbox.setSingleStep(1)
         spinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
         return spinbox
     elif index.column() in (X, Y, Z):  ###this works
         dspinbox = QDoubleSpinBox(parent)
         dspinbox.setRange(-200000, 200000)
         dspinbox.setSingleStep(0.1)
         dspinbox.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
         return dspinbox
     else:
         return QStyledItemDelegate.createEditor(self, parent, option,
                                                 index)
    def __init__(self, lower, upper, step_size, default):
        super(DoubleTextfield, self).__init__()

        # Textfield
        self.textfield = QDoubleSpinBox()

        self.textfield.setRange(lower, upper)
        self.textfield.setSingleStep(step_size)
        self.textfield.setValue(default)
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout())

        # Pre wait
        self.preWaitGroup = QGroupBox(self)
        self.preWaitGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.preWaitGroup)

        self.preWaitSpin = QDoubleSpinBox(self.preWaitGroup)
        self.preWaitSpin.setMaximum(3600 * 24)
        self.preWaitGroup.layout().addWidget(self.preWaitSpin)

        self.preWaitLabel = QLabel(self.preWaitGroup)
        self.preWaitLabel.setAlignment(Qt.AlignCenter)
        self.preWaitGroup.layout().addWidget(self.preWaitLabel)

        # Post wait
        self.postWaitGroup = QGroupBox(self)
        self.postWaitGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.postWaitGroup)

        self.postWaitSpin = QDoubleSpinBox(self.postWaitGroup)
        self.postWaitSpin.setMaximum(3600 * 24)
        self.postWaitGroup.layout().addWidget(self.postWaitSpin)

        self.postWaitLabel = QLabel(self.postWaitGroup)
        self.postWaitLabel.setAlignment(Qt.AlignCenter)
        self.postWaitGroup.layout().addWidget(self.postWaitLabel)

        # Next action
        self.nextActionGroup = QGroupBox(self)
        self.nextActionGroup.setLayout(QHBoxLayout())
        self.layout().addWidget(self.nextActionGroup)

        self.nextActionCombo = QComboBox(self.nextActionGroup)
        self.nextActionCombo.addItems([e.value for e in CueNextAction])
        self.nextActionGroup.layout().addWidget(self.nextActionCombo)

        # Checks
        self.stopPauseCheck = QCheckBox(self)
        self.layout().addWidget(self.stopPauseCheck)

        self.retranslateUi()
Beispiel #19
0
    def __init__(self, tool):
        super(Widget, self).__init__(tool)
        self.mainwindow = tool.mainwindow()
        self.define = None

        import panelmanager
        self.svgview = panelmanager.manager(tool.mainwindow()).svgview.widget().view

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

        self.elemLabel = QLabel()

        self.XOffsetBox = QDoubleSpinBox()
        self.XOffsetBox.setRange(-99,99)
        self.XOffsetBox.setSingleStep(0.1)
        self.XOffsetLabel = l = QLabel()
        l.setBuddy(self.XOffsetBox)

        self.YOffsetBox = QDoubleSpinBox()
        self.YOffsetBox.setRange(-99,99)
        self.YOffsetBox.setSingleStep(0.1)
        self.YOffsetLabel = l = QLabel()
        l.setBuddy(self.YOffsetBox)

        self.insertButton = QPushButton("insert offset in source", self)
        self.insertButton.clicked.connect(self.callInsert)

        layout.addWidget(self.elemLabel)
        layout.addWidget(self.XOffsetLabel)
        layout.addWidget(self.XOffsetBox)
        layout.addWidget(self.YOffsetLabel)
        layout.addWidget(self.YOffsetBox)
        layout.addWidget(self.insertButton)

        layout.addStretch(1)

        app.translateUI(self)
        self.loadSettings()

        self.connectSlots()
Beispiel #20
0
    def createDoubleSpinBoxes(self):
        self.doubleSpinBoxesGroup = QGroupBox("Double precision spinboxes")

        precisionLabel = QLabel("Number of decimal places to show:")
        precisionSpinBox = QSpinBox()
        precisionSpinBox.setRange(0, 100)
        precisionSpinBox.setValue(2)

        doubleLabel = QLabel("Enter a value between %d and %d:" % (-20, 20))
        self.doubleSpinBox = QDoubleSpinBox()
        self.doubleSpinBox.setRange(-20.0, 20.0)
        self.doubleSpinBox.setSingleStep(1.0)
        self.doubleSpinBox.setValue(0.0)

        scaleLabel = QLabel("Enter a scale factor between %d and %d:" % (0, 1000))
        self.scaleSpinBox = QDoubleSpinBox()
        self.scaleSpinBox.setRange(0.0, 1000.0)
        self.scaleSpinBox.setSingleStep(10.0)
        self.scaleSpinBox.setSuffix('%')
        self.scaleSpinBox.setSpecialValueText("No scaling")
        self.scaleSpinBox.setValue(100.0)

        priceLabel = QLabel("Enter a price between %d and %d:" % (0, 1000))
        self.priceSpinBox = QDoubleSpinBox()
        self.priceSpinBox.setRange(0.0, 1000.0)
        self.priceSpinBox.setSingleStep(1.0)
        self.priceSpinBox.setPrefix('$')
        self.priceSpinBox.setValue(99.99)

        precisionSpinBox.valueChanged.connect(self.changePrecision)

        spinBoxLayout = QVBoxLayout()
        spinBoxLayout.addWidget(precisionLabel)
        spinBoxLayout.addWidget(precisionSpinBox)
        spinBoxLayout.addWidget(doubleLabel)
        spinBoxLayout.addWidget(self.doubleSpinBox)
        spinBoxLayout.addWidget(scaleLabel)
        spinBoxLayout.addWidget(self.scaleSpinBox)
        spinBoxLayout.addWidget(priceLabel)
        spinBoxLayout.addWidget(self.priceSpinBox)
        self.doubleSpinBoxesGroup.setLayout(spinBoxLayout)
Beispiel #21
0
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle("Dash results")
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        grid = QGridLayout()
        self.test_name_label = QLabel()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel("Control"), 1, 0)
        grid.addWidget(QLabel("Rendered"), 1, 1)
        grid.addWidget(QLabel("Difference"), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel("Current Mask"), 3, 0)
        grid.addWidget(QLabel("New Mask"), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        v_layout = QVBoxLayout()
        v_layout.addLayout(grid, 1)

        next_image_button = QPushButton()
        next_image_button.setText("Skip")
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)

        preview_mask_button = QPushButton()
        preview_mask_button.setText("Preview New Mask")
        preview_mask_button.pressed.connect(self.preview_mask)

        save_mask_button = QPushButton()
        save_mask_button.setText("Save New Mask")
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel("Mask diff multiplier:"))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)
    def __init__(self):
        """The constructor initializes the class NewVariantDialog."""
        super().__init__()

        self.value = 0

        # create the input fields
        self.x = QDoubleSpinBox(decimals=1, maximum=99, singleStep=0.1, suffix=" m")
        self.y = QDoubleSpinBox(decimals=1, maximum=99, singleStep=0.1, suffix=" m")
        label = QLabel("x")

        # dialog main layout
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.x)
        layout.addWidget(label)
        layout.addWidget(self.y)

        # connect actions
        self.x.valueChanged.connect(self.calculate)
        self.y.valueChanged.connect(self.calculate)
Beispiel #23
0
    def __init__(self, *args, **kwargs):
        super(FullScreenQuad, self).__init__(*args, **kwargs)

        self.propertiesWidget = QWidget()

        self.vlayout = QVBoxLayout()

        self.xoffsetWidget = QDoubleSpinBox()
        self.xoffsetWidget.setMaximum(9999)
        self.xoffsetWidget.setMinimum(-9999)
        self.yoffsetWidget = QDoubleSpinBox()
        self.yoffsetWidget.setMaximum(9999)
        self.yoffsetWidget.setMinimum(-9999)
        self.vlayout.addWidget(self.xoffsetWidget)
        self.vlayout.addWidget(self.yoffsetWidget)

        self.xoffsetWidget.valueChanged.connect(self.offsetchange)
        self.yoffsetWidget.valueChanged.connect(self.offsetchange)

        self.vlayout.addItem(QSpacerItem(40, 20, QSizePolicy.Minimum, QSizePolicy.Expanding))

        self.propertiesWidget.setLayout(self.vlayout)
Beispiel #24
0
    def eventFilter(self, *args: Any, **kwargs: Any) -> bool:
        """Filter MousePressEvent and show num pad."""
        sender = args[0]
        event = args[1]

        if event.type() == QEvent.MouseButtonPress:
            if self.isEnabled() and not self.isReadOnly():
                numpad = NumPad(self, sender.text())
                if numpad.exec_() == QDialog.Accepted:
                    newValue = string_to_float(numpad.outputLineEdit.text())
                    self.setValue(int(newValue))

        return QDoubleSpinBox.eventFilter(self, *args, **kwargs)
class DoubleTextfield(QDoubleSpinBox):
    """
    A customized QDoubleSpinBox that is used by the SliderWidget to allow users to enter float values.
    """

    def __init__(self, lower, upper, step_size, default):
        super(DoubleTextfield, self).__init__()

        # Textfield
        self.textfield = QDoubleSpinBox()

        self.textfield.setRange(lower, upper)
        self.textfield.setSingleStep(step_size)
        self.textfield.setValue(default)
        self.textfield.setFixedWidth(75)
Beispiel #26
0
	def __init__(self, parent=None):
		super(Form, self).__init__(parent)

		principalLabel = QLabel("Principal:")
		self.principalSpinBox = QDoubleSpinBox()
		self.principalSpinBox.setRange(1, 1000000000)
		self.principalSpinBox.setValue(1000)
		self.principalSpinBox.setPrefix("RMB ")
		rateLabel = QLabel("Rate:")
		self.rateSpinBox = QDoubleSpinBox()
		self.rateSpinBox.setRange(1, 100)
		self.rateSpinBox.setValue(5)
		self.rateSpinBox.setSuffix(" %")
		yearsLabel = QLabel("Years:")
		self.yearsComboBox = QComboBox()
		self.yearsComboBox.addItem("1 year")
		self.yearsComboBox.addItems(["{0} years".format(x)
									 for x in range(2, 31)])
		amountLabel = QLabel("Amount")
		self.amountLabel = QLabel()

		grid = QGridLayout()
		grid.addWidget(principalLabel, 0, 0)
		grid.addWidget(self.principalSpinBox, 0, 1)
		grid.addWidget(rateLabel, 1, 0)
		grid.addWidget(self.rateSpinBox, 1, 1)
		grid.addWidget(yearsLabel, 2, 0)
		grid.addWidget(self.yearsComboBox, 2, 1)
		grid.addWidget(amountLabel, 3, 0)
		grid.addWidget(self.amountLabel, 3, 1)
		self.setLayout(grid)

		self.principalSpinBox.valueChanged.connect(self.updateUi)
		self.rateSpinBox.valueChanged.connect(self.updateUi)
		self.yearsComboBox.currentIndexChanged.connect(self.updateUi)
		
		self.setWindowTitle("Interest")
		self.updateUi()
Beispiel #27
0
class CharMap(preferences.Group):
    def __init__(self, page):
        super(CharMap, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

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

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

    def translateUI(self):
        self.setTitle(_("Special Characters"))
        self.fontLabel.setText(_("Font:"))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("charmaptool")
        font = self.font()
        family = s.value("fontfamily", "", str)
        if family:
            font.setFamily(family)
        font.setPointSizeF(s.value("fontsize", font.pointSizeF(), float))
        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(font)
            self.fontSize.setValue(font.pointSizeF())

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("charmaptool")
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
Beispiel #28
0
	def makeSweepControl(self):

		ptsLabel = QLabel('Number of Points:')
		self.ptsCtrl  = QSpinBox()
		self.ptsCtrl.setRange(1, 2500)
		self.ptsCtrl.setValue(1024)

		stFLabel = QLabel('Start Freq:')
		self.strtCtrl = QDoubleSpinBox()
		self.strtCtrl.setRange(375, 6050)
		self.strtCtrl.setValue(375)
		self.strtCtrl.setSuffix(" Mhz")
		spFLabel = QLabel('Stop Freq:')
		self.stpCtrl  = QDoubleSpinBox()
		self.stpCtrl.setRange(375, 6050)
		self.stpCtrl.setValue(6050)
		self.stpCtrl.setSuffix(" Mhz")

		self.ptsCtrl.valueChanged.connect(self.updateSweepParameters)
		self.strtCtrl.valueChanged.connect(self.updateSweepParameters)
		self.stpCtrl.valueChanged.connect(self.updateSweepParameters)


		inputlayout = QGridLayout()
		inputlayout.addWidget(QLabel('Start:'),      0, 0, 1, 1)
		inputlayout.addWidget(QLabel('Stop:'),       1, 0, 1, 1)
		inputlayout.addWidget(QLabel('Points:'),     2, 0, 1, 1)
		inputlayout.addWidget(self.strtCtrl,         0, 1, 1, 3)
		inputlayout.addWidget(self.stpCtrl,          1, 1, 1, 3)
		inputlayout.addWidget(self.ptsCtrl,          2, 1, 1, 3)


		self.sweep_parameters_group = QGroupBox("Sweep Parameters");
		self.sweep_parameters_group.setLayout(inputlayout)

		return self.sweep_parameters_group
    def __init__(self, parent, min_=1, max_=1000, step=1, round_option=True):
        QWidget.__init__(self, parent)
        layout = QVBoxLayout(self)
        hlayout = QHBoxLayout()
        self.start = QDoubleSpinBox(self)
        self.start.setMinimum(min_)
        self.start.setMaximum(max_)
        self.end = QDoubleSpinBox(self)
        self.end.setMinimum(min_)
        self.end.setMaximum(max_)
        self.end.setValue(max_)
        self.start.setSingleStep(step)
        self.end.setSingleStep(step)

        self.start.valueChanged.connect(self.on_value_start_changed)
        self.end.valueChanged.connect(self.on_value_end_changed)

        hlayout.addWidget(self.start)
        hlayout.addWidget(self.end)
        layout.addLayout(hlayout)

        if round_option:
            self.integerCheckBox = QCheckBox("Round to integer values", self)
            layout.addWidget(self.integerCheckBox)
    def auswahlKlasse(self):
        if self.auswahlAlter.currentIndex() == 0:
            return False
        elif self.auswahlGeschlecht.currentIndex() == 0:
            return False
        elif self.auswahlDisziplin.currentIndex() == 0:
            return False

        self.clearAuswahl()

        disziplin = self.auswahlDisziplin.currentIndex()-1
        if self.auswahlDisziplin.currentText() is "-":
            return

        for sportler in QueryTool().queryAndFetch("SELECT ID, Name, Vorname FROM LG_NGD WHERE WieAlt = ? AND Geschlecht = ?",
                                                 self.auswahlAlter.currentIndex()+2,
                                                 bool(self.auswahlGeschlecht.currentIndex()-1)):
            self._sportler += [sportler[0]]
            name = "{} {}".format(sportler[2],sportler[1])
            #UID, Name

            for werte in reversed(QueryTool().queryAndFetch("SELECT Wert1, Wert2, Wert3 FROM LG_NGD_Ergebnisse WHERE UID = ? "
                                                   "AND Typ = ? UNION SELECT 0, 0, 0",
                                                   sportler[0],
                                                   disziplin)):

                row = self.mainLayout.rowCount()

                self.mainLayout.addWidget(QLabel(name), row, 0)
                for i in range(0,felderzahl[disziplin]):
                    el = QDoubleSpinBox()
                    el.setMaximum(99999)
                    el.setValue(werte[i])
                    el.setSuffix(" "+einheiten[disziplin])
                    el.setSingleStep(0.01)
                    self.mainLayout.addWidget(el, row, i+1, 1, 3/felderzahl[disziplin])
                break
        self._speichern = QPushButton("Speichern")
        self._speichern.clicked.connect(self.speichern)
        self.mainLayout.addWidget(self._speichern, self.mainLayout.rowCount(), 0, 1, 4)
Beispiel #31
0
    def fill_table2(self, values=[]):

        if len(values) == 0:
            values = [0.0] * self.n_params()

        self.tableWidget.setColumnCount(self.n_col)
        self.tableWidget.setRowCount(self.n_row())

        # column header
        item = QTableWidgetItem()
        item.setText('Eff')
        self.tableWidget.setHorizontalHeaderItem(0, item)

        item = QTableWidgetItem()
        item.setText('Er_F')
        self.tableWidget.setHorizontalHeaderItem(1, item)

        item = QTableWidgetItem()
        item.setText('Er_C')
        self.tableWidget.setHorizontalHeaderItem(2, item)

        # Eff nodes
        for i_row in range(self.n_Eff):
            # header
            item = QTableWidgetItem()
            item.setText('E{:d}'.format(i_row + 1))
            self.tableWidget.setVerticalHeaderItem(i_row, item)

            # cells
            # item = QCheckBox()
            for i_col in range(self.n_col):
                i_value = self.n_col * i_row + i_col
                item = QDoubleSpinBox()
                item.setValue(values[i_value])
                item.setDecimals(3)
                item.setMinimum(np.finfo(dtype=np.float64).min)
                item.setMaximum(np.finfo(dtype=np.float64).max)
                item.setSingleStep(0.001)
                self.tableWidget.setCellWidget(i_row, i_col, item)

        # nuisance
        for i_row in range(self.n_Eff, self.n_row()):

            nui_ix = list(range(self.n_col * (i_row - self.n_Eff) + 1,
                                np.amin([self.n_nuisance + 1, self.n_col * (i_row - self.n_Eff) + 4])))
            # row header
            item = QTableWidgetItem()
            if len(nui_ix) > 0:
                item.setText('?' + str(nui_ix))
            else:
                item.setText('+/- node')
            self.tableWidget.setVerticalHeaderItem(i_row, item)

            for i_col in range(self.n_col):
                i_value = self.n_col * i_row + i_col
                item = QDoubleSpinBox()
                if i_value < self.n_params():
                    item.setValue(values[i_value])
                else:
                    item.setValue(0.0)
                item.setDecimals(3)
                item.setMinimum(np.finfo(dtype=np.float64).min)
                item.setMaximum(np.finfo(dtype=np.float64).max)
                item.setSingleStep(0.001)
                self.tableWidget.setCellWidget(i_row, i_col, item)

        self.resize_table()
        self.connect_signal()
Beispiel #32
0
class Information_frame(QFrame):
    def __init__(self, display):
        super().__init__()
        self.display_frame = display
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.load_map()
        self.load_data()
        self.thread_running = False
        self.trainning_option()
        self.running_option()
        self.PSO_RBFN_setting()
        self.trian_detail_setting()
        self.monitor_setting()
        self.__init_controller()
        self.running_threads = []
        self.rbfn = None

    def running_option(self):
        self.run_group = []
        group = QGroupBox("Simulation option")
        group_layout = QHBoxLayout()
        group.setLayout(group_layout)

        self.run_btn = QPushButton("Run")
        self.run_btn.clicked.connect(self.start_simulation)
        self.pause_btn = QPushButton("Pause")
        self.pause_btn.setDisabled(True)
        self.stop_btn = QPushButton("Stop")
        self.stop_btn.setDisabled(True)

        self.save_btn = QPushButton("Save")
        self.save_btn.clicked.connect(self.save_data)
        self.save_btn.setDisabled(True)

        self.run_group.append(self.run_btn)
        self.run_group.append(self.pause_btn)
        self.run_group.append(self.stop_btn)
        self.run_group.append(self.save_btn)
        group_layout.addWidget(self.run_btn)
        group_layout.addWidget(self.pause_btn)
        group_layout.addWidget(self.stop_btn)
        group_layout.addWidget(self.save_btn)
        self.layout.addWidget(group)

    def trainning_option(self):
        self.train_group = []
        group = QGroupBox("Trainning option")
        group_layout = QHBoxLayout()
        group.setLayout(group_layout)

        self.train_btn = QPushButton("Train")
        self.train_btn.clicked.connect(self.start_tranning)
        self.stop_train_btn = QPushButton("Stop")
        self.stop_train_btn.setDisabled(True)
        self.save_param_btn = QPushButton("Save")
        self.save_param_btn.clicked.connect(self.save_params)
        self.save_param_btn.setEnabled(False)
        self.load_params_btn = QPushButton("Load")
        self.load_params_btn.clicked.connect(self.load_params)
        self.trainning_data_selector = QComboBox()
        self.trainning_data_selector.addItems(self.train_dataset.keys())

        self.train_group.append(self.train_btn)
        self.train_group.append(self.stop_train_btn)
        self.train_group.append(self.save_param_btn)
        self.train_group.append(self.trainning_data_selector)
        self.train_group.append(self.load_params_btn)
        group_layout.addWidget(self.train_btn)
        group_layout.addWidget(self.stop_train_btn)
        group_layout.addWidget(self.save_param_btn)
        group_layout.addWidget(self.load_params_btn)
        group_layout.addWidget(self.trainning_data_selector)

        self.layout.addWidget(group)

    def PSO_RBFN_setting(self):
        group = QGroupBox("GA parameters setting")
        group_layout = QFormLayout()
        group.setLayout(group_layout)
        self.iter_times = QSpinBox()
        self.iter_times.setRange(1, 1000)
        self.iter_times.setValue(100)

        self.population_size = QSpinBox()
        self.population_size.setRange(1, 500)
        self.population_size.setValue(100)

        self.inertia_weight = QDoubleSpinBox()
        self.inertia_weight.setRange(0, 1.5)
        self.inertia_weight.setValue(1.0)
        self.inertia_weight.setSingleStep(0.1)

        self.cognitive_weight = QDoubleSpinBox()
        self.cognitive_weight.setRange(0, 5)
        self.cognitive_weight.setValue(2)
        self.cognitive_weight.setSingleStep(0.5)

        self.social_weight = QDoubleSpinBox()
        self.social_weight.setRange(0, 5)
        self.social_weight.setValue(2)
        self.social_weight.setSingleStep(0.5)

        self.num_neuron = QSpinBox()
        self.num_neuron.setRange(1, 100)
        self.num_neuron.setValue(3)

        group_layout.addRow(QLabel("iterate times : "), self.iter_times)
        group_layout.addRow(QLabel("population size : "), self.population_size)
        group_layout.addRow(QLabel("inertia factor : "), self.inertia_weight)
        group_layout.addRow(QLabel("cognitive weight upper bound : "),
                            self.cognitive_weight)
        group_layout.addRow(QLabel("social weight upper bound : "),
                            self.social_weight)
        group_layout.addRow(QLabel("number of neuron : "), self.num_neuron)

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

    def trian_detail_setting(self):
        group = QGroupBox("Trainning detail for single iteration")
        group_layout = QFormLayout()

        self.current_iter = QLabel("0")
        self.min_error = QLabel("0.0")
        self.Gbest_error = QLabel("0.0")
        self.average_error = QLabel("0.0")
        self.train_progress = QProgressBar()
        self.current_iter.setAlignment(Qt.AlignCenter)
        self.Gbest_error.setAlignment(Qt.AlignCenter)
        self.min_error.setAlignment(Qt.AlignCenter)
        self.average_error.setAlignment(Qt.AlignCenter)

        group_layout.addRow(QLabel("Current iteration : "), self.current_iter)
        group_layout.addRow(QLabel("iter Min error : "), self.min_error)
        group_layout.addRow(QLabel("Swarm min error : "), self.Gbest_error)
        group_layout.addRow(QLabel("Average error of swarm : "),
                            self.average_error)
        group_layout.addRow(self.train_progress)
        group.setLayout(group_layout)
        self.layout.addWidget(group)

    def monitor_setting(self):
        group = QGroupBox("Simulation imformation")
        group_layout = QFormLayout()

        self.l_car_pos = QLabel("0 , 0")
        self.l_front_dist = QLabel("0.0")
        self.label_l_dist = QLabel("0.0")
        self.label_r_dist = QLabel("0.0")
        self.l_car_angle = QLabel("0.0")
        self.l_wheel_angle = QLabel("0.0")

        self.l_car_pos.setAlignment(Qt.AlignCenter)
        self.l_front_dist.setAlignment(Qt.AlignCenter)
        self.label_l_dist.setAlignment(Qt.AlignCenter)
        self.label_r_dist.setAlignment(Qt.AlignCenter)
        self.l_car_angle.setAlignment(Qt.AlignCenter)
        self.l_wheel_angle.setAlignment(Qt.AlignCenter)
        group_layout.addRow(QLabel("Car position :"), self.l_car_pos)
        group_layout.addRow(QLabel("Car angle :"), self.l_car_angle)
        group_layout.addRow(QLabel("Front distance :"), self.l_front_dist)
        group_layout.addRow(QLabel("Left side distance :"), self.label_l_dist)
        group_layout.addRow(QLabel("Right side distance :"), self.label_r_dist)
        group_layout.addRow(QLabel("Wheel angle :"), self.l_wheel_angle)

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

    @pyqtSlot()
    def start_tranning(self):
        @pyqtSlot()
        def train_settting():
            for obj in self.run_group:
                obj.setDisabled(True)
            self.train_btn.setDisabled(True)
            self.stop_train_btn.setEnabled(True)

        self.train_progress.setMaximum(self.iter_times.value())
        current_data = self.trainning_data_selector.currentText()
        train_data = self.train_dataset[current_data]
        m_range = (min(min(data["data"]) for data in train_data),
                   max(max(data["data"]) for data in train_data))

        self.rbfn = RBFN(self.num_neuron.value(), len(train_data[0]["data"]))
        self.trainning_thread = PSO(train_data, self.iter_times.value(),
                                    self.population_size.value(), m_range,
                                    self.inertia_weight.value(),
                                    self.social_weight.value(),
                                    self.cognitive_weight.value(), self.rbfn)

        self.trainning_thread.sig_train_detail.connect(self.show_train_detail)
        self.stop_train_btn.clicked.connect(self.trainning_thread.stop)
        self.trainning_thread.started.connect(train_settting)
        self.trainning_thread.finished.connect(self.__reset_controller)

        self.running_threads.append(self.trainning_thread)
        self.thread_running = True
        self.trainning_thread.start()

    @pyqtSlot()
    def start_simulation(self):
        @pyqtSlot()
        def simulate_setting():
            for obj in self.train_group:
                obj.setDisabled(True)
            self.run_btn.setDisabled(True)
            self.pause_btn.setEnabled(True)
            self.stop_btn.setEnabled(True)
            self.save_btn.setDisabled(True)

        self.simulator_thread = Run(dataset=self.map, rbfn=self.rbfn)
        self.pause_btn.clicked.connect(self.simulator_thread.paused)
        self.stop_btn.clicked.connect(self.simulator_thread.stop)
        self.simulator_thread.started.connect(simulate_setting)
        self.simulator_thread.finished.connect(self.__reset_controller)
        self.simulator_thread.sig_connect(p_init=self.display_frame.init_walls,
                                          p_car=self.move_car,
                                          collide=self.display_frame.collide,
                                          log=self.simulation_log)

        self.running_threads.append(self.simulator_thread)
        self.thread_running = True
        self.simulator_thread.start()

    def __init_controller(self):
        for widget in self.run_group:
            widget.setDisabled(True)
        self.stop_train_btn.setDisabled(True)
        self.save_param_btn.setDisabled(True)

    @pyqtSlot()
    def __reset_controller(self):
        self.simulate_allow = True if self.train_progress.value(
        ) == self.train_progress.maximum() else False
        for widget in self.run_group:
            widget.setEnabled(self.simulate_allow)
        for widget in self.train_group:
            widget.setEnabled(True)
        self.pause_btn.setDisabled(True)
        self.stop_btn.setDisabled(True)
        self.stop_train_btn.setDisabled(True)

    @pyqtSlot(int, float, float, float)
    def show_train_detail(self, time, min_err, gbest_err, avg_err):
        self.current_iter.setText(str(time))
        self.min_error.setText(str(min_err))
        self.Gbest_error.setText(str(gbest_err))
        self.average_error.setText(str(avg_err))
        self.train_progress.setValue(time)

    @pyqtSlot(list, list, list, float)
    def move_car(self, pos_angle, inters, dists, wheel_ouput):
        self.l_car_pos.setText("{:.3f},{:.3f}".format(*pos_angle[:2]))
        self.l_car_angle.setText(str(pos_angle[2]))
        self.l_front_dist.setText(str(dists[0]))
        self.label_r_dist.setText(str(dists[1]))
        self.label_l_dist.setText(str(dists[2]))
        self.l_wheel_angle.setText(str(wheel_ouput))

        self.display_frame.update_car(pos_angle, inters)

    @pyqtSlot(dict)
    def simulation_log(self, log):
        #TODO:
        self.log = log
        self.display_frame.show_path(self.log['x'], self.log['y'])

    @pyqtSlot()
    def save_data(self):
        #TODO:
        save_dir = QFileDialog.getExistingDirectory(self, 'Save As')
        path_4d = join(save_dir, 'train4D.txt')
        path_6d = join(save_dir, 'train6D.txt')
        data_lines = list(zip(*self.log.values()))
        with open(path_6d, 'w') as f6d:
            for line in data_lines:
                f6d.write("{:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}\n".format(
                    line[0], line[1], line[2], line[3], line[4], line[5]))

        with open(path_4d, 'w') as f4d:
            for l in data_lines:
                f4d.write("{:.3f} {:.3f} {:.3f} {:.3f}\n".format(
                    l[2], l[3], l[4], l[5]))

    @pyqtSlot()
    def save_params(self):
        save_dir = QFileDialog.getExistingDirectory(self, 'Save As')
        params_path = join(save_dir, "RBFN model params.txt")
        with open(params_path, 'w') as f:
            f.write("{:.3f}\n".format(self.rbfn.list_neuron[0].weight))
            for neuron in self.rbfn.list_neuron[1:]:
                f.write("{:.3f} ".format(neuron.weight))
                for mean in neuron.means:
                    f.write("{:.3f} ".format(mean))
                f.write("{:.3f}\n".format(neuron.dev))

    @pyqtSlot()
    def load_params(self):
        load_dir = QFileDialog.getOpenFileName(self, 'RBFN params file')[0]
        if (load_dir != ''):
            params = []
            with open(load_dir, 'r', encoding='utf8') as f:
                for line in f:
                    neuron_param = list(map(float, line.strip().split()))
                    params.append(neuron_param)
            num_neuron = len(params)
            data_dim = len(params[-1]) - 2

            if self.rbfn == None:
                self.rbfn = RBFN(num_neuron - 1, data_dim)
            self.rbfn.load_parameters(params)
            self.train_progress.setValue(self.train_progress.maximum())
            self.__reset_controller()

    def load_map(self, map_path='./maps/case01.txt'):
        data = []
        with open(map_path, 'r', encoding='utf8') as f:
            for line in f:
                data.append(tuple(line.strip().split(',')))
        self.map = {
            "start_pos": data[0][:2],
            "start_wheel_angle": data[0][2],
            "finishline_l": data[1],
            "finishline_r": data[2],
            "walls": data[3:]
        }

    def load_data(self, folderpath='data'):
        self.train_dataset = {}
        folderpath = Path(folderpath)
        for f in folderpath.glob("*.txt"):
            with f.open() as data:
                content = []
                for line in data:
                    raw = tuple(map(float, line.strip().split()))
                    content.append({'data': raw[:-1], 'label': raw[-1]})
            self.train_dataset[f.stem] = content
Beispiel #33
0
class ShowGroundTruth(QFrame):

    sig_groundtruth_changed = pyqtSignal(float, float)

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

        self.parent = parent
        self.buildUI()

    def buildUI(self):
        self.setSizePolicy(QtWidgets.QSizePolicy.Minimum,
                           QtWidgets.QSizePolicy.Minimum)
        self.showGT_cb = QCheckBox("Show Ground Truth")

        self.lat_spinbox = QDoubleSpinBox()
        self.lat_spinbox.setMinimum(-90)
        self.lat_spinbox.setMaximum(90)
        self.lat_spinbox.setSuffix(' deg')
        self.lat_spinbox.setEnabled(False)
        self.lat_spinbox.valueChanged.connect(self.groundTruthChanged)

        self.lon_spinbox = QDoubleSpinBox()
        self.lon_spinbox.setMinimum(-180)
        self.lon_spinbox.setMaximum(180)
        self.lon_spinbox.setSuffix(' deg')
        self.lon_spinbox.setEnabled(False)
        self.lon_spinbox.valueChanged.connect(self.groundTruthChanged)

        formlayout = QFormLayout()
        formlayout.addRow('Lon: ', self.lon_spinbox)
        formlayout.addRow('Lat: ', self.lat_spinbox)

        layout = QVBoxLayout()
        layout.addWidget(self.showGT_cb)
        layout.addLayout(formlayout)

        self.setFrameStyle(QFrame.Box | QFrame.Plain)
        layout.setAlignment(Qt.AlignCenter)
        self.setLayout(layout)

        self.showGT_cb.toggled.connect(self.enableSpins)

    @pyqtSlot(bool)
    def enableSpins(self, enabled):
        # this will enable or disable to ground truth lat lons
        self.lat_spinbox.setEnabled(enabled)
        self.lon_spinbox.setEnabled(enabled)

    def groundTruthChanged(self):
        self.sig_groundtruth_changed.emit(self.lon_spinbox.value(),
                                          self.lat_spinbox.value())
Beispiel #34
0
 def __init__(self, parent, gps_config_data, model, version):
     super().__init__(parent)
     self.gps_config_data = GpsConfigData(gps_config_data)
     self.model = model
     self.version = version
     # Layout form
     dlg_layout = QVBoxLayout(self)
     form_layout = QFormLayout()
     caption_constellation = QLabel(self)
     caption_constellation.setText(
         "Constellations Tracked:\n\n  (Not all combos supported)")
     gnss_layout = QVBoxLayout()
     self.gps_checkbox = QCheckBox(self)
     self.gps_checkbox.setText("GPS")
     self.glonass_checkbox = QCheckBox(self)
     self.glonass_checkbox.setText("GLONASS")
     self.beidou_checkbox = QCheckBox(self)
     self.beidou_checkbox.setText("BEIDOU")
     self.galileo_checkbox = QCheckBox(self)
     self.galileo_checkbox.setText("GALILEO")
     gnss_layout.addWidget(self.gps_checkbox)
     gnss_layout.addWidget(self.glonass_checkbox)
     gnss_layout.addWidget(self.beidou_checkbox)
     gnss_layout.addWidget(self.galileo_checkbox)
     if self.is_old_fs740():
         caption_constellation.hide()
         self.gps_checkbox.hide()
         self.glonass_checkbox.hide()
         self.beidou_checkbox.hide()
         self.galileo_checkbox.hide()
     form_layout.setWidget(0, QFormLayout.LabelRole, caption_constellation)
     form_layout.setLayout(0, QFormLayout.FieldRole, gnss_layout)
     caption_alignment = QLabel(self)
     caption_alignment.setText("Timing Alignment:")
     self.align_combobox = QComboBox(self)
     self.align_combobox.addItem("Align to UTC")
     self.align_combobox.addItem("Align to GPS")
     if not self.is_old_fs740():
         self.align_combobox.addItem("Align to GLONASS")
         self.align_combobox.addItem("Align to BEIDOU")
         self.align_combobox.addItem("Align to GALILEO")
     form_layout.setWidget(1, QFormLayout.LabelRole, caption_alignment)
     form_layout.setWidget(1, QFormLayout.FieldRole, self.align_combobox)
     caption_quality = QLabel(self)
     caption_quality.setText("Timing Quality:")
     self.quality_combobox = QComboBox(self)
     self.quality_combobox.addItem("Require only 1 satellite")
     self.quality_combobox.addItem("Require 3 satellites")
     form_layout.setWidget(2, QFormLayout.LabelRole, caption_quality)
     form_layout.setWidget(2, QFormLayout.FieldRole, self.quality_combobox)
     caption_min_snr = QLabel(self)
     caption_min_snr.setText("Minimum SNR:")
     self.min_snr_spinbox = QSpinBox(self)
     self.min_snr_spinbox.setMinimum(0)
     self.min_snr_spinbox.setMaximum(55)
     form_layout.setWidget(3, QFormLayout.LabelRole, caption_min_snr)
     form_layout.setWidget(3, QFormLayout.FieldRole, self.min_snr_spinbox)
     caption_min_elevation = QLabel(self)
     caption_min_elevation.setText("Minimum Sat. Elevation (Deg):")
     self.min_elevation_spinbox = QSpinBox(self)
     self.min_elevation_spinbox.setMinimum(0)
     self.min_elevation_spinbox.setMaximum(90)
     form_layout.setWidget(4, QFormLayout.LabelRole, caption_min_elevation)
     form_layout.setWidget(4, QFormLayout.FieldRole,
                           self.min_elevation_spinbox)
     caption_survey_mode = QLabel(self)
     caption_survey_mode.setText("Position Survey:")
     self.survey_combobox = QComboBox(self)
     self.survey_combobox.addItem("Disabled")
     self.survey_combobox.addItem("Redo survey at power on")
     self.survey_combobox.addItem("Remember survey results")
     form_layout.setWidget(5, QFormLayout.LabelRole, caption_survey_mode)
     form_layout.setWidget(5, QFormLayout.FieldRole, self.survey_combobox)
     caption_survey_fixes = QLabel(self)
     caption_survey_fixes.setText("Position Fixes in Survey:")
     self.fixes_spinbox = QSpinBox(self)
     self.fixes_spinbox.setMinimum(1)
     self.fixes_spinbox.setMaximum(2**31 - 1)
     form_layout.setWidget(6, QFormLayout.LabelRole, caption_survey_fixes)
     form_layout.setWidget(6, QFormLayout.FieldRole, self.fixes_spinbox)
     caption_antenna_delay = QLabel(self)
     caption_antenna_delay.setText("Antenna Delay Correction (ns):")
     self.antenna_delay_spinbox = QSpinBox(self)
     self.antenna_delay_spinbox.setMinimum(-32768)
     self.antenna_delay_spinbox.setMaximum(32767)
     form_layout.setWidget(7, QFormLayout.LabelRole, caption_antenna_delay)
     form_layout.setWidget(7, QFormLayout.FieldRole,
                           self.antenna_delay_spinbox)
     caption_local_time_offset = QLabel(self)
     caption_local_time_offset.setText("Local Time Offset (hr):")
     self.local_offset_spinbox = QDoubleSpinBox(self)
     self.local_offset_spinbox.setDecimals(1)
     self.local_offset_spinbox.setMinimum(-24.0)
     self.local_offset_spinbox.setMaximum(+24.0)
     form_layout.setWidget(8, QFormLayout.LabelRole,
                           caption_local_time_offset)
     form_layout.setWidget(8, QFormLayout.FieldRole,
                           self.local_offset_spinbox)
     dlg_layout.addLayout(form_layout)
     # Layout dialog buttons
     dialog_btns = QDialogButtonBox(self)
     dialog_btns.setStandardButtons(QDialogButtonBox.Ok
                                    | QDialogButtonBox.Cancel)
     dlg_layout.addWidget(dialog_btns)
     # Initialize widgets
     if not self.is_old_fs740():
         self.gps_checkbox.setChecked(True if (gps_config_data.constellation
                                               & 1) else False)
         self.glonass_checkbox.setChecked(True if (
             gps_config_data.constellation & 2) else False)
         self.beidou_checkbox.setChecked(True if (
             gps_config_data.constellation & 4) else False)
         self.galileo_checkbox.setChecked(True if (
             gps_config_data.constellation & 8) else False)
     if self.is_old_fs740():
         if "GPS" == gps_config_data.time_alignment:
             index = 1
         else:
             index = 0
     else:
         if "GPS" == gps_config_data.time_alignment:
             index = 1
         elif "GLON" == gps_config_data.time_alignment:
             index = 2
         elif "BEID" == gps_config_data.time_alignment:
             index = 3
         elif "GAL" == gps_config_data.time_alignment:
             index = 4
         else:
             index = 0
     self.align_combobox.setCurrentIndex(index)
     self.quality_combobox.setCurrentIndex(
         0 if "1SAT" == gps_config_data.time_quality else 1)
     if "DIS" == gps_config_data.survey_mode:
         index = 0
     elif "REM" == gps_config_data.survey_mode:
         index = 2
     else:
         index = 1
     self.survey_combobox.setCurrentIndex(index)
     self.min_snr_spinbox.setValue(round(gps_config_data.min_snr))
     self.min_elevation_spinbox.setValue(
         round(gps_config_data.min_elevation))
     self.fixes_spinbox.setValue(gps_config_data.survey_fixes)
     self.antenna_delay_spinbox.setValue(
         int(round(gps_config_data.antenna_delay * 1e9)))
     self.local_offset_spinbox.setValue(gps_config_data.local_time_offset /
                                        3600.0)
     # Connect signals
     dialog_btns.accepted.connect(self.on_ok)
     dialog_btns.rejected.connect(self.reject)
Beispiel #35
0
    def _build_ui(self, window_x, window_y, cal_channel, cal_wl, cal_threshold,
                  cal_interval, cal_retry_interval):
        self.window = QWidget()
        self.window.setWindowTitle(self.title)

        self.window.move(window_x, window_y)

        self.v_layout = QVBoxLayout()

        self.window.setLayout(self.v_layout)

        indicator_font = QFont()
        indicator_font.setPointSize(18)
        self.calibration_timestamp_display = QLabel()
        self.calibration_timestamp_display.setFont(indicator_font)
        self.calibration_countdown_display = QLabel()
        self.calibration_countdown_display.setFont(indicator_font)

        startstop_gb = QGroupBox("Measurement")
        startstop_gb_layout = QHBoxLayout()
        startstop_gb.setLayout(startstop_gb_layout)

        start_button = QPushButton("&Start measurement")

        def start():
            if self._rpc_client is not None:
                logger.info("sending RPC start_measurement()")
                self._rpc_client.start_measurement()

        start_button.clicked.connect(start)
        startstop_gb_layout.addWidget(start_button)

        stop_button = QPushButton("S&top measurement")

        def stop():
            if self._rpc_client is not None:
                logger.info("sending RPC stop_measurement()")
                self._rpc_client.stop_measurement()

        stop_button.clicked.connect(stop)
        startstop_gb_layout.addWidget(stop_button)

        self.v_layout.addWidget(startstop_gb)

        cal_gb = QGroupBox("Calibration")
        cal_gb_outer_layout = QVBoxLayout()
        cal_gb_outer_layout.addWidget(self.calibration_timestamp_display)
        cal_gb_outer_layout.addWidget(self.calibration_countdown_display)
        cal_gb_layout = QHBoxLayout()
        cal_gb_outer_layout.addLayout(cal_gb_layout)
        cal_gb.setLayout(cal_gb_outer_layout)

        calibrate_gb = QGroupBox("Calibrate")
        calibrate_gb_layout = QFormLayout()
        calibrate_gb.setLayout(calibrate_gb_layout)

        calibrate_button = QPushButton("&Calibrate")

        def calibrate():
            ch = int(self._ui_input_elements["cal_channel"].value())
            wl = self._ui_input_elements["cal_wl"].value()
            if self._rpc_client is not None:
                logger.info(
                    "sending RPC calibrate(channel={}, wavelength={})".format(
                        ch, wl))
                self._rpc_client.calibrate(ch, wl)

        calibrate_button.clicked.connect(calibrate)

        calibrate_gb_layout.addRow("", calibrate_button)

        self._ui_input_elements.update({"cal_channel": QDoubleSpinBox()})
        self._ui_input_elements["cal_channel"].setRange(1, 100)
        self._ui_input_elements["cal_channel"].setSingleStep(1)
        self._ui_input_elements["cal_channel"].setDecimals(0)
        self._ui_input_elements["cal_channel"].setValue(cal_channel)
        calibrate_gb_layout.addRow("Channel",
                                   self._ui_input_elements["cal_channel"])

        self._ui_input_elements.update({"cal_wl": QDoubleSpinBox()})
        self._ui_input_elements["cal_wl"].setRange(1., 10000.)
        self._ui_input_elements["cal_wl"].setSingleStep(1e-10)
        self._ui_input_elements["cal_wl"].setDecimals(10)
        self._ui_input_elements["cal_wl"].setSuffix(" nm")
        self._ui_input_elements["cal_wl"].setValue(cal_wl)
        calibrate_gb_layout.addRow("Wavelength",
                                   self._ui_input_elements["cal_wl"])

        cal_gb_layout.addWidget(calibrate_gb)

        autocalibration_gb = QGroupBox("Autocalibration")
        autocalibration_gb_layout = QFormLayout()
        autocalibration_gb.setLayout(autocalibration_gb_layout)

        start_autocalibration_button = QPushButton("Start &autocalibration")

        def start_autocalibration():
            ch = int(self._ui_input_elements["autocal_channel"].value())
            wl = self._ui_input_elements["autocal_wl"].value()
            thr = self._ui_input_elements["autocal_threshold"].value()
            interval = int(self._ui_input_elements["autocal_interval"].value())
            retry_interval = int(
                self._ui_input_elements["autocal_retry_interval"].value())
            if self._rpc_client is not None:
                logger.info(
                    "sending RPC start_autocalibration(channel={}, wavelength={}, threshold={}, "
                    "interval={}, retry_interval={})".format(
                        ch, wl, thr, interval, retry_interval))
                self._rpc_client.start_autocalibration(ch, wl, thr, interval,
                                                       retry_interval)

        start_autocalibration_button.clicked.connect(start_autocalibration)

        autocalibration_gb_layout.addRow("", start_autocalibration_button)

        self._ui_input_elements.update({"autocal_channel": QDoubleSpinBox()})
        self._ui_input_elements["autocal_channel"].setRange(1, 100)
        self._ui_input_elements["autocal_channel"].setSingleStep(1)
        self._ui_input_elements["autocal_channel"].setDecimals(0)
        self._ui_input_elements["autocal_channel"].setValue(cal_channel)
        autocalibration_gb_layout.addRow(
            "Channel", self._ui_input_elements["autocal_channel"])

        self._ui_input_elements.update({"autocal_wl": QDoubleSpinBox()})
        self._ui_input_elements["autocal_wl"].setRange(1., 10000.)
        self._ui_input_elements["autocal_wl"].setSingleStep(1e-10)
        self._ui_input_elements["autocal_wl"].setDecimals(10)
        self._ui_input_elements["autocal_wl"].setSuffix(" nm")
        self._ui_input_elements["autocal_wl"].setValue(cal_wl)
        autocalibration_gb_layout.addRow("Wavelength",
                                         self._ui_input_elements["autocal_wl"])

        self._ui_input_elements.update({"autocal_threshold": QDoubleSpinBox()})
        self._ui_input_elements["autocal_threshold"].setRange(1e-10, 10000.)
        self._ui_input_elements["autocal_threshold"].setSingleStep(1e-10)
        self._ui_input_elements["autocal_threshold"].setDecimals(10)
        self._ui_input_elements["autocal_threshold"].setSuffix(" nm")
        self._ui_input_elements["autocal_threshold"].setValue(cal_threshold)
        autocalibration_gb_layout.addRow(
            "Threshold", self._ui_input_elements["autocal_threshold"])

        self._ui_input_elements.update({"autocal_interval": QDoubleSpinBox()})
        self._ui_input_elements["autocal_interval"].setRange(1, 100000)
        self._ui_input_elements["autocal_interval"].setSingleStep(1)
        self._ui_input_elements["autocal_interval"].setDecimals(0)
        self._ui_input_elements["autocal_interval"].setSuffix(" s")
        self._ui_input_elements["autocal_interval"].setValue(cal_interval)
        autocalibration_gb_layout.addRow(
            "Interval", self._ui_input_elements["autocal_interval"])

        self._ui_input_elements.update(
            {"autocal_retry_interval": QDoubleSpinBox()})
        self._ui_input_elements["autocal_retry_interval"].setRange(1, 100000)
        self._ui_input_elements["autocal_retry_interval"].setSingleStep(1)
        self._ui_input_elements["autocal_retry_interval"].setDecimals(0)
        self._ui_input_elements["autocal_retry_interval"].setSuffix(" s")
        self._ui_input_elements["autocal_retry_interval"].setValue(
            cal_retry_interval)
        autocalibration_gb_layout.addRow(
            "Retry interval",
            self._ui_input_elements["autocal_retry_interval"])

        stop_autocalibration_button = QPushButton("St&op autocalibration")

        def stop_autocalibration():
            if self._rpc_client is not None:
                logger.info("sending RPC stop_autocalibration()")
                self._rpc_client.stop_autocalibration()

        stop_autocalibration_button.clicked.connect(stop_autocalibration)

        autocalibration_gb_layout.addRow("", stop_autocalibration_button)

        cal_gb_layout.addWidget(autocalibration_gb)

        self.v_layout.addWidget(cal_gb)

        exposure_gb = QGroupBox("Exposure")
        exposure_gb_layout = QHBoxLayout()
        exposure_gb.setLayout(exposure_gb_layout)

        control_form = QFormLayout()
        self._ui_input_elements.update({"exp_channel": QDoubleSpinBox()})
        self._ui_input_elements["exp_channel"].setRange(1, 100)
        self._ui_input_elements["exp_channel"].setSingleStep(1)
        self._ui_input_elements["exp_channel"].setDecimals(0)
        self._ui_input_elements["exp_channel"].setValue(1)
        control_form.addRow("Channel", self._ui_input_elements["exp_channel"])

        self._ui_input_elements.update({"exp_time1": QDoubleSpinBox()})
        self._ui_input_elements["exp_time1"].setRange(1, 2000)
        self._ui_input_elements["exp_time1"].setSingleStep(1)
        self._ui_input_elements["exp_time1"].setDecimals(0)
        self._ui_input_elements["exp_time1"].setSuffix(" ms")
        self._ui_input_elements["exp_time1"].setValue(1)
        control_form.addRow("Time 1", self._ui_input_elements["exp_time1"])

        self._ui_input_elements.update({"exp_time2": QDoubleSpinBox()})
        self._ui_input_elements["exp_time2"].setRange(0, 2000)
        self._ui_input_elements["exp_time2"].setSingleStep(1)
        self._ui_input_elements["exp_time2"].setDecimals(0)
        self._ui_input_elements["exp_time2"].setSuffix(" ms")
        self._ui_input_elements["exp_time2"].setValue(1)
        control_form.addRow("Time 2", self._ui_input_elements["exp_time2"])

        self._ui_input_elements.update({"exp_auto": QCheckBox()})
        control_form.addRow("Auto adjust", self._ui_input_elements["exp_auto"])

        exposure_gb_layout.addLayout(control_form)

        exposure_button_layout = QVBoxLayout()

        exposure_get_button = QPushButton("&Get")

        def exposure_get():
            channel = int(self._ui_input_elements["exp_channel"].value())
            if self._rpc_client is not None:
                logger.info(
                    "sending RPC get_exposure_time({}, 1)".format(channel))
                time1 = self._rpc_client.get_exposure_time(channel, 1)
                logger.info(
                    "sending RPC get_exposure_time({}, 2)".format(channel))
                time2 = self._rpc_client.get_exposure_time(channel, 2)
                logger.info(
                    "sending RPC get_exposure_auto_adjust({})".format(channel))
                auto = self._rpc_client.get_exposure_auto_adjust(channel)
                self._ui_input_elements["exp_time1"].setValue(time1)
                self._ui_input_elements["exp_time2"].setValue(time2)
                self._ui_input_elements["exp_auto"].setChecked(auto)

        exposure_get_button.clicked.connect(exposure_get)

        exposure_button_layout.addWidget(exposure_get_button)

        exposure_set_button = QPushButton("S&et")

        def exposure_set():
            channel = int(self._ui_input_elements["exp_channel"].value())
            time1 = int(self._ui_input_elements["exp_time1"].value())
            time2 = int(self._ui_input_elements["exp_time2"].value())
            auto = bool(self._ui_input_elements["exp_auto"].isChecked())
            if self._rpc_client is not None:
                logger.info("sending RPC set_exposure_time({}, 1, {})".format(
                    channel, time1))
                self._rpc_client.set_exposure_time(channel, 1, time1)
                logger.info("sending RPC set_exposure_time({}, 2, {})".format(
                    channel, time2))
                self._rpc_client.set_exposure_time(channel, 2, time2)
                logger.info(
                    "sending RPC set_exposure_auto_adjust({}, {})".format(
                        channel, auto))
                self._rpc_client.set_exposure_auto_adjust(channel, auto)

        exposure_set_button.clicked.connect(exposure_set)

        exposure_button_layout.addWidget(exposure_set_button)

        exposure_gb_layout.addLayout(exposure_button_layout)

        self.v_layout.addWidget(exposure_gb)
Beispiel #36
0
    def InitUserInterface(self):
        self.color_red = QPalette()
        self.color_red.setColor(QPalette.WindowText, Qt.red)
        self.color_green = QPalette()
        self.color_green.setColor(QPalette.WindowText, QColor(0, 128, 0))
        self.color_black = QPalette()
        self.color_black.setColor(QPalette.WindowText, Qt.black)

        self.list_exchange = [
            define.DEF_EXCHANGE_STOCK_SH, define.DEF_EXCHANGE_STOCK_SZ
        ]
        self.list_entr_type = [
            define.DEF_PRICE_TYPE_STOCK_LIMIT,
            define.DEF_PRICE_TYPE_STOCK_MARKET
        ]

        self.setWindowTitle("手动交易-股票-APE %s" % self.version_info)
        self.resize(380, 300)
        self.setFont(QFont("SimSun", 9))

        self.label_exchange = QLabel("交易市场")
        self.label_exchange.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_symbol = QLabel("证券代码")
        self.label_symbol.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_name = QLabel("证券名称")
        self.label_name.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_entr_type = QLabel("委托方式")
        self.label_entr_type.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_can_use = QLabel("可用金额")
        self.label_can_use.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_can_sell = QLabel("可用数量")
        self.label_can_sell.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_price = QLabel("委托价格")
        self.label_price.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_volume = QLabel("委托数量")
        self.label_volume.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        self.label_can_use_unit = QLabel("元")
        self.label_can_use_unit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_can_sell_unit = QLabel("股")
        self.label_can_sell_unit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_price_unit = QLabel("元")
        self.label_price_unit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_volume_unit = QLabel("股")
        self.label_volume_unit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        self.combo_exchange = QComboBox()
        self.combo_exchange.addItems(self.list_exchange)
        self.line_edit_symbol = QLineEdit("")
        self.line_edit_symbol.setStyleSheet("color:red")  # 初始红色
        self.line_edit_symbol.setFont(QFont("SimSun", 9))
        self.line_edit_name = QLineEdit("")
        self.line_edit_name.setReadOnly(True)
        self.line_edit_name.setFont(QFont("SimSun", 9))
        self.line_edit_name.setStyleSheet(
            "background-color:rgb(240,240,240);color:red")  # 初始红色
        self.line_edit_name.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.combo_entr_type = QComboBox()
        self.combo_entr_type.addItems(self.list_entr_type)
        self.line_edit_can_use = QLineEdit("0.00")
        self.line_edit_can_use.setReadOnly(True)
        self.line_edit_can_use.setStyleSheet(
            "background-color:rgb(240,240,240)")
        self.line_edit_can_use.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.line_edit_can_sell = QLineEdit("0")
        self.line_edit_can_sell.setReadOnly(True)
        self.line_edit_can_sell.setStyleSheet(
            "background-color:rgb(240,240,240)")
        self.line_edit_can_sell.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.spin_price = QDoubleSpinBox()
        self.spin_price.setDecimals(4)
        self.spin_price.setMinimum(0)
        self.spin_price.setMaximum(100000)
        self.spin_price.setStyleSheet("color:red")  # 初始红色
        self.spin_price.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.spin_volume = QSpinBox()
        self.spin_volume.setMinimum(0)
        self.spin_volume.setMaximum(1000000)
        self.spin_volume.setSingleStep(100)
        self.spin_volume.setStyleSheet("color:red")  # 初始红色
        self.spin_volume.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.grid_layout_essential = QGridLayout()
        self.grid_layout_essential.setContentsMargins(-1, -1, -1, -1)
        self.grid_layout_essential.addWidget(self.label_exchange, 0, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_symbol, 1, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_name, 2, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_entr_type, 3, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_can_use, 4, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_can_sell, 5, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_price, 6, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_volume, 7, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.combo_exchange, 0, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.line_edit_symbol, 1, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.line_edit_name, 2, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.combo_entr_type, 3, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.line_edit_can_use, 4, 1, 1,
                                             1)
        self.grid_layout_essential.addWidget(self.line_edit_can_sell, 5, 1, 1,
                                             1)
        self.grid_layout_essential.addWidget(self.spin_price, 6, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.spin_volume, 7, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.label_can_use_unit, 4, 2, 1,
                                             1)
        self.grid_layout_essential.addWidget(self.label_can_sell_unit, 5, 2, 1,
                                             1)
        self.grid_layout_essential.addWidget(self.label_price_unit, 6, 2, 1, 1)
        self.grid_layout_essential.addWidget(self.label_volume_unit, 7, 2, 1,
                                             1)

        self.radio_button_buy = QRadioButton("买 入")
        self.radio_button_buy.setStyleSheet("color:red")
        self.radio_button_buy.setFont(QFont("SimSun", 9))
        self.radio_button_buy.setChecked(True)
        self.radio_button_buy.setFixedWidth(70)
        self.radio_button_sell = QRadioButton("卖 出")
        self.radio_button_sell.setStyleSheet("color:green")
        self.radio_button_sell.setFont(QFont("SimSun", 9))
        self.radio_button_sell.setFixedWidth(70)
        self.button_place_order = QPushButton("下 单")
        self.button_place_order.setFont(QFont("SimSun", 9))
        self.button_place_order.setStyleSheet("font:bold;color:red")  # 初始红色
        self.button_place_order.setFixedWidth(70)

        self.label_order_id = QLabel("撤单委托编号")
        self.label_order_id.setFixedWidth(70)
        self.label_order_id.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.line_edit_order_id = QLineEdit("")
        self.line_edit_order_id.setFixedWidth(70)
        self.line_edit_order_id.setStyleSheet("color:blue")
        self.line_edit_order_id.setFont(QFont("SimSun", 9))
        self.button_cancel_order = QPushButton("撤 单")
        self.button_cancel_order.setFont(QFont("SimSun", 9))
        self.button_cancel_order.setStyleSheet("font:bold;color:blue")
        self.button_cancel_order.setFixedWidth(70)

        self.h_box_layout_order_buttons = QHBoxLayout()
        self.h_box_layout_order_buttons.setContentsMargins(-1, -1, -1, -1)
        self.h_box_layout_order_buttons.addStretch(1)
        self.h_box_layout_order_buttons.addWidget(self.radio_button_buy)
        self.h_box_layout_order_buttons.addStretch(1)
        self.h_box_layout_order_buttons.addWidget(self.radio_button_sell)
        self.h_box_layout_order_buttons.addStretch(1)
        self.h_box_layout_order_buttons.addWidget(self.button_place_order)
        self.h_box_layout_order_buttons.addStretch(1)

        self.h_box_layout_cancel_order = QHBoxLayout()
        self.h_box_layout_cancel_order.setContentsMargins(-1, -1, -1, -1)  #
        self.h_box_layout_cancel_order.addStretch(1)
        self.h_box_layout_cancel_order.addWidget(self.label_order_id)
        self.h_box_layout_cancel_order.addStretch(1)
        self.h_box_layout_cancel_order.addWidget(self.line_edit_order_id)
        self.h_box_layout_cancel_order.addStretch(1)
        self.h_box_layout_cancel_order.addWidget(self.button_cancel_order)
        self.h_box_layout_cancel_order.addStretch(1)

        self.v_box_layout_order = QVBoxLayout()
        self.v_box_layout_order.setContentsMargins(-1, -1, -1, -1)
        self.v_box_layout_order.addLayout(self.grid_layout_essential)
        self.v_box_layout_order.addLayout(self.h_box_layout_order_buttons)
        self.v_box_layout_order.addLayout(self.h_box_layout_cancel_order)

        self.label_high_limit = QLabel("涨停")
        self.label_ask_5 = QLabel("卖五")
        self.label_ask_4 = QLabel("卖四")
        self.label_ask_3 = QLabel("卖三")
        self.label_ask_2 = QLabel("卖二")
        self.label_ask_1 = QLabel("卖一")
        self.label_last = QLabel("最新")
        self.label_last.setMinimumWidth(35)
        self.label_bid_1 = QLabel("买一")
        self.label_bid_2 = QLabel("买二")
        self.label_bid_3 = QLabel("买三")
        self.label_bid_4 = QLabel("买四")
        self.label_bid_5 = QLabel("买五")
        self.label_low_limit = QLabel("跌停")

        self.label_high_limit.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_last.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_low_limit.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.label_high_limit_price = QLabel("0.00")
        self.label_high_limit_price.setMinimumWidth(60)
        self.label_ask_price_5 = QLabel("0.00")
        self.label_ask_price_4 = QLabel("0.00")
        self.label_ask_price_3 = QLabel("0.00")
        self.label_ask_price_2 = QLabel("0.00")
        self.label_ask_price_1 = QLabel("0.00")
        self.label_ask_volume_5 = QLabel("0")
        self.label_ask_volume_4 = QLabel("0")
        self.label_ask_volume_3 = QLabel("0")
        self.label_ask_volume_2 = QLabel("0")
        self.label_ask_volume_1 = QLabel("0")
        self.label_last_price = QLabel("0.00")
        self.label_last_price.setMinimumWidth(60)
        self.label_last_up_down = QLabel("0.00%")
        self.label_last_up_down.setMinimumWidth(60)
        self.label_bid_price_1 = QLabel("0.00")
        self.label_bid_price_2 = QLabel("0.00")
        self.label_bid_price_3 = QLabel("0.00")
        self.label_bid_price_4 = QLabel("0.00")
        self.label_bid_price_5 = QLabel("0.00")
        self.label_bid_volume_1 = QLabel("0")
        self.label_bid_volume_2 = QLabel("0")
        self.label_bid_volume_3 = QLabel("0")
        self.label_bid_volume_4 = QLabel("0")
        self.label_bid_volume_5 = QLabel("0")
        self.label_low_limit_price = QLabel("0.00")
        self.label_low_limit_price.setMinimumWidth(60)

        self.label_high_limit_price.setPalette(self.color_red)
        self.label_ask_price_5.setPalette(self.color_green)
        self.label_ask_price_4.setPalette(self.color_green)
        self.label_ask_price_3.setPalette(self.color_green)
        self.label_ask_price_2.setPalette(self.color_green)
        self.label_ask_price_1.setPalette(self.color_green)
        self.label_ask_volume_5.setPalette(self.color_green)
        self.label_ask_volume_4.setPalette(self.color_green)
        self.label_ask_volume_3.setPalette(self.color_green)
        self.label_ask_volume_2.setPalette(self.color_green)
        self.label_ask_volume_1.setPalette(self.color_green)
        self.label_last_price.setPalette(self.color_black)
        self.label_last_up_down.setPalette(self.color_black)
        self.label_bid_price_1.setPalette(self.color_red)
        self.label_bid_price_2.setPalette(self.color_red)
        self.label_bid_price_3.setPalette(self.color_red)
        self.label_bid_price_4.setPalette(self.color_red)
        self.label_bid_price_5.setPalette(self.color_red)
        self.label_bid_volume_1.setPalette(self.color_red)
        self.label_bid_volume_2.setPalette(self.color_red)
        self.label_bid_volume_3.setPalette(self.color_red)
        self.label_bid_volume_4.setPalette(self.color_red)
        self.label_bid_volume_5.setPalette(self.color_red)
        self.label_low_limit_price.setPalette(self.color_green)

        self.label_high_limit_price.setAlignment(Qt.AlignRight
                                                 | Qt.AlignVCenter)
        self.label_ask_price_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_price_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_price_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_price_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_price_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_last_price.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_last_up_down.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_low_limit_price.setAlignment(Qt.AlignRight
                                                | Qt.AlignVCenter)

        self.grid_layout_quote = QGridLayout()
        self.grid_layout_quote.addWidget(self.label_high_limit, 0, 0)  #
        self.grid_layout_quote.addWidget(self.label_ask_5, 1, 0)
        self.grid_layout_quote.addWidget(self.label_ask_4, 2, 0)
        self.grid_layout_quote.addWidget(self.label_ask_3, 3, 0)
        self.grid_layout_quote.addWidget(self.label_ask_2, 4, 0)
        self.grid_layout_quote.addWidget(self.label_ask_1, 5, 0)
        self.grid_layout_quote.addWidget(self.label_last, 6, 0)  #
        self.grid_layout_quote.addWidget(self.label_bid_1, 7, 0)
        self.grid_layout_quote.addWidget(self.label_bid_2, 8, 0)
        self.grid_layout_quote.addWidget(self.label_bid_3, 9, 0)
        self.grid_layout_quote.addWidget(self.label_bid_4, 10, 0)
        self.grid_layout_quote.addWidget(self.label_bid_5, 11, 0)
        self.grid_layout_quote.addWidget(self.label_low_limit, 12, 0)  #
        self.grid_layout_quote.addWidget(self.label_high_limit_price, 0, 1)  #
        self.grid_layout_quote.addWidget(self.label_ask_price_5, 1, 1)
        self.grid_layout_quote.addWidget(self.label_ask_price_4, 2, 1)
        self.grid_layout_quote.addWidget(self.label_ask_price_3, 3, 1)
        self.grid_layout_quote.addWidget(self.label_ask_price_2, 4, 1)
        self.grid_layout_quote.addWidget(self.label_ask_price_1, 5, 1)
        self.grid_layout_quote.addWidget(self.label_last_price, 6, 1)  #
        self.grid_layout_quote.addWidget(self.label_bid_price_1, 7, 1)
        self.grid_layout_quote.addWidget(self.label_bid_price_2, 8, 1)
        self.grid_layout_quote.addWidget(self.label_bid_price_3, 9, 1)
        self.grid_layout_quote.addWidget(self.label_bid_price_4, 10, 1)
        self.grid_layout_quote.addWidget(self.label_bid_price_5, 11, 1)
        self.grid_layout_quote.addWidget(self.label_low_limit_price, 12, 1)  #
        self.grid_layout_quote.addWidget(self.label_ask_volume_5, 1, 2)
        self.grid_layout_quote.addWidget(self.label_ask_volume_4, 2, 2)
        self.grid_layout_quote.addWidget(self.label_ask_volume_3, 3, 2)
        self.grid_layout_quote.addWidget(self.label_ask_volume_2, 4, 2)
        self.grid_layout_quote.addWidget(self.label_ask_volume_1, 5, 2)
        self.grid_layout_quote.addWidget(self.label_last_up_down, 6, 2)  #
        self.grid_layout_quote.addWidget(self.label_bid_volume_1, 7, 2)
        self.grid_layout_quote.addWidget(self.label_bid_volume_2, 8, 2)
        self.grid_layout_quote.addWidget(self.label_bid_volume_3, 9, 2)
        self.grid_layout_quote.addWidget(self.label_bid_volume_4, 10, 2)
        self.grid_layout_quote.addWidget(self.label_bid_volume_5, 11, 2)

        self.main_text_edit_bottom = QTextEdit(self)
        self.main_text_edit_bottom.setText("")
        self.main_text_edit_bottom.setFont(QFont("SimSun", 9))

        self.h_box_layout_1 = QHBoxLayout()
        self.h_box_layout_1.addLayout(self.v_box_layout_order)
        self.h_box_layout_1.addLayout(self.grid_layout_quote)

        self.h_box_layout_2 = QHBoxLayout()
        self.h_box_layout_2.setContentsMargins(-1, -1, -1, -1)
        self.h_box_layout_2.addWidget(self.main_text_edit_bottom)

        self.v_box_layout_mian = QVBoxLayout()
        self.v_box_layout_mian.setContentsMargins(-1, -1, -1, -1)
        self.v_box_layout_mian.addLayout(self.h_box_layout_1)
        self.v_box_layout_mian.addLayout(self.h_box_layout_2)

        self.setLayout(self.v_box_layout_mian)

        self.combo_exchange.activated[str].connect(self.OnChangeExchange)
        self.line_edit_symbol.editingFinished.connect(self.OnChangeSymbol)
        self.radio_button_buy.clicked.connect(self.OnChangeBuySell)
        self.radio_button_sell.clicked.connect(self.OnChangeBuySell)
        self.button_place_order.clicked.connect(self.OnButtonPlaceOrder)
        self.button_cancel_order.clicked.connect(self.OnButtonCancelOrder)
Beispiel #37
0
class MeasureWidgetWithSecondaryParameters(MeasureWidget):
    secondaryChanged = pyqtSignal(dict)

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

        self._params = 0

        self._spinPowIn = QDoubleSpinBox(parent=self)
        self._spinPowIn.setMinimum(-50)
        self._spinPowIn.setMaximum(50)
        self._spinPowIn.setSingleStep(1)
        self._spinPowIn.setValue(-20)
        self._spinPowIn.setSuffix(' дБм')
        self._devices._layout.addRow('Pвх=', self._spinPowIn)

        self._spinFreqStart = QDoubleSpinBox(parent=self)
        self._spinFreqStart.setMinimum(0)
        self._spinFreqStart.setMaximum(20)
        self._spinFreqStart.setSingleStep(1)
        self._spinFreqStart.setValue(0.01)
        self._spinFreqStart.setSuffix(' ГГц')
        self._devices._layout.addRow('Fнач=', self._spinFreqStart)

        self._spinFreqEnd = QDoubleSpinBox(parent=self)
        self._spinFreqEnd.setMinimum(0)
        self._spinFreqEnd.setMaximum(20)
        self._spinFreqEnd.setSingleStep(1)
        self._spinFreqEnd.setValue(6)
        self._spinFreqEnd.setSuffix(' ГГц')
        self._devices._layout.addRow('Fкон=', self._spinFreqEnd)

        self._spinLevel = QDoubleSpinBox(parent=self)
        self._spinLevel.setMinimum(-100)
        self._spinLevel.setMaximum(100)
        self._spinLevel.setSingleStep(1)
        self._spinLevel.setValue(-5)
        self._spinLevel.setSuffix(' dB')
        self._devices._layout.addRow('Kп=', self._spinLevel)

        self._spinFreq1 = QDoubleSpinBox(parent=self)
        self._spinFreq1.setMinimum(0)
        self._spinFreq1.setMaximum(20)
        self._spinFreq1.setSingleStep(1)
        self._spinFreq1.setValue(0.01)
        self._spinFreq1.setSuffix(' ГГц')
        self._devices._layout.addRow('Fгр1=', self._spinFreq1)

        self._spinFreq2 = QDoubleSpinBox(parent=self)
        self._spinFreq2.setMinimum(0)
        self._spinFreq2.setMaximum(20)
        self._spinFreq2.setSingleStep(1)
        self._spinFreq2.setValue(6)
        self._spinFreq2.setSuffix(' ГГц')
        self._devices._layout.addRow('Fгр2=', self._spinFreq2)

        self._spinFreqStat = QDoubleSpinBox(parent=self)
        self._spinFreqStat.setMinimum(0)
        self._spinFreqStat.setMaximum(20)
        self._spinFreqStat.setSingleStep(1)
        self._spinFreqStat.setValue(1.5)
        self._spinFreqStat.setSuffix(' ГГц')
        self._devices._layout.addRow('Fstat=', self._spinFreqStat)

        self._spinCycles = QSpinBox(parent=self)
        self._spinCycles.setMinimum(1)
        self._spinCycles.setMaximum(10000)
        self._spinCycles.setSingleStep(1)
        self._spinCycles.setValue(1)
        self._devices._layout.addRow('N=', self._spinCycles)

        self._connectSignals()

    def _connectSignals(self):
        # self._spinFreq.valueChanged.connect(self.on_params_changed)
        self._spinPowIn.valueChanged.connect(self.on_params_changed)
        self._spinFreqStart.valueChanged.connect(self.on_params_changed)
        self._spinFreqEnd.valueChanged.connect(self.on_params_changed)
        self._spinLevel.valueChanged.connect(self.on_params_changed)
        self._spinFreq1.valueChanged.connect(self.on_params_changed)
        self._spinFreq2.valueChanged.connect(self.on_params_changed)
        self._spinFreqStat.valueChanged.connect(self.on_params_changed)
        self._spinCycles.valueChanged.connect(self.on_params_changed)

        self._spinFreqStart.valueChanged.connect(self.on_spinFreqStart_valueChanged)
        self._spinFreqEnd.valueChanged.connect(self.on_spinFreqEnd_valueChanged)
        self._spinFreq1.valueChanged.connect(self.on_spinFreq1_valueChanged)
        self._spinFreq2.valueChanged.connect(self.on_spinFreq2_valueChanged)

    def _modePreConnect(self):
        super()._modePreConnect()
        # self._spinFreq.setEnabled(True)

    def _modePreCheck(self):
        super()._modePreCheck()
        # self._spinFreq.setEnabled(True)

    def _modeDuringCheck(self):
        super()._modeDuringCheck()
        # self._spinFreq.setEnabled(False)

    def _modePreMeasure(self):
        super()._modePreMeasure()
        # self._spinFreq.setEnabled(False)

    def _modeDuringMeasure(self):
        super()._modeDuringMeasure()
        # self._spinFreq.setEnabled(False)

    def check(self):
        print('subclass checking...')
        self._modeDuringCheck()
        self._threads.start(MeasureTask(self._controller.check,
                                        self.checkTaskComplete,
                                        [self._selectedDevice, self._params]))

    def measure(self):
        print('subclass measuring...')
        self._modeDuringMeasure()
        self._threads.start(MeasureTask(self._controller.measure,
                                        self.measureTaskComplete,
                                        [self._selectedDevice, self._params]))

    @pyqtSlot(float)
    def on_spinFreqStart_valueChanged(self, value):
        self._spinFreqEnd.setMinimum(value)
        self._spinFreq1.setMinimum(value)
        self._spinFreq1.setMaximum(self._spinFreq2.value())
        self._spinFreq2.setMinimum(self._spinFreq1.value())

    @pyqtSlot(float)
    def on_spinFreqEnd_valueChanged(self, value):
        self._spinFreqStart.setMaximum(value)
        self._spinFreq2.setMaximum(value)
        self._spinFreq2.setMinimum(self._spinFreq1.value())
        self._spinFreq1.setMaximum(self._spinFreq2.value())

    @pyqtSlot(float)
    def on_spinFreq1_valueChanged(self, value):
        self._spinFreq2.setMinimum(value)

    @pyqtSlot(float)
    def on_spinFreq2_valueChanged(self, value):
        self._spinFreq1.setMaximum(value)

    def on_params_changed(self, value):
        params = {
            'Pin': self._spinPowIn.value(),
            'F1': self._spinFreqStart.value(),
            'F2': self._spinFreqEnd.value(),
            'kp': self._spinLevel.value(),
            'Fborder1': self._spinFreq1.value(),
            'Fborder2': self._spinFreq2.value(),
            'Fstat': self._spinFreqStat.value(),
            'cycles': self._spinCycles.value()
        }
        self.secondaryChanged.emit(params)
Beispiel #38
0
    def __init__(self, parent=None, controller=None):
        super().__init__(parent=parent, controller=controller)

        self._params = 0

        self._spinPowIn = QDoubleSpinBox(parent=self)
        self._spinPowIn.setMinimum(-50)
        self._spinPowIn.setMaximum(50)
        self._spinPowIn.setSingleStep(1)
        self._spinPowIn.setValue(-20)
        self._spinPowIn.setSuffix(' дБм')
        self._devices._layout.addRow('Pвх=', self._spinPowIn)

        self._spinFreqStart = QDoubleSpinBox(parent=self)
        self._spinFreqStart.setMinimum(0)
        self._spinFreqStart.setMaximum(20)
        self._spinFreqStart.setSingleStep(1)
        self._spinFreqStart.setValue(0.01)
        self._spinFreqStart.setSuffix(' ГГц')
        self._devices._layout.addRow('Fнач=', self._spinFreqStart)

        self._spinFreqEnd = QDoubleSpinBox(parent=self)
        self._spinFreqEnd.setMinimum(0)
        self._spinFreqEnd.setMaximum(20)
        self._spinFreqEnd.setSingleStep(1)
        self._spinFreqEnd.setValue(6)
        self._spinFreqEnd.setSuffix(' ГГц')
        self._devices._layout.addRow('Fкон=', self._spinFreqEnd)

        self._spinLevel = QDoubleSpinBox(parent=self)
        self._spinLevel.setMinimum(-100)
        self._spinLevel.setMaximum(100)
        self._spinLevel.setSingleStep(1)
        self._spinLevel.setValue(-5)
        self._spinLevel.setSuffix(' dB')
        self._devices._layout.addRow('Kп=', self._spinLevel)

        self._spinFreq1 = QDoubleSpinBox(parent=self)
        self._spinFreq1.setMinimum(0)
        self._spinFreq1.setMaximum(20)
        self._spinFreq1.setSingleStep(1)
        self._spinFreq1.setValue(0.01)
        self._spinFreq1.setSuffix(' ГГц')
        self._devices._layout.addRow('Fгр1=', self._spinFreq1)

        self._spinFreq2 = QDoubleSpinBox(parent=self)
        self._spinFreq2.setMinimum(0)
        self._spinFreq2.setMaximum(20)
        self._spinFreq2.setSingleStep(1)
        self._spinFreq2.setValue(6)
        self._spinFreq2.setSuffix(' ГГц')
        self._devices._layout.addRow('Fгр2=', self._spinFreq2)

        self._spinFreqStat = QDoubleSpinBox(parent=self)
        self._spinFreqStat.setMinimum(0)
        self._spinFreqStat.setMaximum(20)
        self._spinFreqStat.setSingleStep(1)
        self._spinFreqStat.setValue(1.5)
        self._spinFreqStat.setSuffix(' ГГц')
        self._devices._layout.addRow('Fstat=', self._spinFreqStat)

        self._spinCycles = QSpinBox(parent=self)
        self._spinCycles.setMinimum(1)
        self._spinCycles.setMaximum(10000)
        self._spinCycles.setSingleStep(1)
        self._spinCycles.setValue(1)
        self._devices._layout.addRow('N=', self._spinCycles)

        self._connectSignals()
Beispiel #39
0
    def initUI(self):
        self.setWindowTitle('TEST PROGRAM')

        self.data_choose = QComboBox()
        d = self.data.get_data()
        for i in range(len(d)):
            if d.index[i][0] != self.data_choose.itemText(i - 1):
                self.data_choose.addItem(d.index[i][0])
        self.data_choose.activated[str].connect(self.onActivated)

        self.data_condition = QComboBox()
        dc = d.loc[d.index[0][0]]
        for i in range(len(dc)):
            self.data_condition.addItem(dc.index.values[i])
        self.data_condition.activated[str].connect(self.onActivated_condition)

        self.fig, self.ax = plt.subplots(figsize=(50, 100))
        self.vis = Visualize(self.ax, self.data)
        self.canvas = FigureCanvas(self.fig)
        self.cal_button = QPushButton('Calculate')
        self.cal_button.clicked.connect(self.calculate)
        self.clr_button = QPushButton('Clear')
        self.clr_button.clicked.connect(self.clear)
        tempx, tempy = self.data.get_listdata(d.index[0][0],
                                              dc.index.values[0])
        self.data_cell = QTableWidget()
        self.data_cell.setColumnCount(7)
        self.data_cell.setRowCount(2)
        self.data_cell.setMaximumHeight(100)
        self.data_cell.setHorizontalHeaderLabels([
            'Point1', 'Point2', 'Point3', 'Point4', 'Point5', 'Point6',
            'Point7'
        ])
        self.data_cell.setVerticalHeaderLabels(['x', 'y'])
        self.graph_print = QPushButton('Print')
        self.graph_print.clicked.connect(self.print_graph)
        for idx, item in enumerate(tempx):
            self.data_cell.setItem(0, idx, QTableWidgetItem(str(item[0])))
        for idx, item in enumerate(tempy):
            self.data_cell.setItem(1, idx, QTableWidgetItem(str(item[0])))
        self.data_cell.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.input_num = QSpinBox()
        self.input_num.setMaximumWidth(100)
        self.input_num.setValue(1)
        self.input_num.valueChanged.connect(self.changeCellNum)
        self.input_cell_x = [QDoubleSpinBox()]
        self.input_cell_y = [QDoubleSpinBox()]
        self.hbox = QHBoxLayout()
        self.vbox = QVBoxLayout()
        self.inputbox_x = QHBoxLayout()
        self.inputbox_y = QHBoxLayout()
        self.inputbox_xy = QVBoxLayout()
        self.inputbox = QHBoxLayout()
        self.btnbox = QHBoxLayout()

        self.btnbox.addWidget(self.cal_button)
        self.btnbox.addWidget(self.clr_button)
        self.btnbox.addWidget(self.graph_print)
        self.vbox.addWidget(self.data_choose)
        self.vbox.addWidget(self.data_condition)
        self.vbox.addWidget(self.data_cell)
        self.inputbox.addWidget(self.input_num)
        self.inputbox_x.addWidget(self.input_cell_x[0])
        self.inputbox_y.addWidget(self.input_cell_y[0])
        self.inputbox_xy.addLayout(self.inputbox_x)
        self.inputbox_xy.addLayout(self.inputbox_y)
        self.inputbox.addLayout(self.inputbox_xy)
        self.vbox.addLayout(self.inputbox)
        self.vbox.addLayout(self.btnbox)
        self.vbox.addWidget(self.canvas)
        self.hbox.addLayout(self.vbox)
        self.ax = self.vis.draw_data()
        self.canvas.draw()

        self.setLayout(self.hbox)

        self.showMaximized()
 def __genDoubleEditEntry(self, key, setting):
     newItem = QTreeWidgetItem(self.__ui.settingsTree, [key, ""])
     editWidget = QDoubleSpinBox(self.__ui.settingsTree)
     if "range" in setting:
         editWidget.setRange(setting["range"]["lower"],
                             setting["range"]["upper"])
     else:
         editWidget.setRange(-sys.float_info.max, sys.float_info.max)
     editWidget.setSingleStep(setting.get("step", 1.0))
     editWidget.setProperty("key", key)
     editWidget.setValue(setting["value"])
     editWidget.valueChanged[float].connect(self.__floatBoxChanged)
     self.__ui.settingsTree.setItemWidget(newItem, 1, editWidget)
     return newItem
Beispiel #41
0
class CustomMainWindow(QtWidgets.QMainWindow):
    def __init__(self, device=Device.EEG, mock=False, log_keyboard=False):
        super(CustomMainWindow, self).__init__()
        self.communicator = Communicate()
        self.is_recording = False
        self.recorder = None
        self.device = device
        self.mock = mock
        self.log_keyboard = log_keyboard

        self.keyboard_logger = None
        self.threadpool = QThreadPool()

        self.setWindowTitle("ExpApp")
        self.setGeometry(100, 100, WINDOW_X, WINDOW_Y)
        self.options = [
            _EO,
            _EC,
            _PINCODE_4_TRUE_SEQ_REP_3,
            _P300_SECRET_9,
            _MI_CALIBRATION,
            _MI_INPUT,
            _SSVEP1,
            _SSVEP2,
            _SSVEP3,
        ]

        # Default parameters
        self.exp_params = ExperimentParams()
        self.exp_params.experiment = self.options[0]

        self.main_widget = QtWidgets.QWidget()
        self.main_layout = QtWidgets.QGridLayout()
        self.main_widget.setLayout(self.main_layout)
        self.setCentralWidget(self.main_widget)

        # Experiment window
        self.exp_window = None

        # Create graph frame
        graph_col_span = 8
        self.graph_layout = QtWidgets.QGridLayout()
        self.graph_frame = QtWidgets.QFrame(self)
        self.graph_frame.setLayout(self.graph_layout)
        self.main_layout.addWidget(self.graph_frame, 0, 0, 3, graph_col_span)
        self.myFig = GraphWidget(True if self.device == Device.EMG else False)
        self.graph_layout.addWidget(self.myFig)
        my_data_loop = threading.Thread(name='my_data_loop',
                                        target=self.data_send_loop,
                                        daemon=True,
                                        args=(self.add_data_callback_func, ))
        my_data_loop.start()

        # Create control panel frame
        cpr = 0
        self.control_panel_layout = QtWidgets.QGridLayout()
        self.control_panel_frame = QtWidgets.QFrame(self)
        self.control_panel_frame.setLayout(self.control_panel_layout)
        self.main_layout.addWidget(self.control_panel_frame, cpr,
                                   graph_col_span, 1, 3)
        self.is_paused = False

        # Default font for text elements
        label = QLabel()
        font = label.font()
        font.setPointSize(12)
        font.setItalic(True)
        label.setFont(font)

        if True:
            # Pause button
            self.pause_button = QPushButton(PAUSE_GRAPH)
            self.pause_button.setStyleSheet(elem_style)
            self.pause_button.clicked.connect(lambda: self.pause_graphs())
            self.control_panel_layout.addWidget(self.pause_button, cpr, 0, 1,
                                                3)
            cpr += 1

            # Record panel
            self.record_button = QPushButton('Record')
            self.record_button.setStyleSheet(elem_style)
            self.record_button.clicked.connect(lambda: self.start_record_())
            self.record_time_input = QDoubleSpinBox()
            self.record_time_input.setStyleSheet(elem_style)
            self.record_count = 1
            self.record_time_input.setValue(self.exp_params.record_duration)
            self.record_time_input.setSingleStep(0.1)
            self.record_time_input.setMaximum(MAX_RECORD_DURATION)
            self.record_time_input.valueChanged.connect(self.set_record_time)
            self.record_countdown = QLabel("")
            self.record_countdown.setFont(font)
            self.control_panel_layout.addWidget(self.record_time_input, cpr, 0)
            self.control_panel_layout.addWidget(self.record_countdown, cpr, 1,
                                                1, 1)
            self.control_panel_layout.addWidget(self.record_button, cpr, 2, 1,
                                                1)
            cpr += 1

            # Experiment setup panel
            # File name
            self.prefix_input = QComboBox()
            self.prefix_input.setStyleSheet(elem_style)
            gesture_set = SET6  # all gestures
            self.prefix_input.addItems(gesture_set)
            self.exp_params.name_prefix = gesture_set[0]
            self.prefix_input.currentIndexChanged.connect(self.set_exp_name)
            label = QLabel("File Name Prefix: ")
            label.setFont(font)

            self.control_panel_layout.addWidget(label, cpr, 0, 1, 1)
            self.control_panel_layout.addWidget(self.prefix_input, cpr, 1, 1,
                                                2)
            cpr += 1
            # Subject id
            self.exp_subject_id_prefix_input = QLineEdit()
            self.exp_subject_id_prefix_input.setStyleSheet(elem_style)
            self.exp_subject_id_prefix_input.setText(PARTICIPANT_LIST[0])
            self.set_exp_subject()
            self.exp_subject_id_prefix_input.editingFinished.connect(
                self.set_exp_subject)
            label = QLabel("User: "******"Gender:"), cpr, 0,
                                                    1, 1)
                self.exp_m_input = QRadioButton("male")
                self.exp_m_input.setChecked(
                    self.exp_params.gender == self.exp_m_input.text())
                self.exp_m_input.toggled.connect(
                    lambda checked: self.set_exp_gender(
                        self.exp_m_input.text(), checked))
                self.exp_f_input = QRadioButton("female")
                self.exp_f_input.setChecked(
                    self.exp_params.gender == self.exp_f_input.text())
                self.exp_f_input.toggled.connect(
                    lambda checked: self.set_exp_gender(
                        self.exp_f_input.text(), checked))
                self.control_panel_layout.addWidget(self.exp_m_input, cpr, 1,
                                                    1, 1)
                self.control_panel_layout.addWidget(self.exp_f_input, cpr, 2,
                                                    1, 1)
                cpr += 1
                # Age
                self.control_panel_layout.addWidget(QLabel("Age:"), cpr, 0, 1,
                                                    1)
                self.exp_age_input = QSpinBox()
                self.exp_age_input.setValue(self.exp_params.age)
                self.exp_age_input.editingFinished.connect(self.set_exp_age)
                self.control_panel_layout.addWidget(self.exp_age_input, cpr, 1,
                                                    1, 2)
                cpr += 1
                # Electrodes
                self.exp_electrodes_input = QLineEdit()
                self.exp_electrodes_input.setText(self.exp_params.electrodes)
                self.exp_electrodes_input.editingFinished.connect(
                    self.set_electrodes)
                self.control_panel_layout.addWidget(QLabel("Electrodes:"), cpr,
                                                    0, 1, 1)
                self.control_panel_layout.addWidget(self.exp_electrodes_input,
                                                    cpr, 1, 1, 2)
                cpr += 1

                # Experiment selection
                self.exp_selection_box = QComboBox()
                self.exp_selection_box.addItems(self.options)
                self.exp_selection_box.currentIndexChanged.connect(
                    self.set_exp)
                self.exp_run_button = QPushButton("Run")
                self.exp_run_button.clicked.connect(self.exp_run)
                self.control_panel_layout.addWidget(self.exp_run_button, cpr,
                                                    0, 1, 1)
                self.control_panel_layout.addWidget(self.exp_selection_box,
                                                    cpr, 1, 1, 2)

        if self.device == Device.EMG:
            self.setStyleSheet("background-color: " + BACKGROUND_COLOR + ";")

        self.show()

    def set_exp(self):
        self.exp_params.experiment = self.exp_selection_box.currentText()

    def exp_run(self):
        # Flash
        if self.exp_params.experiment == _FLASH:
            self.exp_params.record_duration = EP_FLASH_RECORD_DURATION
            self.start_record()
            self.exp_window = FlashWindow()
            self.exp_window.showFullScreen()
        # EO / EC
        elif self.exp_params.experiment == _EC or self.exp_params.experiment == _EO:
            self.exp_params.record_duration = EP_EO_DURATION
            self.start_record()
        # SSVEP
        elif self.exp_params.experiment[:5] == "SSVEP":
            id = int(self.exp_params.experiment[5:6]) - 1
            self.exp_params.record_duration = SSVEP_TIME_WINDOW * len(
                FREQ[id]) / 1000
            self.exp_window = None
            self.start_record()
            path = path_fix + "./Widgets/ssvep_exp.py"
            subprocess.Popen(["python", path, str(id)])
        # PINCODE TRUE SEQ
        elif self.exp_params.experiment == _PINCODE_4_TRUE_SEQ_REP_3:
            true_seq = PINCODE_TRUE_SEQ
            repetitions = PINCODE_REPETITIONS
            self.exp_window = PinCodeWindow(sequence=true_seq,
                                            repetitions=repetitions)
            self.exp_params.record_duration = (
                (len(true_seq) + 1) * PINCODE_FLASH_INTERVAL /
                1000) * repetitions
            self.start_record()
            self.exp_window.showFullScreen()
        # P300 Secret
        elif self.exp_params.experiment == _P300_SECRET_9:
            length = PINCODE_LENGTH
            self.exp_window = P300SecretSpeller(length=length)
            self.exp_params.record_duration = (9 * PINCODE_FLASH_INTERVAL /
                                               1000) * length
            self.start_record()
            self.exp_window.showFullScreen()
        # MOTOR IMG
        elif self.exp_params.experiment == _MI_CALIBRATION:
            self.exp_window = MotorImgWindow(sequence=SEQUENCE.CALIBRATION,
                                             device=self.device)
            tracker = EMG_TRIAL_STEPS(
            ) if self.device == Device.EMG else TRIAL_STEPS()
            self.exp_params.record_duration = MI_LABELS * MI_CALIBRATION_TRIALS * tracker.TRIAL_END / 1000
            self.start_record()
            self.exp_window.showFullScreen()
        elif self.exp_params.experiment == _MI_INPUT:
            self.exp_window = MotorImgWindow(sequence=SEQUENCE.INPUT,
                                             device=self.device)
            tracker = EMG_TRIAL_STEPS(
            ) if self.device == Device.EMG else TRIAL_STEPS()
            self.exp_params.record_duration = MI_INPUT_LENGTH * tracker.TRIAL_END / 1000
            self.start_record()
            self.exp_window.showFullScreen()

    def start_record_(self):
        self.exp_params.experiment = 'Record'
        self.start_record()

    def set_electrodes(self):
        self.exp_params.electrodes = self.exp_electrodes_input.text()

    def set_exp_age(self):
        self.exp_params.age = self.exp_age_input.value()

    def set_exp_gender(self, value, checked):
        if checked:
            self.exp_params.gender = value

    def set_exp_name(self):
        self.exp_params.name_prefix = self.prefix_input.currentText()

    def set_exp_subject(self):
        self.exp_params.subject_id = self.exp_subject_id_prefix_input.text()

    def set_record_time(self):
        self.exp_params.record_duration = self.record_time_input.value()

    def looper(self, time_left):
        if time_left < 0: return
        self.record_countdown.setText('%5.1f' % time_left + " s")
        interval = 0.5
        threading.Timer(interval,
                        lambda: self.looper(time_left - interval)).start()

    def start_record(self):
        t = threading.Timer(int(self.exp_params.record_duration),
                            lambda: self.stop_record())
        self.looper(self.exp_params.record_duration)
        self.is_recording = True
        self.record_button.setDisabled(self.is_recording)
        subdir = ""
        if self.mock:
            subdir = DEBUG_SUBDIR
        if self.device == Device.EMG:
            subdir = str(Device.EMG) + "/"
        subdir += self.exp_params.subject_id + "/"
        self.recorder = Recorder(_dir=path_fix,
                                 file_name=self.exp_params.to_file_name(),
                                 subdir=subdir)
        if self.log_keyboard:
            self.keyboard_logger = KeyboardLogger(
                file_name=self.recorder.full_name)
            self.keyboard_logger.start()
        self.exp_params.exp_id += 1
        t.start()

    def stop_record(self):
        self.is_recording = False
        self.record_button.setDisabled(self.is_recording)
        self.exp_params.exp_id += 1
        self.recorder.stop()
        if self.exp_window is not None:
            del self.exp_window
            self.exp_window = None
        if self.log_keyboard and self.keyboard_logger != None:
            self.keyboard_logger.stop()

    def pause_graphs(self):
        self.is_paused = not self.is_paused
        self.pause_button.setText(
            RESUME_GRAPH if self.is_paused else PAUSE_GRAPH)

    def add_data_callback_func(self, value):
        if not self.is_paused:
            self.myFig.addData(value)
        if self.is_recording:
            self.recorder.record_sample(value)

    def data_handler(self, sample):
        timestamp = time()
        value = sample.channel_data
        value.append(timestamp)
        self.communicator.data_signal.emit(value)

    def data_send_loop(self, add_data_callback_func):
        self.communicator.data_signal.connect(add_data_callback_func)
        if self.mock:
            file_name = "EEGMOCK" if self.device == Device.EEG else "EMGMOCK"
            reader = ReadSample(path_fix + file_name)
            sample = reader.read_sample()

            while sample is not None:
                time.sleep(1. / 50.)
                value = sample.channel_data
                value.append(sample.timestamp)
                self.communicator.data_signal.emit(value)
                sample = reader.read_sample()
        else:
            if self.device == Device.EEG:
                board = OBCIConnector()
                board.attach_handlers(self.data_handler)
            elif self.device == Device.EMG:
                self.exp_params.name_prefix = "EMG"
                EMGConnector(self.communicator)
Beispiel #42
0
class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        grid = QGridLayout()

        priceLabel = QLabel("{:>10}".format("Principal:"))
        rateLabel = QLabel("{:>10}".format("Rate:"))
        yearLabel = QLabel("{:>10}".format("Year:"))
        Amountlabel = QLabel("{:>10}".format("Amount:"))
        grid.addWidget(priceLabel, 0, 0)
        grid.addWidget(rateLabel, 1, 0)
        grid.addWidget(yearLabel, 2, 0)
        grid.addWidget(Amountlabel, 3, 0)

        self.pricelabelspinBox = QDoubleSpinBox()
        self.pricelabelspinBox.setRange(1, 1000000)
        self.pricelabelspinBox.setValue(1000)
        self.pricelabelspinBox.setPrefix("$ ")
        self.pricelabelspinBox.valueChanged.connect(self.updateUI)
        grid.addWidget(self.pricelabelspinBox, 0 ,1)

        self.ratelabelspinBox = QDoubleSpinBox()
        self.ratelabelspinBox.setRange(1, 100)
        self.ratelabelspinBox.setValue(5)
        self.ratelabelspinBox.setSuffix(" %")
        self.ratelabelspinBox.valueChanged.connect(self.updateUI)
        grid.addWidget(self.ratelabelspinBox, 1,1)

        self.yearCombox = QComboBox()
        self.yearCombox.addItems(("{} year".format(i) for i in range(1,11)))
        self.yearCombox.currentIndexChanged.connect(self.updateUI)
        grid.addWidget(self.yearCombox, 2, 1)

        self.amountlabel = QLabel("$")
        grid.addWidget(self.amountlabel, 3, 1)


        self.setLayout(grid)

        self.setGeometry(300, 300, 300, 100)
        self.setWindowTitle('compound interest')

    def updateUI(self):
        """计算金额"""
        pricipal = self.pricelabelspinBox.value()
        rate = self.ratelabelspinBox.value()
        years = self.yearCombox.currentIndex() + 1
        ammount = pricipal * ((1 + rate / 100.0) ** years)
        self.amountlabel.setText("$ {:.2f}".format(ammount))
Beispiel #43
0
class Panel(QDialog):
    def __init__(self, **kwargs):
        super(Panel, self).__init__()
        self.strategy = kwargs.get("strategy", "")
        self.version_info = "V0.1.0-Beta Build 20180422"
        self.log_text = ""
        self.log_cate = "Panel_Trader_STK_APE"
        self.logger = logger.Logger()

        self.InitUserInterface()

        self.symbol = ""
        self.exchange = ""  # SH、SZ 或 SSE、SZE # 目前只订阅个股行情,不考虑沪深个股和指数代码重合问题
        self.trader = None  # 策略中赋值
        self.subscribe = False  # 行情订阅标志
        self.center = center.Center()

        self.quote_data = None
        self.price_round_stock = 2  # 小数位数
        self.price_round_index = 2  # 小数位数

    def OnWorking(self):  # 供具体策略继承调用,在 运行 前执行一些操作
        if self.subscribe == False:
            self.center.RegQuoteSub(self.strategy, self.OnQuoteStock,
                                    "stock_ltp")  # 目前只订阅个股
            self.subscribe = True
        self.trader = trader.Trader().GetTrader("hbzq")
        if self.trader == None:
            self.logger.SendMessage("E", 4, self.log_cate,
                                    "获取标识为 hbzq 的交易服务失败!", "M")

    def OnSuspend(self):  # 供具体策略继承调用,在 暂停 前执行一些操作
        pass

    def OnContinue(self):  # 供具体策略继承调用,在 继续 前执行一些操作
        pass

    def OnTerminal(self):  # 供具体策略继承调用,在 停止 前执行一些操作
        if self.subscribe == True:
            self.center.DelQuoteSub(self.strategy, "stock_ltp")
            self.subscribe = False

    def event(self, event):
        if event.type() == define.DEF_EVENT_TRADER_STK_APE_UPDATE_QUOTE:
            if self.quote_data != None:
                self.OnUpdateQuote(self.quote_data, self.price_round_stock)
        return QDialog.event(self, event)

    def OnTraderEvent(self, trader, ret_func, task_item):  # 交易模块事件通知,供具体策略继承调用
        if ret_func == define.trade_placeorder_s_func:
            self.log_text = "%s:%s %d:%d" % (self.strategy, trader, ret_func,
                                             task_item.order.order_id)
            self.logger.SendMessage("H", 2, self.log_cate, self.log_text, "T")

    def OnQuoteStock(self, msg):  # 行情触发
        try:
            str_code = msg.data[0].decode()
            if str_code == self.symbol:
                if "60" == str_code[0:2] or "000" == str_code[
                        0:3] or "001" == str_code[0:3] or "002" == str_code[
                            0:3] or "300" == str_code[0:3]:
                    self.quote_data = msg.data
                    QApplication.postEvent(
                        self,
                        QEvent(define.DEF_EVENT_TRADER_STK_APE_UPDATE_QUOTE
                               ))  # postEvent异步,sendEvent同步
        except Exception as e:
            self.log_text = "%s:函数 OnQuoteStock 异常!%s" % (self.strategy, e)
            self.logger.SendMessage("E", 4, self.log_cate, self.log_text, "M")

    def InitUserInterface(self):
        self.color_red = QPalette()
        self.color_red.setColor(QPalette.WindowText, Qt.red)
        self.color_green = QPalette()
        self.color_green.setColor(QPalette.WindowText, QColor(0, 128, 0))
        self.color_black = QPalette()
        self.color_black.setColor(QPalette.WindowText, Qt.black)

        self.list_exchange = [
            define.DEF_EXCHANGE_STOCK_SH, define.DEF_EXCHANGE_STOCK_SZ
        ]
        self.list_entr_type = [
            define.DEF_PRICE_TYPE_STOCK_LIMIT,
            define.DEF_PRICE_TYPE_STOCK_MARKET
        ]

        self.setWindowTitle("手动交易-股票-APE %s" % self.version_info)
        self.resize(380, 300)
        self.setFont(QFont("SimSun", 9))

        self.label_exchange = QLabel("交易市场")
        self.label_exchange.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_symbol = QLabel("证券代码")
        self.label_symbol.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_name = QLabel("证券名称")
        self.label_name.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_entr_type = QLabel("委托方式")
        self.label_entr_type.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_can_use = QLabel("可用金额")
        self.label_can_use.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_can_sell = QLabel("可用数量")
        self.label_can_sell.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_price = QLabel("委托价格")
        self.label_price.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_volume = QLabel("委托数量")
        self.label_volume.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        self.label_can_use_unit = QLabel("元")
        self.label_can_use_unit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_can_sell_unit = QLabel("股")
        self.label_can_sell_unit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_price_unit = QLabel("元")
        self.label_price_unit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label_volume_unit = QLabel("股")
        self.label_volume_unit.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        self.combo_exchange = QComboBox()
        self.combo_exchange.addItems(self.list_exchange)
        self.line_edit_symbol = QLineEdit("")
        self.line_edit_symbol.setStyleSheet("color:red")  # 初始红色
        self.line_edit_symbol.setFont(QFont("SimSun", 9))
        self.line_edit_name = QLineEdit("")
        self.line_edit_name.setReadOnly(True)
        self.line_edit_name.setFont(QFont("SimSun", 9))
        self.line_edit_name.setStyleSheet(
            "background-color:rgb(240,240,240);color:red")  # 初始红色
        self.line_edit_name.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.combo_entr_type = QComboBox()
        self.combo_entr_type.addItems(self.list_entr_type)
        self.line_edit_can_use = QLineEdit("0.00")
        self.line_edit_can_use.setReadOnly(True)
        self.line_edit_can_use.setStyleSheet(
            "background-color:rgb(240,240,240)")
        self.line_edit_can_use.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.line_edit_can_sell = QLineEdit("0")
        self.line_edit_can_sell.setReadOnly(True)
        self.line_edit_can_sell.setStyleSheet(
            "background-color:rgb(240,240,240)")
        self.line_edit_can_sell.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.spin_price = QDoubleSpinBox()
        self.spin_price.setDecimals(4)
        self.spin_price.setMinimum(0)
        self.spin_price.setMaximum(100000)
        self.spin_price.setStyleSheet("color:red")  # 初始红色
        self.spin_price.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.spin_volume = QSpinBox()
        self.spin_volume.setMinimum(0)
        self.spin_volume.setMaximum(1000000)
        self.spin_volume.setSingleStep(100)
        self.spin_volume.setStyleSheet("color:red")  # 初始红色
        self.spin_volume.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.grid_layout_essential = QGridLayout()
        self.grid_layout_essential.setContentsMargins(-1, -1, -1, -1)
        self.grid_layout_essential.addWidget(self.label_exchange, 0, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_symbol, 1, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_name, 2, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_entr_type, 3, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_can_use, 4, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_can_sell, 5, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_price, 6, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.label_volume, 7, 0, 1, 1)
        self.grid_layout_essential.addWidget(self.combo_exchange, 0, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.line_edit_symbol, 1, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.line_edit_name, 2, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.combo_entr_type, 3, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.line_edit_can_use, 4, 1, 1,
                                             1)
        self.grid_layout_essential.addWidget(self.line_edit_can_sell, 5, 1, 1,
                                             1)
        self.grid_layout_essential.addWidget(self.spin_price, 6, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.spin_volume, 7, 1, 1, 1)
        self.grid_layout_essential.addWidget(self.label_can_use_unit, 4, 2, 1,
                                             1)
        self.grid_layout_essential.addWidget(self.label_can_sell_unit, 5, 2, 1,
                                             1)
        self.grid_layout_essential.addWidget(self.label_price_unit, 6, 2, 1, 1)
        self.grid_layout_essential.addWidget(self.label_volume_unit, 7, 2, 1,
                                             1)

        self.radio_button_buy = QRadioButton("买 入")
        self.radio_button_buy.setStyleSheet("color:red")
        self.radio_button_buy.setFont(QFont("SimSun", 9))
        self.radio_button_buy.setChecked(True)
        self.radio_button_buy.setFixedWidth(70)
        self.radio_button_sell = QRadioButton("卖 出")
        self.radio_button_sell.setStyleSheet("color:green")
        self.radio_button_sell.setFont(QFont("SimSun", 9))
        self.radio_button_sell.setFixedWidth(70)
        self.button_place_order = QPushButton("下 单")
        self.button_place_order.setFont(QFont("SimSun", 9))
        self.button_place_order.setStyleSheet("font:bold;color:red")  # 初始红色
        self.button_place_order.setFixedWidth(70)

        self.label_order_id = QLabel("撤单委托编号")
        self.label_order_id.setFixedWidth(70)
        self.label_order_id.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.line_edit_order_id = QLineEdit("")
        self.line_edit_order_id.setFixedWidth(70)
        self.line_edit_order_id.setStyleSheet("color:blue")
        self.line_edit_order_id.setFont(QFont("SimSun", 9))
        self.button_cancel_order = QPushButton("撤 单")
        self.button_cancel_order.setFont(QFont("SimSun", 9))
        self.button_cancel_order.setStyleSheet("font:bold;color:blue")
        self.button_cancel_order.setFixedWidth(70)

        self.h_box_layout_order_buttons = QHBoxLayout()
        self.h_box_layout_order_buttons.setContentsMargins(-1, -1, -1, -1)
        self.h_box_layout_order_buttons.addStretch(1)
        self.h_box_layout_order_buttons.addWidget(self.radio_button_buy)
        self.h_box_layout_order_buttons.addStretch(1)
        self.h_box_layout_order_buttons.addWidget(self.radio_button_sell)
        self.h_box_layout_order_buttons.addStretch(1)
        self.h_box_layout_order_buttons.addWidget(self.button_place_order)
        self.h_box_layout_order_buttons.addStretch(1)

        self.h_box_layout_cancel_order = QHBoxLayout()
        self.h_box_layout_cancel_order.setContentsMargins(-1, -1, -1, -1)  #
        self.h_box_layout_cancel_order.addStretch(1)
        self.h_box_layout_cancel_order.addWidget(self.label_order_id)
        self.h_box_layout_cancel_order.addStretch(1)
        self.h_box_layout_cancel_order.addWidget(self.line_edit_order_id)
        self.h_box_layout_cancel_order.addStretch(1)
        self.h_box_layout_cancel_order.addWidget(self.button_cancel_order)
        self.h_box_layout_cancel_order.addStretch(1)

        self.v_box_layout_order = QVBoxLayout()
        self.v_box_layout_order.setContentsMargins(-1, -1, -1, -1)
        self.v_box_layout_order.addLayout(self.grid_layout_essential)
        self.v_box_layout_order.addLayout(self.h_box_layout_order_buttons)
        self.v_box_layout_order.addLayout(self.h_box_layout_cancel_order)

        self.label_high_limit = QLabel("涨停")
        self.label_ask_5 = QLabel("卖五")
        self.label_ask_4 = QLabel("卖四")
        self.label_ask_3 = QLabel("卖三")
        self.label_ask_2 = QLabel("卖二")
        self.label_ask_1 = QLabel("卖一")
        self.label_last = QLabel("最新")
        self.label_last.setMinimumWidth(35)
        self.label_bid_1 = QLabel("买一")
        self.label_bid_2 = QLabel("买二")
        self.label_bid_3 = QLabel("买三")
        self.label_bid_4 = QLabel("买四")
        self.label_bid_5 = QLabel("买五")
        self.label_low_limit = QLabel("跌停")

        self.label_high_limit.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_last.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_low_limit.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.label_high_limit_price = QLabel("0.00")
        self.label_high_limit_price.setMinimumWidth(60)
        self.label_ask_price_5 = QLabel("0.00")
        self.label_ask_price_4 = QLabel("0.00")
        self.label_ask_price_3 = QLabel("0.00")
        self.label_ask_price_2 = QLabel("0.00")
        self.label_ask_price_1 = QLabel("0.00")
        self.label_ask_volume_5 = QLabel("0")
        self.label_ask_volume_4 = QLabel("0")
        self.label_ask_volume_3 = QLabel("0")
        self.label_ask_volume_2 = QLabel("0")
        self.label_ask_volume_1 = QLabel("0")
        self.label_last_price = QLabel("0.00")
        self.label_last_price.setMinimumWidth(60)
        self.label_last_up_down = QLabel("0.00%")
        self.label_last_up_down.setMinimumWidth(60)
        self.label_bid_price_1 = QLabel("0.00")
        self.label_bid_price_2 = QLabel("0.00")
        self.label_bid_price_3 = QLabel("0.00")
        self.label_bid_price_4 = QLabel("0.00")
        self.label_bid_price_5 = QLabel("0.00")
        self.label_bid_volume_1 = QLabel("0")
        self.label_bid_volume_2 = QLabel("0")
        self.label_bid_volume_3 = QLabel("0")
        self.label_bid_volume_4 = QLabel("0")
        self.label_bid_volume_5 = QLabel("0")
        self.label_low_limit_price = QLabel("0.00")
        self.label_low_limit_price.setMinimumWidth(60)

        self.label_high_limit_price.setPalette(self.color_red)
        self.label_ask_price_5.setPalette(self.color_green)
        self.label_ask_price_4.setPalette(self.color_green)
        self.label_ask_price_3.setPalette(self.color_green)
        self.label_ask_price_2.setPalette(self.color_green)
        self.label_ask_price_1.setPalette(self.color_green)
        self.label_ask_volume_5.setPalette(self.color_green)
        self.label_ask_volume_4.setPalette(self.color_green)
        self.label_ask_volume_3.setPalette(self.color_green)
        self.label_ask_volume_2.setPalette(self.color_green)
        self.label_ask_volume_1.setPalette(self.color_green)
        self.label_last_price.setPalette(self.color_black)
        self.label_last_up_down.setPalette(self.color_black)
        self.label_bid_price_1.setPalette(self.color_red)
        self.label_bid_price_2.setPalette(self.color_red)
        self.label_bid_price_3.setPalette(self.color_red)
        self.label_bid_price_4.setPalette(self.color_red)
        self.label_bid_price_5.setPalette(self.color_red)
        self.label_bid_volume_1.setPalette(self.color_red)
        self.label_bid_volume_2.setPalette(self.color_red)
        self.label_bid_volume_3.setPalette(self.color_red)
        self.label_bid_volume_4.setPalette(self.color_red)
        self.label_bid_volume_5.setPalette(self.color_red)
        self.label_low_limit_price.setPalette(self.color_green)

        self.label_high_limit_price.setAlignment(Qt.AlignRight
                                                 | Qt.AlignVCenter)
        self.label_ask_price_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_price_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_price_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_price_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_price_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_ask_volume_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_last_price.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_last_up_down.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_price_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_bid_volume_5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.label_low_limit_price.setAlignment(Qt.AlignRight
                                                | Qt.AlignVCenter)

        self.grid_layout_quote = QGridLayout()
        self.grid_layout_quote.addWidget(self.label_high_limit, 0, 0)  #
        self.grid_layout_quote.addWidget(self.label_ask_5, 1, 0)
        self.grid_layout_quote.addWidget(self.label_ask_4, 2, 0)
        self.grid_layout_quote.addWidget(self.label_ask_3, 3, 0)
        self.grid_layout_quote.addWidget(self.label_ask_2, 4, 0)
        self.grid_layout_quote.addWidget(self.label_ask_1, 5, 0)
        self.grid_layout_quote.addWidget(self.label_last, 6, 0)  #
        self.grid_layout_quote.addWidget(self.label_bid_1, 7, 0)
        self.grid_layout_quote.addWidget(self.label_bid_2, 8, 0)
        self.grid_layout_quote.addWidget(self.label_bid_3, 9, 0)
        self.grid_layout_quote.addWidget(self.label_bid_4, 10, 0)
        self.grid_layout_quote.addWidget(self.label_bid_5, 11, 0)
        self.grid_layout_quote.addWidget(self.label_low_limit, 12, 0)  #
        self.grid_layout_quote.addWidget(self.label_high_limit_price, 0, 1)  #
        self.grid_layout_quote.addWidget(self.label_ask_price_5, 1, 1)
        self.grid_layout_quote.addWidget(self.label_ask_price_4, 2, 1)
        self.grid_layout_quote.addWidget(self.label_ask_price_3, 3, 1)
        self.grid_layout_quote.addWidget(self.label_ask_price_2, 4, 1)
        self.grid_layout_quote.addWidget(self.label_ask_price_1, 5, 1)
        self.grid_layout_quote.addWidget(self.label_last_price, 6, 1)  #
        self.grid_layout_quote.addWidget(self.label_bid_price_1, 7, 1)
        self.grid_layout_quote.addWidget(self.label_bid_price_2, 8, 1)
        self.grid_layout_quote.addWidget(self.label_bid_price_3, 9, 1)
        self.grid_layout_quote.addWidget(self.label_bid_price_4, 10, 1)
        self.grid_layout_quote.addWidget(self.label_bid_price_5, 11, 1)
        self.grid_layout_quote.addWidget(self.label_low_limit_price, 12, 1)  #
        self.grid_layout_quote.addWidget(self.label_ask_volume_5, 1, 2)
        self.grid_layout_quote.addWidget(self.label_ask_volume_4, 2, 2)
        self.grid_layout_quote.addWidget(self.label_ask_volume_3, 3, 2)
        self.grid_layout_quote.addWidget(self.label_ask_volume_2, 4, 2)
        self.grid_layout_quote.addWidget(self.label_ask_volume_1, 5, 2)
        self.grid_layout_quote.addWidget(self.label_last_up_down, 6, 2)  #
        self.grid_layout_quote.addWidget(self.label_bid_volume_1, 7, 2)
        self.grid_layout_quote.addWidget(self.label_bid_volume_2, 8, 2)
        self.grid_layout_quote.addWidget(self.label_bid_volume_3, 9, 2)
        self.grid_layout_quote.addWidget(self.label_bid_volume_4, 10, 2)
        self.grid_layout_quote.addWidget(self.label_bid_volume_5, 11, 2)

        self.main_text_edit_bottom = QTextEdit(self)
        self.main_text_edit_bottom.setText("")
        self.main_text_edit_bottom.setFont(QFont("SimSun", 9))

        self.h_box_layout_1 = QHBoxLayout()
        self.h_box_layout_1.addLayout(self.v_box_layout_order)
        self.h_box_layout_1.addLayout(self.grid_layout_quote)

        self.h_box_layout_2 = QHBoxLayout()
        self.h_box_layout_2.setContentsMargins(-1, -1, -1, -1)
        self.h_box_layout_2.addWidget(self.main_text_edit_bottom)

        self.v_box_layout_mian = QVBoxLayout()
        self.v_box_layout_mian.setContentsMargins(-1, -1, -1, -1)
        self.v_box_layout_mian.addLayout(self.h_box_layout_1)
        self.v_box_layout_mian.addLayout(self.h_box_layout_2)

        self.setLayout(self.v_box_layout_mian)

        self.combo_exchange.activated[str].connect(self.OnChangeExchange)
        self.line_edit_symbol.editingFinished.connect(self.OnChangeSymbol)
        self.radio_button_buy.clicked.connect(self.OnChangeBuySell)
        self.radio_button_sell.clicked.connect(self.OnChangeBuySell)
        self.button_place_order.clicked.connect(self.OnButtonPlaceOrder)
        self.button_cancel_order.clicked.connect(self.OnButtonCancelOrder)

    def OnChangeExchange(self, str_exchange):
        self.symbol = ""
        self.exchange = ""
        self.line_edit_symbol.setText("")
        self.line_edit_name.setText("")
        self.OnChangeSymbol()

    def OnChangeSymbol(self):
        self.exchange = ""
        self.symbol = self.line_edit_symbol.text(
        )  #str(unicode(self.line_edit_symbol.text(), "gb2312"))

        self.spin_price.setValue(0)
        self.spin_volume.setValue(0)

        self.label_high_limit_price.setText("0.00")
        self.label_ask_price_5.setText("0.00")
        self.label_ask_price_4.setText("0.00")
        self.label_ask_price_3.setText("0.00")
        self.label_ask_price_2.setText("0.00")
        self.label_ask_price_1.setText("0.00")
        self.label_ask_volume_5.setText("0")
        self.label_ask_volume_4.setText("0")
        self.label_ask_volume_3.setText("0")
        self.label_ask_volume_2.setText("0")
        self.label_ask_volume_1.setText("0")
        self.label_last_price.setText("0.00")
        self.label_last_up_down.setText("0.00%")
        self.label_bid_price_1.setText("0.00")
        self.label_bid_price_2.setText("0.00")
        self.label_bid_price_3.setText("0.00")
        self.label_bid_price_4.setText("0.00")
        self.label_bid_price_5.setText("0.00")
        self.label_bid_volume_1.setText("0")
        self.label_bid_volume_2.setText("0")
        self.label_bid_volume_3.setText("0")
        self.label_bid_volume_4.setText("0")
        self.label_bid_volume_5.setText("0")
        self.label_low_limit_price.setText("0.00")

    def OnChangeBuySell(self):
        if self.radio_button_buy.isChecked():
            self.line_edit_symbol.setStyleSheet("color:red")
            self.line_edit_name.setStyleSheet(
                "background-color:rgb(240,240,240);color:red")
            self.spin_price.setStyleSheet("color:red")
            self.spin_volume.setStyleSheet("color:red")
            self.button_place_order.setStyleSheet("font:bold;color:red")
        if self.radio_button_sell.isChecked():
            self.line_edit_symbol.setStyleSheet("color:green")
            self.line_edit_name.setStyleSheet(
                "background-color:rgb(240,240,240);color:green")
            self.spin_price.setStyleSheet("color:green")
            self.spin_volume.setStyleSheet("color:green")
            self.button_place_order.setStyleSheet("font:bold;color:green")

    def OnUpdateQuote(self, data, price_round):
        try:
            self.exchange = data[3].decode()  # 证券市场
            self.line_edit_name.setText(
                str(data[1].decode("gbk"))
            )  # 证券名称 #QString.fromLocal8Bit(data[1].decode("gbk")) # 含中文
            self.label_ask_price_5.setText(str(round(data[13][4],
                                                     price_round)))
            self.label_ask_price_4.setText(str(round(data[13][3],
                                                     price_round)))
            self.label_ask_price_3.setText(str(round(data[13][2],
                                                     price_round)))
            self.label_ask_price_2.setText(str(round(data[13][1],
                                                     price_round)))
            self.label_ask_price_1.setText(str(round(data[13][0],
                                                     price_round)))
            self.label_ask_volume_5.setText(str(data[14][4]))
            self.label_ask_volume_4.setText(str(data[14][3]))
            self.label_ask_volume_3.setText(str(data[14][2]))
            self.label_ask_volume_2.setText(str(data[14][1]))
            self.label_ask_volume_1.setText(str(data[14][0]))
            self.label_bid_price_1.setText(str(round(data[15][0],
                                                     price_round)))
            self.label_bid_price_2.setText(str(round(data[15][1],
                                                     price_round)))
            self.label_bid_price_3.setText(str(round(data[15][2],
                                                     price_round)))
            self.label_bid_price_4.setText(str(round(data[15][3],
                                                     price_round)))
            self.label_bid_price_5.setText(str(round(data[15][4],
                                                     price_round)))
            self.label_bid_volume_1.setText(str(data[16][0]))
            self.label_bid_volume_2.setText(str(data[16][1]))
            self.label_bid_volume_3.setText(str(data[16][2]))
            self.label_bid_volume_4.setText(str(data[16][3]))
            self.label_bid_volume_5.setText(str(data[16][4]))
            self.label_high_limit_price.setText(
                str(round(data[17], price_round)))  # 涨停价
            self.label_low_limit_price.setText(
                str(round(data[18], price_round)))  # 跌停价
            self.label_last_price.setText(str(round(data[5],
                                                    price_round)))  # 最新价
            if data[10] > 0.0:  # 昨收价
                f_last_up_down = (data[5] / data[10]) - 1.0
                self.label_last_up_down.setText(
                    ("%.2f%%" % (f_last_up_down * 100.0)))
                if f_last_up_down > 0.0:
                    self.label_last_up_down.setPalette(self.color_red)
                elif f_last_up_down < 0.0:
                    self.label_last_up_down.setPalette(self.color_green)
                else:
                    self.label_last_up_down.setPalette(self.color_black)
            else:
                self.label_last_up_down.setText("0.00%")
        except Exception as e:
            self.log_text = "%s:函数 OnUpdateQuote 异常!%s" % (self.strategy, e)
            self.logger.SendMessage("E", 4, self.log_cate, self.log_text, "M")

    def OnButtonPlaceOrder(self):
        if self.trader != None:
            if self.trader.IsTraderReady() == False:
                self.logger.SendMessage("E", 4, self.log_cate, "交易服务尚未开启!",
                                        "M")
            else:
                if self.line_edit_symbol.text() == "":
                    QMessageBox.warning(self, "提示", "证券代码为空!", QMessageBox.Ok)
                    return
                str_symbol = self.line_edit_symbol.text(
                )  #str(unicode(self.line_edit_symbol.text(), "gb2312"))
                str_exchange = ""
                if self.combo_exchange.currentText(
                ) == define.DEF_EXCHANGE_STOCK_SH:
                    str_exchange = "SH"
                elif self.combo_exchange.currentText(
                ) == define.DEF_EXCHANGE_STOCK_SZ:
                    str_exchange = "SZ"
                f_price = self.spin_price.value()
                n_amount = self.spin_volume.value()
                n_entr_type = 0
                if self.combo_entr_type.currentText(
                ) == define.DEF_PRICE_TYPE_STOCK_LIMIT:
                    n_entr_type = 1
                elif self.combo_entr_type.currentText(
                ) == define.DEF_PRICE_TYPE_STOCK_MARKET:
                    n_entr_type = 2
                n_exch_side = 0
                if self.radio_button_buy.isChecked():
                    n_exch_side = 1
                elif self.radio_button_sell.isChecked():
                    n_exch_side = 2
                order = self.trader.Order(symbol=str_symbol,
                                          exchange=str_exchange,
                                          price=f_price,
                                          amount=n_amount,
                                          entr_type=n_entr_type,
                                          exch_side=n_exch_side)
                task_place = self.trader.PlaceOrder(order, self.strategy)
                QMessageBox.information(self, "提示", "委托下单提交完成。",
                                        QMessageBox.Ok)
        else:
            self.logger.SendMessage("E", 4, self.log_cate, "交易服务尚未获取!", "M")

    def OnButtonCancelOrder(self):
        if self.trader != None:
            if self.trader.IsTraderReady() == False:
                self.logger.SendMessage("E", 4, self.log_cate, "交易服务尚未开启!",
                                        "M")
            else:
                if self.line_edit_order_id.text() == "":
                    QMessageBox.warning(self, "提示", "撤单委托编号为空!",
                                        QMessageBox.Ok)
                    return
                order = self.trader.Order()
                order.order_id = int(self.line_edit_order_id.text())  # int
                task_cancel = self.trader.CancelOrder(order, self.strategy)
                QMessageBox.information(self, "提示", "委托撤单提交完成。",
                                        QMessageBox.Ok)
        else:
            self.logger.SendMessage("E", 4, self.log_cate, "交易服务尚未获取!", "M")
Beispiel #44
0
class FloatSpinBoxAndSliderPidget(PidgetStub):
    NUM_SLIDER_STEPS = 200

    def __init__(self, param, parent_instance):
        assert isinstance(param, FloatParameter)

        super().__init__(param, parent_instance)

        self.grid.setColumnStretch(0, 7)
        self.grid.setColumnStretch(1, 3)

        label = QLabel(self)
        suffix = " [{}]".format(param.unit) if param.unit else ""
        label.setText(param.label + suffix)
        self.grid.addWidget(label, 0, 0, 1, 1)

        self.spin_box = QDoubleSpinBox(self)
        self.spin_box.setDecimals(param.decimals)
        self.spin_box.setSingleStep(10**(-param.decimals))
        self.spin_box.valueChanged.connect(self._subwidget_event_handler)
        self.spin_box.setKeyboardTracking(False)
        self.spin_box.setMinimum(param.limits[0])
        self.spin_box.setMaximum(param.limits[1])
        self.grid.addWidget(self.spin_box, 0, 1, 1, 1)

        slider_widget = QWidget()
        slider_layout = QHBoxLayout(slider_widget)
        slider_layout.setContentsMargins(0, 0, 0, 0)
        slider_layout.addWidget(QLabel(str(param.limits[0])))
        self.slider = QSlider(QtCore.Qt.Horizontal)
        self.slider.setRange(0, self.NUM_SLIDER_STEPS)
        self.slider.sliderPressed.connect(self.__slider_event_handler)
        self.slider.valueChanged.connect(self.__slider_event_handler)
        slider_layout.addWidget(self.slider, 1)
        slider_layout.addWidget(QLabel(str(param.limits[1])))
        self.grid.addWidget(slider_widget, 1, 0, 1, 2)

        self.update()

    def _update(self):
        super()._update()
        value = self._get_param_value()
        self.spin_box.setValue(value)
        self.slider.setValue(self.__to_slider_scale(value))

    def __slider_event_handler(self, x=None):
        if x is None:
            x = self.slider.sliderPosition()

        self._subwidget_event_handler(self.__from_slider_scale(x))

    def __to_slider_scale(self, x):
        lower, upper = self.param.limits

        if self.param.logscale:
            lower = np.log(lower)
            upper = np.log(upper)
            x = np.log(x)

        y = (x - lower) / (upper - lower) * self.NUM_SLIDER_STEPS
        return int(round(y))

    def __from_slider_scale(self, y):
        lower, upper = self.param.limits

        if self.param.logscale:
            lower = np.log(lower)
            upper = np.log(upper)

        x = y / self.NUM_SLIDER_STEPS * (upper - lower) + lower

        if self.param.logscale:
            x = np.exp(x)

        return x
Beispiel #45
0
class BrowserWidget(QWidget):
    def __init__(self, parent):
        super(BrowserWidget, self).__init__(parent)
        self.browser = WebView(self)
        self.__layout()
        self.__bookmark = None
        self.filename = ''

    def __layout(self):
        self.browser.loadFinished.connect(self.__onLoadFinished)
        self.__vbox = QVBoxLayout()

        self.__ctrls_layout = QHBoxLayout()

        self.__edit_url = QLineEdit()
        self.__ctrls_layout.addWidget(self.__edit_url)

        # self.__btn_go = QPushButton('Go')
        # self.__btn_go.clicked.connect(self.__on_btn_go)
        # self.__ctrls_layout.addWidget(self.__btn_go)
        # https://www.learnpyqt.com/examples/mooseache/
        # https://doc.qt.io/qt-5/qstyle.html#StandardPixmap-enum
        self.__btn_back = QPushButton()
        self.__btn_back.setIcon(self.style().standardIcon(QStyle.SP_ArrowLeft))
        self.__btn_back.setFlat(True)
        self.__btn_back.setToolTip('Back')
        self.__btn_back.clicked.connect(self.browser.back)
        self.__ctrls_layout.addWidget(self.__btn_back)

        self.__btn_forward = QPushButton()
        self.__btn_forward.setIcon(self.style().standardIcon(
            QStyle.SP_ArrowForward))
        self.__btn_forward.setFlat(True)
        self.__btn_forward.setToolTip('Forward')
        self.__btn_forward.clicked.connect(self.browser.forward)
        self.__ctrls_layout.addWidget(self.__btn_forward)

        self.__btn_reload = QPushButton()
        self.__btn_reload.setIcon(self.style().standardIcon(
            QStyle.SP_BrowserReload))
        self.__btn_reload.setFlat(True)
        self.__btn_reload.setToolTip('Reload')
        self.__btn_reload.clicked.connect(self.browser.reload)
        self.__ctrls_layout.addWidget(self.__btn_reload)

        self.__btn_stop = QPushButton()
        self.__btn_stop.setIcon(self.style().standardIcon(
            QStyle.SP_BrowserStop))
        self.__btn_stop.setFlat(True)
        self.__btn_stop.setToolTip('Stop')
        self.__btn_stop.clicked.connect(self.browser.stop)
        self.__ctrls_layout.addWidget(self.__btn_stop)

        self.browser.urlChanged.connect(self.update_urlbar)

        self.__label_zoom = QLabel()
        self.__label_zoom.setText('Zoom')
        self.__label_zoom.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.__ctrls_layout.addWidget(self.__label_zoom,
                                      alignment=Qt.AlignRight)

        self.__spin_zoom = QDoubleSpinBox()
        self.__spin_zoom.setRange(0.125, 15)
        self.__spin_zoom.setValue(1.0)
        self.__spin_zoom.setSingleStep(0.125)
        self.__spin_zoom.valueChanged.connect(self.__spin_zoom_valueChanged)
        self.__spin_zoom.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        # https://stackoverflow.com/questions/53573382/pyqt5-set-widget-size-to-minimum-and-fix
        self.__ctrls_layout.addWidget(self.__spin_zoom,
                                      alignment=Qt.AlignRight)

        self.__vbox.addLayout(self.__ctrls_layout)

        self.__vbox.addWidget(self.browser)

        self.setLayout(self.__vbox)

        self.__ctrl_plus_shortcut = QShortcut(QKeySequence("Ctrl++"), self)
        self.__ctrl_plus_shortcut.activated.connect(self.__on_ctrl_plus)

        self.__ctrl_minus_shortcut = QShortcut(QKeySequence("Ctrl+-"), self)
        self.__ctrl_minus_shortcut.activated.connect(self.__on_ctrl_minus)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Return:
            self.__on_btn_go()

    def update_urlbar(self, q):
        """
        if q.scheme() == 'https':
            # Secure padlock icon
            self.httpsicon.setPixmap( QPixmap( os.path.join('icons','lock-ssl.png') ) )

        else:
            # Insecure padlock icon
            self.httpsicon.setPixmap( QPixmap( os.path.join('icons','lock-nossl.png') ) )
        """
        self.__edit_url.setText(q.toString())
        self.__edit_url.setCursorPosition(0)

    def __onLoadFinished(self, ok):
        if self.__bookmark is not None:
            self.__spin_zoom.setValue(self.__bookmark.zoomFactor)
            text = self.__bookmark.text
            if len(text) > 0:
                self.browser.findText(text)
        self.__bookmark = None

    def __spin_zoom_valueChanged(self, value):
        self.browser.setZoomFactor(value)

    def __on_ctrl_plus(self):
        self.__spin_zoom.setValue(self.__spin_zoom.value() +
                                  self.__spin_zoom.singleStep())

    def __on_ctrl_minus(self):
        self.__spin_zoom.setValue(self.__spin_zoom.value() -
                                  self.__spin_zoom.singleStep())

    def load_page(self, url):
        qurl = QUrl(url)
        self.__edit_url.setText(qurl.toString())
        self.browser.stop()
        self.browser.load(qurl)

    def __on_btn_go(self, *args):
        if len(self.__edit_url.text()) > 0:
            self.filename = self.__edit_url.text()
            self.load_page(QUrl.fromUserInput(self.filename))

    def open_local_text(self, textFile):
        if len(textFile) > 0:
            self.filename = textFile
            self.load_page(QUrl.fromUserInput(textFile))

    def toggle_internet_controls(self, show=True):
        if show:
            self.__edit_url.show()
            self.__btn_go.show()
        else:
            self.__edit_url.hide()
            self.__btn_go.hide()
            # https://doc.qt.io/qtforpython/PySide2/QtWidgets/QBoxLayout.html#PySide2.QtWidgets.PySide2.QtWidgets.QBoxLayout.insertStretch
            self.__ctrls_layout.insertStretch(0, stretch=0)
        return self
Beispiel #46
0
class BasicParams(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self.left = 10
        self.top = 10
        self.width = 500
        self.height = 300
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.initUI()

    def initUI(self):

        #TODO ewentualnie nazwy pol _spinBox do zmiany
        self.labela = QLabel("Rozrodczosc ofiar - r", self)
        self.rSpinBox = QDoubleSpinBox()
        self.rSpinBox.setStyleSheet("background-color: #2d3847; color: white")
        self.rSpinBox.setValue(2)
        self.rSpinBox.stepBy(0.1)

        self.labelb = QLabel("Śmiertelność ofiar (skuteczność polowań) - a",
                             self)
        self.aSpinBox = QDoubleSpinBox()
        self.aSpinBox.setStyleSheet("background-color: #2d3847; color: white")
        self.aSpinBox.setValue(0.5)
        self.aSpinBox.stepBy(0.1)

        self.labelc = QLabel("Śmiertelność drapiezników - s", self)
        self.sSpinBox = QDoubleSpinBox()
        self.sSpinBox.setStyleSheet("background-color: #2d3847; color: white")
        self.sSpinBox.setValue(0.3)
        self.sSpinBox.stepBy(0.1)

        self.labeld = QLabel(
            "Część upolowanych ofiar \nprzeznaczona na reprodukcję rapieżników - b",
            self)
        self.bSpinBox = QDoubleSpinBox()
        self.bSpinBox.setStyleSheet("background-color: #2d3847; color: white")
        self.bSpinBox.setValue(0.8)
        self.bSpinBox.stepBy(0.1)

        fundamentalParamsLV = QVBoxLayout(self)
        fundamentalParamsLV.addWidget(self.labela)
        fundamentalParamsLV.addWidget(self.rSpinBox)
        fundamentalParamsLV.addSpacing(20)
        fundamentalParamsLV.addWidget(self.labelb)
        fundamentalParamsLV.addWidget(self.aSpinBox)
        fundamentalParamsLV.addSpacing(20)
        fundamentalParamsLV.addWidget(self.labelc)
        fundamentalParamsLV.addWidget(self.sSpinBox)
        fundamentalParamsLV.addSpacing(20)
        fundamentalParamsLV.addWidget(self.labeld)
        fundamentalParamsLV.addWidget(self.bSpinBox)
        fundamentalParamsLV.addStretch(1)
Beispiel #47
0
    def __init__(self, persepolis_setting):
        super().__init__()
        # MainWindow
        self.persepolis_setting = persepolis_setting

        # add support for other languages
        locale = str(self.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

        # set ui direction
        ui_direction = self.persepolis_setting.value('ui_direction')

        if ui_direction == 'rtl':
            self.setLayoutDirection(Qt.RightToLeft)

        elif ui_direction in 'ltr':
            self.setLayoutDirection(Qt.LeftToRight)

        icons = ':/' + \
            str(self.persepolis_setting.value('settings/icons')) + '/'

        self.setWindowTitle(
            QCoreApplication.translate("mainwindow_ui_tr",
                                       "Persepolis Download Manager"))
        self.setWindowIcon(
            QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg')))

        self.centralwidget = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.centralwidget)

        # enable drag and drop
        self.setAcceptDrops(True)

        # frame
        self.frame = QFrame(self.centralwidget)

        # download_table_horizontalLayout
        download_table_horizontalLayout = QHBoxLayout()
        horizontal_splitter = QSplitter(Qt.Horizontal)

        vertical_splitter = QSplitter(Qt.Vertical)

        # category_tree
        self.category_tree_qwidget = QWidget(self)
        category_tree_verticalLayout = QVBoxLayout()
        self.category_tree = CategoryTreeView(self)
        category_tree_verticalLayout.addWidget(self.category_tree)

        self.category_tree_model = QStandardItemModel()
        self.category_tree.setModel(self.category_tree_model)
        category_table_header = [
            QCoreApplication.translate("mainwindow_ui_tr", 'Category')
        ]

        self.category_tree_model.setHorizontalHeaderLabels(
            category_table_header)
        self.category_tree.header().setStretchLastSection(True)

        self.category_tree.header().setDefaultAlignment(Qt.AlignCenter)

        # queue_panel
        self.queue_panel_widget = QWidget(self)

        queue_panel_verticalLayout_main = QVBoxLayout(self.queue_panel_widget)

        # queue_panel_show_button
        self.queue_panel_show_button = QPushButton(self)

        queue_panel_verticalLayout_main.addWidget(self.queue_panel_show_button)

        # queue_panel_widget_frame
        self.queue_panel_widget_frame = QFrame(self)
        self.queue_panel_widget_frame.setFrameShape(QFrame.StyledPanel)
        self.queue_panel_widget_frame.setFrameShadow(QFrame.Raised)

        queue_panel_verticalLayout_main.addWidget(
            self.queue_panel_widget_frame)

        queue_panel_verticalLayout = QVBoxLayout(self.queue_panel_widget_frame)
        queue_panel_verticalLayout_main.setContentsMargins(50, -1, 50, -1)

        # start_end_frame
        self.start_end_frame = QFrame(self)

        # start time
        start_verticalLayout = QVBoxLayout(self.start_end_frame)
        self.start_checkBox = QCheckBox(self)
        start_verticalLayout.addWidget(self.start_checkBox)

        self.start_frame = QFrame(self)
        self.start_frame.setFrameShape(QFrame.StyledPanel)
        self.start_frame.setFrameShadow(QFrame.Raised)

        start_frame_verticalLayout = QVBoxLayout(self.start_frame)

        self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame)
        self.start_time_qDataTimeEdit.setDisplayFormat('H:mm')
        start_frame_verticalLayout.addWidget(self.start_time_qDataTimeEdit)

        start_verticalLayout.addWidget(self.start_frame)

        # end time
        self.end_checkBox = QCheckBox(self)
        start_verticalLayout.addWidget(self.end_checkBox)

        self.end_frame = QFrame(self)
        self.end_frame.setFrameShape(QFrame.StyledPanel)
        self.end_frame.setFrameShadow(QFrame.Raised)

        end_frame_verticalLayout = QVBoxLayout(self.end_frame)

        self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame)
        self.end_time_qDateTimeEdit.setDisplayFormat('H:mm')
        end_frame_verticalLayout.addWidget(self.end_time_qDateTimeEdit)

        start_verticalLayout.addWidget(self.end_frame)

        self.reverse_checkBox = QCheckBox(self)
        start_verticalLayout.addWidget(self.reverse_checkBox)

        queue_panel_verticalLayout.addWidget(self.start_end_frame)

        # limit_after_frame
        self.limit_after_frame = QFrame(self)

        # limit_checkBox
        limit_verticalLayout = QVBoxLayout(self.limit_after_frame)
        self.limit_checkBox = QCheckBox(self)
        limit_verticalLayout.addWidget(self.limit_checkBox)

        # limit_frame
        self.limit_frame = QFrame(self)
        self.limit_frame.setFrameShape(QFrame.StyledPanel)
        self.limit_frame.setFrameShadow(QFrame.Raised)
        limit_verticalLayout.addWidget(self.limit_frame)

        limit_frame_verticalLayout = QVBoxLayout(self.limit_frame)

        # limit_spinBox
        limit_frame_horizontalLayout = QHBoxLayout()
        self.limit_spinBox = QDoubleSpinBox(self)
        self.limit_spinBox.setMinimum(1)
        self.limit_spinBox.setMaximum(1023)
        limit_frame_horizontalLayout.addWidget(self.limit_spinBox)

        # limit_comboBox
        self.limit_comboBox = QComboBox(self)
        self.limit_comboBox.addItem("")
        self.limit_comboBox.addItem("")
        limit_frame_horizontalLayout.addWidget(self.limit_comboBox)
        limit_frame_verticalLayout.addLayout(limit_frame_horizontalLayout)

        # limit_pushButton
        self.limit_pushButton = QPushButton(self)
        limit_frame_verticalLayout.addWidget(self.limit_pushButton)

        # after_checkBox
        self.after_checkBox = QCheckBox(self)
        limit_verticalLayout.addWidget(self.after_checkBox)

        # after_frame
        self.after_frame = QFrame(self)
        self.after_frame.setFrameShape(QFrame.StyledPanel)
        self.after_frame.setFrameShadow(QFrame.Raised)
        limit_verticalLayout.addWidget(self.after_frame)

        after_frame_verticalLayout = QVBoxLayout(self.after_frame)

        # after_comboBox
        self.after_comboBox = QComboBox(self)
        self.after_comboBox.addItem("")

        after_frame_verticalLayout.addWidget(self.after_comboBox)

        # after_pushButton
        self.after_pushButton = QPushButton(self)
        after_frame_verticalLayout.addWidget(self.after_pushButton)

        queue_panel_verticalLayout.addWidget(self.limit_after_frame)
        category_tree_verticalLayout.addWidget(self.queue_panel_widget)

        # keep_awake_checkBox
        self.keep_awake_checkBox = QCheckBox(self)
        queue_panel_verticalLayout.addWidget(self.keep_awake_checkBox)

        self.category_tree_qwidget.setLayout(category_tree_verticalLayout)
        horizontal_splitter.addWidget(self.category_tree_qwidget)

        # download table widget
        self.download_table_content_widget = QWidget(self)
        download_table_content_widget_verticalLayout = QVBoxLayout(
            self.download_table_content_widget)

        # download_table
        self.download_table = DownloadTableWidget(self)
        vertical_splitter.addWidget(self.download_table)

        horizontal_splitter.addWidget(self.download_table_content_widget)

        self.download_table.setColumnCount(13)
        self.download_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.download_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.download_table.verticalHeader().hide()

        # hide gid and download dictioanry section
        self.download_table.setColumnHidden(8, True)
        self.download_table.setColumnHidden(9, True)

        download_table_header = [
            QCoreApplication.translate("mainwindow_ui_tr", 'File Name'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Status'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Size'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Downloaded'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Percentage'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Connections'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Transfer rate'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Estimated time left'), 'Gid',
            QCoreApplication.translate("mainwindow_ui_tr", 'Link'),
            QCoreApplication.translate("mainwindow_ui_tr", 'First try date'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Last try date'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Category')
        ]

        self.download_table.setHorizontalHeaderLabels(download_table_header)

        # fixing the size of download_table when window is Maximized!
        self.download_table.horizontalHeader().setSectionResizeMode(0)
        self.download_table.horizontalHeader().setStretchLastSection(True)

        horizontal_splitter.setStretchFactor(0, 3)  # category_tree width
        horizontal_splitter.setStretchFactor(1, 10)  # ratio of tables's width

        # video_finder_widget
        self.video_finder_widget = QWidget(self)
        video_finder_horizontalLayout = QHBoxLayout(self.video_finder_widget)

        self.muxing_pushButton = QPushButton(self)
        self.muxing_pushButton.setIcon(QIcon(icons + 'video_finder'))
        video_finder_horizontalLayout.addWidget(self.muxing_pushButton)
        video_finder_horizontalLayout.addSpacing(20)

        video_audio_verticalLayout = QVBoxLayout()

        self.video_label = QLabel(self)
        video_audio_verticalLayout.addWidget(self.video_label)

        self.audio_label = QLabel(self)
        video_audio_verticalLayout.addWidget(self.audio_label)
        video_finder_horizontalLayout.addLayout(video_audio_verticalLayout)

        status_muxing_verticalLayout = QVBoxLayout()

        self.video_finder_status_label = QLabel(self)
        status_muxing_verticalLayout.addWidget(self.video_finder_status_label)

        self.muxing_status_label = QLabel(self)
        status_muxing_verticalLayout.addWidget(self.muxing_status_label)
        video_finder_horizontalLayout.addLayout(status_muxing_verticalLayout)

        vertical_splitter.addWidget(self.video_finder_widget)

        download_table_content_widget_verticalLayout.addWidget(
            vertical_splitter)

        download_table_horizontalLayout.addWidget(horizontal_splitter)

        self.frame.setLayout(download_table_horizontalLayout)

        self.verticalLayout.addWidget(self.frame)

        self.setCentralWidget(self.centralwidget)

        # menubar
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 600, 24))
        self.setMenuBar(self.menubar)
        fileMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", '&File'))
        editMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", '&Edit'))
        viewMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", '&View'))
        downloadMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", '&Download'))
        queueMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", '&Queue'))
        videoFinderMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'V&ideo Finder'))
        helpMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", '&Help'))

        # viewMenu submenus
        sortMenu = viewMenu.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'Sort by'))

        # statusbar
        self.statusbar = QStatusBar(self)
        self.setStatusBar(self.statusbar)
        self.statusbar.showMessage(
            QCoreApplication.translate("mainwindow_ui_tr",
                                       "Persepolis Download Manager"))

        # toolBar
        self.toolBar2 = QToolBar(self)
        self.addToolBar(Qt.TopToolBarArea, self.toolBar2)
        self.toolBar2.setWindowTitle(
            QCoreApplication.translate("mainwindow_ui_tr", 'Menu'))
        self.toolBar2.setFloatable(False)
        self.toolBar2.setMovable(False)

        self.toolBar = QToolBar(self)
        self.addToolBar(Qt.TopToolBarArea, self.toolBar)
        self.toolBar.setWindowTitle(
            QCoreApplication.translate("mainwindow_ui_tr", 'Toolbar'))
        self.toolBar.setFloatable(False)
        self.toolBar.setMovable(False)

        #toolBar and menubar and actions
        self.persepolis_setting.beginGroup('settings/shortcuts')

        # videoFinderAddLinkAction
        self.videoFinderAddLinkAction = QAction(
            QIcon(icons + 'video_finder'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Find Video Links'),
            self,
            statusTip=QCoreApplication.translate(
                "mainwindow_ui_tr",
                'Download video or audio from Youtube, Vimeo, etc...'),
            triggered=self.showVideoFinderAddLinkWindow)

        self.videoFinderAddLinkAction_shortcut = QShortcut(
            self.persepolis_setting.value('video_finder_shortcut'), self,
            self.showVideoFinderAddLinkWindow)

        videoFinderMenu.addAction(self.videoFinderAddLinkAction)

        # stopAllAction
        self.stopAllAction = QAction(QIcon(icons + 'stop_all'),
                                     QCoreApplication.translate(
                                         "mainwindow_ui_tr",
                                         'Stop all active downloads'),
                                     self,
                                     statusTip='Stop all active downloads',
                                     triggered=self.stopAllDownloads)
        downloadMenu.addAction(self.stopAllAction)

        # sort_file_name_Action
        self.sort_file_name_Action = QAction(QCoreApplication.translate(
            "mainwindow_ui_tr", 'File name'),
                                             self,
                                             triggered=self.sortByName)
        sortMenu.addAction(self.sort_file_name_Action)

        # sort_file_size_Action
        self.sort_file_size_Action = QAction(QCoreApplication.translate(
            "mainwindow_ui_tr", 'File size'),
                                             self,
                                             triggered=self.sortBySize)
        sortMenu.addAction(self.sort_file_size_Action)

        # sort_first_try_date_Action
        self.sort_first_try_date_Action = QAction(
            QCoreApplication.translate("mainwindow_ui_tr", 'First try date'),
            self,
            triggered=self.sortByFirstTry)
        sortMenu.addAction(self.sort_first_try_date_Action)

        # sort_last_try_date_Action
        self.sort_last_try_date_Action = QAction(QCoreApplication.translate(
            "mainwindow_ui_tr", 'Last try date'),
                                                 self,
                                                 triggered=self.sortByLastTry)
        sortMenu.addAction(self.sort_last_try_date_Action)

        # sort_download_status_Action
        self.sort_download_status_Action = QAction(QCoreApplication.translate(
            "mainwindow_ui_tr", 'Download status'),
                                                   self,
                                                   triggered=self.sortByStatus)
        sortMenu.addAction(self.sort_download_status_Action)

        # trayAction
        self.trayAction = QAction(
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Show system tray icon'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 "Show/Hide system tray icon"),
            triggered=self.showTray)
        self.trayAction.setCheckable(True)
        viewMenu.addAction(self.trayAction)

        # showMenuBarAction
        self.showMenuBarAction = QAction(
            QCoreApplication.translate("mainwindow_ui_tr", 'Show menubar'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Show menubar'),
            triggered=self.showMenuBar)
        self.showMenuBarAction.setCheckable(True)
        viewMenu.addAction(self.showMenuBarAction)

        # showSidePanelAction
        self.showSidePanelAction = QAction(
            QCoreApplication.translate("mainwindow_ui_tr", 'Show side panel'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Show side panel'),
            triggered=self.showSidePanel)
        self.showSidePanelAction.setCheckable(True)
        viewMenu.addAction(self.showSidePanelAction)

        # minimizeAction
        self.minimizeAction = QAction(
            QIcon(icons + 'minimize'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Minimize to system tray'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 "Minimize to system tray"),
            triggered=self.minMaxTray)

        self.minimizeAction_shortcut = QShortcut(
            self.persepolis_setting.value('hide_window_shortcut'), self,
            self.minMaxTray)
        viewMenu.addAction(self.minimizeAction)

        # addlinkAction
        self.addlinkAction = QAction(
            QIcon(icons + 'add'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Add New Download Link'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 "Add New Download Link"),
            triggered=self.addLinkButtonPressed)

        self.addlinkAction_shortcut = QShortcut(
            self.persepolis_setting.value('add_new_download_shortcut'), self,
            self.addLinkButtonPressed)
        fileMenu.addAction(self.addlinkAction)

        # importText
        self.addtextfileAction = QAction(
            QIcon(icons + 'file'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Import links from text file'),
            self,
            statusTip=QCoreApplication.translate(
                "mainwindow_ui_tr",
                'Create a Text file and put links in it.line by line!'),
            triggered=self.importText)

        self.addtextfileAction_shortcut = QShortcut(
            self.persepolis_setting.value('import_text_shortcut'), self,
            self.importText)

        fileMenu.addAction(self.addtextfileAction)

        # resumeAction
        self.resumeAction = QAction(
            QIcon(icons + 'play'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Resume Download'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 "Resume Download"),
            triggered=self.resumeButtonPressed)

        downloadMenu.addAction(self.resumeAction)

        # pauseAction
        self.pauseAction = QAction(
            QIcon(icons + 'pause'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Pause Download'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 "Pause Download"),
            triggered=self.pauseButtonPressed)

        downloadMenu.addAction(self.pauseAction)

        # stopAction
        self.stopAction = QAction(
            QIcon(icons + 'stop'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Stop Download'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 "Stop/Cancel Download"),
            triggered=self.stopButtonPressed)

        downloadMenu.addAction(self.stopAction)

        # propertiesAction
        self.propertiesAction = QAction(
            QIcon(icons + 'setting'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Properties'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 "Properties"),
            triggered=self.propertiesButtonPressed)

        downloadMenu.addAction(self.propertiesAction)

        # progressAction
        self.progressAction = QAction(
            QIcon(icons + 'window'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Progress'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 "Progress"),
            triggered=self.progressButtonPressed)

        downloadMenu.addAction(self.progressAction)

        # openFileAction
        self.openFileAction = QAction(
            QIcon(icons + 'file'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Open file'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Open file'),
            triggered=self.openFile)
        fileMenu.addAction(self.openFileAction)

        # openDownloadFolderAction
        self.openDownloadFolderAction = QAction(
            QIcon(icons + 'folder'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Open download folder'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Open download folder'),
            triggered=self.openDownloadFolder)

        fileMenu.addAction(self.openDownloadFolderAction)

        # openDefaultDownloadFolderAction
        self.openDefaultDownloadFolderAction = QAction(
            QIcon(icons + 'folder'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Open default download folder'),
            self,
            statusTip=QCoreApplication.translate(
                "mainwindow_ui_tr", 'Open default download folder'),
            triggered=self.openDefaultDownloadFolder)

        fileMenu.addAction(self.openDefaultDownloadFolderAction)

        # exitAction
        self.exitAction = QAction(
            QIcon(icons + 'exit'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Exit'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr", "Exit"),
            triggered=self.closeAction)

        self.exitAction_shortcut = QShortcut(
            self.persepolis_setting.value('quit_shortcut'), self,
            self.closeAction)

        fileMenu.addAction(self.exitAction)

        # clearAction
        self.clearAction = QAction(QIcon(icons + 'multi_remove'),
                                   QCoreApplication.translate(
                                       "mainwindow_ui_tr",
                                       'Clear download list'),
                                   self,
                                   statusTip=QCoreApplication.translate(
                                       "mainwindow_ui_tr",
                                       'Clear all items in download list'),
                                   triggered=self.clearDownloadList)
        editMenu.addAction(self.clearAction)

        # removeSelectedAction
        self.removeSelectedAction = QAction(
            QIcon(icons + 'remove'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Remove selected downloads from list'),
            self,
            statusTip=QCoreApplication.translate(
                "mainwindow_ui_tr", 'Remove selected downloads form list'),
            triggered=self.removeSelected)

        self.removeSelectedAction_shortcut = QShortcut(
            self.persepolis_setting.value('remove_shortcut'), self,
            self.removeSelected)

        editMenu.addAction(self.removeSelectedAction)
        self.removeSelectedAction.setEnabled(False)

        # deleteSelectedAction
        self.deleteSelectedAction = QAction(
            QIcon(icons + 'trash'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Delete selected download files'),
            self,
            statusTip=QCoreApplication.translate(
                "mainwindow_ui_tr", 'Delete selected download files'),
            triggered=self.deleteSelected)

        self.deleteSelectedAction_shortcut = QShortcut(
            self.persepolis_setting.value('delete_shortcut'), self,
            self.deleteSelected)

        editMenu.addAction(self.deleteSelectedAction)
        self.deleteSelectedAction.setEnabled(False)

        # moveSelectedDownloadsAction
        self.moveSelectedDownloadsAction = QAction(
            QIcon(icons + 'folder'),
            QCoreApplication.translate(
                "mainwindow_ui_tr",
                'move selected download files to another folder'),
            self,
            statusTip=QCoreApplication.translate(
                "mainwindow_ui_tr",
                'move selected download files to another folder'),
            triggered=self.moveSelectedDownloads)

        editMenu.addAction(self.moveSelectedDownloadsAction)
        self.moveSelectedDownloadsAction.setEnabled(False)

        # createQueueAction
        self.createQueueAction = QAction(
            QIcon(icons + 'add_queue'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Create new queue'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Create new download queue'),
            triggered=self.createQueue)
        queueMenu.addAction(self.createQueueAction)

        # removeQueueAction
        self.removeQueueAction = QAction(
            QIcon(icons + 'remove_queue'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Remove this queue'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Remove this queue'),
            triggered=self.removeQueue)
        queueMenu.addAction(self.removeQueueAction)

        # startQueueAction
        self.startQueueAction = QAction(
            QIcon(icons + 'start_queue'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Start this queue'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Start this queue'),
            triggered=self.startQueue)

        queueMenu.addAction(self.startQueueAction)

        # stopQueueAction
        self.stopQueueAction = QAction(
            QIcon(icons + 'stop_queue'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Stop this queue'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Stop this queue'),
            triggered=self.stopQueue)

        queueMenu.addAction(self.stopQueueAction)

        # moveUpSelectedAction
        self.moveUpSelectedAction = QAction(
            QIcon(icons + 'multi_up'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Move up selected items'),
            self,
            statusTip=QCoreApplication.translate(
                "mainwindow_ui_tr",
                'Move currently selected items up by one row'),
            triggered=self.moveUpSelected)

        self.moveUpSelectedAction_shortcut = QShortcut(
            self.persepolis_setting.value('move_up_selection_shortcut'), self,
            self.moveUpSelected)

        queueMenu.addAction(self.moveUpSelectedAction)

        # moveDownSelectedAction
        self.moveDownSelectedAction = QAction(
            QIcon(icons + 'multi_down'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Move down selected items'),
            self,
            statusTip=QCoreApplication.translate(
                "mainwindow_ui_tr",
                'Move currently selected items down by one row'),
            triggered=self.moveDownSelected)
        self.moveDownSelectedAction_shortcut = QShortcut(
            self.persepolis_setting.value('move_down_selection_shortcut'),
            self, self.moveDownSelected)

        queueMenu.addAction(self.moveDownSelectedAction)

        # preferencesAction
        self.preferencesAction = QAction(
            QIcon(icons + 'preferences'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Preferences'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Preferences'),
            triggered=self.openPreferences,
            menuRole=5)
        editMenu.addAction(self.preferencesAction)

        # aboutAction
        self.aboutAction = QAction(
            QIcon(icons + 'about'),
            QCoreApplication.translate("mainwindow_ui_tr", 'About'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'About'),
            triggered=self.openAbout,
            menuRole=4)
        helpMenu.addAction(self.aboutAction)

        # issueAction
        self.issueAction = QAction(
            QIcon(icons + 'about'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Report an issue'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Report an issue'),
            triggered=self.reportIssue)
        helpMenu.addAction(self.issueAction)

        # updateAction
        self.updateAction = QAction(
            QIcon(icons + 'about'),
            QCoreApplication.translate("mainwindow_ui_tr",
                                       'Check for newer version'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr",
                                                 'Check for newer release'),
            triggered=self.newUpdate)
        helpMenu.addAction(self.updateAction)

        # logAction
        self.logAction = QAction(
            QIcon(icons + 'about'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Show log file'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'),
            triggered=self.showLog)
        helpMenu.addAction(self.logAction)

        # helpAction
        self.helpAction = QAction(
            QIcon(icons + 'about'),
            QCoreApplication.translate("mainwindow_ui_tr", 'Help'),
            self,
            statusTip=QCoreApplication.translate("mainwindow_ui_tr", 'Help'),
            triggered=self.persepolisHelp)
        helpMenu.addAction(self.helpAction)

        self.persepolis_setting.endGroup()

        self.qmenu = MenuWidget(self)

        self.toolBar2.addWidget(self.qmenu)

        # labels
        self.queue_panel_show_button.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "Hide options"))
        self.start_checkBox.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "Start Time"))

        self.end_checkBox.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "End Time"))

        self.reverse_checkBox.setText(
            QCoreApplication.translate("mainwindow_ui_tr",
                                       "Download bottom of\n the list first"))

        self.limit_checkBox.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "Limit Speed"))
        self.limit_comboBox.setItemText(0, "KiB/s")
        self.limit_comboBox.setItemText(1, "MiB/s")
        self.limit_pushButton.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "Apply"))

        self.after_checkBox.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "After download"))
        self.after_comboBox.setItemText(
            0, QCoreApplication.translate("mainwindow_ui_tr", "Shut Down"))

        self.keep_awake_checkBox.setText(
            QCoreApplication.translate("mainwindow_ui_tr",
                                       "Keep system awake!"))
        self.keep_awake_checkBox.setToolTip(
            QCoreApplication.translate(
                "mainwindow_ui_tr",
                "<html><head/><body><p>This option is preventing system from going to sleep.\
            This is necessary if your power manager is suspending system automatically. </p></body></html>"
            ))

        self.after_pushButton.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "Apply"))

        self.muxing_pushButton.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "start muxing"))

        self.video_label.setText(
            QCoreApplication.translate("mainwindow_ui_tr",
                                       "<b>Video file status: </b>"))
        self.audio_label.setText(
            QCoreApplication.translate("mainwindow_ui_tr",
                                       "<b>Audio file status: </b>"))

        self.video_finder_status_label.setText(
            QCoreApplication.translate("mainwindow_ui_tr", "<b>Status: </b>"))
        self.muxing_status_label.setText(
            QCoreApplication.translate("mainwindow_ui_tr",
                                       "<b>Muxing status: </b>"))
    def setupWindow(self):
        """Set up widgets in the main window."""
        self.image_label = QLabel()
        self.image_label.setObjectName("ImageLabel")

        # Create various widgets for image processing in the side panel
        contrast_label = QLabel("Contrast [Range: 0.0:4.0]")
        self.contrast_spinbox = QDoubleSpinBox()
        self.contrast_spinbox.setMinimumWidth(100)
        self.contrast_spinbox.setRange(0.0, 4.0)
        self.contrast_spinbox.setValue(1.0)
        self.contrast_spinbox.setSingleStep(.10)
        self.contrast_spinbox.valueChanged.connect(self.adjustContrast)

        brightness_label = QLabel("Brightness [Range: -127:127]")
        self.brightness_spinbox = QSpinBox()
        self.brightness_spinbox.setMinimumWidth(100)
        self.brightness_spinbox.setRange(-127, 127)
        self.brightness_spinbox.setValue(0)
        self.brightness_spinbox.setSingleStep(1)
        self.brightness_spinbox.valueChanged.connect(self.adjustBrightness)

        smoothing_label = QLabel("Image Smoothing Filters")
        self.filter_2D_cb = QCheckBox("2D Convolution")
        self.filter_2D_cb.stateChanged.connect(self.imageSmoothingFilter)

        edges_label = QLabel("Detect Edges")
        self.canny_cb = QCheckBox("Canny Edge Detector")
        self.canny_cb.stateChanged.connect(self.edgeDetection)

        self.apply_process_button = QPushButton("Apply Processes")
        self.apply_process_button.setEnabled(False)  
        self.apply_process_button.clicked.connect(self.applyImageProcessing)

        reset_button = QPushButton("Reset Image Settings")
        reset_button.clicked.connect(self.resetImageAndSettings)

        # Create horizontal and vertical layouts for the side panel and main window
        side_panel_v_box = QVBoxLayout()
        side_panel_v_box.setAlignment(Qt.AlignTop)
        side_panel_v_box.addWidget(contrast_label)
        side_panel_v_box.addWidget(self.contrast_spinbox)
        side_panel_v_box.addWidget(brightness_label)
        side_panel_v_box.addWidget(self.brightness_spinbox)
        side_panel_v_box.addSpacing(15)
        side_panel_v_box.addWidget(smoothing_label)
        side_panel_v_box.addWidget(self.filter_2D_cb)
        side_panel_v_box.addWidget(edges_label)
        side_panel_v_box.addWidget(self.canny_cb)
        side_panel_v_box.addWidget(self.apply_process_button)
        side_panel_v_box.addStretch(1)
        side_panel_v_box.addWidget(reset_button)

        side_panel_frame = QFrame()
        side_panel_frame.setMinimumWidth(200)
        side_panel_frame.setFrameStyle(QFrame.WinPanel)
        side_panel_frame.setLayout(side_panel_v_box)

        main_h_box = QHBoxLayout()
        main_h_box.addWidget(self.image_label, 1)
        main_h_box.addWidget(side_panel_frame)

        # Create container widget and set main window's widget
        container = QWidget()
        container.setLayout(main_h_box)
        self.setCentralWidget(container)       
Beispiel #49
0
    def buildUI(self):

        self.setSizePolicy(QtWidgets.QSizePolicy.Minimum,
                           QtWidgets.QSizePolicy.Minimum)

        title_label = QLabel('General Settings')
        title_label.setStyleSheet("font-weight: bold;")

        self.bm_width_edit = QDoubleSpinBox()
        self.bm_width_edit.setMinimum(2.5)
        self.bm_width_edit.setMaximum(45.0)
        self.bm_width_edit.setValue(10)
        self.bm_width_edit.setSuffix(' deg')
        self.bm_width_edit.valueChanged.connect(self.enable_update_dm_button)

        self.rad_min_edit = QDoubleSpinBox()
        self.rad_min_edit.setMinimum(50)
        self.rad_min_edit.setMaximum(np.pi * self.earth_radius)
        self.rad_min_edit.setValue(100.0)
        self.rad_min_edit.setSuffix(' km')
        self.rad_min_edit.valueChanged.connect(self.enable_update_dm_button)

        self.rad_max_edit = QDoubleSpinBox()
        self.rad_max_edit.setMinimum(50)
        self.rad_max_edit.setMaximum(np.pi * self.earth_radius)
        self.rad_max_edit.setValue(1000.0)
        self.rad_max_edit.setSuffix(' km')
        self.rad_max_edit.valueChanged.connect(self.enable_update_dm_button)

        self.rng_max_edit = QDoubleSpinBox()
        self.rng_max_edit.setMinimum(10)
        self.rng_max_edit.setMaximum(np.pi * self.earth_radius)
        self.rng_max_edit.setValue(3000.0)
        self.rng_max_edit.setSuffix(' km')
        self.rng_max_edit.valueChanged.connect(self.enable_update_dm_button)

        self.resolution_edit = QSpinBox()
        self.resolution_edit.setMinimum(10)
        self.resolution_edit.setMaximum(10000)
        self.resolution_edit.setValue(180)
        self.resolution_edit.valueChanged.connect(self.enable_update_dm_button)

        self.confidence_edit = QSpinBox()
        self.confidence_edit.setMinimum(1)
        self.confidence_edit.setMaximum(99)
        self.confidence_edit.setValue(95)
        self.confidence_edit.setSuffix(' %')

        layout = QFormLayout()
        layout.addRow(self.tr('Beam Width: '), self.bm_width_edit)
        layout.addRow(self.tr('Radius Min.: '), self.rad_min_edit)
        layout.addRow(self.tr('Radius Max.: '), self.rad_max_edit)
        layout.addRow(self.tr('Range Max.: '), self.rng_max_edit)
        layout.addRow(self.tr('Resolution'), self.resolution_edit)
        layout.addRow(self.tr('Confidence'), self.confidence_edit)

        self.run_bisl_button = QPushButton('Run BISL')
        self.run_bisl_button.setMaximumWidth(110)

        self.update_dm_button = QPushButton('Update Dist. Matrix')

        mainlayout = QVBoxLayout()
        mainlayout.setAlignment(Qt.AlignCenter)
        mainlayout.addWidget(title_label)
        mainlayout.addLayout(layout)

        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.run_bisl_button)
        buttonLayout.addWidget(self.update_dm_button)

        mainlayout.addLayout(buttonLayout)

        self.setFrameStyle(QFrame.Box | QFrame.Plain)
        self.setLayout(mainlayout)
Beispiel #50
0
 def __init__(self, parent, timebase_data):
     super().__init__(parent)
     self.timebase_data = TimebaseData(timebase_data)
     # Layout form
     dlg_layout = QVBoxLayout(self)
     form_layout = QFormLayout()
     caption_lock = QLabel(self)
     caption_lock.setText("Lock to GNSS:")
     self.lock_combobox = QComboBox(self)
     self.lock_combobox.addItem("Yes")
     self.lock_combobox.addItem("No")
     form_layout.setWidget(0, QFormLayout.LabelRole, caption_lock)
     form_layout.setWidget(0, QFormLayout.FieldRole, self.lock_combobox)
     caption_bandwidth = QLabel(self)
     caption_bandwidth.setText("Loop Bandwidth Control:")
     self.bandwidth_combobox = QComboBox(self)
     self.bandwidth_combobox.addItem("Automatic")
     self.bandwidth_combobox.addItem("Manual")
     form_layout.setWidget(1, QFormLayout.LabelRole, caption_bandwidth)
     form_layout.setWidget(1, QFormLayout.FieldRole,
                           self.bandwidth_combobox)
     caption_manual_tc = QLabel(self)
     caption_manual_tc.setText("Manual Time Consant:")
     self.manual_tc_spinbox = QSpinBox(self)
     self.manual_tc_spinbox.setMinimum(3)
     self.manual_tc_spinbox.setMaximum(1000000)
     form_layout.setWidget(2, QFormLayout.LabelRole, caption_manual_tc)
     form_layout.setWidget(2, QFormLayout.FieldRole, self.manual_tc_spinbox)
     caption_holdover_error = QLabel(self)
     caption_holdover_error.setText("Enter Holdover if Error (us) >")
     self.holdover_error_spinbox = QDoubleSpinBox(self)
     self.holdover_error_spinbox.setMinimum(0.1)
     self.holdover_error_spinbox.setMaximum(1000000.0)
     self.holdover_error_spinbox.setDecimals(3)
     form_layout.setWidget(3, QFormLayout.LabelRole, caption_holdover_error)
     form_layout.setWidget(3, QFormLayout.FieldRole,
                           self.holdover_error_spinbox)
     caption_holdover_mode = QLabel(self)
     caption_holdover_mode.setText("To Leave Holdover:")
     self.holdover_mode_combobox = QComboBox(self)
     self.holdover_mode_combobox.addItem("Wait for Good 1pps")
     self.holdover_mode_combobox.addItem("Jump to Good 1pps")
     self.holdover_mode_combobox.addItem("Slew to Good 1pps")
     form_layout.setWidget(4, QFormLayout.LabelRole, caption_holdover_mode)
     form_layout.setWidget(4, QFormLayout.FieldRole,
                           self.holdover_mode_combobox)
     dlg_layout.addLayout(form_layout)
     # Layout dialog buttons
     dialog_btns = QDialogButtonBox(self)
     dialog_btns.setStandardButtons(QDialogButtonBox.Ok
                                    | QDialogButtonBox.Cancel)
     dlg_layout.addWidget(dialog_btns)
     # Initialize widgets
     self.lock_combobox.setCurrentIndex(0 if timebase_data.lock_gnss else 1)
     self.bandwidth_combobox.setCurrentIndex(
         (0 if "AUT" == timebase_data.bandwidth else 1))
     self.manual_tc_spinbox.setValue(timebase_data.manual_time_constant)
     self.holdover_error_spinbox.setValue(timebase_data.holdover_limit *
                                          1e6)
     mode = 1
     if "WAIT" == timebase_data.holdover_mode:
         mode = 0
     elif "SLEW" == timebase_data.holdover_mode:
         mode = 2
     self.holdover_mode_combobox.setCurrentIndex(mode)
     # Connect signals
     dialog_btns.accepted.connect(self.on_ok)
     dialog_btns.rejected.connect(self.reject)
Beispiel #51
0
    def __init__(self, param, parent_instance):
        assert isinstance(param, FloatRangeParameter)

        super().__init__(param, parent_instance)

        self.grid.setColumnStretch(0, 1)
        self.grid.setColumnStretch(1, 1)

        label = QLabel(self)
        suffix = " [{}]".format(param.unit) if param.unit else ""
        label.setText(param.label + suffix)
        self.grid.addWidget(label, 0, 0, 1, 1)

        self.spin_boxes = []
        for i in range(2):
            spin_box = QDoubleSpinBox(self)
            spin_box.setDecimals(param.decimals)
            spin_box.setSingleStep(10**(-param.decimals))
            spin_box.valueChanged.connect(
                lambda v, i=i: self.__spin_box_event_handler(v, i))
            spin_box.setKeyboardTracking(False)
            spin_box.setMinimum(param.limits[0])
            spin_box.setMaximum(param.limits[1])
            self.grid.addWidget(spin_box, 1, i, 1, 1)
            self.spin_boxes.append(spin_box)

        self.update()
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle('Dash results')
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        self.scrollArea = QScrollArea()
        self.widget = QWidget()

        self.test_name_label = QLabel()
        grid = QGridLayout()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel('Control'), 1, 0)
        grid.addWidget(QLabel('Rendered'), 1, 1)
        grid.addWidget(QLabel('Difference'), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel('Current Mask'), 3, 0)
        grid.addWidget(QLabel('New Mask'), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        self.widget.setLayout(grid)
        self.scrollArea.setWidget(self.widget)
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.scrollArea, 1)

        next_image_button = QPushButton()
        next_image_button.setText('Skip')
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)
        self.overload_spin.valueChanged.connect(
            lambda: save_mask_button.setEnabled(False))

        preview_mask_button = QPushButton()
        preview_mask_button.setText('Preview New Mask')
        preview_mask_button.pressed.connect(self.preview_mask)
        preview_mask_button.pressed.connect(
            lambda: save_mask_button.setEnabled(True))

        save_mask_button = QPushButton()
        save_mask_button.setText('Save New Mask')
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel('Mask diff multiplier:'))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)
Beispiel #53
0
class FloatSpinBoxPidget(PidgetStub):
    def __init__(self, param, parent_instance):
        assert isinstance(param, FloatParameter)

        super().__init__(param, parent_instance)

        self.grid.setColumnStretch(0, 7)
        self.grid.setColumnStretch(1, 3)

        label = QLabel(self)
        suffix = " [{}]".format(param.unit) if param.unit else ""
        label.setText(param.label + suffix)
        self.grid.addWidget(label, 0, 0, 1, 1)

        self.spin_box = QDoubleSpinBox(self)
        self.spin_box.setDecimals(param.decimals)
        self.spin_box.setSingleStep(10**(-param.decimals))
        self.spin_box.valueChanged.connect(self._subwidget_event_handler)
        self.spin_box.setKeyboardTracking(False)
        self.spin_box.setMinimum(param.limits[0])
        self.spin_box.setMaximum(param.limits[1])
        self.grid.addWidget(self.spin_box, 0, 1, 1, 1)

        self.update()

    def _update(self):
        super()._update()
        value = self._get_param_value()
        self.spin_box.setValue(value)
Beispiel #54
0
class AssociationSettings(QFrame):
    def __init__(self, parent):
        super().__init__()
        self.parent = parent
        self.buildUI()

    def buildUI(self):

        self.setSizePolicy(QtWidgets.QSizePolicy.Minimum,
                           QtWidgets.QSizePolicy.Minimum)

        title_label = QLabel('Association Settings')
        title_label.setStyleSheet("font-weight: bold;")

        self.threshold_edit = QDoubleSpinBox()
        self.threshold_edit.setMinimum(0.0)
        self.threshold_edit.setMaximum(1000.0)
        self.threshold_edit.setValue(5.0)

        self.dist_max_edit = QDoubleSpinBox()
        self.dist_max_edit.setMinimum(0.0)
        self.dist_max_edit.setMaximum(1000.0)
        self.dist_max_edit.setValue(10.0)

        layout = QFormLayout()
        layout.addRow(self.tr('Threshold: '), self.threshold_edit)
        layout.addRow(self.tr('Maximum Distance.: '), self.dist_max_edit)

        self.update_assoc_button = QPushButton('Update Associations')

        mainlayout = QVBoxLayout()
        mainlayout.setAlignment(Qt.AlignCenter)
        mainlayout.addWidget(title_label)
        mainlayout.addLayout(layout)

        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.update_assoc_button)

        mainlayout.addLayout(buttonLayout)
        self.setFrameStyle(QFrame.Box | QFrame.Plain)
        self.setLayout(mainlayout)
Beispiel #55
0
 def initRewardsForm(self):
     self.collateralHidden = True
     self.rewardsForm = QGroupBox()
     self.rewardsForm.setTitle("Transfer Rewards")
     layout = QFormLayout()
     layout.setContentsMargins(10, 10, 10, 10)
     layout.setSpacing(13)
     layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
     ##--- ROW 1
     hBox = QHBoxLayout()
     self.mnSelect = QComboBox()
     self.mnSelect.setToolTip("Select Masternode") 
     hBox.addWidget(self.mnSelect)
     self.btn_ReloadUTXOs = QPushButton()
     self.btn_ReloadUTXOs.setToolTip("Reload UTXOs")
     refresh_icon = QIcon(os.path.join(self.caller.imgDir, 'icon_refresh.png'))
     self.btn_ReloadUTXOs.setIcon(refresh_icon)
     hBox.addWidget(self.btn_ReloadUTXOs)
     hBox.addStretch(1)
     label = QLabel("Total Address Balance")
     label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
     hBox.addWidget(label)
     self.addrAvailLine = QLabel()
     self.addrAvailLine.setToolTip("PIVX Address total balance")
     self.addrAvailLine.setText("--")
     hBox.addWidget(self.addrAvailLine)
     self.btn_toggleCollateral = QPushButton("Show Collateral")
     hBox.addWidget(self.btn_toggleCollateral)
     layout.addRow(QLabel("Masternode"), hBox)             
     ## --- ROW 2: REWARDS
     self.rewardsList = QVBoxLayout()
     self.rewardsList.statusLabel = QLabel()
     self.rewardsList.statusLabel.setMinimumWidth(116)
     self.resetStatusLabel()
     self.rewardsList.addWidget(self.rewardsList.statusLabel)
     self.rewardsList.box = QTableWidget()
     self.rewardsList.box.setMinimumHeight(140)
     #self.rewardsList.box.setMaximumHeight(140)
     self.rewardsList.box.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.rewardsList.box.setSelectionMode(QAbstractItemView.MultiSelection)
     self.rewardsList.box.setSelectionBehavior(QAbstractItemView.SelectRows)
     self.rewardsList.box.setShowGrid(True)
     self.rewardsList.box.setColumnCount(4)
     self.rewardsList.box.setRowCount(0)
     self.rewardsList.box.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
     self.rewardsList.box.verticalHeader().hide()
     item = QTableWidgetItem()
     item.setText("PIVs")
     item.setTextAlignment(Qt.AlignCenter)
     self.rewardsList.box.setHorizontalHeaderItem(0, item)
     item = QTableWidgetItem()
     item.setText("Confirmations")
     item.setTextAlignment(Qt.AlignCenter)
     self.rewardsList.box.setHorizontalHeaderItem(1, item)
     item = QTableWidgetItem()
     item.setText("TX Hash")
     item.setTextAlignment(Qt.AlignCenter)
     self.rewardsList.box.setHorizontalHeaderItem(2, item)
     item = QTableWidgetItem()
     item.setText("TX Output N")
     item.setTextAlignment(Qt.AlignCenter)
     self.rewardsList.box.setHorizontalHeaderItem(3, item)
     item = QTableWidgetItem()        
     self.rewardsList.addWidget(self.rewardsList.box)
     layout.addRow(self.rewardsList)
     ##--- ROW 3
     hBox2 = QHBoxLayout()
     self.btn_selectAllRewards = QPushButton("Select All")
     self.btn_selectAllRewards.setToolTip("Select all available UTXOs")
     hBox2.addWidget(self.btn_selectAllRewards)
     self.btn_deselectAllRewards = QPushButton("Deselect all")
     self.btn_deselectAllRewards.setToolTip("Deselect current selection")
     hBox2.addWidget(self.btn_deselectAllRewards)
     hBox2.addWidget(QLabel("Selected rewards"))
     self.selectedRewardsLine = QLabel()
     self.selectedRewardsLine.setMinimumWidth(200)
     self.selectedRewardsLine.setStyleSheet("color: purple")
     self.selectedRewardsLine.setToolTip("PIVX to move away")
     hBox2.addWidget(self.selectedRewardsLine)    
     hBox2.addStretch(1)
     self.swiftxCheck = QCheckBox()
     self.swiftxCheck.setToolTip("check for SwiftX instant transaction (flat fee rate of 0.01 PIV)")
     hBox2.addWidget(QLabel("Use SwiftX"))
     hBox2.addWidget(self.swiftxCheck)
     layout.addRow(hBox2)
     ##--- ROW 4
     hBox3 = QHBoxLayout()
     self.destinationLine = QLineEdit()
     self.destinationLine.setToolTip("PIVX address to transfer rewards to")
     hBox3.addWidget(self.destinationLine)
     hBox3.addWidget(QLabel("Fee"))
     self.feeLine = QDoubleSpinBox()
     self.feeLine.setDecimals(8)
     self.feeLine.setPrefix("PIV  ")
     self.feeLine.setToolTip("Insert a small fee amount")
     self.feeLine.setFixedWidth(150)
     self.feeLine.setSingleStep(0.001)
     hBox3.addWidget(self.feeLine)
     self.btn_sendRewards = QPushButton("Send")
     hBox3.addWidget(self.btn_sendRewards)
     layout.addRow(QLabel("Destination Address"), hBox3)
     ##--- ROW 5
     hBox4 = QHBoxLayout()
     hBox4.addStretch(1)
     self.loadingLine = QLabel("<b style='color:red'>Preparing TX.</b> Completed: ")
     self.loadingLinePercent = QProgressBar()
     self.loadingLinePercent.setMaximumWidth(200)
     self.loadingLinePercent.setMaximumHeight(10)
     self.loadingLinePercent.setRange(0, 100)
     hBox4.addWidget(self.loadingLine)
     hBox4.addWidget(self.loadingLinePercent)
     self.loadingLine.hide()
     self.loadingLinePercent.hide()
     layout.addRow(hBox4)
     #--- Set Layout    
     self.rewardsForm.setLayout(layout)
     #--- ROW 5
     self.btn_Cancel = QPushButton("Clear/Reload")
class ImageProcessingGUI(QMainWindow):

    def __init__(self):
        super().__init__() 
        self.initializeUI() 

    def initializeUI(self):
        """Initialize the window and display its contents to the screen."""
        self.setMinimumSize(900, 600)
        self.setWindowTitle('5.1 - Image Processing GUI')

        self.contrast_adjusted = False
        self.brightness_adjusted = False
        self.image_smoothing_checked = False
        self.edge_detection_checked = False

        self.setupWindow()
        self.setupMenu()
        self.show()

    def setupWindow(self):
        """Set up widgets in the main window."""
        self.image_label = QLabel()
        self.image_label.setObjectName("ImageLabel")

        # Create various widgets for image processing in the side panel
        contrast_label = QLabel("Contrast [Range: 0.0:4.0]")
        self.contrast_spinbox = QDoubleSpinBox()
        self.contrast_spinbox.setMinimumWidth(100)
        self.contrast_spinbox.setRange(0.0, 4.0)
        self.contrast_spinbox.setValue(1.0)
        self.contrast_spinbox.setSingleStep(.10)
        self.contrast_spinbox.valueChanged.connect(self.adjustContrast)

        brightness_label = QLabel("Brightness [Range: -127:127]")
        self.brightness_spinbox = QSpinBox()
        self.brightness_spinbox.setMinimumWidth(100)
        self.brightness_spinbox.setRange(-127, 127)
        self.brightness_spinbox.setValue(0)
        self.brightness_spinbox.setSingleStep(1)
        self.brightness_spinbox.valueChanged.connect(self.adjustBrightness)

        smoothing_label = QLabel("Image Smoothing Filters")
        self.filter_2D_cb = QCheckBox("2D Convolution")
        self.filter_2D_cb.stateChanged.connect(self.imageSmoothingFilter)

        edges_label = QLabel("Detect Edges")
        self.canny_cb = QCheckBox("Canny Edge Detector")
        self.canny_cb.stateChanged.connect(self.edgeDetection)

        self.apply_process_button = QPushButton("Apply Processes")
        self.apply_process_button.setEnabled(False)  
        self.apply_process_button.clicked.connect(self.applyImageProcessing)

        reset_button = QPushButton("Reset Image Settings")
        reset_button.clicked.connect(self.resetImageAndSettings)

        # Create horizontal and vertical layouts for the side panel and main window
        side_panel_v_box = QVBoxLayout()
        side_panel_v_box.setAlignment(Qt.AlignTop)
        side_panel_v_box.addWidget(contrast_label)
        side_panel_v_box.addWidget(self.contrast_spinbox)
        side_panel_v_box.addWidget(brightness_label)
        side_panel_v_box.addWidget(self.brightness_spinbox)
        side_panel_v_box.addSpacing(15)
        side_panel_v_box.addWidget(smoothing_label)
        side_panel_v_box.addWidget(self.filter_2D_cb)
        side_panel_v_box.addWidget(edges_label)
        side_panel_v_box.addWidget(self.canny_cb)
        side_panel_v_box.addWidget(self.apply_process_button)
        side_panel_v_box.addStretch(1)
        side_panel_v_box.addWidget(reset_button)

        side_panel_frame = QFrame()
        side_panel_frame.setMinimumWidth(200)
        side_panel_frame.setFrameStyle(QFrame.WinPanel)
        side_panel_frame.setLayout(side_panel_v_box)

        main_h_box = QHBoxLayout()
        main_h_box.addWidget(self.image_label, 1)
        main_h_box.addWidget(side_panel_frame)

        # Create container widget and set main window's widget
        container = QWidget()
        container.setLayout(main_h_box)
        self.setCentralWidget(container)       

    def setupMenu(self):
        """Simple menu bar to select and save local images."""
        # Create actions for file menu
        open_act = QAction('Open...', self)
        open_act.setShortcut('Ctrl+O')
        open_act.triggered.connect(self.openImageFile)

        save_act = QAction('Save...', self)
        save_act.setShortcut('Ctrl+S')
        save_act.triggered.connect(self.saveImageFile)

        # Create menu bar
        menu_bar = self.menuBar()
        menu_bar.setNativeMenuBar(False)

        # Create file menu and add actions
        file_menu = menu_bar.addMenu('File')
        file_menu.addAction(open_act)
        file_menu.addAction(save_act)

    def adjustContrast(self):
        """The slot corresponding to adjusting image contrast."""
        if self.image_label.pixmap() != None:
            self.contrast_adjusted = True

    def adjustBrightness(self):
        """The slot corresponding to adjusting image brightness."""
        if self.image_label.pixmap() != None:
            self.brightness_adjusted = True

    def imageSmoothingFilter(self, state):
        """The slot corresponding to applying 2D Convolution for smoothing the image."""
        if state == Qt.Checked and self.image_label.pixmap() != None:
            self.image_smoothing_checked = True
        elif state != Qt.Checked and self.image_label.pixmap() != None:
            self.image_smoothing_checked = False

    def edgeDetection(self, state):
        """The slot corresponding to applying edge detection."""
        if state == Qt.Checked and self.image_label.pixmap() != None:
            self.edge_detection_checked = True
        elif state != Qt.Checked and self.image_label.pixmap() != None:
            self.edge_detection_checked = False

    def applyImageProcessing(self):
        """For the boolean variables related to the image processing techniques, if 
        True, apply the corresponding process to the image and display the changes 
        in the QLabel, image_label."""
        if self.contrast_adjusted == True or self.brightness_adjusted == True:
            contrast = self.contrast_spinbox.value()
            brightness = self.brightness_spinbox.value()
            self.cv_image = cv2.convertScaleAbs(self.cv_image, self.processed_cv_image, contrast, brightness)
        if self.image_smoothing_checked == True:
            kernel = np.ones((5, 5), np.float32) / 25
            self.cv_image = cv2.filter2D(self.cv_image, -1, kernel)
        if self.edge_detection_checked == True:
            self.cv_image = cv2.Canny(self.cv_image, 100, 200)
        self.convertCVToQImage(self.cv_image)

        self.image_label.repaint() # Repaint the updated image on the label

    def resetImageAndSettings(self):
        """Reset the displayed image and widgets used for image processing."""
        answer = QMessageBox.information(self, "Reset Image",
                "Are you sure you want to reset the image settings?", QMessageBox.Yes
                | QMessageBox.No, QMessageBox.No)
        
        if answer == QMessageBox.No:
            pass
        elif answer == QMessageBox.Yes and self.image_label.pixmap() != None:
            self.resetWidgetValues()
            self.cv_image = self.copy_cv_image
            self.convertCVToQImage(self.copy_cv_image)

    def resetWidgetValues(self):
        """Reset the spinbox and checkbox values to their beginning values."""
        self.contrast_spinbox.setValue(1.0)
        self.brightness_spinbox.setValue(0)
        self.filter_2D_cb.setChecked(False)
        self.canny_cb.setChecked(False)

    def openImageFile(self):
        """Open an image file and display the contents in the label widget."""
        image_file, _ = QFileDialog.getOpenFileName(self, "Open Image", 
            os.getenv('HOME'), "Images (*.png *.jpeg *.jpg *.bmp)")
        
        if image_file:
            self.resetWidgetValues() # Reset the states of the widgets
            self.apply_process_button.setEnabled(True) 

            self.cv_image = cv2.imread(image_file) # Original image
            self.copy_cv_image = self.cv_image # A copy of the original image
            # Create a destination image for the contrast and brightness processes
            self.processed_cv_image = np.zeros(self.cv_image.shape, self.cv_image.dtype)
            self.convertCVToQImage(self.cv_image) # Convert the OpenCV image to a Qt Image
        else:
            QMessageBox.information(self, "Error",
                "No image was loaded.", QMessageBox.Ok)

    def saveImageFile(self):
        """Save the contents of the image_label to file."""
        image_file, _ = QFileDialog.getSaveFileName(self, "Save Image", os.getenv('HOME'), 
            "JPEG (*.jpeg);;JPG (*.jpg);;PNG (*.png);;Bitmap (*.bmp)")

        if image_file and self.image_label.pixmap() != None:
            # Save the file using OpenCV's imwrite() function
            cv2.imwrite(image_file, self.cv_image)
        else:
            QMessageBox.information(self, "Error",
                "Unable to save image.", QMessageBox.Ok)

    def convertCVToQImage(self, image):
        """Load a cv image and convert the image to a Qt QImage. Display the image in image_label."""
        cv_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        # Get the shape of the image, height * width * channels. BGR/RGB/HSV images have 3 channels
        height, width, channels = cv_image.shape # Format: (rows, columns, channels)
        # Number of bytes required by the image pixels in a row; dependency on the number of channels
        bytes_per_line = width * channels
        # Create instance of QImage using data from cv_image
        converted_Qt_image = QImage(cv_image, width, height, bytes_per_line, QImage.Format_RGB888)
        
        self.image_label.setPixmap(QPixmap.fromImage(converted_Qt_image).scaled(
            self.image_label.width(), self.image_label.height(), Qt.KeepAspectRatio))
Beispiel #57
0
 def _default_double():
     widget = QDoubleSpinBox()
     widget.setMinimum(-999999999)
     widget.setMaximum(999999999)
     return widget
class ResultHandler(QDialog):
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle('Dash results')
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        self.scrollArea = QScrollArea()
        self.widget = QWidget()

        self.test_name_label = QLabel()
        grid = QGridLayout()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel('Control'), 1, 0)
        grid.addWidget(QLabel('Rendered'), 1, 1)
        grid.addWidget(QLabel('Difference'), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel('Current Mask'), 3, 0)
        grid.addWidget(QLabel('New Mask'), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        self.widget.setLayout(grid)
        self.scrollArea.setWidget(self.widget)
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.scrollArea, 1)

        next_image_button = QPushButton()
        next_image_button.setText('Skip')
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)
        self.overload_spin.valueChanged.connect(
            lambda: save_mask_button.setEnabled(False))

        preview_mask_button = QPushButton()
        preview_mask_button.setText('Preview New Mask')
        preview_mask_button.pressed.connect(self.preview_mask)
        preview_mask_button.pressed.connect(
            lambda: save_mask_button.setEnabled(True))

        save_mask_button = QPushButton()
        save_mask_button.setText('Save New Mask')
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel('Mask diff multiplier:'))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)

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

    def parse_url(self, url):
        print('Fetching dash results from: {}'.format(url))
        page = urllib.request.urlopen(url)
        soup = BeautifulSoup(page, "lxml")

        # build up list of rendered images
        measurement_img = [
            img for img in soup.find_all('img')
            if img.get('alt') and img.get('alt').startswith('Rendered Image')
        ]

        images = {}
        for img in measurement_img:
            m = re.search('Rendered Image (.*?)\s', img.get('alt'))
            test_name = m.group(1)
            rendered_image = img.get('src')
            images[test_name] = '{}/{}'.format(dash_url, rendered_image)

        if images:
            print('found images:\n{}'.format(images))
        else:
            print('no images found\n')
        self.images = images
        self.load_next()

    def load_next(self):
        if not self.images:
            # all done
            self.accept()
            exit(0)

        test_name, rendered_image = self.images.popitem()
        self.test_name_label.setText(test_name)
        control_image = self.get_control_image_path(test_name)
        if not control_image:
            self.load_next()
            return

        self.mask_image_path = control_image[:-4] + '_mask.png'
        self.load_images(control_image, rendered_image, self.mask_image_path)

    def load_images(self, control_image_path, rendered_image_path,
                    mask_image_path):
        self.control_image = imageFromPath(control_image_path)
        if not self.control_image:
            error('Could not read control image {}'.format(control_image_path))

        self.rendered_image = imageFromPath(rendered_image_path)
        if not self.rendered_image:
            error(
                'Could not read rendered image {}'.format(rendered_image_path))
        if not self.rendered_image.width() == self.control_image.width(
        ) or not self.rendered_image.height() == self.control_image.height():
            print(
                'Size mismatch - control image is {}x{}, rendered image is {}x{}'
                .format(self.control_image.width(),
                        self.control_image.height(),
                        self.rendered_image.width(),
                        self.rendered_image.height()))

        max_width = min(self.rendered_image.width(),
                        self.control_image.width())
        max_height = min(self.rendered_image.height(),
                         self.control_image.height())

        # read current mask, if it exist
        self.mask_image = imageFromPath(mask_image_path)
        if self.mask_image.isNull():
            print('Mask image does not exist, creating {}'.format(
                mask_image_path))
            self.mask_image = QImage(self.control_image.width(),
                                     self.control_image.height(),
                                     QImage.Format_ARGB32)
            self.mask_image.fill(QColor(0, 0, 0))

        self.diff_image = self.create_diff_image(self.control_image,
                                                 self.rendered_image,
                                                 self.mask_image)
        if not self.diff_image:
            self.load_next()
            return

        self.control_label.setPixmap(QPixmap.fromImage(self.control_image))
        self.rendered_label.setPixmap(QPixmap.fromImage(self.rendered_image))
        self.mask_label.setPixmap(QPixmap.fromImage(self.mask_image))
        self.diff_label.setPixmap(QPixmap.fromImage(self.diff_image))
        self.preview_mask()

    def preview_mask(self):
        self.new_mask_image = self.create_mask(self.control_image,
                                               self.rendered_image,
                                               self.mask_image,
                                               self.overload_spin.value())
        self.new_mask_label.setPixmap(QPixmap.fromImage(self.new_mask_image))

    def save_mask(self):
        self.new_mask_image.save(self.mask_image_path, "png")
        self.load_next()

    def create_mask(self,
                    control_image,
                    rendered_image,
                    mask_image,
                    overload=1):
        max_width = min(rendered_image.width(), control_image.width())
        max_height = min(rendered_image.height(), control_image.height())

        new_mask_image = QImage(control_image.width(), control_image.height(),
                                QImage.Format_ARGB32)
        new_mask_image.fill(QColor(0, 0, 0))

        # loop through pixels in rendered image and compare
        mismatch_count = 0
        linebytes = max_width * 4
        for y in range(max_height):
            control_scanline = control_image.constScanLine(y).asstring(
                linebytes)
            rendered_scanline = rendered_image.constScanLine(y).asstring(
                linebytes)
            mask_scanline = mask_image.scanLine(y).asstring(linebytes)

            for x in range(max_width):
                currentTolerance = qRed(
                    struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0])

                if currentTolerance == 255:
                    # ignore pixel
                    new_mask_image.setPixel(
                        x, y,
                        qRgb(currentTolerance, currentTolerance,
                             currentTolerance))
                    continue

                expected_rgb = struct.unpack(
                    'I', control_scanline[x * 4:x * 4 + 4])[0]
                rendered_rgb = struct.unpack(
                    'I', rendered_scanline[x * 4:x * 4 + 4])[0]
                difference = min(
                    255,
                    colorDiff(expected_rgb, rendered_rgb) * overload)

                if difference > currentTolerance:
                    # update mask image
                    new_mask_image.setPixel(
                        x, y, qRgb(difference, difference, difference))
                    mismatch_count += 1
                else:
                    new_mask_image.setPixel(
                        x, y,
                        qRgb(currentTolerance, currentTolerance,
                             currentTolerance))
        return new_mask_image

    def get_control_image_path(self, test_name):
        if os.path.isfile(test_name):
            return path

        # else try and find matching test image
        script_folder = os.path.dirname(os.path.realpath(sys.argv[0]))
        control_images_folder = os.path.join(
            script_folder, '../tests/testdata/control_images')

        matching_control_images = [
            x[0] for x in os.walk(control_images_folder) if test_name in x[0]
        ]
        if len(matching_control_images) > 1:
            QMessageBox.warning(
                self, 'Result',
                'Found multiple matching control images for {}'.format(
                    test_name))
            return None
        elif len(matching_control_images) == 0:
            QMessageBox.warning(
                self, 'Result',
                'No matching control images found for {}'.format(test_name))
            return None

        found_control_image_path = matching_control_images[0]

        # check for a single matching expected image
        images = glob.glob(os.path.join(found_control_image_path, '*.png'))
        filtered_images = [i for i in images if not i[-9:] == '_mask.png']
        if len(filtered_images) > 1:
            error('Found multiple matching control images for {}'.format(
                test_name))
        elif len(filtered_images) == 0:
            error('No matching control images found for {}'.format(test_name))

        found_image = filtered_images[0]
        print('Found matching control image: {}'.format(found_image))
        return found_image

    def create_diff_image(self, control_image, rendered_image, mask_image):
        # loop through pixels in rendered image and compare
        mismatch_count = 0
        max_width = min(rendered_image.width(), control_image.width())
        max_height = min(rendered_image.height(), control_image.height())
        linebytes = max_width * 4

        diff_image = QImage(control_image.width(), control_image.height(),
                            QImage.Format_ARGB32)
        diff_image.fill(QColor(152, 219, 249))

        for y in range(max_height):
            control_scanline = control_image.constScanLine(y).asstring(
                linebytes)
            rendered_scanline = rendered_image.constScanLine(y).asstring(
                linebytes)
            mask_scanline = mask_image.scanLine(y).asstring(linebytes)

            for x in range(max_width):
                currentTolerance = qRed(
                    struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0])

                if currentTolerance == 255:
                    # ignore pixel
                    continue

                expected_rgb = struct.unpack(
                    'I', control_scanline[x * 4:x * 4 + 4])[0]
                rendered_rgb = struct.unpack(
                    'I', rendered_scanline[x * 4:x * 4 + 4])[0]
                difference = colorDiff(expected_rgb, rendered_rgb)

                if difference > currentTolerance:
                    # update mask image
                    diff_image.setPixel(x, y, qRgb(255, 0, 0))
                    mismatch_count += 1

        if mismatch_count:
            return diff_image
        else:
            print('No mismatches')
            return None
Beispiel #59
0
    def __init__(self, device=Device.EEG, mock=False, log_keyboard=False):
        super(CustomMainWindow, self).__init__()
        self.communicator = Communicate()
        self.is_recording = False
        self.recorder = None
        self.device = device
        self.mock = mock
        self.log_keyboard = log_keyboard

        self.keyboard_logger = None
        self.threadpool = QThreadPool()

        self.setWindowTitle("ExpApp")
        self.setGeometry(100, 100, WINDOW_X, WINDOW_Y)
        self.options = [
            _EO,
            _EC,
            _PINCODE_4_TRUE_SEQ_REP_3,
            _P300_SECRET_9,
            _MI_CALIBRATION,
            _MI_INPUT,
            _SSVEP1,
            _SSVEP2,
            _SSVEP3,
        ]

        # Default parameters
        self.exp_params = ExperimentParams()
        self.exp_params.experiment = self.options[0]

        self.main_widget = QtWidgets.QWidget()
        self.main_layout = QtWidgets.QGridLayout()
        self.main_widget.setLayout(self.main_layout)
        self.setCentralWidget(self.main_widget)

        # Experiment window
        self.exp_window = None

        # Create graph frame
        graph_col_span = 8
        self.graph_layout = QtWidgets.QGridLayout()
        self.graph_frame = QtWidgets.QFrame(self)
        self.graph_frame.setLayout(self.graph_layout)
        self.main_layout.addWidget(self.graph_frame, 0, 0, 3, graph_col_span)
        self.myFig = GraphWidget(True if self.device == Device.EMG else False)
        self.graph_layout.addWidget(self.myFig)
        my_data_loop = threading.Thread(name='my_data_loop',
                                        target=self.data_send_loop,
                                        daemon=True,
                                        args=(self.add_data_callback_func, ))
        my_data_loop.start()

        # Create control panel frame
        cpr = 0
        self.control_panel_layout = QtWidgets.QGridLayout()
        self.control_panel_frame = QtWidgets.QFrame(self)
        self.control_panel_frame.setLayout(self.control_panel_layout)
        self.main_layout.addWidget(self.control_panel_frame, cpr,
                                   graph_col_span, 1, 3)
        self.is_paused = False

        # Default font for text elements
        label = QLabel()
        font = label.font()
        font.setPointSize(12)
        font.setItalic(True)
        label.setFont(font)

        if True:
            # Pause button
            self.pause_button = QPushButton(PAUSE_GRAPH)
            self.pause_button.setStyleSheet(elem_style)
            self.pause_button.clicked.connect(lambda: self.pause_graphs())
            self.control_panel_layout.addWidget(self.pause_button, cpr, 0, 1,
                                                3)
            cpr += 1

            # Record panel
            self.record_button = QPushButton('Record')
            self.record_button.setStyleSheet(elem_style)
            self.record_button.clicked.connect(lambda: self.start_record_())
            self.record_time_input = QDoubleSpinBox()
            self.record_time_input.setStyleSheet(elem_style)
            self.record_count = 1
            self.record_time_input.setValue(self.exp_params.record_duration)
            self.record_time_input.setSingleStep(0.1)
            self.record_time_input.setMaximum(MAX_RECORD_DURATION)
            self.record_time_input.valueChanged.connect(self.set_record_time)
            self.record_countdown = QLabel("")
            self.record_countdown.setFont(font)
            self.control_panel_layout.addWidget(self.record_time_input, cpr, 0)
            self.control_panel_layout.addWidget(self.record_countdown, cpr, 1,
                                                1, 1)
            self.control_panel_layout.addWidget(self.record_button, cpr, 2, 1,
                                                1)
            cpr += 1

            # Experiment setup panel
            # File name
            self.prefix_input = QComboBox()
            self.prefix_input.setStyleSheet(elem_style)
            gesture_set = SET6  # all gestures
            self.prefix_input.addItems(gesture_set)
            self.exp_params.name_prefix = gesture_set[0]
            self.prefix_input.currentIndexChanged.connect(self.set_exp_name)
            label = QLabel("File Name Prefix: ")
            label.setFont(font)

            self.control_panel_layout.addWidget(label, cpr, 0, 1, 1)
            self.control_panel_layout.addWidget(self.prefix_input, cpr, 1, 1,
                                                2)
            cpr += 1
            # Subject id
            self.exp_subject_id_prefix_input = QLineEdit()
            self.exp_subject_id_prefix_input.setStyleSheet(elem_style)
            self.exp_subject_id_prefix_input.setText(PARTICIPANT_LIST[0])
            self.set_exp_subject()
            self.exp_subject_id_prefix_input.editingFinished.connect(
                self.set_exp_subject)
            label = QLabel("User: "******"Gender:"), cpr, 0,
                                                    1, 1)
                self.exp_m_input = QRadioButton("male")
                self.exp_m_input.setChecked(
                    self.exp_params.gender == self.exp_m_input.text())
                self.exp_m_input.toggled.connect(
                    lambda checked: self.set_exp_gender(
                        self.exp_m_input.text(), checked))
                self.exp_f_input = QRadioButton("female")
                self.exp_f_input.setChecked(
                    self.exp_params.gender == self.exp_f_input.text())
                self.exp_f_input.toggled.connect(
                    lambda checked: self.set_exp_gender(
                        self.exp_f_input.text(), checked))
                self.control_panel_layout.addWidget(self.exp_m_input, cpr, 1,
                                                    1, 1)
                self.control_panel_layout.addWidget(self.exp_f_input, cpr, 2,
                                                    1, 1)
                cpr += 1
                # Age
                self.control_panel_layout.addWidget(QLabel("Age:"), cpr, 0, 1,
                                                    1)
                self.exp_age_input = QSpinBox()
                self.exp_age_input.setValue(self.exp_params.age)
                self.exp_age_input.editingFinished.connect(self.set_exp_age)
                self.control_panel_layout.addWidget(self.exp_age_input, cpr, 1,
                                                    1, 2)
                cpr += 1
                # Electrodes
                self.exp_electrodes_input = QLineEdit()
                self.exp_electrodes_input.setText(self.exp_params.electrodes)
                self.exp_electrodes_input.editingFinished.connect(
                    self.set_electrodes)
                self.control_panel_layout.addWidget(QLabel("Electrodes:"), cpr,
                                                    0, 1, 1)
                self.control_panel_layout.addWidget(self.exp_electrodes_input,
                                                    cpr, 1, 1, 2)
                cpr += 1

                # Experiment selection
                self.exp_selection_box = QComboBox()
                self.exp_selection_box.addItems(self.options)
                self.exp_selection_box.currentIndexChanged.connect(
                    self.set_exp)
                self.exp_run_button = QPushButton("Run")
                self.exp_run_button.clicked.connect(self.exp_run)
                self.control_panel_layout.addWidget(self.exp_run_button, cpr,
                                                    0, 1, 1)
                self.control_panel_layout.addWidget(self.exp_selection_box,
                                                    cpr, 1, 1, 2)

        if self.device == Device.EMG:
            self.setStyleSheet("background-color: " + BACKGROUND_COLOR + ";")

        self.show()
Beispiel #60
0
    def __layout(self):
        self.browser.loadFinished.connect(self.__onLoadFinished)
        self.__vbox = QVBoxLayout()

        self.__ctrls_layout = QHBoxLayout()

        self.__edit_url = QLineEdit()
        self.__ctrls_layout.addWidget(self.__edit_url)

        # self.__btn_go = QPushButton('Go')
        # self.__btn_go.clicked.connect(self.__on_btn_go)
        # self.__ctrls_layout.addWidget(self.__btn_go)
        # https://www.learnpyqt.com/examples/mooseache/
        # https://doc.qt.io/qt-5/qstyle.html#StandardPixmap-enum
        self.__btn_back = QPushButton()
        self.__btn_back.setIcon(self.style().standardIcon(QStyle.SP_ArrowLeft))
        self.__btn_back.setFlat(True)
        self.__btn_back.setToolTip('Back')
        self.__btn_back.clicked.connect(self.browser.back)
        self.__ctrls_layout.addWidget(self.__btn_back)

        self.__btn_forward = QPushButton()
        self.__btn_forward.setIcon(self.style().standardIcon(
            QStyle.SP_ArrowForward))
        self.__btn_forward.setFlat(True)
        self.__btn_forward.setToolTip('Forward')
        self.__btn_forward.clicked.connect(self.browser.forward)
        self.__ctrls_layout.addWidget(self.__btn_forward)

        self.__btn_reload = QPushButton()
        self.__btn_reload.setIcon(self.style().standardIcon(
            QStyle.SP_BrowserReload))
        self.__btn_reload.setFlat(True)
        self.__btn_reload.setToolTip('Reload')
        self.__btn_reload.clicked.connect(self.browser.reload)
        self.__ctrls_layout.addWidget(self.__btn_reload)

        self.__btn_stop = QPushButton()
        self.__btn_stop.setIcon(self.style().standardIcon(
            QStyle.SP_BrowserStop))
        self.__btn_stop.setFlat(True)
        self.__btn_stop.setToolTip('Stop')
        self.__btn_stop.clicked.connect(self.browser.stop)
        self.__ctrls_layout.addWidget(self.__btn_stop)

        self.browser.urlChanged.connect(self.update_urlbar)

        self.__label_zoom = QLabel()
        self.__label_zoom.setText('Zoom')
        self.__label_zoom.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.__ctrls_layout.addWidget(self.__label_zoom,
                                      alignment=Qt.AlignRight)

        self.__spin_zoom = QDoubleSpinBox()
        self.__spin_zoom.setRange(0.125, 15)
        self.__spin_zoom.setValue(1.0)
        self.__spin_zoom.setSingleStep(0.125)
        self.__spin_zoom.valueChanged.connect(self.__spin_zoom_valueChanged)
        self.__spin_zoom.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        # https://stackoverflow.com/questions/53573382/pyqt5-set-widget-size-to-minimum-and-fix
        self.__ctrls_layout.addWidget(self.__spin_zoom,
                                      alignment=Qt.AlignRight)

        self.__vbox.addLayout(self.__ctrls_layout)

        self.__vbox.addWidget(self.browser)

        self.setLayout(self.__vbox)

        self.__ctrl_plus_shortcut = QShortcut(QKeySequence("Ctrl++"), self)
        self.__ctrl_plus_shortcut.activated.connect(self.__on_ctrl_plus)

        self.__ctrl_minus_shortcut = QShortcut(QKeySequence("Ctrl+-"), self)
        self.__ctrl_minus_shortcut.activated.connect(self.__on_ctrl_minus)