Beispiel #1
0
 def initDialog(self):
     """Creates buttons for each sequence option and add them to the dialog.
     Maps the clicked signal of those buttons to keep track of what sequence
     gets selected.
     """
     ui_dlg = Ui_AddSeqDialog()
     ui_dlg.setupUi(self.dialog)
     self.signal_mapper = QSignalMapper(self)
     # set up the radio buttons
     for i, name in enumerate(['Abstract', 'Custom'] + sorted(sequences.keys())):
         radio_button = QRadioButton(ui_dlg.group_box)
         radio_button.setObjectName(name + "Button")
         radio_button.setText(name)
         self.buttons.append(radio_button)
         ui_dlg.horizontalLayout.addWidget(radio_button)
         self.signal_mapper.setMapping(radio_button, i)
         radio_button.clicked.connect(self.signal_mapper.map)
         if name in sequences:
             self.sequence_radio_button_id[sequences[name]] = i
     self.signal_mapper.mapped.connect(self.sequenceOptionChangedSlot)
     # disable apply until valid option or custom sequence is chosen
     self.apply_button = ui_dlg.custom_button_box.button(QDialogButtonBox.Apply)
     self.apply_button.setEnabled(False)
     # watch sequence textedit box to validate custom sequences
     self.seq_box = ui_dlg.seq_text_edit
     self.seq_box.textChanged.connect(self.validateCustomSequence)
     self.highlighter = DNAHighlighter(self.seq_box)
     # finally, pre-click the first radio button
     self.buttons[0].click()
 def initUI(self):
     super().initUI()
     self.setWindowTitle("ノイズ付与設定")
     self.layout = QGridLayout()
     self.radioButton1 = QRadioButton("ごま塩ノイズ")
     self.radioButton2 = QRadioButton("gaussianノイズ")
     self.soltSlider = HorizontalSlider()
     self.soltSlider.setTickPosition(QSlider.TicksBelow)
     self.soltSlider.setTickInterval(20)
     self.gaussSlider = HorizontalSlider()
     self.soltTextLine = TextLine(text=str(self.soltSlider.value()),
                                             width=60, readmode=True)
     self.gaussTextLine = TextLine(text=str(self.gaussSlider.value()),
                                             width=60, readmode=True)
     self.buttonGroup = QButtonGroup()
     self.buttonGroup.addButton(self.radioButton1)
     self.buttonGroup.addButton(self.radioButton2)
     self.soltSlider.valueChanged[int].connect(self.changedSoltSliderValue)
     self.gaussSlider.valueChanged[int].connect(self.changedGaussSliderValue)
     self.layout.addWidget(self.radioButton1, 0, 0)
     self.layout.addWidget(QLabel("ノイズ割合"), 1, 0)
     self.layout.addWidget(self.soltSlider, 1, 1)
     self.layout.addWidget(self.soltTextLine, 1, 2)
     self.layout.addWidget(self.radioButton2, 2, 0)
     self.layout.addWidget(QLabel("分散"), 3, 0)
     self.layout.addWidget(self.gaussSlider, 3, 1)
     self.layout.addWidget(self.gaussTextLine, 3, 2)
     self.layout.addWidget(self.btnBox, 4, 2)
     self.setLayout(self.layout)
    def _initUi(self, dlgName):
        self.setWindowTitle(dlgName)
 
        allRadioButton = QRadioButton('所有'); allRadioButton.setChecked(True)
        highlightRadioButton = QRadioButton('高亮')

        # 添加到QButtonGroup
        self._buttonGroup = QButtonGroup()
        self._buttonGroup.addButton(allRadioButton, 1); 
        self._buttonGroup.addButton(highlightRadioButton, 2)

        cancelPushButton = QPushButton('Cancel')
        okPushButton = QPushButton('OK')
        cancelPushButton.clicked.connect(self._cancel)
        okPushButton.clicked.connect(self._ok)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)
 
        grid.addWidget(allRadioButton, 1, 0)
        grid.addWidget(highlightRadioButton, 1, 1)

        grid.addWidget(okPushButton, 2, 1)
        grid.addWidget(cancelPushButton, 2, 0)
 
        self.setLayout(grid)
        self.setMinimumWidth(QApplication.desktop().size().width()//5)
Beispiel #4
0
    def initUI(self):
        """ Object method
            Params: None
            Return: None
            This method sets the dialog box's layout.
            The Dialog box conatains two radio buttons and OK/Cancel buttons.
            sizeHint() sets the box to an ideal size.
        """

        #creating layout
        settings_layout = QVBoxLayout();

        #creating Radio buttons
        self.nat_order = QRadioButton("Natural order", self);
        self.alph_order = QRadioButton("Alphabetical", self);

        #creating the buttons
        buttons = QDialogButtonBox();

        #creating OK button and connecting it to the dialog
        buttons.addButton(QDialogButtonBox.Ok);
        buttons.accepted.connect(self.accept)
        
        #creating Cancel button and connecting it to the dialog
        buttons.addButton(QDialogButtonBox.Cancel);
        buttons.rejected.connect(self.reject)

        #adding created buttons to the layout
        settings_layout.addWidget(self.nat_order);
        settings_layout.addWidget(self.alph_order);
        settings_layout.addWidget(buttons);

        #adding layout to dialog
        self.setLayout(settings_layout);
        self.sizeHint()
class FilterConfigDialog(ConfigDialog):

    def __init__(self, mode=None, params=None):
        super().__init__()
        self.initUI()
        self.setSelectedFilterMode(mode)
        self.kSizeSlider.initValueAndRange(minimum=2, maximum=20, value=params["ksize"])
        self.sigmaSlider.initValueAndRange(value=params["sigma"])

    def initUI(self):
        super().initUI()
        self.setWindowTitle("フィルタリング(ぼかし)設定")
        self.layout = QGridLayout()
        self.gaussBtn = QRadioButton("Gaussianフィルタ")
        self.aveBtn = QRadioButton("移動平均フィルタ")
        self.kSizeSlider = HorizontalSlider()
        self.sigmaSlider = HorizontalSlider()
        self.kSizeTextLine = TextLine(text=str(self.kSizeSlider.value()),
                                                    width=50, readmode=True)
        self.sigmaTextLine = TextLine(text=str(self.sigmaSlider.value()),
                                                    width=50, readmode=True)
        self.kSizeSlider.valueChanged[int].connect(self.changedKSizeSliderValue)
        self.sigmaSlider.valueChanged[int].connect(self.changedSigmaSliderValue)
        self.layout.addWidget(self.gaussBtn, 0, 0)
        self.layout.addWidget(self.aveBtn, 0, 1)
        self.layout.addWidget(QLabel("フィルタサイズ"), 1, 0, Qt.AlignCenter)
        self.layout.addWidget(self.kSizeSlider, 1, 1, 1, 2)
        self.layout.addWidget(self.kSizeTextLine, 1, 4)
        self.layout.addWidget(QLabel("分散"), 2, 0, Qt.AlignCenter)
        self.layout.addWidget(self.sigmaSlider, 2, 1, 1, 2)
        self.layout.addWidget(self.sigmaTextLine, 2, 4)
        self.layout.addWidget(self.btnBox, 4, 4)
        self.setLayout(self.layout)

    """フィルタリング設定モードUI反映処理"""
    def setSelectedFilterMode(self, mode):
        if mode == Constant.GAUSSIAN_FILTER_MODE or mode is None:
            self.gaussBtn.setChecked(True)
        else:
            self.aveBtn.setChecked(True)

    """フィルタリング設定モード取得処理"""
    def getSelectedFilterMode(self):
        if self.gaussBtn.isChecked():
            return Constant.GAUSSIAN_FILTER_MODE
        else:
            return Constant.AVERAGE_FILTER_MODE

    """フィルタリング設定パラメータ値取得処理"""
    def getSelectedFilterConfig(self):
        filterParams = {"ksize": self.kSizeSlider.value(),
                        "sigma": self.sigmaSlider.value()}
        return self.getSelectedFilterMode(), filterParams

    """スライダー値変更反映処理"""
    def changedKSizeSliderValue(self, value):
        self.kSizeTextLine.setText(str(value))

    def changedSigmaSliderValue(self, value):
        self.sigmaTextLine.setText(str(value))
Beispiel #6
0
class OnOffToggleWidget(QWidget):
    """
    A widget that contains a label and two 'On'/'Off' radio buttons on a
    single horizontal row.
    """

    def __init__(self, label='', value=True, parent=None):
        super(OnOffToggleWidget, self).__init__(parent)
        self.setup(label, value)

    def setup(self, label, value):
        """Setup the widget with the provided options."""
        self.toggle_on = QRadioButton('On')
        self.toggle_off = QRadioButton('Off')
        self.set_value(value)

        layout = QGridLayout(self)
        layout.addWidget(QLabel(label + ' :'), 0, 0)
        layout.addWidget(self.toggle_on, 0, 2)
        layout.addWidget(self.toggle_off, 0, 3)
        layout.setColumnStretch(1, 100)
        layout.setContentsMargins(0, 0, 0, 0)

    def value(self):
        """Return True if the toggle is 'On' and False if it is 'Off'."""
        return self.toggle_on.isChecked()

    def set_value(self, value):
        """Set to 'On' if value is True and set to 'Off' if it is False."""
        if value:
            self.toggle_on.toggle()
        else:
            self.toggle_off.toggle()
Beispiel #7
0
    def __init__(self, currentGlyph, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Layer actions…"))
        self._workableLayers = []
        for layer in currentGlyph.layerSet:
            if layer != currentGlyph.layer:
                self._workableLayers.append(layer)

        copyBox = QRadioButton(self.tr("Copy"), self)
        moveBox = QRadioButton(self.tr("Move"), self)
        swapBox = QRadioButton(self.tr("Swap"), self)
        self.otherCheckBoxes = (moveBox, swapBox)
        copyBox.setChecked(True)

        self.layersList = QListWidget(self)
        self.layersList.addItems(layer.name for layer in self._workableLayers)
        if self.layersList.count():
            self.layersList.setCurrentRow(0)
        self.layersList.itemDoubleClicked.connect(self.accept)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        layout = QGridLayout(self)
        l = 0
        layout.addWidget(copyBox, l, 0, 1, 2)
        layout.addWidget(moveBox, l, 2, 1, 2)
        layout.addWidget(swapBox, l, 4, 1, 2)
        l += 1
        layout.addWidget(self.layersList, l, 0, 1, 6)
        l += 1
        layout.addWidget(buttonBox, l, 0, 1, 6)
        self.setLayout(layout)
Beispiel #8
0
    def __init__(self, msg, choices, on_clicked=None, checked_index=0):
        vbox = QVBoxLayout()
        if len(msg) > 50:
            vbox.addWidget(WWLabel(msg))
            msg = ""
        gb2 = QGroupBox(msg)
        vbox.addWidget(gb2)

        vbox2 = QVBoxLayout()
        gb2.setLayout(vbox2)

        self.group = group = QButtonGroup()
        for i,c in enumerate(choices):
            button = QRadioButton(gb2)
            button.setText(c)
            vbox2.addWidget(button)
            group.addButton(button)
            group.setId(button, i)
            if i==checked_index:
                button.setChecked(True)

        if on_clicked:
            group.buttonClicked.connect(partial(on_clicked, self))

        self.vbox = vbox
    def _show_templates(self):
        """
        Update templates on shoeEvent.
        """

        cols = 3
        templates = template_module.Template.get_all()

        for j, item in enumerate(self.visible_items):
            if not templates[item.id]:
                l = QLabel("Нет шаблонов для данного объекта\nУправлять шаблонами можно на вкладке настроек")
                l.setAlignment(Qt.AlignCenter)
                self.templates_layout.addWidget(l)
                continue
            layouts = [QVBoxLayout() for _ in range(cols)]
            for i, each in enumerate(templates[item.id]):
                b = QRadioButton(each.name)
                b.setChecked(item.template == each)
                b.clicked.connect(functools.partial(self._template_clicked, j, each))
                b.mouseDoubleClickEvent = functools.partial(self.open_template_edit_widget, j, each)
                layouts[i % cols].addWidget(b)

            wrapper = QHBoxLayout()
            for each in layouts:
                each.addStretch()
                wrapper.addLayout(each, stretch=int(100 / cols))
            self.templates_layout.addWidget(utils.get_scrollable(wrapper))
        class LabelDistributionOptionsDlg( QDialog ):
            """
            A little dialog to let the user specify how the labels should be
            distributed from the current stages to the other stages.
            """
            def __init__(self, source_stage_index, num_stages, *args, **kwargs):
                super(LabelDistributionOptionsDlg, self).__init__(*args, **kwargs)

                from PyQt5.QtCore import Qt
                from PyQt5.QtWidgets import QGroupBox, QCheckBox, QRadioButton, QDialogButtonBox
            
                self.setWindowTitle("Distributing from Stage {}".format(source_stage_index+1))

                self.stage_checkboxes = []
                for stage_index in range(1, num_stages+1):
                    self.stage_checkboxes.append( QCheckBox("Stage {}".format( stage_index )) )
                
                # By default, send labels back into the current stage, at least.
                self.stage_checkboxes[source_stage_index].setChecked(True)
                
                stage_selection_layout = QVBoxLayout()
                for checkbox in self.stage_checkboxes:
                    stage_selection_layout.addWidget( checkbox )

                stage_selection_groupbox = QGroupBox("Send labels from Stage {} to:".format( source_stage_index+1 ), self)
                stage_selection_groupbox.setLayout(stage_selection_layout)
                
                self.copy_button = QRadioButton("Copy", self)
                self.partition_button = QRadioButton("Partition", self)
                self.partition_button.setChecked(True)
                distribution_mode_layout = QVBoxLayout()
                distribution_mode_layout.addWidget(self.copy_button)
                distribution_mode_layout.addWidget(self.partition_button)
                
                distribution_mode_group = QGroupBox("Distribution Mode", self)
                distribution_mode_group.setLayout(distribution_mode_layout)
                
                buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self )
                buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel )
                buttonbox.accepted.connect( self.accept )
                buttonbox.rejected.connect( self.reject )
                
                dlg_layout = QVBoxLayout()
                dlg_layout.addWidget(stage_selection_groupbox)
                dlg_layout.addWidget(distribution_mode_group)
                dlg_layout.addWidget(buttonbox)
                self.setLayout(dlg_layout)

            def distribution_mode(self):
                if self.copy_button.isChecked():
                    return "copy"
                if self.partition_button.isChecked():
                    return "partition"
                assert False, "Shouldn't get here."
            
            def destination_stages(self):
                """
                Return the list of stage_indexes (0-based) that the user checked.
                """
                return [ i for i,box in enumerate(self.stage_checkboxes) if box.isChecked() ]
    def _initUi(self):
        self.setWindowTitle('指数均线K线图统计')
 
        # 控件
        startDateLable = QLabel('开始日期')
        self._startDateLineEdit = QLineEdit(datetime.now().strftime("%Y-%m-%d"))

        endDateLable = QLabel('结束日期')
        self._endDateLineEdit = QLineEdit(datetime.now().strftime("%Y-%m-%d"))

        # 指数和股票代码
        shIndexRadioButton = QRadioButton('上证指数'); shIndexRadioButton.setChecked(True)
        szIndexRadioButton = QRadioButton('深证成指')
        cybIndexRadioButton = QRadioButton('创业板指')
        zxbIndexRadioButton = QRadioButton('中小板指')

        hs300IndexRadioButton = QRadioButton('沪深300')
        zz500IndexRadioButton = QRadioButton('中证500')

        # 添加到QButtonGroup
        self._stocksButtonGroup = QButtonGroup()
        self._stocksButtonGroup.addButton(shIndexRadioButton, 1); 
        self._stocksButtonGroup.addButton(szIndexRadioButton, 2)
        self._stocksButtonGroup.addButton(cybIndexRadioButton, 3)
        self._stocksButtonGroup.addButton(zxbIndexRadioButton, 4)

        self._stocksButtonGroup.addButton(hs300IndexRadioButton, 4)
        self._stocksButtonGroup.addButton(zz500IndexRadioButton, 4)

        cancelPushButton = QPushButton('Cancel')
        okPushButton = QPushButton('OK')
        cancelPushButton.clicked.connect(self._cancel)
        okPushButton.clicked.connect(self._ok)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)
 
        grid.addWidget(startDateLable, 0, 0)
        grid.addWidget(self._startDateLineEdit, 1, 0)

        grid.addWidget(endDateLable, 0, 1)
        grid.addWidget(self._endDateLineEdit, 1, 1)

        grid.addWidget(shIndexRadioButton, 2, 0)
        grid.addWidget(szIndexRadioButton, 2, 1)
        grid.addWidget(cybIndexRadioButton, 3, 0)
        grid.addWidget(zxbIndexRadioButton, 3, 1)

        grid.addWidget(hs300IndexRadioButton, 4, 0)
        grid.addWidget(zz500IndexRadioButton, 4, 1)

        grid.addWidget(okPushButton, 5, 1)
        grid.addWidget(cancelPushButton, 5, 0)
 
        self.setLayout(grid)
Beispiel #12
0
def radio_dialog(options, name='Selection', default_idx=0):

    ok = False
    def _pressed_ok():
        nonlocal ok
        w.close()
        app.quit()
        ok |= True
    def _pressed_cancel():
        nonlocal ok
        w.close()
        app.quit()
        ok &= False

    app = QCoreApplication.instance() or QApplication([])

    w = QWidget()
    w.setWindowTitle(name)
    grid = QGridLayout()
    grid.setSpacing(10)
    edit = []
    for i in range(len(options)):
        r = QRadioButton(options[i])
        if i == default_idx:
            r.setChecked(True)
        edit.append(r)
        grid.addWidget(r,0,i)



    #Ok Button
    qbtn = QPushButton('Ok', w)
    qbtn.clicked.connect(_pressed_ok)
    qbtn.resize(qbtn.sizeHint())
    grid.addWidget(qbtn, 2*(i+1), 0)
    #Cancel Button
    qbtn = QPushButton('Cancel', w)
    qbtn.clicked.connect(_pressed_cancel)
    qbtn.resize(qbtn.sizeHint())
    grid.addWidget(qbtn, 2*(i+1), 1)

    #Defining the layout of the window:
    w.setLayout(grid)
    w.resize(50, i*50)
    qr = w.frameGeometry()
    cp = QDesktopWidget().availableGeometry().center()
    qr.moveCenter(cp)
    w.move(qr.topLeft())

    w.show()
    app.exec_()

    for r in edit:
        if r.isChecked(): text = r.text()
    return ok, text
Beispiel #13
0
    def setup(self, label, value):
        """Setup the widget with the provided options."""
        self.toggle_on = QRadioButton('On')
        self.toggle_off = QRadioButton('Off')
        self.set_value(value)

        layout = QGridLayout(self)
        layout.addWidget(QLabel(label + ' :'), 0, 0)
        layout.addWidget(self.toggle_on, 0, 2)
        layout.addWidget(self.toggle_off, 0, 3)
        layout.setColumnStretch(1, 100)
        layout.setContentsMargins(0, 0, 0, 0)
Beispiel #14
0
    def mode_radio(self):
        self.fu1 = QRadioButton("FU1")
        self.controls.addWidget(self.fu1)

        self.fu2 = QRadioButton("FU2")
        self.controls.addWidget(self.fu2)

        self.fu3 = QRadioButton("FU3")
        self.controls.addWidget(self.fu3)

        self.fu4 = QRadioButton("FU4")
        self.controls.addWidget(self.fu4)
Beispiel #15
0
    def createGroupBox(self):
        self.groupBox = QGroupBox(self.tr("View"))
        perspectiveRadioButton = QRadioButton(self.tr("Perspective"))
        isometricRadioButton = QRadioButton(self.tr("Isometric"))
        obliqueRadioButton = QRadioButton(self.tr("Oblique"))
        perspectiveRadioButton.setChecked(True)

        self.groupBoxLayout = QVBoxLayout()
        self.groupBoxLayout.addWidget(perspectiveRadioButton)
        self.groupBoxLayout.addWidget(isometricRadioButton)
        self.groupBoxLayout.addWidget(obliqueRadioButton)
        self.groupBox.setLayout(self.groupBoxLayout)
Beispiel #16
0
    def __init__(self, parent=None):
        super(ClassInfoPage, self).__init__(parent)

        self.setTitle("Class Information")
        self.setSubTitle("Specify basic information about the class for "
                "which you want to generate skeleton source code files.")
        self.setPixmap(QWizard.LogoPixmap, QPixmap(':/images/logo1.png'))

        classNameLabel = QLabel("&Class name:")
        classNameLineEdit = QLineEdit()
        classNameLabel.setBuddy(classNameLineEdit)

        baseClassLabel = QLabel("B&ase class:")
        baseClassLineEdit = QLineEdit()
        baseClassLabel.setBuddy(baseClassLineEdit)

        qobjectMacroCheckBox = QCheckBox("Generate Q_OBJECT &macro")

        groupBox = QGroupBox("C&onstructor")

        qobjectCtorRadioButton = QRadioButton("&QObject-style constructor")
        qwidgetCtorRadioButton = QRadioButton("Q&Widget-style constructor")
        defaultCtorRadioButton = QRadioButton("&Default constructor")
        copyCtorCheckBox = QCheckBox("&Generate copy constructor and operator=")

        defaultCtorRadioButton.setChecked(True)

        defaultCtorRadioButton.toggled.connect(copyCtorCheckBox.setEnabled)

        self.registerField('className*', classNameLineEdit)
        self.registerField('baseClass', baseClassLineEdit)
        self.registerField('qobjectMacro', qobjectMacroCheckBox)
        self.registerField('qobjectCtor', qobjectCtorRadioButton)
        self.registerField('qwidgetCtor', qwidgetCtorRadioButton)
        self.registerField('defaultCtor', defaultCtorRadioButton)
        self.registerField('copyCtor', copyCtorCheckBox)

        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.addWidget(qobjectCtorRadioButton)
        groupBoxLayout.addWidget(qwidgetCtorRadioButton)
        groupBoxLayout.addWidget(defaultCtorRadioButton)
        groupBoxLayout.addWidget(copyCtorCheckBox)
        groupBox.setLayout(groupBoxLayout)

        layout = QGridLayout()
        layout.addWidget(classNameLabel, 0, 0)
        layout.addWidget(classNameLineEdit, 0, 1)
        layout.addWidget(baseClassLabel, 1, 0)
        layout.addWidget(baseClassLineEdit, 1, 1)
        layout.addWidget(qobjectMacroCheckBox, 2, 0, 1, 2)
        layout.addWidget(groupBox, 3, 0, 1, 2)
        self.setLayout(layout)
Beispiel #17
0
    def createGroupBox(self, layout):
        group1 = QGroupBox(self)
        group1.setTitle(self.tr("Clicking Behavior"))
        group1.setMinimumHeight(150)
        group1.setMaximumWidth(300)
        layout.addWidget(group1)

        vlayout1 = QVBoxLayout(group1)
        buttonGroup = QButtonGroup(group1)
        
        self.radiobutton1 = QRadioButton(group1)
        self.radiobutton1.setText(self.tr("Single-click to open files and folders."))
        self.radiobutton1.setChecked(True)
        vlayout1.addWidget(self.radiobutton1)
        
        self.radiobutton2 = QRadioButton(group1)
        self.radiobutton2.setText(self.tr("Double-click to open files and folders."))
        self.radiobutton2.setChecked(False)
        vlayout1.addWidget(self.radiobutton2)

        buttonGroup.addButton(self.radiobutton1)
        buttonGroup.addButton(self.radiobutton2)

        buttonGroup.buttonClicked.connect(self.folderClick)

        group2 = QGroupBox(self)
        group2.setTitle(self.tr("Button Order"))
        group2.setMinimumHeight(150)
        group2.setMaximumWidth(300)
        layout.addWidget(group2)

        vlayout2 = QVBoxLayout(group2)
        buttonGroup2 = QButtonGroup(group2)

        self.radiobutton3 = QRadioButton(group2)
        self.radiobutton3.setText(self.tr("Right hand."))
        self.radiobutton3.setChecked(True)
        vlayout2.addWidget(self.radiobutton3)

        self.radiobutton4 = QRadioButton(group2)
        self.radiobutton4.setText(self.tr("Left hand."))
        vlayout2.addWidget(self.radiobutton4)

        buttonGroup2.addButton(self.radiobutton3)
        buttonGroup2.addButton(self.radiobutton4)

        buttonGroup2.buttonClicked.connect(self.mouseButton)

        self.checkbox = QCheckBox(group2)
        self.checkbox.setText(self.tr("Reverse scrolling."))
        self.checkbox.clicked.connect(self.reverseScroll)
        vlayout2.addWidget(self.checkbox)
Beispiel #18
0
    def __init__(self, parent):
        super(NewValuesWidget, self).__init__(parent)

        self.new_rd = QRadioButton(self)
        self.new_sb = QSpinBox(self)
        self.system_missing = QRadioButton(self)
        self.copy_old_values = QRadioButton(self)
        self.grid = QGridLayout(self)

        self.ui()
        self.properties()

        self.new_rd.toggled.connect(self.new_rd_toggled)
Beispiel #19
0
 def add_radiobuttons(self):
     from PyQt5.QtWidgets import QRadioButton, QButtonGroup
     self.buttonGroup = QButtonGroup()
     self.buttongroup_results = {}
     i = 1
     while i < len(arguments.radiolist):
         radiobutton = QRadioButton(arguments.radiolist[i+1])
         self.buttongroup_results[radiobutton] = arguments.radiolist[i]
         if arguments.radiolist[i+2].lower() == "true":
             radiobutton.setChecked(True)
         self.scrollLayout.addWidget(radiobutton)
         self.buttonGroup.addButton(radiobutton)
         i += 3
Beispiel #20
0
    def __init__(self, parent):
        super(GeneralPreferences, self).__init__(parent)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.typq = QCheckBox()
        self.tagl = QCheckBox()
        self.barnum = QCheckBox()
        self.neutdir = QCheckBox()
        self.midi = QCheckBox()
        self.metro = QCheckBox()

        # paper size
        self.paperSizeLabel = QLabel()
        self.paper = QComboBox()
        self.paper.addItems(paperSizes)
        self.paper.activated.connect(self.slotPaperChanged)
        paperSizeBox = QHBoxLayout(spacing=2)
        paperSizeBox.addWidget(self.paperSizeLabel)
        paperSizeBox.addWidget(self.paper)

        # paper orientation
        self.paperRegularBtn = QRadioButton(self)
        self.paperLandscapeBtn = QRadioButton(self)
        self.paperRotatedBtn = QRadioButton(self)
        self.paperOrientationBox = QGroupBox()
        pg = self.paperOrientationGroup = QButtonGroup()
        pg.setExclusive(True)
        pg.addButton(self.paperRegularBtn, 0)
        pg.addButton(self.paperLandscapeBtn, 1)
        pg.addButton(self.paperRotatedBtn, 2)
        orientationBox = QHBoxLayout()
        orientationBox.addWidget(self.paperRegularBtn)
        orientationBox.addWidget(self.paperLandscapeBtn)
        orientationBox.addWidget(self.paperRotatedBtn)
        self.paperOrientationBox.setLayout(orientationBox)

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

        app.translateUI(self)

        self.loadSettings()
        self.window().finished.connect(self.saveSettings)
Beispiel #21
0
 def __init__(self, page):
     super(Target, self).__init__(page)
     
     layout = QGridLayout()
     self.setLayout(layout)
     
     self.targetPDF = QRadioButton(toggled=page.changed)
     self.targetSVG = QRadioButton(toggled=page.changed)
     self.openDefaultView = QCheckBox(clicked=page.changed)
     
     layout.addWidget(self.targetPDF, 0, 0)
     layout.addWidget(self.targetSVG, 0, 1)
     layout.addWidget(self.openDefaultView, 1, 0, 1, 5)
     app.translateUI(self)
Beispiel #22
0
    def __init__(self, *args):
        super(MyRecurrenceBox, self).__init__(*args)
        Lumberjack.info('spawning a << MyRecurrenceBox >>')
        _translate = QCoreApplication.translate

        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Raised)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")

        self.spinBox = QSpinBox(self)
        self.spinBox.setObjectName("spinBox")
        self.spinBox.setValue(1)
        self.verticalLayout.addWidget(self.spinBox)
        self.spinBox.valueChanged.connect(self.on_value_spin)

        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.dailyRadioButton = QRadioButton(self)
        self.dailyRadioButton.setObjectName("dailyRadioButton")
        self.horizontalLayout_2.addWidget(self.dailyRadioButton)
        self.dailyRadioButton.setText(_translate("Form", "Days"))
        self.dailyRadioButton.setChecked(True)
        self.selected_radio_button = self.dailyRadioButton
        self.dailyRadioButton.toggled.connect(self.on_radio_toggle)

        self.weeklyRadioButton = QRadioButton(self)
        self.weeklyRadioButton.setObjectName("weeklyRadioButton")
        self.horizontalLayout_2.addWidget(self.weeklyRadioButton)
        self.weeklyRadioButton.setText(_translate("Form", "Weeks"))
        self.weeklyRadioButton.toggled.connect(self.on_radio_toggle)

        self.monthlyRadioButton = QRadioButton(self)
        self.monthlyRadioButton.setObjectName("monthlyRadioButton")
        self.horizontalLayout_2.addWidget(self.monthlyRadioButton)
        self.monthlyRadioButton.setText(_translate("Form", "Months"))
        self.monthlyRadioButton.toggled.connect(self.on_radio_toggle)

        self.yearlyRadioButton = QRadioButton(self)
        self.yearlyRadioButton.setObjectName("yearlyRadioButton")
        self.horizontalLayout_2.addWidget(self.yearlyRadioButton)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.yearlyRadioButton.setText(_translate("Form", "Years"))
        self.yearlyRadioButton.toggled.connect(self.on_radio_toggle)

        self.radio_buttons = [self.dailyRadioButton,
                              self.weeklyRadioButton,
                              self.monthlyRadioButton,
                              self.yearlyRadioButton]
Beispiel #23
0
class NewValuesWidget(QGroupBox):
    def __init__(self, parent):
        super(NewValuesWidget, self).__init__(parent)

        self.new_rd = QRadioButton(self)
        self.new_sb = QSpinBox(self)
        self.system_missing = QRadioButton(self)
        self.copy_old_values = QRadioButton(self)
        self.grid = QGridLayout(self)

        self.ui()
        self.properties()

        self.new_rd.toggled.connect(self.new_rd_toggled)

    def new_rd_toggled(self, event):
        self.new_sb.setEnabled(event)

    def properties(self):
        self.setTitle("New Values")
        self.new_rd.setText("Value")
        self.system_missing.setText("System missing")
        self.copy_old_values.setText("Copy old values")

        self.new_rd.setChecked(True)

    def ui(self):
        self.grid.addWidget(self.new_rd, 0, 0, 1, 1, Qt.AlignTop)
        self.grid.addWidget(self.new_sb, 0, 1, 1, 9, Qt.AlignTop)
        self.grid.addWidget(self.system_missing, 1, 0, 1, 10, Qt.AlignTop)
        self.grid.addWidget(self.copy_old_values, 2, 0, 1, 10)
        self.grid.setSpacing(1)
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
Beispiel #24
0
 def createWidgets(self, layout):
     self.bookOutputInfo = QLabel(wordWrap=True)
     self.bookOutputLabel = QLabel()
     self.bookOutput = widgets.lineedit.LineEdit()
     self.bookOutputFileName = QRadioButton()
     self.bookOutputSuffix = QRadioButton(checked=True)
     
     layout.addWidget(self.bookOutputInfo)
     grid = QGridLayout(spacing=0)
     grid.addWidget(self.bookOutputLabel, 0, 0)
     grid.addWidget(self.bookOutput, 0, 1, 1, 2)
     grid.addWidget(self.bookOutputFileName, 1, 1)
     grid.addWidget(self.bookOutputSuffix, 1, 2)
     layout.addLayout(grid)
Beispiel #25
0
    def createTopRightGroupBox(self):
        self.topRightGroupBox = QGroupBox("Default Variable Type")
        self.nonNegConRadioButton = QRadioButton("Non Negative Continuous")
        self.nonNegIntRadioButton = QRadioButton("Non Negative Integer")
        self.binaryRadioButton = QRadioButton("Binary(0,1)")
        self.unrestrictedRadioButton = QRadioButton("Unrestricted")
        self.unrestrictedRadioButton.setChecked(True)

        layout = QVBoxLayout()
        layout.addWidget(self.nonNegConRadioButton)
        layout.addWidget(self.nonNegIntRadioButton)
        layout.addWidget(self.binaryRadioButton)
        layout.addWidget(self.unrestrictedRadioButton)

        self.topRightGroupBox.setLayout(layout)
Beispiel #26
0
    def __init__(self, font, parent=None):
        super().__init__(parent, Qt.Window)
        self._autoDirection = True
        self._font = font
        self._font.groups.addObserver(self, "_groupsChanged", "Groups.Changed")
        self._font.info.addObserver(self, "_fontInfoChanged", "Info.Changed")

        groups = self._font.groups
        self.groupsListView = GroupListView(self)
        self.groupsListView.setList(sorted(groups.keys()))
        self.groupsListView.setHeaderLabels(["Name"])
        self.groupsListView.alignmentChanged.connect(self._alignmentChanged)
        # self.groupsListView.groupDeleted.connect(self._groupDeleted)
        self.groupsListView.currentItemChanged.connect(self._groupChanged)
        self.groupsListView.valueChanged.connect(self._groupRenamed)

        self.stackWidget = GlyphStackWidget(self)

        self.addGroupButton = QPushButton("+", self)
        self.addGroupButton.clicked.connect(self._groupAdd)
        self.removeGroupButton = QPushButton("−", self)
        self.removeGroupButton.clicked.connect(self._groupDeleted)
        if not groups:
            self.removeGroupButton.setEnabled(False)

        self.alignLeftBox = QRadioButton(self.tr("Align left"), self)
        self.alignRightBox = QRadioButton(self.tr("Align right"), self)
        self.alignRightBox.toggled.connect(self._alignmentChanged)
        self.alignLeftBox.setChecked(True)

        self.groupCellView = GroupCellView(font, self)
        self.groupCellView.glyphsDropped.connect(self._glyphsDropped)
        self.groupCellView.selectionDeleted.connect(self._selectionDeleted)

        layout = QGridLayout(self)
        layout.addWidget(self.groupsListView, 0, 0, 5, 4)
        layout.addWidget(self.stackWidget, 0, 4, 5, 4)
        layout.addWidget(self.addGroupButton, 5, 0)
        layout.addWidget(self.removeGroupButton, 5, 3)
        layout.addWidget(self.alignLeftBox, 5, 4)
        layout.addWidget(self.alignRightBox, 5, 7)
        layout.addWidget(self.groupCellView, 6, 0, 4, 8)
        # TODO: calib this more
        layout.setColumnStretch(4, 1)
        self.setLayout(layout)

        self.adjustSize()
        self.updateWindowTitle(font=self._font)
Beispiel #27
0
    def initUI(self):
        self.widgetLayout = QHBoxLayout(self)
        self.playerGroup = QGroupBox(self)
        self.widgetLayout.addWidget(self.playerGroup)
        self.playerButtonGroup = QButtonGroup(self)
        self.playerGroupLayout = QGridLayout(self.playerGroup)

        b = QRadioButton("", self.playerGroup)
#        self.playerGroupLayout.addWidget(b)
        self.playerButtonGroup.addButton(b, 0)
        self.playerButtons = [b]
        b.hide()
        for i, player in enumerate(self.engine.getListPlayers(), 1):
            b = QRadioButton(
                '{}. {}'.format(i, player), self.playerGroup)
            if len(self.engine.getListPlayers()) > 2:
                self.playerGroupLayout.addWidget(b, (i-1) % 2, (i-1)/2)
            else:
                self.playerGroupLayout.addWidget(b, 0, (i-1) % 2)
            self.playerButtonGroup.addButton(b, i)
            self.playerButtons.append(b)

        self.kindGroup = QGroupBox(self)
        self.widgetLayout.addWidget(self.kindGroup)
        self.kindButtonGroup = QButtonGroup(self)
        self.kindGroupLayout = QGridLayout(self.kindGroup)

        b = QRadioButton("", self.kindGroup)
#        self.kindGroupLayout.addWidget(b)
        self.kindButtonGroup.addButton(b, 0)
        self.kindButtons = [b]
        b.hide()

        self.scoreSpinBox = ScoreSpinBox(self)
        self.scoreSpinBox.setAlignment(QtCore.Qt.AlignCenter)
        self.scoreSpinBox.setMaximumWidth(60)
        self.scoreSpinBox.setRange(0, 300)

        for i, kind in enumerate(self.engine.getEntryKinds(), 1):
            lbl = i18n("CarcassonneInputWidget", kind)
            b = QRadioButton('{}. {}'.format(i, lbl), self.kindGroup)
            self.kindGroupLayout.addWidget(b, (i-1) % 2, (i-1)/2)
            self.kindButtonGroup.addButton(b, i)
            b.clicked.connect(self.scoreSpinBox.setFocus)
            self.kindButtons.append(b)

        self.kindButtons[3].toggled.connect(self.setCloisterPoints)
        self.kindButtons[5].toggled.connect(self.setGoodsPoints)
        self.kindButtons[6].toggled.connect(self.setFairPoints)

        self.scoreGroup = QGroupBox(self)
        self.widgetLayout.addWidget(self.scoreGroup)
        self.scoreGroupLayout = QHBoxLayout(self.scoreGroup)

        self.scoreGroupLayout.addWidget(self.scoreSpinBox)

        self.reset()
        self.retranslateUI()
Beispiel #28
0
    def show_available_colormaps(self):
        height = 50

        selected = colormaps.read_selected_colormap_name_from_settings()
        for colormap_name in sorted(colormaps.maps.keys()):
            image = Spectrogram.create_colormap_image(colormap_name, height=height)
            rb = QRadioButton(colormap_name)
            rb.setObjectName(colormap_name)
            rb.setChecked(colormap_name == selected)
            rb.setIcon(QIcon(QPixmap.fromImage(image)))
            rb.setIconSize(QSize(256, height))
            self.ui.scrollAreaWidgetSpectrogramColormapContents.layout().addWidget(rb)
    def _create_libdmtx(self, settings):
        radio = QRadioButton('My objects are labelled with Data Matrix barcodes')
        radio.setChecked('libdmtx' == settings['engine'])
        radio.setEnabled(libdmtx_available())
        self._layout.addWidget(radio)

        prompt = QLabel(HTML_LINK_TEMPLATE.format(
            'Barcodes will be decoded using the open-source '
            '<a href="http://libdmtx.sourceforge.net/">libdmtx</a> library'
        ))
        prompt.setOpenExternalLinks(True)
        prompt.setStyleSheet(self.STYLESHEET)
        self._layout.addWidget(prompt)

        self._layout.addWidget(HorizontalLine())
        return radio
Beispiel #30
0
    def initUI(self):
        self.winnerButtonGroup = QButtonGroup()
        self.nobodyWinnerRadioButton = QRadioButton(self)
        self.nobodyWinnerRadioButton.hide()
        self.nobodyWinnerRadioButton.setChecked(True)
        self.winnerButtonGroup.addButton(self.nobodyWinnerRadioButton)

        players = self.engine.getListPlayers()
        if len(players) >= 4:
            players_grid = True
            self.widgetLayout = QGridLayout(self)
        else:
            players_grid = False
            self.widgetLayout = QVBoxLayout(self)
#             self.widgetLayout.addStretch()

        for np, player in enumerate(players):
            self.playerInputList[player] = Phase10PlayerWidget(
                player, self.engine, self.winnerButtonGroup, self)
            self.playerInputList[player].roundWinnerSet.connect(
                self.changedWinner)
            if players_grid:
                self.widgetLayout.addWidget(
                    self.playerInputList[player], np/2, np % 2)
            else:
                self.widgetLayout.addWidget(self.playerInputList[player])
Beispiel #31
0
 def setRadioButton(self, radioButton: QRadioButton, mode):
     radioButton.setAutoExclusive(False)
     if mode == 0:
         radioButton.setChecked(False)
     if mode == 1:
         radioButton.setChecked(True)
     if mode == 2:
         radioButton.setChecked(not radioButton.isChecked())
     radioButton.setAutoExclusive(True)
     QApplication.processEvents()
Beispiel #32
0
    def initWindow(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        # main layout
        frameWidget = QWidget()
        mainWidget = QSplitter(Qt.Horizontal)
        frameLayout = QVBoxLayout()
        self.settingWidget = QWidget()
        self.settingWidget.setProperty("class", "settingWidget")
        self.receiveSendWidget = QSplitter(Qt.Vertical)
        self.functionalWiget = QWidget()
        settingLayout = QVBoxLayout()
        sendReceiveLayout = QVBoxLayout()
        sendFunctionalLayout = QVBoxLayout()
        mainLayout = QHBoxLayout()
        self.settingWidget.setLayout(settingLayout)
        self.receiveSendWidget.setLayout(sendReceiveLayout)
        self.functionalWiget.setLayout(sendFunctionalLayout)
        mainLayout.addWidget(self.settingWidget)
        mainLayout.addWidget(self.receiveSendWidget)
        mainLayout.addWidget(self.functionalWiget)
        mainLayout.setStretch(0, 2)
        mainLayout.setStretch(1, 6)
        mainLayout.setStretch(2, 2)
        menuLayout = QHBoxLayout()
        mainWidget.setLayout(mainLayout)
        frameLayout.addLayout(menuLayout)
        frameLayout.addWidget(mainWidget)
        frameWidget.setLayout(frameLayout)
        self.setCentralWidget(frameWidget)

        # option layout
        self.settingsButton = QPushButton()
        self.skinButton = QPushButton("")
        # self.waveButton = QPushButton("")
        self.aboutButton = QPushButton()
        self.functionalButton = QPushButton()
        self.encodingCombobox = ComboBox()
        self.encodingCombobox.addItem("ASCII")
        self.encodingCombobox.addItem("UTF-8")
        self.encodingCombobox.addItem("UTF-16")
        self.encodingCombobox.addItem("GBK")
        self.encodingCombobox.addItem("GB2312")
        self.encodingCombobox.addItem("GB18030")
        self.settingsButton.setProperty("class", "menuItem1")
        self.skinButton.setProperty("class", "menuItem2")
        self.aboutButton.setProperty("class", "menuItem3")
        self.functionalButton.setProperty("class", "menuItem4")
        # self.waveButton.setProperty("class", "menuItem5")
        self.settingsButton.setObjectName("menuItem")
        self.skinButton.setObjectName("menuItem")
        self.aboutButton.setObjectName("menuItem")
        self.functionalButton.setObjectName("menuItem")
        # self.waveButton.setObjectName("menuItem")
        menuLayout.addWidget(self.settingsButton)
        menuLayout.addWidget(self.skinButton)
        # menuLayout.addWidget(self.waveButton)
        menuLayout.addWidget(self.aboutButton)
        menuLayout.addStretch(0)
        menuLayout.addWidget(self.encodingCombobox)
        menuLayout.addWidget(self.functionalButton)

        # widgets receive and send area
        self.receiveArea = QTextEdit()
        self.sendArea = QTextEdit()
        self.clearReceiveButtion = QPushButton(parameters.strClearReceive)
        self.sendButtion = QPushButton(parameters.strSend)
        self.sendHistory = ComboBox()
        sendWidget = QWidget()
        sendAreaWidgetsLayout = QHBoxLayout()
        sendWidget.setLayout(sendAreaWidgetsLayout)
        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.clearReceiveButtion)
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.sendButtion)
        sendAreaWidgetsLayout.addWidget(self.sendArea)
        sendAreaWidgetsLayout.addLayout(buttonLayout)
        sendReceiveLayout.addWidget(self.receiveArea)
        sendReceiveLayout.addWidget(sendWidget)
        sendReceiveLayout.addWidget(self.sendHistory)
        sendReceiveLayout.setStretch(0, 7)
        sendReceiveLayout.setStretch(1, 2)
        sendReceiveLayout.setStretch(2, 1)

        # widgets serial settings
        serialSettingsGroupBox = QGroupBox(parameters.strSerialSettings)
        serialSettingsLayout = QGridLayout()
        serialReceiveSettingsLayout = QGridLayout()
        serialSendSettingsLayout = QGridLayout()
        serialPortLabek = QLabel(parameters.strSerialPort)
        serailBaudrateLabel = QLabel(parameters.strSerialBaudrate)
        serailBytesLabel = QLabel(parameters.strSerialBytes)
        serailParityLabel = QLabel(parameters.strSerialParity)
        serailStopbitsLabel = QLabel(parameters.strSerialStopbits)
        self.serialPortCombobox = ComboBox()
        self.serailBaudrateCombobox = ComboBox()
        self.serailBaudrateCombobox.addItem("9600")
        self.serailBaudrateCombobox.addItem("19200")
        self.serailBaudrateCombobox.addItem("38400")
        self.serailBaudrateCombobox.addItem("57600")
        self.serailBaudrateCombobox.addItem("115200")
        self.serailBaudrateCombobox.setCurrentIndex(4)
        self.serailBaudrateCombobox.setEditable(True)
        self.serailBytesCombobox = ComboBox()
        self.serailBytesCombobox.addItem("5")
        self.serailBytesCombobox.addItem("6")
        self.serailBytesCombobox.addItem("7")
        self.serailBytesCombobox.addItem("8")
        self.serailBytesCombobox.setCurrentIndex(3)
        self.serailParityCombobox = ComboBox()
        self.serailParityCombobox.addItem("None")
        self.serailParityCombobox.addItem("Odd")
        self.serailParityCombobox.addItem("Even")
        self.serailParityCombobox.addItem("Mark")
        self.serailParityCombobox.addItem("Space")
        self.serailParityCombobox.setCurrentIndex(0)
        self.serailStopbitsCombobox = ComboBox()
        self.serailStopbitsCombobox.addItem("1")
        self.serailStopbitsCombobox.addItem("1.5")
        self.serailStopbitsCombobox.addItem("2")
        self.serailStopbitsCombobox.setCurrentIndex(0)
        self.checkBoxRts = QCheckBox("rts")
        self.checkBoxDtr = QCheckBox("dtr")
        self.serialOpenCloseButton = QPushButton(parameters.strOpen)
        serialSettingsLayout.addWidget(serialPortLabek, 0, 0)
        serialSettingsLayout.addWidget(serailBaudrateLabel, 1, 0)
        serialSettingsLayout.addWidget(serailBytesLabel, 2, 0)
        serialSettingsLayout.addWidget(serailParityLabel, 3, 0)
        serialSettingsLayout.addWidget(serailStopbitsLabel, 4, 0)
        serialSettingsLayout.addWidget(self.serialPortCombobox, 0, 1)
        serialSettingsLayout.addWidget(self.serailBaudrateCombobox, 1, 1)
        serialSettingsLayout.addWidget(self.serailBytesCombobox, 2, 1)
        serialSettingsLayout.addWidget(self.serailParityCombobox, 3, 1)
        serialSettingsLayout.addWidget(self.serailStopbitsCombobox, 4, 1)
        serialSettingsLayout.addWidget(self.checkBoxRts, 5, 0, 1, 1)
        serialSettingsLayout.addWidget(self.checkBoxDtr, 5, 1, 1, 1)
        serialSettingsLayout.addWidget(self.serialOpenCloseButton, 6, 0, 1, 2)
        serialSettingsGroupBox.setLayout(serialSettingsLayout)
        settingLayout.addWidget(serialSettingsGroupBox)

        # serial receive settings
        serialReceiveSettingsGroupBox = QGroupBox(
            parameters.strSerialReceiveSettings)
        self.receiveSettingsAscii = QRadioButton(parameters.strAscii)
        self.receiveSettingsHex = QRadioButton(parameters.strHex)
        self.receiveSettingsAscii.setChecked(True)
        self.receiveSettingsAutoLinefeed = QCheckBox(
            parameters.strAutoLinefeed)
        self.receiveSettingsAutoLinefeedTime = QLineEdit(
            parameters.strAutoLinefeedTime)
        self.receiveSettingsAutoLinefeed.setMaximumWidth(75)
        self.receiveSettingsAutoLinefeedTime.setMaximumWidth(75)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAscii, 1, 0,
                                              1, 1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsHex, 1, 1, 1,
                                              1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAutoLinefeed,
                                              2, 0, 1, 1)
        serialReceiveSettingsLayout.addWidget(
            self.receiveSettingsAutoLinefeedTime, 2, 1, 1, 1)
        serialReceiveSettingsGroupBox.setLayout(serialReceiveSettingsLayout)
        settingLayout.addWidget(serialReceiveSettingsGroupBox)

        # serial send settings
        serialSendSettingsGroupBox = QGroupBox(
            parameters.strSerialSendSettings)
        self.sendSettingsAscii = QRadioButton(parameters.strAscii)
        self.sendSettingsHex = QRadioButton(parameters.strHex)
        self.sendSettingsAscii.setChecked(True)
        self.sendSettingsScheduledCheckBox = QCheckBox(parameters.strScheduled)
        self.sendSettingsScheduled = QLineEdit(parameters.strScheduledTime)
        self.sendSettingsScheduledCheckBox.setMaximumWidth(75)
        self.sendSettingsScheduled.setMaximumWidth(75)
        self.sendSettingsCFLF = QCheckBox(parameters.strCRLF)
        self.sendSettingsCFLF.setChecked(False)
        serialSendSettingsLayout.addWidget(self.sendSettingsAscii, 1, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsHex, 1, 1, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsScheduledCheckBox,
                                           2, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsScheduled, 2, 1, 1,
                                           1)
        serialSendSettingsLayout.addWidget(self.sendSettingsCFLF, 3, 0, 1, 2)
        serialSendSettingsGroupBox.setLayout(serialSendSettingsLayout)
        settingLayout.addWidget(serialSendSettingsGroupBox)

        settingLayout.setStretch(0, 5)
        settingLayout.setStretch(1, 2.5)
        settingLayout.setStretch(2, 2.5)

        # right functional layout
        self.filePathWidget = QLineEdit()
        self.openFileButton = QPushButton("Open File")
        self.sendFileButton = QPushButton("Send File")
        self.clearHistoryButton = QPushButton("Clear History")
        self.addButton = QPushButton(parameters.strAdd)
        fileSendGroupBox = QGroupBox(parameters.strSendFile)
        fileSendGridLayout = QGridLayout()
        fileSendGridLayout.addWidget(self.filePathWidget, 0, 0, 1, 1)
        fileSendGridLayout.addWidget(self.openFileButton, 0, 1, 1, 1)
        fileSendGridLayout.addWidget(self.sendFileButton, 1, 0, 1, 2)
        fileSendGroupBox.setLayout(fileSendGridLayout)
        sendFunctionalLayout.addWidget(fileSendGroupBox)
        sendFunctionalLayout.addWidget(self.clearHistoryButton)
        sendFunctionalLayout.addWidget(self.addButton)
        sendFunctionalLayout.addStretch(1)
        self.isHideFunctinal = True
        self.hideFunctional()

        # main window
        self.statusBarStauts = QLabel()
        self.statusBarStauts.setMinimumWidth(80)
        self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                     ("#008200", parameters.strReady))
        self.statusBarSendCount = QLabel(parameters.strSend + "(bytes): " +
                                         "0")
        self.statusBarReceiveCount = QLabel(parameters.strReceive +
                                            "(bytes): " + "0")
        self.statusBar().addWidget(self.statusBarStauts)
        self.statusBar().addWidget(self.statusBarSendCount, 2)
        self.statusBar().addWidget(self.statusBarReceiveCount, 3)
        # self.statusBar()

        self.resize(800, 500)
        self.MoveToCenter()
        self.setWindowTitle(parameters.appName + " V" +
                            str(helpAbout.versionMajor) + "." +
                            str(helpAbout.versionMinor))
        icon = QIcon()
        print("icon path:" + self.DataPath + "/" + parameters.appIcon)
        icon.addPixmap(QPixmap(self.DataPath + "/" + parameters.appIcon),
                       QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        if sys.platform == "win32":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                "comtool")
        self.show()
        print("config file path:", os.getcwd() + "/comtool.settings.config")
Beispiel #33
0
        def __init__(self, parent=None, data=None):
            self.parent = parent
            self.data = data
            super().__init__(parent=self.parent)
            self.setWindowTitle('My WavelengthMeter')
            self.setWindowIcon(QIcon('icon.jpg'))
            self.plot_window1 = pg.PlotWidget()
            self.plot_window2 = pg.PlotWidget()
            # self.plot_window.plot(range(10),range(10))

            main_layout = QVBoxLayout()

            menu_layout = QHBoxLayout()
            chan_btn = QPushButton('Channels')
            chan_menu = QMenu(chan_btn)
            chan_menu.aboutToShow.connect(self.updateChannelsMenu)
            chan_btn.setMenu(chan_menu)
            menu_layout.addWidget(chan_btn)

            n_channels_per_line = QSpinBox()
            n_channels_per_line.setMinimum(2)
            n_channels_per_line.setMaximum(10)
            n_channels_per_line.setValue(self.data.n_channels)
            n_channels_per_line.valueChanged.connect(self.nCannelsChanged)
            menu_layout.addWidget(n_channels_per_line)

            menu_layout.addWidget(QLabel('per line'))

            menu_layout.addStretch(1)

            timer_len = QSpinBox()
            timer_len.setMinimum(10)
            timer_len.setMaximum(10000)
            timer_len.setValue(self.data.timer_interval)
            timer_len.valueChanged.connect(self.temerIntervalChanged)
            menu_layout.addWidget(timer_len)

            mode_group = QButtonGroup()
            self.all_btn = QRadioButton('all')
            self.all_btn.setChecked(self.data.mode=='all')
            self.all_btn.toggled.connect(self.modeChanged)
            mode_group.addButton(self.all_btn)
            menu_layout.addWidget(self.all_btn)

            self.single_btn = QRadioButton('single')
            self.single_btn.setChecked(self.data.mode != 'all')
            self.single_btn.toggled.connect(self.modeChanged)
            mode_group.addButton(self.single_btn)
            menu_layout.addWidget(self.single_btn)

            single_menu_btn = QPushButton('Single ch.')
            single_menu = QMenu(single_menu_btn)
            single_menu.aboutToShow.connect(self.updateSingleMenu)
            single_menu_btn.setMenu(single_menu)
            menu_layout.addWidget(single_menu_btn)

            main_layout.addLayout(menu_layout)

            main_layout.addWidget(self.plot_window1)
            main_layout.addWidget(self.plot_window2)

            self.channels_layout = QGridLayout()
            self.drawChannels()

            main_layout.addLayout(self.channels_layout)
            self.setLayout(main_layout)
            print('WLM_GUI created')
            self.timer = QTimer(self)
            self.timer.setInterval(self.data.timer_interval)
            self.timer.timeout.connect(self.routine)
            self.timer.start()
Beispiel #34
0
class ChromAbWidget(QWidget):
    def __init__(self, parent=None):
        super(ChromAbWidget, self).__init__(parent)

        self.maxD = 20
        self.deadZ = 5
        self.isShapeRadial = True
        self.isFalloffExp = True
        self.direction = 100

        self.shapeInfo = QLabel("Shape and Direction:", self)
        self.shapeChoice = QButtonGroup(self)
        self.shapeBtn1 = QRadioButton("Radial")
        self.shapeBtn2 = QRadioButton("Linear")
        self.shapeChoice.addButton(self.shapeBtn1)
        self.shapeChoice.addButton(self.shapeBtn2)
        self.shapeBtn1.setChecked(True)
        self.shapeBtn1.pressed.connect(self.changeShape1)
        self.shapeBtn2.pressed.connect(self.changeShape2)

        self.theDial = QDial()
        self.theDial.setMinimum(0)
        self.theDial.setMaximum(359)
        self.theDial.setValue(100)
        self.theDial.setWrapping(True)
        self.theDial.valueChanged.connect(self.updateDial)

        self.maxInfo = QLabel("Max Displacement: 20px", self)
        self.maxDisplace = QSlider(Qt.Horizontal, self)
        self.maxDisplace.setRange(1, 300)
        self.maxDisplace.setValue(20)
        self.maxDisplace.valueChanged.connect(self.updateMax)

        self.falloffInfo = QLabel("Falloff:", self)
        self.falloffChoice = QButtonGroup(self)
        self.foBtn1 = QRadioButton("Exponential")
        self.foBtn2 = QRadioButton("Linear")
        self.falloffChoice.addButton(self.foBtn1)
        self.falloffChoice.addButton(self.foBtn2)
        self.foBtn1.setChecked(True)
        self.foBtn1.pressed.connect(self.changeFalloff1)
        self.foBtn2.pressed.connect(self.changeFalloff2)

        self.deadInfo = QLabel("Deadzone: 5%", self)
        self.deadzone = QSlider(Qt.Horizontal, self)
        self.deadzone.setRange(0, 100)
        self.deadzone.setValue(5)
        self.deadzone.valueChanged.connect(self.updateDead)

        vbox = QVBoxLayout()
        vbox.addWidget(self.shapeInfo)
        vbox.addWidget(self.shapeBtn1)
        vbox.addWidget(self.shapeBtn2)
        vbox.addWidget(self.theDial)
        vbox.addWidget(self.maxInfo)
        vbox.addWidget(self.maxDisplace)
        vbox.addWidget(self.falloffInfo)
        vbox.addWidget(self.foBtn1)
        vbox.addWidget(self.foBtn2)
        vbox.addWidget(self.deadInfo)
        vbox.addWidget(self.deadzone)

        self.setLayout(vbox)
        self.show()

    # Update labels and members
    def updateMax(self, value):
        self.maxInfo.setText("Max Displacement: " + str(value) + "px")
        self.maxD = value

    def updateDead(self, value):
        self.deadInfo.setText("Deadzone: " + str(value) + "%")
        self.deadZ = value

    def changeShape1(self):
        self.isShapeRadial = True

    def changeShape2(self):
        self.isShapeRadial = False

    def changeFalloff1(self):
        self.isFalloffExp = True

    def changeFalloff2(self):
        self.isFalloffExp = False

    def updateDial(self, value):
        self.direction = value

    # Return the new color of the pixel at the specified index
    def applyOnePixel(self, coords, imgData, imgSize):
        baseColor = getColorAtIndex((coords[1] * imgSize[0]) + coords[0],
                                    imgData)
        # linear direction is easy
        if not self.isShapeRadial:
            displace = [
                -1 * math.sin(math.radians(self.direction)),
                math.cos(math.radians(self.direction))
            ]
            displace = scaleVect(displace, self.maxD)
        else:
            # get direction vector
            floatDeadzone = self.deadZ / 100
            center = ((imgSize[0] - 1) / 2, (imgSize[1] - 1) / 2)
            displace = addVect(coords, scaleVect(center, -1))
            # normalize, length of displace will be [0,1]
            displace = scaleVect(displace, 1 / lenVect(center))
            # if inside the deadzone, return original color
            if lenVect(displace) <= floatDeadzone:
                return baseColor
            else:
                # scale vector to 0 at the edge of deadzone, 1 at edge of screen
                displace = scaleVect(displace,
                                     (lenVect(displace) - floatDeadzone) *
                                     (1 / (1 - floatDeadzone)))
                # use exponential falloff
                if self.isFalloffExp:
                    displace = scaleVect(displace, lenVect(displace))
                # scale vector to final length based on max displacement
                displace = scaleVect(displace, self.maxD)
        # blend original green channel with blue and red from other pixels
        redChannel = sampleAt(addVect(coords, displace), imgData, imgSize)
        blueChannel = sampleAt(addVect(coords, scaleVect(displace, -1)),
                               imgData, imgSize)
        return [redChannel[0], baseColor[1], blueChannel[2], baseColor[3]]

    # Iterate over the image applying the filter
    def applyFilter(self, imgData, imgSize):
        newData = []
        idx = 0
        while idx < imgData.length():
            # convert to x,y coordinates
            coords = ((idx / 4) % imgSize[0], (idx / 4) // imgSize[0])
            newPixel = self.applyOnePixel(coords, imgData, imgSize)
            for i in range(4):
                # truncate to int
                newData.append(int(newPixel[i]))
            idx += 4
        return bytes(newData)
Beispiel #35
0
    def setupUi(self, Tab):
        Tab.setWindowTitle('OpenETran')

        # Project Tab
        self.Project = QWidget()
        grid = QGridLayout()

        save = QPushButton('Save')
        load = QPushButton('Load')

        # RadioButtons to select the simplified or full interface. Simplified selected by default
        guiSimple = QRadioButton('Simplified interface')
        guiNormal = QRadioButton('Full interface')

        guiSimple.setChecked(True)

        grid.addWidget(save, 0, 0)
        grid.addWidget(load, 0, 1)
        grid.addWidget(guiSimple, 0, 3)
        grid.addWidget(guiNormal, 0, 4)

        self.Project.setLayout(grid)
        Tab.addTab(self.Project, 'Project')

        # Simulation Tab
        self.Simulation = QWidget()
        grid = QGridLayout()
        self.Simulation.setLayout(grid)

        names = [
            'Number of conductors', '', 'Number of poles', '', 'Line Span (m)',
            '', 'Left Termination (1/0)', '', 'Right Termination (1/0)', '',
            'Time Step (s)', '', 'Simulation Max Time (s)', ''
        ]

        addWidgets(grid, names, 7, 2)

        simulate = QPushButton('Simulate !')
        grid.addWidget(simulate, 0, 3)

        # RadioButtons for the simulation mode - One shot mode is selected by default
        plotMode = QRadioButton('One shot mode simulation')
        plotMode.setChecked(True)
        grid.addWidget(plotMode, 1, 3)

        critMode = QRadioButton('Critical current iteration simulation')
        grid.addWidget(critMode, 2, 3)

        # LineEdit fields for Critical current iteration mode
        pole1 = QLineEdit()
        pole2 = QLineEdit()
        wire = QLineEdit()

        pole1_text = QLabel('First pole to hit')
        pole2_text = QLabel('Last pole to hit')
        wire_text = QLabel('Wire sequence')

        Tab.addTab(self.Simulation, 'Simulation')

        # Conductor Tab
        self.Conductor = QWidget()
        grid = QGridLayout()
        self.Conductor.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Conductor', '/', '/', '/', 'Number',
            '', 'Height (m)', '', 'Horizontal Position (m)', '', 'Radius (m)',
            '', 'Voltage Bias (V)', '', 'Sag (m)', '', 'Nb', '', 'Sb (m)', ''
        ]

        addWidgets(grid, names, 6, 4)

        Tab.addTab(self.Conductor, 'Conductors')

        # Label Tab
        self.Label = QWidget()
        grid = QGridLayout()
        self.Label.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Label', '/', '/', '/', 'Type', '//',
            'Element number', '', 'Name', '', '/', '/'
        ]

        positions = [(i, j) for i in range(4) for j in range(4)]
        for position, name in zip(positions, names):
            if name == '':
                widget = QLineEdit()

            elif name == 'New' or name == 'Delete':
                widget = QPushButton(name)

            elif name == '/':
                widget = QLabel()

            elif name == '//':
                widget = QComboBox()
                widget.addItem('Phase')
                widget.addItem('Pole')

            else:
                widget = QLabel(name)

            grid.addWidget(widget, *position)

        Tab.addTab(self.Label, 'Labels')

        # Ground Tab
        self.Ground = QWidget()
        grid = QGridLayout()
        self.Ground.setLayout(grid)

        names = [
            'New', 'Delete', 'Get Counterpoise R60', '/', '/', '/', 'Ground',
            '/', '/', '/', '/', '/', 'R60 (Ohm)', '', 'Resistivity (Ohm.m)',
            '', 'Soil Breakdown Gradient (V.m)', '400e+03',
            'Downlead Inductance (H/m)', '', 'Length of downlead (m)', '',
            'Counterpoise radius (m)', '', 'Counterpoise depth (m)', '',
            'Counterpoise length (m)', '', 'Number of segments', '',
            'Soil relative permittivity', '', 'Pairs', '', 'Poles', ''
        ]

        addWidgets(grid, names, 6, 6)

        Tab.addTab(self.Ground, 'Ground')

        # Surge Tab with surge parameters
        self.Surge = QWidget()
        grid = QGridLayout()
        self.Surge.setLayout(grid)

        names = [
            'Crest Current (A)', '', '30-90 Front Time (s)', '',
            '50% Fail Time (s)', '', 'Surge Starting Time (s)', '', 'Pairs',
            '', 'Poles', ''
        ]

        addWidgets(grid, names, 6, 2)

        Tab.addTab(self.Surge, 'Surge')

        # Steepfront Tab - not added by default (not part of simplified interface)
        self.Steepfront = QWidget()
        grid = QGridLayout()
        self.Steepfront.setLayout(grid)

        names = [
            'Crest Current (A)', '', '30-90 Front Time (s)', '',
            '50% Fail Time (s)', '', 'Surge Starting Time (s)', '',
            'Max Current Steepness (per unit)', '', 'Pairs', '', 'Poles', ''
        ]

        addWidgets(grid, names, 7, 2)

        # Arrester Tab - not added by default (not part of simplified interface)
        self.Arrester = QWidget()
        grid = QGridLayout()
        self.Arrester.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Arrester', '/', '/', '/',
            'Sparkover voltage (V)', '', 'Turn-on voltage (V)', '',
            'Characteristic"s slope (Ohm)', '', 'Inductance of lead (H/m)', '',
            'Lead length (m)', '', 'Pairs', '', 'Poles', '', '/', '/'
        ]

        addWidgets(grid, names, 6, 4)

        # Arrbez Tab
        self.Arrbez = QWidget()
        grid = QGridLayout()
        self.Arrbez.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Arrbez', '/', '/', '/',
            'Sparkover voltage (V)', '', '10kA 8x20 discharge voltage (V)', '',
            'Reference voltage (p.u)', '0.051', 'Inductance of lead (H/m)', '',
            'Lead length (m)', '', 'Plot arrester current ? (1/0)', '',
            'Pairs', '', 'Poles', ''
        ]

        addWidgets(grid, names, 6, 4)

        Tab.addTab(self.Arrbez, 'Arrbez')

        # Insulator Tab - not added by default (not part of simplified interface)
        self.Insulator = QWidget()
        grid = QGridLayout()
        self.Insulator.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Insulator', '/', '/', '/', 'CFO (V)',
            '', 'Minimum volt. for destructive effects (V)', '',
            'beta (no unit)', '', 'DE', '', 'Pairs', '', 'Poles', ''
        ]

        addWidgets(grid, names, 5, 4)

        # LPM Tab
        self.LPM = QWidget()

        grid = QGridLayout()
        self.LPM.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'LPM', '/', '/', '/', 'CFO (V)', '',
            'E0 (V/m)', '535e+03', 'Kl (no unit)', '7.785e-07', 'Pairs', '',
            'Poles', '', '/', '/'
        ]

        addWidgets(grid, names, 5, 4)

        Tab.addTab(self.LPM, 'LPM')

        # Meter Tab
        self.Meter = QWidget()
        grid = QGridLayout()
        self.Meter.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Meter', '/', '/', '/', 'Type', '//',
            'Pairs', '', 'Poles', '', '/', '/'
        ]

        positions = [(i, j) for i in range(4) for j in range(4)]
        for position, name in zip(positions, names):
            if name == '':
                widget = QLineEdit()

            elif name == 'New' or name == 'Delete':
                widget = QPushButton(name)

            elif name == '/':
                widget = QLabel()

            elif name == '//':
                widget = QComboBox()
                widget.addItem('Voltage')
                widget.addItem('Arrester/Arrbez current')
                widget.addItem('Ground current')
                widget.addItem('Customer house current')
                widget.addItem('Transformer X2 term. current')
                widget.addItem('Pipegap current')

            else:
                widget = QLabel(name)

            grid.addWidget(widget, *position)

        Tab.addTab(self.Meter, 'Meter')

        # Resistor Tab - not added by default (not part of simplified interface)
        self.Resistor = QWidget()
        grid = QGridLayout()
        self.Resistor.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Resistor', '/', '/', '/',
            'Value (Ohm)', '', 'Pairs', '', 'Poles', '', '/', '/'
        ]

        addWidgets(grid, names, 4, 4)
        Tab.addTab(self.Resistor, 'Resistor')

        # Capacitor Tab - not added by default (not part of simplified interface)
        self.Capacitor = QWidget()
        grid = QGridLayout()
        self.Capacitor.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Capacitor', '/', '/', '/', 'Value (F)',
            '', 'Pairs', '', 'Poles', '', '/', '/'
        ]

        addWidgets(grid, names, 4, 4)

        # Inductor Tab
        self.Inductor = QWidget()
        grid = QGridLayout()
        self.Inductor.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Inductor', '/', '/', '/',
            'Series resistance (Ohm)', '', 'Value (H)', '', 'Pairs', '',
            'Poles', ''
        ]

        addWidgets(grid, names, 4, 4)

        # Customer Tab - not added by default (not part of simplified interface)
        self.Customer = QWidget()
        grid = QGridLayout()
        self.Customer.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', '/', '/', 'Customer', '/', '/', '/',
            '/', '/', 'Rhg (Ohm)', '', 'Soil resistivity (Ohm.m)', '',
            'E0 (V/m)', '', 'Lhg (H/m)', '', 'Ground lead length (m)', '',
            'Transf. turns ratio', '', 'Lp (H)', '', 'Ls1 (H)', '', 'Ls2 (H)',
            '', 'Lcm (H/m)', '', 'rA (m)', '', 'rN (m)', '', 'Dan (m)', '',
            'Daa (m)', '', 'Service drop length (m)', '', 'Pairs', '', 'Poles',
            '', '/', '/'
        ]

        addWidgets(grid, names, 8, 6)

        # Pipegap Tab - not added by default (not part of simplified interface)
        self.Pipegap = QWidget()
        grid = QGridLayout()
        self.Pipegap.setLayout(grid)

        names = [
            'New', 'Delete', '/', '/', 'Pipegap', '/', '/', '/',
            'CFO between conductors (V)', '', 'Series resistance (Ohm)', '',
            'Pairs', '', 'Poles', ''
        ]

        addWidgets(grid, names, 4, 4)

        @pyqtSlot()
        def dispNormal():
            if guiNormal.isChecked() == True:
                Tab.addTab(self.Steepfront, 'Steepfront')
                Tab.addTab(self.Arrester, 'Arrester')
                Tab.addTab(self.Insulator, 'Insulator')
                # Tab.addTab(self.Resistor, 'Resistor')
                Tab.addTab(self.Capacitor, 'Capacitor')
                Tab.addTab(self.Inductor, 'Inductor')
                Tab.addTab(self.Customer, 'Customer')
                Tab.addTab(self.Pipegap, 'Pipegap')

        @pyqtSlot()
        def dispSimple():
            if guiSimple.isChecked() == True:
                Tab.removeTab(Tab.indexOf(self.Steepfront))
                Tab.removeTab(Tab.indexOf(self.Arrester))
                Tab.removeTab(Tab.indexOf(self.Insulator))
                # Tab.removeTab( Tab.indexOf(self.Resistor) )
                Tab.removeTab(Tab.indexOf(self.Capacitor))
                Tab.removeTab(Tab.indexOf(self.Inductor))
                Tab.removeTab(Tab.indexOf(self.Customer))
                Tab.removeTab(Tab.indexOf(self.Pipegap))

        @pyqtSlot()
        def simOneShot():
            if plotMode.isChecked() == True:
                pole1.setParent(None)
                pole2.setParent(None)
                wire.setParent(None)

                pole1_text.setParent(None)
                pole2_text.setParent(None)
                wire_text.setParent(None)

        @pyqtSlot()
        def simCrit():
            if critMode.isChecked() == True:
                grid = self.Simulation.layout()
                grid.addWidget(pole1_text, 7, 0)
                grid.addWidget(pole2_text, 8, 0)
                grid.addWidget(wire_text, 9, 0)

                grid.addWidget(pole1, 7, 1)
                grid.addWidget(pole2, 8, 1)
                grid.addWidget(wire, 9, 1)

        @pyqtSlot()
        def simulateProject():
            openetran = saveProject()
            Project.simulateProject(plotMode, self, openetran)

        @pyqtSlot()
        def saveProject():
            # Read the structure in the GUI in case it changed
            openetran = ReadStruct.read(self, guiNormal)
            self.lastDirectory = Project.saveProject(self, openetran,
                                                     self.lastDirectory)

            return openetran

        @pyqtSlot()
        def loadProject():
            self.lastDirectory = Project.loadProject(self, guiNormal,
                                                     self.lastDirectory)

        @pyqtSlot()
        def newConductor():
            Add_Delete_Widgets.addConductor(self, self.Conductor.layout())

        @pyqtSlot()
        def deleteConductor():
            Add_Delete_Widgets.deleteConductor(self, self.Conductor.layout())

        @pyqtSlot()
        def newGround():
            Add_Delete_Widgets.addGround(self, self.Ground.layout())

        @pyqtSlot()
        def deleteGround():
            Add_Delete_Widgets.deleteGround(self, self.Ground.layout())

        @pyqtSlot()
        def calculateR60():
            openetran = ReadStruct.read(self, guiNormal)
            R60.calcR60(openetran, self.Ground.layout())

        @pyqtSlot()
        def newArrester():
            Add_Delete_Widgets.addArrester(self, self.Arrester.layout())

        @pyqtSlot()
        def deleteArrester():
            Add_Delete_Widgets.deleteArrester(self, self.Arrester.layout())

        @pyqtSlot()
        def newArrbez():
            Add_Delete_Widgets.addArrbez(self, self.Arrbez.layout())

        @pyqtSlot()
        def deleteArrbez():
            Add_Delete_Widgets.deleteArrbez(self, self.Arrbez.layout())

        @pyqtSlot()
        def newInsulator():
            Add_Delete_Widgets.addInsulator(self, self.Insulator.layout())

        @pyqtSlot()
        def deleteInsulator():
            Add_Delete_Widgets.deleteInsulator(self, self.Insulator.layout())

        @pyqtSlot()
        def newLPM():
            Add_Delete_Widgets.addLPM(self, self.LPM.layout())

        @pyqtSlot()
        def deleteLPM():
            Add_Delete_Widgets.deleteLPM(self, self.LPM.layout())

        @pyqtSlot()
        def newMeter():
            Add_Delete_Widgets.addMeter(self, self.Meter.layout())

        @pyqtSlot()
        def deleteMeter():
            Add_Delete_Widgets.deleteMeter(self, self.Meter.layout())

        @pyqtSlot()
        def newLabel():
            Add_Delete_Widgets.addLabel(self, self.Label.layout())

        @pyqtSlot()
        def deleteLabel():
            Add_Delete_Widgets.deleteLabel(self, self.Label.layout())

        @pyqtSlot()
        def newResistor():
            Add_Delete_Widgets.addResistor(self, self.Resistor.layout())

        @pyqtSlot()
        def deleteResistor():
            Add_Delete_Widgets.deleteResistor(self, self.Resistor.layout())

        @pyqtSlot()
        def newCapacitor():
            Add_Delete_Widgets.addCapacitor(self, self.Capacitor.layout())

        @pyqtSlot()
        def deleteCapacitor():
            Add_Delete_Widgets.deleteCapacitor(self, self.Capacitor.layout())

        @pyqtSlot()
        def newInductor():
            Add_Delete_Widgets.addInductor(self, self.Inductor.layout())

        @pyqtSlot()
        def deleteInductor():
            Add_Delete_Widgets.deleteInductor(self, self.Inductor.layout())

        @pyqtSlot()
        def newCustomer():
            Add_Delete_Widgets.addCustomer(self, self.Customer.layout())

        @pyqtSlot()
        def deleteCustomer():
            Add_Delete_Widgets.deleteCustomer(self, self.Customer.layout())

        @pyqtSlot()
        def newPipegap():
            Add_Delete_Widgets.addPipegap(self, self.Pipegap.layout())

        @pyqtSlot()
        def deletePipegap():
            Add_Delete_Widgets.deletePipegap(self, self.Pipegap.layout())

        # Connect buttons to each actions
        save.pressed.connect(saveProject)
        load.pressed.connect(loadProject)
        simulate.pressed.connect(simulateProject)

        # Conductor
        layout = self.Conductor.layout()
        connectButtons(layout, newConductor, deleteConductor)

        # Ground
        layout = self.Ground.layout()
        connectButtons(layout, newGround, deleteGround)

        calcR60 = layout.itemAtPosition(0, 2).widget()
        calcR60.pressed.connect(calculateR60)

        # Arrester
        layout = self.Arrester.layout()
        connectButtons(layout, newArrester, deleteArrester)

        # Arrbez
        layout = self.Arrbez.layout()
        connectButtons(layout, newArrbez, deleteArrbez)

        # Insulator
        layout = self.Insulator.layout()
        connectButtons(layout, newInsulator, deleteInsulator)

        # LPM
        layout = self.LPM.layout()
        connectButtons(layout, newLPM, deleteLPM)

        # Meter
        layout = self.Meter.layout()
        connectButtons(layout, newMeter, deleteMeter)

        # Labels
        layout = self.Label.layout()
        connectButtons(layout, newLabel, deleteLabel)

        # Resistor
        layout = self.Resistor.layout()
        connectButtons(layout, newResistor, deleteResistor)

        # Capacitor
        layout = self.Capacitor.layout()
        connectButtons(layout, newCapacitor, deleteCapacitor)

        # Inductor
        layout = self.Inductor.layout()
        connectButtons(layout, newInductor, deleteInductor)

        # Customer
        layout = self.Customer.layout()
        connectButtons(layout, newCustomer, deleteCustomer)

        # Pipegap
        layout = self.Pipegap.layout()
        connectButtons(layout, newPipegap, deletePipegap)

        # RadioButtons
        guiSimple.toggled.connect(dispSimple)
        guiNormal.toggled.connect(dispNormal)

        plotMode.toggled.connect(simOneShot)
        critMode.toggled.connect(simCrit)
    def init_ui(self):
        # 设置窗体无边框
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setFixedSize(500, 600)
        # 设置背景透明
        self.setAttribute(Qt.WA_TranslucentBackground)
        parent_grid = QVBoxLayout()
        parent_grid.setSpacing(0)
        self.setLayout(parent_grid)

        top_grid_widget = QWidget(self)
        top_grid_widget.setObjectName("top_widget")
        top_grid = QGridLayout()
        top_grid_widget.setLayout(top_grid)
        top_grid_widget.setFixedHeight(40)
        top_grid.setSpacing(0)
        top_grid.setContentsMargins(0, 0, 0, 0)
        top_grid.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        top_grid_widget.setStyleSheet(
            "#top_widget{background:#434343;border-top-right-radius: 5px;border-top-left-radius: 5px}"
        )


        close_btn_style = r'QPushButton{border:solid 0px grey;width:40px;height:40px;border-radius:0px;color:white;}' \
                     r'QPushButton:hover{background-color:rgb(220,20,60); border-style: inset; }'
        min_btn_style = r'QPushButton{border:solid 0px grey;width:40px;height:40px;border-radius:0px;color:white;}' \
                          r'QPushButton:hover{background-color:rgb(220,220,220); border-style: inset; }'
        close_btn = QPushButton(top_grid_widget)
        close_btn.setText("X")
        close_btn.setStyleSheet(close_btn_style)
        close_btn.setContentsMargins(0, 0, 0, 0)
        close_btn.clicked.connect(self.close_dialog)
        min_btn = QPushButton(top_grid_widget)
        min_btn.setText("-")
        min_btn.setStyleSheet(min_btn_style)
        min_btn.setContentsMargins(0, 0, 0, 0)
        min_btn.clicked.connect(self.showMinimized)
        title_label = QLabel(top_grid_widget)
        title_label.setText("采集设置")
        title_label.setStyleSheet(
            "QLabel{font:bold;color:white;margin-right:125}")

        top_grid.addWidget(close_btn, 0, 2, 1, 1)
        top_grid.addWidget(min_btn, 0, 1, 1, 1)
        top_grid.addWidget(title_label, 0, 0, 1, 1)

        button_grid_widget = QWidget(self)
        button_grid = QGridLayout()
        button_grid_widget.setLayout(button_grid)
        button_grid_widget.setStyleSheet("QWidget{background:#F5F5F5}")
        button_grid.setSpacing(20)
        button_grid.setContentsMargins(35, 30, 0, 0)
        button_grid.setAlignment(Qt.AlignTop | Qt.AlignLeft)

        yr_label = QLabel(button_grid_widget)
        yr_label.setText("导航动态渲染")
        yr_label.setStyleSheet("font:bold;")
        yr_buttonGroup = QButtonGroup(button_grid_widget)
        self.yr_yes = QRadioButton('是')
        self.yr_no = QRadioButton('否')
        self.yr_no.setChecked(True)
        yr_buttonGroup.addButton(self.yr_yes)
        yr_buttonGroup.addButton(self.yr_no)

        detail_yr_label = QLabel(button_grid_widget)
        detail_yr_label.setText("详情动态渲染")
        detail_yr_label.setStyleSheet("font:bold;")
        detail_yr_buttonGroup = QButtonGroup(button_grid_widget)
        self.detail_yr_yes = QRadioButton('是')
        self.detail_yr_no = QRadioButton('否')
        self.detail_yr_no.setChecked(True)
        detail_yr_buttonGroup.addButton(self.detail_yr_yes)
        detail_yr_buttonGroup.addButton(self.detail_yr_no)

        ip_label = QLabel(button_grid_widget)
        ip_label.setText("使用IP代理")
        ip_label.setStyleSheet("font:bold;")
        ip_buttonGroup = QButtonGroup(button_grid_widget)
        self.ip_yes = QRadioButton('是')
        self.ip_no = QRadioButton('否')
        self.ip_yes.setChecked(True)
        ip_buttonGroup.addButton(self.ip_yes)
        ip_buttonGroup.addButton(self.ip_no)

        ua_label = QLabel(button_grid_widget)
        ua_label.setText("用户代理(UA)")
        ua_label.setStyleSheet("font:bold;")
        ua_buttonGroup = QButtonGroup(button_grid_widget)
        self.ua_default = QRadioButton('默认')
        self.ua_random = QRadioButton('随机')
        self.ua_default.setChecked(True)
        ua_buttonGroup.addButton(self.ua_default)
        ua_buttonGroup.addButton(self.ua_random)
        ua_pool_btn = QPushButton(button_grid_widget)
        ua_pool_btn.setText("UA池")
        self.us_default_value = QTextEdit(button_grid_widget)

        navi_thread_label = QLabel(button_grid_widget)
        navi_thread_label.setText("导航线程数")
        navi_thread_label.setStyleSheet("font:bold;")

        self.navi_thread_num = QSpinBox(button_grid_widget)
        self.navi_thread_num.setStyleSheet(
            r'QSpinBox{height:30;width:50;background:white}')

        detail_thread_label = QLabel(button_grid_widget)
        detail_thread_label.setText("详情线程数")
        detail_thread_label.setStyleSheet("font:bold;")

        self.detail_thread_num = QSpinBox(button_grid_widget)
        self.detail_thread_num.setStyleSheet(
            r'QSpinBox{height:30;width:50;background:white}')

        self.saveBtn = QPushButton(button_grid_widget)
        self.saveBtn.setText("确定")
        self.saveBtn.setStyleSheet(
            r'QPushButton{background-color:#6495ED;color:white}')
        self.saveBtn.clicked.connect(self.save_setting)
        self.cancelBtn = QPushButton(button_grid_widget)
        self.cancelBtn.setText("取消")
        self.cancelBtn.setStyleSheet(
            r'QPushButton{background-color:grey;color:white}')
        self.cancelBtn.clicked.connect(self.close_dialog)

        button_grid.addWidget(ip_label, 0, 0, 1, 1)
        button_grid.addWidget(self.ip_yes, 0, 1, 1, 1)
        button_grid.addWidget(self.ip_no, 0, 2, 1, 1)

        button_grid.addWidget(yr_label, 1, 0, 1, 1)
        button_grid.addWidget(self.yr_yes, 1, 1, 1, 1)
        button_grid.addWidget(self.yr_no, 1, 2, 1, 1)

        button_grid.addWidget(detail_yr_label, 2, 0, 1, 1)
        button_grid.addWidget(self.detail_yr_yes, 2, 1, 1, 1)
        button_grid.addWidget(self.detail_yr_no, 2, 2, 1, 1)

        button_grid.addWidget(ua_label, 3, 0, 1, 1)
        button_grid.addWidget(self.ua_default, 3, 1, 1, 1)
        button_grid.addWidget(self.ua_random, 3, 2, 1, 1)
        button_grid.addWidget(ua_pool_btn, 3, 3, 1, 1)

        button_grid.addWidget(self.us_default_value, 4, 0, 1, 4)

        button_grid.addWidget(navi_thread_label, 5, 0, 1, 1)
        button_grid.addWidget(self.navi_thread_num, 5, 1, 1, 1)

        button_grid.addWidget(detail_thread_label, 5, 2, 1, 1)
        button_grid.addWidget(self.detail_thread_num, 5, 3, 1, 1)

        button_grid.addWidget(self.saveBtn, 7, 2, 1, 1)
        button_grid.addWidget(self.cancelBtn, 7, 3, 1, 1)

        button_grid.setRowStretch(0, 1)
        button_grid.setRowStretch(1, 1)
        button_grid.setRowStretch(2, 1)
        button_grid.setRowStretch(3, 2)
        button_grid.setRowStretch(4, 1)
        button_grid.setRowStretch(5, 1)
        button_grid.setRowStretch(6, 1)
        button_grid.setRowStretch(7, 1)
        button_grid.setRowStretch(8, 1)

        parent_grid.addWidget(top_grid_widget)
        parent_grid.addWidget(button_grid_widget)

        self.load_data()
Beispiel #37
0
    def create_connection_pane(self):
        """Create the pane that allows the user to initiate a connection"""

        # choose listener or client radio buttons
        rad_listen = QRadioButton('Wait for a connection')
        rad_connect = QRadioButton('Connect to...')
        rad_help = QRadioButton('HELP')  # help button

        rad_listen.setChecked(True)

        # Hideable listen pane

        # displays the IP address of the user
        lbl_ip_address = QLabel(Network.get_ip())

        # for the user to listen for an incoming connection
        btn_listen = QPushButton('Wait for connection')
        btn_listen.clicked.connect(self.btn_listen_clicked)

        listen_pane = make_container_widget([lbl_ip_address, btn_listen])

        # for the user to type an IP address and connect to it
        lbl_connect_address = QLabel('IP address')
        inp_connect_address = QLineEdit()
        inp_connect_address.setText('localhost')

        btn_connect = QPushButton('Connect')
        btn_connect.clicked.connect(self.btn_connect_clicked)

        connect_pane = make_container_widget(
            [lbl_connect_address, inp_connect_address, btn_connect])

        # assemble everything into a container
        show_help = QTextEdit()
        show_help.setText(
            'Hi player, wait for connection means that the interface is actively listening for connections to the other side\n\n\n connect to... means that it can connect to another player\n here is a URL to help see the instructions for the game: https://github.com/pramjoshcyb/Peer-to-Peer/blob/master/README.md'
        )
        help_pane = make_container_widget([show_help])
        connection_pane = make_container_widget([
            rad_listen, rad_connect, rad_help, listen_pane, connect_pane,
            help_pane
        ])

        # set up the radio buttons to control which pane is visible
        def show_listen_pane():
            """method to show the pane to listen to connections"""
            connect_pane.hide()
            connection_pane.adjustSize()
            listen_pane.show()
            help_pane.hide()

        def show_client_pane():
            """ method to show the client panes"""
            listen_pane.hide()
            connection_pane.adjustSize()
            connect_pane.show()
            help_pane.hide()

        def show_help_pane():
            """ method to show the help pane"""
            listen_pane.hide()
            connection_pane.adjustSize()
            connect_pane.hide()
            help_pane.show()

        rad_listen.clicked.connect(show_listen_pane)
        rad_connect.clicked.connect(show_client_pane)
        rad_help.clicked.connect(show_help_pane)

        show_listen_pane()

        self.connection_pane = connection_pane
        self.inp_connect_address = inp_connect_address
Beispiel #38
0
    def request_trezor_init_settings(self, wizard, method, device_id):
        vbox = QVBoxLayout()
        next_enabled = True

        devmgr = self.device_manager()
        client = devmgr.client_by_id(device_id)
        if not client:
            raise Exception(_("The device was disconnected."))
        model = client.get_trezor_model()
        fw_version = client.client.version
        capabilities = client.client.features.capabilities
        have_shamir = Capability.Shamir in capabilities

        # label
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        # Backup type
        gb_backuptype = QGroupBox()
        hbox_backuptype = QHBoxLayout()
        gb_backuptype.setLayout(hbox_backuptype)
        vbox.addWidget(gb_backuptype)
        gb_backuptype.setTitle(_('Select backup type:'))
        bg_backuptype = QButtonGroup()

        rb_single = QRadioButton(gb_backuptype)
        rb_single.setText(_('Single seed (BIP39)'))
        bg_backuptype.addButton(rb_single)
        bg_backuptype.setId(rb_single, BackupType.Bip39)
        hbox_backuptype.addWidget(rb_single)
        rb_single.setChecked(True)

        rb_shamir = QRadioButton(gb_backuptype)
        rb_shamir.setText(_('Shamir'))
        bg_backuptype.addButton(rb_shamir)
        bg_backuptype.setId(rb_shamir, BackupType.Slip39_Basic)
        hbox_backuptype.addWidget(rb_shamir)
        rb_shamir.setEnabled(Capability.Shamir in capabilities)
        rb_shamir.setVisible(False)  # visible with "expert settings"

        rb_shamir_groups = QRadioButton(gb_backuptype)
        rb_shamir_groups.setText(_('Super Shamir'))
        bg_backuptype.addButton(rb_shamir_groups)
        bg_backuptype.setId(rb_shamir_groups, BackupType.Slip39_Advanced)
        hbox_backuptype.addWidget(rb_shamir_groups)
        rb_shamir_groups.setEnabled(Capability.ShamirGroups in capabilities)
        rb_shamir_groups.setVisible(False)  # visible with "expert settings"

        # word count
        word_count_buttons = {}

        gb_numwords = QGroupBox()
        hbox1 = QHBoxLayout()
        gb_numwords.setLayout(hbox1)
        vbox.addWidget(gb_numwords)
        gb_numwords.setTitle(_("Select seed/share length:"))
        bg_numwords = QButtonGroup()
        for count in (12, 18, 20, 24, 33):
            rb = QRadioButton(gb_numwords)
            word_count_buttons[count] = rb
            rb.setText(_("{:d} words").format(count))
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, count)
            hbox1.addWidget(rb)
            rb.setChecked(True)

        def configure_word_counts():
            if model == "1":
                checked_wordcount = 24
            else:
                checked_wordcount = 12

            if method == TIM_RECOVER:
                if have_shamir:
                    valid_word_counts = (12, 18, 20, 24, 33)
                else:
                    valid_word_counts = (12, 18, 24)
            elif rb_single.isChecked():
                valid_word_counts = (12, 18, 24)
                gb_numwords.setTitle(_('Select seed length:'))
            else:
                valid_word_counts = (20, 33)
                checked_wordcount = 20
                gb_numwords.setTitle(_('Select share length:'))

            word_count_buttons[checked_wordcount].setChecked(True)
            for c, btn in word_count_buttons.items():
                btn.setVisible(c in valid_word_counts)

        bg_backuptype.buttonClicked.connect(configure_word_counts)
        configure_word_counts()

        # set up conditional visibility:
        # 1. backup_type is only visible when creating new seed
        gb_backuptype.setVisible(method == TIM_NEW)
        # 2. word_count is not visible when recovering on TT
        if method == TIM_RECOVER and model != "1":
            gb_numwords.setVisible(False)

        # PIN
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)
        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        # "expert settings" button
        expert_vbox = QVBoxLayout()
        expert_widget = QWidget()
        expert_widget.setLayout(expert_vbox)
        expert_widget.setVisible(False)
        expert_button = QPushButton(_("Show expert settings"))

        def show_expert_settings():
            expert_button.setVisible(False)
            expert_widget.setVisible(True)
            rb_shamir.setVisible(True)
            rb_shamir_groups.setVisible(True)

        expert_button.clicked.connect(show_expert_settings)
        vbox.addWidget(expert_button)

        # passphrase
        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        expert_vbox.addWidget(passphrase_msg)
        expert_vbox.addWidget(passphrase_warning)
        expert_vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        bg_rectype = None
        if method == TIM_RECOVER and model == '1':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            expert_vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RecoveryDeviceType.ScrambledWords)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RecoveryDeviceType.Matrix)
            hbox_rectype.addWidget(rb2)

        # no backup
        cb_no_backup = None
        if method == TIM_NEW:
            cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''')
            cb_no_backup.setChecked(False)
            if (model == '1' and fw_version >= (1, 7, 1)
                    or model == 'T' and fw_version >= (2, 0, 9)):
                cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING)
            else:
                cb_no_backup.setEnabled(False)
                cb_no_backup.setToolTip(_('Firmware version too old.'))
            expert_vbox.addWidget(cb_no_backup)

        vbox.addWidget(expert_widget)
        wizard.exec_layout(vbox, next_enabled=next_enabled)

        return TrezorInitSettings(
            word_count=bg_numwords.checkedId(),
            label=name.text(),
            pin_enabled=cb_pin.isChecked(),
            passphrase_enabled=cb_phrase.isChecked(),
            recovery_type=bg_rectype.checkedId() if bg_rectype else None,
            backup_type=bg_backuptype.checkedId(),
            no_backup=cb_no_backup.isChecked() if cb_no_backup else False,
        )
class Ui_Acq_Setting(QDialog):
    def __init__(self, task_id, parent=None):
        super(QDialog, self).__init__(parent)
        self.task_id = task_id
        self.init_ui()

    def init_ui(self):
        # 设置窗体无边框
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setFixedSize(500, 600)
        # 设置背景透明
        self.setAttribute(Qt.WA_TranslucentBackground)
        parent_grid = QVBoxLayout()
        parent_grid.setSpacing(0)
        self.setLayout(parent_grid)

        top_grid_widget = QWidget(self)
        top_grid_widget.setObjectName("top_widget")
        top_grid = QGridLayout()
        top_grid_widget.setLayout(top_grid)
        top_grid_widget.setFixedHeight(40)
        top_grid.setSpacing(0)
        top_grid.setContentsMargins(0, 0, 0, 0)
        top_grid.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        top_grid_widget.setStyleSheet(
            "#top_widget{background:#434343;border-top-right-radius: 5px;border-top-left-radius: 5px}"
        )


        close_btn_style = r'QPushButton{border:solid 0px grey;width:40px;height:40px;border-radius:0px;color:white;}' \
                     r'QPushButton:hover{background-color:rgb(220,20,60); border-style: inset; }'
        min_btn_style = r'QPushButton{border:solid 0px grey;width:40px;height:40px;border-radius:0px;color:white;}' \
                          r'QPushButton:hover{background-color:rgb(220,220,220); border-style: inset; }'
        close_btn = QPushButton(top_grid_widget)
        close_btn.setText("X")
        close_btn.setStyleSheet(close_btn_style)
        close_btn.setContentsMargins(0, 0, 0, 0)
        close_btn.clicked.connect(self.close_dialog)
        min_btn = QPushButton(top_grid_widget)
        min_btn.setText("-")
        min_btn.setStyleSheet(min_btn_style)
        min_btn.setContentsMargins(0, 0, 0, 0)
        min_btn.clicked.connect(self.showMinimized)
        title_label = QLabel(top_grid_widget)
        title_label.setText("采集设置")
        title_label.setStyleSheet(
            "QLabel{font:bold;color:white;margin-right:125}")

        top_grid.addWidget(close_btn, 0, 2, 1, 1)
        top_grid.addWidget(min_btn, 0, 1, 1, 1)
        top_grid.addWidget(title_label, 0, 0, 1, 1)

        button_grid_widget = QWidget(self)
        button_grid = QGridLayout()
        button_grid_widget.setLayout(button_grid)
        button_grid_widget.setStyleSheet("QWidget{background:#F5F5F5}")
        button_grid.setSpacing(20)
        button_grid.setContentsMargins(35, 30, 0, 0)
        button_grid.setAlignment(Qt.AlignTop | Qt.AlignLeft)

        yr_label = QLabel(button_grid_widget)
        yr_label.setText("导航动态渲染")
        yr_label.setStyleSheet("font:bold;")
        yr_buttonGroup = QButtonGroup(button_grid_widget)
        self.yr_yes = QRadioButton('是')
        self.yr_no = QRadioButton('否')
        self.yr_no.setChecked(True)
        yr_buttonGroup.addButton(self.yr_yes)
        yr_buttonGroup.addButton(self.yr_no)

        detail_yr_label = QLabel(button_grid_widget)
        detail_yr_label.setText("详情动态渲染")
        detail_yr_label.setStyleSheet("font:bold;")
        detail_yr_buttonGroup = QButtonGroup(button_grid_widget)
        self.detail_yr_yes = QRadioButton('是')
        self.detail_yr_no = QRadioButton('否')
        self.detail_yr_no.setChecked(True)
        detail_yr_buttonGroup.addButton(self.detail_yr_yes)
        detail_yr_buttonGroup.addButton(self.detail_yr_no)

        ip_label = QLabel(button_grid_widget)
        ip_label.setText("使用IP代理")
        ip_label.setStyleSheet("font:bold;")
        ip_buttonGroup = QButtonGroup(button_grid_widget)
        self.ip_yes = QRadioButton('是')
        self.ip_no = QRadioButton('否')
        self.ip_yes.setChecked(True)
        ip_buttonGroup.addButton(self.ip_yes)
        ip_buttonGroup.addButton(self.ip_no)

        ua_label = QLabel(button_grid_widget)
        ua_label.setText("用户代理(UA)")
        ua_label.setStyleSheet("font:bold;")
        ua_buttonGroup = QButtonGroup(button_grid_widget)
        self.ua_default = QRadioButton('默认')
        self.ua_random = QRadioButton('随机')
        self.ua_default.setChecked(True)
        ua_buttonGroup.addButton(self.ua_default)
        ua_buttonGroup.addButton(self.ua_random)
        ua_pool_btn = QPushButton(button_grid_widget)
        ua_pool_btn.setText("UA池")
        self.us_default_value = QTextEdit(button_grid_widget)

        navi_thread_label = QLabel(button_grid_widget)
        navi_thread_label.setText("导航线程数")
        navi_thread_label.setStyleSheet("font:bold;")

        self.navi_thread_num = QSpinBox(button_grid_widget)
        self.navi_thread_num.setStyleSheet(
            r'QSpinBox{height:30;width:50;background:white}')

        detail_thread_label = QLabel(button_grid_widget)
        detail_thread_label.setText("详情线程数")
        detail_thread_label.setStyleSheet("font:bold;")

        self.detail_thread_num = QSpinBox(button_grid_widget)
        self.detail_thread_num.setStyleSheet(
            r'QSpinBox{height:30;width:50;background:white}')

        self.saveBtn = QPushButton(button_grid_widget)
        self.saveBtn.setText("确定")
        self.saveBtn.setStyleSheet(
            r'QPushButton{background-color:#6495ED;color:white}')
        self.saveBtn.clicked.connect(self.save_setting)
        self.cancelBtn = QPushButton(button_grid_widget)
        self.cancelBtn.setText("取消")
        self.cancelBtn.setStyleSheet(
            r'QPushButton{background-color:grey;color:white}')
        self.cancelBtn.clicked.connect(self.close_dialog)

        button_grid.addWidget(ip_label, 0, 0, 1, 1)
        button_grid.addWidget(self.ip_yes, 0, 1, 1, 1)
        button_grid.addWidget(self.ip_no, 0, 2, 1, 1)

        button_grid.addWidget(yr_label, 1, 0, 1, 1)
        button_grid.addWidget(self.yr_yes, 1, 1, 1, 1)
        button_grid.addWidget(self.yr_no, 1, 2, 1, 1)

        button_grid.addWidget(detail_yr_label, 2, 0, 1, 1)
        button_grid.addWidget(self.detail_yr_yes, 2, 1, 1, 1)
        button_grid.addWidget(self.detail_yr_no, 2, 2, 1, 1)

        button_grid.addWidget(ua_label, 3, 0, 1, 1)
        button_grid.addWidget(self.ua_default, 3, 1, 1, 1)
        button_grid.addWidget(self.ua_random, 3, 2, 1, 1)
        button_grid.addWidget(ua_pool_btn, 3, 3, 1, 1)

        button_grid.addWidget(self.us_default_value, 4, 0, 1, 4)

        button_grid.addWidget(navi_thread_label, 5, 0, 1, 1)
        button_grid.addWidget(self.navi_thread_num, 5, 1, 1, 1)

        button_grid.addWidget(detail_thread_label, 5, 2, 1, 1)
        button_grid.addWidget(self.detail_thread_num, 5, 3, 1, 1)

        button_grid.addWidget(self.saveBtn, 7, 2, 1, 1)
        button_grid.addWidget(self.cancelBtn, 7, 3, 1, 1)

        button_grid.setRowStretch(0, 1)
        button_grid.setRowStretch(1, 1)
        button_grid.setRowStretch(2, 1)
        button_grid.setRowStretch(3, 2)
        button_grid.setRowStretch(4, 1)
        button_grid.setRowStretch(5, 1)
        button_grid.setRowStretch(6, 1)
        button_grid.setRowStretch(7, 1)
        button_grid.setRowStretch(8, 1)

        parent_grid.addWidget(top_grid_widget)
        parent_grid.addWidget(button_grid_widget)

        self.load_data()

    def save_setting(self):
        if self.task_id == 0:
            QMessageBox.information(self, "温馨提示", "请先保存录制的站点规则,再设置采集规则")

        else:
            acq_strategy = {}
            acq_strategy['ipProxy'] = (0 if (self.ip_yes.isChecked()) else 1)
            acq_strategy['navi_flag'] = (0 if (self.yr_yes.isChecked()) else 1)
            acq_strategy['detail_flag'] = (0 if
                                           (self.detail_yr_yes.isChecked())
                                           else 1)
            acq_strategy['ua'] = (0 if (self.ua_default.isChecked()) else 1)
            acq_strategy['ua_default'] = self.us_default_value.toPlainText()
            acq_strategy['navi_thread'] = self.navi_thread_num.text()
            acq_strategy['detail_thread'] = self.detail_thread_num.text()

            BasicDao.save_acq_strategy(self.task_id, json.dumps(acq_strategy))

            print(acq_strategy)
        self.close_dialog()

    def load_data(self):
        if self.task_id:
            info = BasicDao.query_strategy_by_taskid(self.task_id)
            if info:
                rule = json.loads(info['rule'])
                self.ip_no.setChecked((False if
                                       (rule['ipProxy'] == 0) else True))
                # self.ip_no.setChecked(True)
                self.yr_yes.setChecked((True if
                                        (rule['navi_flag'] == 0) else False))
                self.detail_yr_yes.setChecked(
                    (True if (rule['detail_flag'] == 0) else False))
                self.ua_random.setChecked((False if
                                           (rule['ua'] == 0) else True))
                self.navi_thread_num.setValue(int(rule['navi_thread']))
                self.detail_thread_num.setValue(int(rule['detail_thread']))

    def close_dialog(self):
        '''
        关闭应用程序
        :return:
        '''
        try:
            self.close()
        except Exception as a:
            print(a)

    # 以下三个函数是覆写窗体函数,实现无标题移动功能
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  #获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  #更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  #更改窗口位置
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))
Beispiel #40
0
class MainWindow(QWidget):
    """Окно графического интерфейса"""
    def __init__(self):
        super().__init__()

        self.sim = PendulumLearning(
            self
        )  # Объект с моделью и обучающейся системой управления маятником

        # Элементы интерфейса
        self.canvas_width = 800  # Ширина холста
        self.canvas_height = 675  # Длина холста
        self.canvas = Plotter(self.canvas_width,
                              self.canvas_height,
                              dpi=100,
                              parent=self)  # Холст с графиками
        # Кнопки
        self.start_button = QPushButton('Start', self)
        self.stop_button = QPushButton('Stop', self)
        self.restart_button = QPushButton('Restart', self)
        self.new_nn_button = QPushButton('New neural net', self)
        self.load_nn_button = QPushButton('Load neural net', self)
        self.save_nn_button = QPushButton('Save neural net', self)
        self.save_plots_button = QPushButton('Save plots', self)
        self.clear_button = QPushButton('Clear', self)
        # Надписи
        self.eps_start_label = QLabel('Initial probability\nof random action',
                                      self)
        self.eps_discount_label = QLabel(
            'Discount of probability\non each step', self)
        self.eps_final_label = QLabel('Final probability\nof random action',
                                      self)
        self.episode_length_label = QLabel('Episode length', self)
        self.batch_size_label = QLabel('Training batch\nsize', self)
        # Поля ввода чисел
        self.eps_start_spinbox = QDoubleSpinBox(self)
        self.eps_discount_spinbox = QDoubleSpinBox(self)
        self.eps_final_spinbox = QDoubleSpinBox(self)
        self.episode_length_spinbox = QSpinBox(self)
        self.batch_size_spinbox = QSpinBox(self)
        # Кнопки выбора обучающейся модели
        self.q_learning_rb = QRadioButton("Deep Q-learning", self)
        self.q_learning2_rb = QRadioButton("Q-learning, net with one output",
                                           self)
        self.actor_critic_rb = QRadioButton("Adaptive critic", self)
        self.actor_critic_DDPG_rb = QRadioButton("Adaptive critic (DDPG)",
                                                 self)
        # Чекбоксы
        self.eps_greedy_checkbox = QCheckBox("Use random actions", self)
        self.learning_checkbox = QCheckBox("Turn training on", self)
        self.endless_episode_checkbox = QCheckBox("Endless episode", self)
        # Вывод данных
        self.output_text_field = QTextBrowser(self)

        self.initUI()

    def initUI(self):
        """Формирование интерфейса"""
        size = (1300, 715)  # Размер окна
        position = (100, 100)  # Начальная позиция окна
        canvas_position = (20, 20)  # Верхний левый угол холста
        buttons_indent = 10  # Расстояние между кнопками
        spinbox_indent = 8  # Расстояние между полями выбора чисел
        labels_indent = 5  # Расстояние между надписями
        # Параметры поля выбора начальной вероятности выбора случайного действия
        eps_start_min = 0
        eps_start_max = 1
        eps_start_step = 0.1
        eps_start_default_value = 0.5
        # Параметры поля выбора шага уменьшения вероятности случайного действия
        eps_discount_min = 0
        eps_discount_max = 1
        eps_discount_step = 0.000001
        eps_discount_default_value = 0.00002
        eps_discount_decimals = 6
        # Параметры поля выбора конечной вероятности выбора случайного действия
        eps_final_min = 0
        eps_final_max = 1
        eps_final_step = 0.01
        eps_final_default_value = 0.05
        # Параметры поля выбора длины эпизода
        episode_length_min = 1
        episode_length_max = 2000
        episode_length_step = 100
        episode_length_default_value = 200
        # Параметры поля выбора размера пачки при обучении
        batch_size_min = 1
        batch_size_max = 300
        batch_size_step = 10
        batch_size_default_value = 50
        # Размер поля вывода данных
        text_field_size = (460, 170)

        buttons_left = canvas_position[
            0] + buttons_indent + self.canvas_width  # Координата левого края блока элементов управления
        buttons_up = canvas_position[
            1]  # Координата верхнего края блока элементов управления

        # Изменяем позицию и перемещаем окно
        self.resize(*size)
        self.move(*position)

        self.canvas.move(*canvas_position)

        # Кнопки старт, стоп, перезапуск
        button_up = buttons_up  # Верхняя позиция текущей кнопки
        self.start_button.resize(self.start_button.sizeHint())
        self.start_button.move(buttons_left, button_up)
        self.start_button.clicked.connect(self.start)

        buttons_distance = self.start_button.height(
        ) + buttons_indent  # Расстояние между верхними позициями кнопок
        spinbox_distance = self.eps_start_spinbox.height() + spinbox_indent
        button_up += buttons_distance

        self.stop_button.resize(self.start_button.sizeHint())
        self.stop_button.move(buttons_left, button_up)
        self.stop_button.clicked.connect(self.stop)
        button_up += buttons_distance

        self.restart_button.resize(self.start_button.sizeHint())
        self.restart_button.move(buttons_left, button_up)
        self.restart_button.clicked.connect(self.restart)

        # Элементы для настройки случайных действий
        # Координата левого края блока элементов для генерации случайной среды
        controls_left = buttons_left + self.start_button.width(
        ) + buttons_indent

        element_up = buttons_up  # Верхняя позиция текущего элемента управления
        self.eps_start_label.resize(self.eps_start_label.sizeHint())
        self.eps_start_label.move(controls_left, element_up)
        element_left = controls_left + self.eps_start_label.width(
        ) + buttons_indent
        self.eps_start_spinbox.move(element_left, element_up)
        self.eps_start_spinbox.setMinimum(eps_start_min)
        self.eps_start_spinbox.setMaximum(eps_start_max)
        self.eps_start_spinbox.setSingleStep(eps_start_step)
        self.eps_start_spinbox.setValue(eps_start_default_value)
        self.eps_start_spinbox.valueChanged.connect(self.change_start_eps)
        self.change_start_eps()
        element_up += spinbox_distance

        self.eps_final_label.resize(self.eps_final_label.sizeHint())
        self.eps_final_label.move(controls_left, element_up)
        element_left = controls_left + self.eps_final_label.width(
        ) + buttons_indent
        self.eps_final_spinbox.move(element_left, element_up)
        self.eps_final_spinbox.setMinimum(eps_final_min)
        self.eps_final_spinbox.setMaximum(eps_final_max)
        self.eps_final_spinbox.setSingleStep(eps_final_step)
        self.eps_final_spinbox.setValue(eps_final_default_value)
        self.eps_final_spinbox.valueChanged.connect(self.change_final_eps)
        self.change_final_eps()
        element_up += spinbox_distance

        self.eps_discount_label.resize(self.eps_discount_label.sizeHint())
        self.eps_discount_label.move(controls_left, element_up)
        element_left = controls_left + self.eps_discount_label.width(
        ) + buttons_indent
        self.eps_discount_spinbox.setDecimals(eps_discount_decimals)
        self.eps_discount_spinbox.resize(self.eps_discount_spinbox.sizeHint())
        self.eps_discount_spinbox.move(element_left, element_up)
        self.eps_discount_spinbox.setMinimum(eps_discount_min)
        self.eps_discount_spinbox.setMaximum(eps_discount_max)
        self.eps_discount_spinbox.setSingleStep(eps_discount_step)
        self.eps_discount_spinbox.setValue(eps_discount_default_value)
        self.eps_discount_spinbox.valueChanged.connect(
            self.change_eps_discount)
        self.change_eps_discount()
        element_up += spinbox_distance

        self.eps_greedy_checkbox.resize(self.eps_greedy_checkbox.sizeHint())
        self.eps_greedy_checkbox.move(controls_left, element_up)
        self.eps_greedy_checkbox.setChecked(True)
        self.eps_greedy_checkbox.stateChanged.connect(self.toggle_eps_greedy)
        self.toggle_eps_greedy()

        labels_distance = self.eps_greedy_checkbox.height() + labels_indent

        element_up += labels_distance

        button_up = max([element_up, button_up])
        self.q_learning_rb.move(buttons_left, button_up)
        self.q_learning_rb.setChecked(True)
        self.q_learning_rb.toggled.connect(self.select_learning_model)
        button_up += labels_distance
        self.q_learning2_rb.move(buttons_left, button_up)
        self.q_learning2_rb.toggled.connect(self.select_learning_model)
        button_up += labels_distance
        self.actor_critic_rb.move(buttons_left, button_up)
        self.actor_critic_rb.toggled.connect(self.select_learning_model)
        button_up += labels_distance
        self.actor_critic_DDPG_rb.move(buttons_left, button_up)
        self.actor_critic_DDPG_rb.toggled.connect(self.select_learning_model)
        self.select_learning_model()
        button_up += labels_distance

        self.learning_checkbox.move(buttons_left, button_up)
        self.learning_checkbox.setChecked(True)
        self.learning_checkbox.stateChanged.connect(self.toggle_learning)
        self.toggle_learning()

        button_up += labels_distance
        self.batch_size_label.resize(self.batch_size_label.sizeHint())
        self.batch_size_label.move(buttons_left, button_up)
        element_left = buttons_left + self.batch_size_label.width(
        ) + buttons_indent
        self.batch_size_spinbox.resize(self.batch_size_spinbox.sizeHint())
        self.batch_size_spinbox.move(element_left, button_up)
        self.batch_size_spinbox.setMinimum(batch_size_min)
        self.batch_size_spinbox.setMaximum(batch_size_max)
        self.batch_size_spinbox.setSingleStep(batch_size_step)
        self.batch_size_spinbox.setValue(batch_size_default_value)
        self.batch_size_spinbox.valueChanged.connect(self.change_batch_size)
        self.change_batch_size()
        button_up += spinbox_distance

        element_up = button_up

        self.new_nn_button.resize(self.save_nn_button.sizeHint())
        self.new_nn_button.move(buttons_left, button_up)
        self.new_nn_button.clicked.connect(self.new_nn)
        button_up += buttons_distance

        self.load_nn_button.resize(self.save_nn_button.sizeHint())
        self.load_nn_button.move(buttons_left, button_up)
        self.load_nn_button.clicked.connect(self.load_nn)
        button_up += buttons_distance

        self.save_nn_button.resize(self.save_nn_button.sizeHint())
        self.save_nn_button.move(buttons_left, button_up)
        self.save_nn_button.clicked.connect(self.save_nn)
        button_up += buttons_distance

        elements_left = buttons_left + self.save_nn_button.width(
        ) + buttons_indent

        self.save_plots_button.resize(self.save_plots_button.sizeHint())
        self.save_plots_button.move(elements_left, element_up)
        self.save_plots_button.clicked.connect(self.save_plots)
        element_up += buttons_distance

        self.clear_button.resize(self.save_plots_button.sizeHint())
        self.clear_button.move(elements_left, element_up)
        self.clear_button.clicked.connect(self.clear)
        element_up += buttons_distance

        self.episode_length_label.resize(self.episode_length_label.sizeHint())
        self.episode_length_label.move(buttons_left, button_up)
        element_left = buttons_left + self.episode_length_label.width(
        ) + buttons_indent
        self.episode_length_spinbox.resize(
            self.episode_length_spinbox.sizeHint())
        self.episode_length_spinbox.move(element_left, button_up)
        self.episode_length_spinbox.setMinimum(episode_length_min)
        self.episode_length_spinbox.setMaximum(episode_length_max)
        self.episode_length_spinbox.setSingleStep(episode_length_step)
        self.episode_length_spinbox.setValue(episode_length_default_value)
        self.episode_length_spinbox.valueChanged.connect(
            self.change_episode_length)
        self.change_episode_length()
        button_up += spinbox_distance

        self.endless_episode_checkbox.move(buttons_left, button_up)
        self.endless_episode_checkbox.setChecked(False)
        self.endless_episode_checkbox.stateChanged.connect(
            self.toggle_endless_episode)
        self.toggle_endless_episode()
        button_up += labels_distance

        self.output_text_field.resize(*text_field_size)
        self.output_text_field.move(buttons_left, button_up)
        self.output_text_field.setReadOnly(True)
        self.setWindowTitle('An Inverted Pendulum')
        self.show()

    def closeEvent(self, event):
        """Закрытие окна"""
        self.sim.exit()
        self.deleteLater()
        self.close()

    def start(self):
        """Запуск моделирования"""
        self.sim.start()

    def stop(self):
        """Остановка моделирования"""
        self.sim.stop()

    def restart(self):
        """Поместить маятник в случайную позицию"""
        self.sim.restart()

    def change_start_eps(self):
        """Изменить начальную вероятность случайного действия"""
        self.sim.set_eps(self.eps_start_spinbox.value())

    def change_final_eps(self):
        """Изменить конечную вероятность случайного действия"""
        self.sim.set_final_eps(self.eps_final_spinbox.value())

    def change_eps_discount(self):
        """Изменить шаг уменьшения вероятности случайного действия"""
        self.sim.set_eps_discount(self.eps_discount_spinbox.value())

    def select_learning_model(self):
        """Выбрать обучающуюся модель"""
        if self.q_learning_rb.isChecked():
            lm_number = 0
        elif self.q_learning2_rb.isChecked():
            lm_number = 1
        elif self.actor_critic_rb.isChecked():
            lm_number = 2
        else:
            lm_number = 3
        self.sim.choose_learning_model(lm_number)

    def toggle_eps_greedy(self):
        """Включить или отключить совершение случайных действий"""
        self.sim.set_eps_greedy(self.eps_greedy_checkbox.isChecked())

    def toggle_learning(self):
        """Производить ли обучение модели, или просто включить управление"""
        enable = self.learning_checkbox.isChecked()
        self.sim.is_learning = enable

    def save_plots(self):
        """Сохранить графики в файл"""
        file_dialogue = QFileDialog()
        file_dialogue.setFileMode(QFileDialog.AnyFile)
        file_dialogue.setAcceptMode(QFileDialog.AcceptSave)
        name_filters = ["PNG images (*.png)", "All files (*.*)"]
        file_dialogue.setNameFilters(name_filters)
        if file_dialogue.exec():
            filename = file_dialogue.selectedFiles()[0]
            try:
                self.canvas.figure.savefig(filename)
            except PermissionError as e:
                QMessageBox.warning(self, "Error", str(e))
                self.canvas.draw()
        file_dialogue.deleteLater()

    def change_batch_size(self):
        """Изменить размер пачки при обучении нейросетей"""
        self.sim.set_batch_size(self.batch_size_spinbox.value())

    def new_nn(self):
        """Создать новую нейросеть со случайными коэффициентами"""
        self.sim.new_nn()  # Создать новую нейросеть и очистить опыт
        self.change_start_eps()  # Обновить вероятность случайного действия

    def load_nn(self):
        """Загрузить нейросеть из файла"""
        file_dialogue = QFileDialog()
        file_dialogue.setFileMode(QFileDialog.ExistingFile)
        file_dialogue.setAcceptMode(QFileDialog.AcceptOpen)
        if self.actor_critic_rb.isChecked(
        ) or self.actor_critic_DDPG_rb.isChecked():
            name_filters = ["TensorFlow session (*.meta)"]
        else:
            name_filters = [
                "Hierarchical data format (*.hdf)", "All files (*.*)"
            ]
        file_dialogue.setNameFilters(name_filters)
        if file_dialogue.exec():
            filename = file_dialogue.selectedFiles()[0]
            try:
                self.sim.load_nn(filename)
            except OSError or FileNotFoundError or FileNotFoundError as e:
                QMessageBox.warning(self, "Error", str(e))
        file_dialogue.deleteLater()

    def save_nn(self):
        """Сохранить нейросеть в файл"""
        file_dialogue = QFileDialog()
        file_dialogue.setFileMode(QFileDialog.AnyFile)
        file_dialogue.setAcceptMode(QFileDialog.AcceptSave)
        if self.actor_critic_rb.isChecked(
        ) or self.actor_critic_DDPG_rb.isChecked():
            name_filters = ["TensorFlow session (*.*)"]
        else:
            name_filters = [
                "Hierarchical data format (*.hdf)", "All files (*.*)"
            ]
        file_dialogue.setNameFilters(name_filters)
        if file_dialogue.exec():
            filename = file_dialogue.selectedFiles()[0]
            try:
                self.sim.save_nn(filename)
            except PermissionError as e:
                QMessageBox.warning(self, "Error", str(e))
        file_dialogue.deleteLater()

    def change_episode_length(self):
        """Изменить длину эпизода - количества шагов перед случайным выбором новой позиции маятника"""
        episode_length = self.episode_length_spinbox.value()
        self.sim.max_ep_steps = episode_length

    def toggle_endless_episode(self):
        """Никогда не выбирать случайную позицию для маятника"""
        enable = self.endless_episode_checkbox.isChecked()
        self.sim.endless = enable

    def clear(self):
        """Очистить графики и поле с информацией об обучении"""
        self.canvas.clear()
        self.canvas.draw()
        self.output_text_field.clear()

    def paint_scene(self, thetas, omegas, moments, times, running_reward,
                    episode):
        """Рисовать графики"""
        self.canvas.clear()
        self.canvas.theta_plot.plot(times, thetas, 'b')
        self.canvas.omega_plot.plot(times, omegas, 'g')
        self.canvas.moment_plot.plot(times, moments, 'r')
        self.canvas.draw()
        eps = self.sim.get_eps()
        self.output_text_field.append(
            "Episode %d: running reward: %d, random probability: %-10.5g" %
            (episode, running_reward, eps))
Beispiel #41
0
class CodecFrame(QFrame):
    def __init__(self, parent, context, frame_id, codec_tab, commands,
                 previous_frame, text):
        super(CodecFrame, self).__init__(parent)
        self._context = context
        self._context.shortcutUpdated.connect(self._shortcut_updated_event)
        self._init_logger(context, frame_id)
        self._frame_id = frame_id
        self._codec_tab = codec_tab
        self._previous_frame = previous_frame
        if previous_frame:
            previous_frame.setNext(self)
        self._next_frame = None
        self._commands = commands
        self._flash_event = None

        self._layout = QHBoxLayout(self)
        self._status_widget = StatusWidget(self)
        input_frame = self._init_input_frame(text)
        button_frame = self._init_button_frame()

        self._group_box = QGroupBox()
        group_box_layout = QHBoxLayout()
        group_box_layout.addWidget(self._status_widget)
        group_box_layout.addWidget(input_frame)
        group_box_layout.addWidget(button_frame, 0, Qt.AlignTop)
        self._group_box.setLayout(group_box_layout)

        _, top, _, bottom = self._layout.getContentsMargins()
        self._layout.addWidget(self._group_box)
        self.setLayout(self._layout)

    """
    Initializes the logger. Encapsulates logger-instance to enhance standard-logging with frame-id.
    """

    def _init_logger(self, context, frame_id):
        self._logger = context.logger()
        # BUG: Using logging with custom field frame_id does not work correctly.
        # WORKAROUND: ???
        #self._logger = context.logger(log_format="%(module)s: %(frame_id)d: %(lineno)d: %(msg)s",log_fields={'frame_id': frame_id})

    def _init_input_frame(self, text):
        input_frame = QFrame()
        frame_layout = QVBoxLayout()
        self._plain_view_widget = PlainView(text)
        self._plain_view_widget.textChanged.connect(self._text_changed_event)
        self._plain_view_widget = self._plain_view_widget
        frame_layout.addWidget(self._plain_view_widget)
        frame_layout.setContentsMargins(0, 6, 6, 6)

        self._hex_view_widget = HexView(self, self._context, self._frame_id,
                                        self.getInputText())
        self._hex_view_widget.textChanged.connect(
            self._hex_view_text_changed_event)
        self._hex_view_widget.setHidden(True)
        frame_layout.addWidget(self._hex_view_widget)
        input_frame.setLayout(frame_layout)
        return input_frame

    def _init_button_frame(self):
        button_frame = QFrame()
        button_frame_layout = QVBoxLayout()
        self._combo_box_frame = ComboBoxFrame(self, self._context)
        self._combo_box_frame.titleSelected.connect(
            self._combo_box_title_selected_event)
        self._combo_box_frame.commandSelected.connect(
            self._execute_command_select)
        button_frame_layout.addWidget(self._combo_box_frame)
        button_frame_layout.addWidget(self._init_radio_frame())
        button_frame.setLayout(button_frame_layout)
        return button_frame

    def _init_radio_frame(self):
        radio_frame = QFrame()
        radio_frame_layout = QHBoxLayout()
        self._plain_radio = QRadioButton("Plain")
        self._plain_radio.setChecked(True)
        self._plain_radio.toggled.connect(self._view_radio_button_toggle_event)
        self._hex_radio = QRadioButton("Hex")
        self._hex_radio.toggled.connect(self._view_radio_button_toggle_event)
        radio_frame_layout.addWidget(self._plain_radio)
        radio_frame_layout.addWidget(self._hex_radio)
        radio_frame.setLayout(radio_frame_layout)
        return radio_frame

    def _shortcut_updated_event(self, shortcut):
        id = shortcut.id()
        tooltip = self._get_tooltip_by_shortcut(shortcut)
        if id == Context.Shortcut.FOCUS_DECODER:
            self._combo_box_frame.decoder().setToolTip(tooltip)
        elif id == Context.Shortcut.FOCUS_ENCODER:
            self._combo_box_frame.encoder().setToolTip(tooltip)
        elif id == Context.Shortcut.FOCUS_HASHER:
            self._combo_box_frame.hasher().setToolTip(tooltip)
        elif id == Context.Shortcut.FOCUS_SCRIPT:
            self._combo_box_frame.script().setToolTip(tooltip)
        elif id == Context.Shortcut.SELECT_PLAIN_VIEW:
            self._plain_radio.setToolTip(tooltip)
        elif id == Context.Shortcut.SELECT_HEX_VIEW:
            self._hex_radio.setToolTip(tooltip)
        else:
            return
        self._logger.debug(
            "Updated tooltip within codec-frame for {id} to {tooltip}".format(
                id=id, tooltip=tooltip))

    def _update_tooltip(self, the_widget, the_shortcut_id):
        tooltip = self._get_tooltip_by_shortcut_id(the_shortcut_id)
        the_widget.setToolTip(tooltip)

    def _get_tooltip_by_shortcut_id(self, the_shortcut_id):
        shortcut = self._context.getShortcutById(the_shortcut_id)
        return self._get_tooltip_by_shortcut(shortcut)

    def _get_tooltip_by_shortcut(self, shortcut):
        return "{description} ({shortcut_key})".format(
            description=shortcut.name(), shortcut_key=shortcut.key())

    def _combo_box_title_selected_event(self):
        self._codec_tab.removeFrames(self._next_frame)
        self.focusInputText()

    def _view_radio_button_toggle_event(self):
        self._plain_view_widget.setVisible(self._plain_radio.isChecked())
        self._hex_view_widget.setVisible(self._hex_radio.isChecked())
        # BUG: Performance Issue When Updating Multiple HexView-Frames During Input Text Changes
        # WORKAROUND: Do only update HexView when it's visible
        if self._hex_radio.isChecked():
            input = self._plain_view_widget.toPlainText()
            self._hex_view_widget.blockSignals(True)
            self._hex_view_widget.setData(input)
            self._hex_view_widget.blockSignals(False)

    def _text_changed_event(self):
        # BUG: Performance Issue When Updating Multiple HexView-Frames When Input Text Changes
        # WORKAROUND: Do only update HexView when it's visible
        if self._hex_view_widget.isVisible():
            input = self._plain_view_widget.toPlainText()
            self._hex_view_widget.blockSignals(True)
            self._hex_view_widget.setData(input)
            self._hex_view_widget.blockSignals(False)
        self._status_widget.setStatus("DEFAULT")
        self._execute()

    def _hex_view_text_changed_event(self, new_text):
        input = new_text
        self._plain_view_widget.blockSignals(True)
        self._plain_view_widget.setPlainText(input)
        self._plain_view_widget.blockSignals(False)
        self._status_widget.setStatus("DEFAULT")
        self._execute()

    def _execute(self):
        command = self._combo_box_frame.selectedCommand()
        if command:
            self._execute_command_run(command)

    def _execute_command_run(self, command):
        input = self.getInputText()
        output = ""
        try:
            output = command.run(input)
            self._codec_tab.newFrame(output,
                                     command.title(),
                                     self,
                                     status=StatusWidget.SUCCESS)
        except Exception as e:
            error = str(e)
            self._logger.error('{} {}: {}'.format(command.name(),
                                                  command.type(), str(e)))
            self._codec_tab.newFrame(output,
                                     command.title(),
                                     self,
                                     status=StatusWidget.ERROR,
                                     msg=error)

    def _execute_command_select(self, command):
        output = ""
        try:
            input = self.getInputText()
            output = command.select(input)
            self._codec_tab.newFrame(output,
                                     command.title(),
                                     self,
                                     status=StatusWidget.SUCCESS)
        except AbortedException as e:
            # User aborted selection. This usually happens when a user clicks the cancel-button within a codec-dialog.
            self._logger.debug(str(e))
        except Exception as e:
            error = str(e)
            self._logger.error('{} {}: {}'.format(command.name(),
                                                  command.type(), error))
            self._codec_tab.newFrame(output,
                                     command.title(),
                                     self,
                                     status=StatusWidget.ERROR,
                                     msg=error)

    def flashStatus(self, status, message):
        self._status_widget.setStatus(status, message)

    def selectComboBoxEntryByCommand(self, command):
        self._combo_box_frame.selectItem(command.type(),
                                         command.name(),
                                         block_signals=True)
        self._execute_command_run(command)

    def selectPlainView(self):
        self._plain_radio.setChecked(True)

    def selectHexView(self):
        self._hex_radio.setChecked(True)

    def toggleSearchField(self):
        self._plain_view_widget.toggleSearchField()

    def hasNext(self):
        return self._next_frame is not None

    def hasPrevious(self):
        return self._previous_frame is not None

    def setNext(self, next_frame):
        self._next_frame = next_frame

    def setPrevious(self, previous_frame):
        self._previous_frame = previous_frame

    def next(self):
        return self._next_frame

    def previous(self):
        return self._previous_frame

    def setTitle(self, title):
        self._group_box.setTitle(title)

    def setInputText(self, text, blockSignals=False):
        self._plain_view_widget.blockSignals(blockSignals)
        self._plain_view_widget.setPlainText(text)
        self._plain_view_widget.blockSignals(False)

    def getInputText(self):
        return self._plain_view_widget.toPlainText()

    def getComboBoxes(self):
        return self._combo_boxes

    def focusInputText(self):
        self._plain_view_widget.setFocus()

    def focusComboBox(self, type):
        self._combo_box_frame.focusType(type)
Beispiel #42
0
    def request_trezor_init_settings(self, wizard, method, device):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        if method in [TIM_NEW, TIM_RECOVER]:
            gb = QGroupBox()
            hbox1 = QHBoxLayout()
            gb.setLayout(hbox1)
            # KeepKey recovery doesn't need a word count
            if method == TIM_NEW:
                vbox.addWidget(gb)
            gb.setTitle(_("Select your seed length:"))
            bg = QButtonGroup()
            for i, count in enumerate([12, 18, 24]):
                rb = QRadioButton(gb)
                rb.setText(_("{} words").format(count))
                bg.addButton(rb)
                bg.setId(rb, i)
                hbox1.addWidget(rb)
                rb.setChecked(True)
            cb_pin = QCheckBox(_('Enable PIN protection'))
            cb_pin.setChecked(True)
        else:
            text = QTextEdit()
            text.setMaximumHeight(60)
            if method == TIM_MNEMONIC:
                msg = _("Enter your BIP39 mnemonic:")
            else:
                msg = _("Enter the master private key beginning with xprv:")

                def set_enabled():
                    from electrum_mue.bip32 import is_xprv
                    wizard.next_button.setEnabled(is_xprv(clean_text(text)))

                text.textChanged.connect(set_enabled)
                next_enabled = False

            vbox.addWidget(QLabel(msg))
            vbox.addWidget(text)
            pin = QLineEdit()
            pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
            pin.setMaximumWidth(100)
            hbox_pin = QHBoxLayout()
            hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
            hbox_pin.addWidget(pin)
            hbox_pin.addStretch(1)

        if method in [TIM_NEW, TIM_RECOVER]:
            vbox.addWidget(WWLabel(RECOMMEND_PIN))
            vbox.addWidget(cb_pin)
        else:
            vbox.addLayout(hbox_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        if method in [TIM_NEW, TIM_RECOVER]:
            item = bg.checkedId()
            pin = cb_pin.isChecked()
        else:
            item = ' '.join(str(clean_text(text)).split())
            pin = str(pin.text())

        return (item, name.text(), pin, cb_phrase.isChecked())
                 "asdf lkjha yuoiqwe asd iuaysd u iasyd uiy "
                 "asdf lkjha yuoiqwe asd iuaysd u iasyd uiy!")

    button = QPushButton()
    buttonProxy = QGraphicsProxyWidget()
    buttonProxy.setWidget(button)
    editProxy = QGraphicsProxyWidget()
    editProxy.setWidget(edit)

    box = QGroupBox()
    box.setFlat(True)
    box.setTitle("Options")

    layout2 = QVBoxLayout()
    box.setLayout(layout2)
    layout2.addWidget(QRadioButton("Herring"))
    layout2.addWidget(QRadioButton("Blue Parrot"))
    layout2.addWidget(QRadioButton("Petunias"))
    layout2.addStretch()

    boxProxy = QGraphicsProxyWidget()
    boxProxy.setWidget(box)

    # Parent widget.
    widget = QGraphicsWidget()
    layout = QGraphicsLinearLayout(Qt.Vertical, widget)
    layout.addItem(editProxy)
    layout.addItem(buttonProxy)
    widget.setLayout(layout)

    p1 = Pixmap(QPixmap(':/digikam.png'))
Beispiel #44
0
    class WMWidget(QWidget):
        # handled = False # flag that value is written from wavemeter
        def __init__(self, parent=None, data=None):
            self.parent = parent
            self.data = data
            super().__init__(parent=self.parent)
            self.setWindowTitle('My WavelengthMeter')
            self.setWindowIcon(QIcon('icon.jpg'))
            self.plot_window1 = pg.PlotWidget()
            self.plot_window2 = pg.PlotWidget()
            # self.plot_window.plot(range(10),range(10))

            main_layout = QVBoxLayout()

            menu_layout = QHBoxLayout()
            chan_btn = QPushButton('Channels')
            chan_menu = QMenu(chan_btn)
            chan_menu.aboutToShow.connect(self.updateChannelsMenu)
            chan_btn.setMenu(chan_menu)
            menu_layout.addWidget(chan_btn)

            n_channels_per_line = QSpinBox()
            n_channels_per_line.setMinimum(2)
            n_channels_per_line.setMaximum(10)
            n_channels_per_line.setValue(self.data.n_channels)
            n_channels_per_line.valueChanged.connect(self.nCannelsChanged)
            menu_layout.addWidget(n_channels_per_line)

            menu_layout.addWidget(QLabel('per line'))

            menu_layout.addStretch(1)

            timer_len = QSpinBox()
            timer_len.setMinimum(10)
            timer_len.setMaximum(10000)
            timer_len.setValue(self.data.timer_interval)
            timer_len.valueChanged.connect(self.temerIntervalChanged)
            menu_layout.addWidget(timer_len)

            mode_group = QButtonGroup()
            self.all_btn = QRadioButton('all')
            self.all_btn.setChecked(self.data.mode=='all')
            self.all_btn.toggled.connect(self.modeChanged)
            mode_group.addButton(self.all_btn)
            menu_layout.addWidget(self.all_btn)

            self.single_btn = QRadioButton('single')
            self.single_btn.setChecked(self.data.mode != 'all')
            self.single_btn.toggled.connect(self.modeChanged)
            mode_group.addButton(self.single_btn)
            menu_layout.addWidget(self.single_btn)

            single_menu_btn = QPushButton('Single ch.')
            single_menu = QMenu(single_menu_btn)
            single_menu.aboutToShow.connect(self.updateSingleMenu)
            single_menu_btn.setMenu(single_menu)
            menu_layout.addWidget(single_menu_btn)

            main_layout.addLayout(menu_layout)

            main_layout.addWidget(self.plot_window1)
            main_layout.addWidget(self.plot_window2)

            self.channels_layout = QGridLayout()
            self.drawChannels()

            main_layout.addLayout(self.channels_layout)
            self.setLayout(main_layout)
            print('WLM_GUI created')
            self.timer = QTimer(self)
            self.timer.setInterval(self.data.timer_interval)
            self.timer.timeout.connect(self.routine)
            self.timer.start()

        def temerIntervalChanged(self, new_val):
            self.data.timer_interval = new_val
            self.data.save()
            self.timer.stop()
            self.timer.setInterval(self.data.timer_interval)
            self.timer.start()

        def nCannelsChanged(self,new_val):
            self.data.n_channels = new_val
            self.data.save()

        def modeChanged(self):
            if self.sender().text() == 'all':
                self.single_btn.setChecked(not self.all_btn.isChecked())
            if self.sender().text() == 'single':
                self.all_btn.setChecked(not self.single_btn.isChecked())
            # print(self.sender().text(),self.sender().isChecked())
            self.data.mode = 'all' if self.all_btn.isChecked() else 'single'

        def updateSingleMenu(self):
            channels_menu = self.sender()
            channels_menu.clear()
            for channel in self.data.channels:
                print(channel.name)
                act = channels_menu.addAction(channel.name)
                act.triggered.connect(self.updateSingleIndex)

        def updateSingleIndex(self):
            name = self.sender().text()
            print('single ',name)
            for i, channel in enumerate(self.data.channels):
                if channel.name == name:
                    self.data.single_index = i
                    break
            print('single index ', self.data.single_index)

        def routine(self):
            global  cicle_counter
            cicle_counter += 1
            print("Cicle #",cicle_counter)
            # print(self.data.current_index)
            print(self.data.active_channels_indexes)
            if self.data.mode == 'all':
                self.data.current_index = self.data.active_channels_indexes[
                (self.data.active_channels_indexes.index(self.data.current_index) + 1) % len(
                    self.data.active_channels_indexes)]
            else:
                self.data.current_index = self.data.single_index
            print('current index ',self.data.current_index)
            arr_to_arduino = [(self.data.channels[i].shutter_number,int(i==self.data.current_index)) for i in range(len(self.data.channels))]
            resp = self.data.arduino.setWMShutters(arr_to_arduino)
            # check resp
            time_per_shot = self.data.wavemeter.exposure * 2
            time.sleep(0.1)
            print('Time per shot ',time_per_shot)
            read_data = []
            read_success = False
            for i in range(self.data.N_SHOTS_MAX):
                time.sleep(time_per_shot*1e-3)
                # print(self.data.wavemeter.wavelength)
                # print(self.data.wavemeter.amplitudes)
                # print(len(self.data.wavemeter.spectrum))
                try:
                    wm_data = {'wavelength':self.data.wavemeter.wavelength,
                               'frequency':self.data.wavemeter.frequency,
                               'amplitudes':self.data.wavemeter.amplitudes,
                               'spectrum': self.data.wavemeter.spectrum
                               }
                except Exception as e:
                    print(e)
                    raise e
                # print(wm_data['wavelength'])
                read_data.append(wm_data)
                # print(wm_data['wavelength'])
                if (i >= self.data.N_SHOTS_MIN and
                            abs(wm_data['wavelength'] - read_data[-2]['wavelength']) <= self.data.EXCEPTABLE_WAVELENGTH_ERROR and
                            abs(wm_data['wavelength'] - read_data[-2]['wavelength']) <= self.data.EXCEPTABLE_WAVELENGTH_ERROR) :
                    print('Steady state reached; i=',i)
                    print(wm_data['wavelength'])
                    read_success = True
                    break
                # set color of text depending on read_success
            # print(self.data.current_index)
            channel = self.data.channels[self.data.current_index]
            channel.wavelength = wm_data['wavelength']
            channel.frequency = wm_data['frequency']
            channel.amplitudes = wm_data['amplitudes']
            channel.spectrum = wm_data['spectrum']
            self.drawChannels()
            self.drawSpecta()
            # self.data.save()

        def drawSpecta(self):
            self.plot_window1.clear()
            self.plot_window2.clear()
            active_channels = [channel for channel in self.data.channels if (channel.is_active  and channel.show_spectrum)]
            for i, channel in enumerate(active_channels):
                spectr = channel.spectrum[0]
                # for spectr in channel.spectrum[:1]:
                if len(spectr):
                    # print(len(spectr))
                    self.plot_window1.plot(np.arange(1024),spectr[:1024],pen=pg.mkPen(color=channel.color))
                spectr = channel.spectrum[1]
                # for spectr in channel.spectrum[:1]:
                if len(spectr):
                    # print(len(spectr))
                    self.plot_window2.plot(np.arange(1024), spectr[:1024], pen=pg.mkPen(color=channel.color))

        def drawChannels(self):
            # cleen up previous grid
            while self.channels_layout.count():
                item = self.channels_layout.takeAt(0)
                item.widget().deleteLater()
            active_channels = [channel for channel in self.data.channels if channel.is_active]
            self.data.active_channels_indexes = [i for i,channel in enumerate(self.data.channels) if channel.is_active]
            # print(active_channels)
            # print('Frame ',self.frameGeometry().width())
            # print('widget', active_channels[0].width())
            for i, channel in enumerate(active_channels):
                # print(i % 2, i // 2)
                chan_widget = channel.WMChannelGUI(parent=self, data=channel)
                # print('Widget ', chan_widget.frameGeometry().width())
                self.channels_layout.addWidget(chan_widget, i // self.data.n_channels, i % self.data.n_channels)

        def updateChannelsMenu(self):
            # print('updateAllScanParams')
            # print(self.data.globals)
            channels_menu = self.sender()
            channels_menu.clear()
            for channel in self.data.channels:
                print(channel.name)
                m = channels_menu.addMenu(channel.name)
                text = 'hide' if channel.is_active else 'show'
                act = m.addAction(text)
                # act.triggered.connect(lambda:self.showHideChannel(channel))
                act.triggered.connect(self.showHideChannel)
                act = m.addAction('del')
                # act.triggered.connect(lambda:self.delChannel(channel))
                act.triggered.connect(self.delChannel)
            new_chan_act = channels_menu.addAction('new')
            new_chan_act.triggered.connect(lambda: self.NewChannelWidget(parent=self))

        def showHideChannel(self, channel):
            # channel.is_active = not channel.is_active
            name = self.sender().parent().title()
            for channel in self.data.channels:
                if channel.name == name:
                    channel.is_active = not channel.is_active
                    break
            self.drawChannels()
            self.data.save()

        def delChannel(self):
            # print(self.sender().parent().title())
            name = self.sender().parent().title()
            self.data.delChannel(name)
            self.drawChannels()
            self.data.save()

        def addNewChannel(self, caller):
            if caller.exit_status:
                # a = self.NewChannelWidget(parent=self)
                new_name = caller.name.text()
                new_shutter_channel = caller.shutter_channel.value()
                self.data.addChannel(name=new_name, shutter_number=new_shutter_channel)
                # self.data.channels.append(new_channel)
                print(new_name, new_shutter_channel)
                self.drawChannels()
            del caller
            self.data.save()

        class NewChannelWidget(QDialog):
            def __init__(self, parent=None, data=None):
                super().__init__(parent)
                self.parent = parent
                # self.data = data
                # self.initUI()
                main_layout = QVBoxLayout()

                line1 = QHBoxLayout()
                line1.addWidget(QLabel('Name'))
                self.name = QLineEdit()
                line1.addWidget(self.name)
                main_layout.addLayout(line1)

                line2 = QHBoxLayout()
                line2.addWidget(QLabel('Shutter_channel'))
                self.shutter_channel = QSpinBox()
                self.shutter_channel.setMaximum(18)
                self.shutter_channel.setMinimum(0)
                self.shutter_channel.setMinimumWidth(10)
                line2.addWidget(self.shutter_channel)
                # line1.addWidget(self.name)
                main_layout.addLayout(line2)

                ok_cancel = QHBoxLayout()
                ok_btn = QPushButton('Create')
                ok_btn.clicked.connect(self.createChannel)
                ok_cancel.addWidget(ok_btn)

                cancel_btn = QPushButton('Cancel')
                cancel_btn.clicked.connect(self.cancelPressed)
                ok_cancel.addWidget(cancel_btn)

                main_layout.addLayout(ok_cancel)
                self.setLayout(main_layout)
                self.show()

            def createChannel(self):
                self.exit_status = True
                # data_to_send = {'name':self.name, 'shutter_channel':self.shutter_channel}
                self.close()
                self.parent.addNewChannel(self)

            def cancelPressed(self):
                self.exit_status = False
                self.close()
                self.parent.addNewChannel(self)
Beispiel #45
0
    def __init__(self, device, *args, **kwargs):
        super(TimersDialog, self).__init__(*args, **kwargs)
        self.device = device
        self.timers = {}
        self.armKey = "Arm"
        self.setWindowTitle("Timers [{}]".format(self.device.name))

        vl = VLayout()

        self.gbTimers = GroupBoxV("Enabled", spacing=5)
        self.gbTimers.setCheckable(True)
        self.gbTimers.toggled.connect(self.toggleTimers)

        self.cbTimer = QComboBox()
        self.cbTimer.addItems(["Timer{}".format(nr + 1) for nr in range(16)])
        self.cbTimer.currentTextChanged.connect(self.loadTimer)

        hl_tmr_arm_rpt = HLayout(0)
        self.cbTimerArm = QCheckBox("Arm")
        self.cbTimerArm.clicked.connect(lambda x: self.describeTimer())
        self.cbTimerRpt = QCheckBox("Repeat")
        self.cbTimerRpt.clicked.connect(lambda x: self.describeTimer())
        hl_tmr_arm_rpt.addWidgets([self.cbTimerArm, self.cbTimerRpt])

        hl_tmr_out_act = HLayout(0)
        self.cbxTimerOut = QComboBox()
        self.cbxTimerOut.addItems(self.device.power().keys())
        self.cbxTimerOut.currentIndexChanged.connect(
            lambda x: self.describeTimer())
        self.cbxTimerAction = QComboBox()
        self.cbxTimerAction.addItems(["Off", "On", "Toggle", "Rule"])
        self.cbxTimerAction.currentIndexChanged.connect(
            lambda x: self.describeTimer())
        hl_tmr_out_act.addWidgets([self.cbxTimerOut, self.cbxTimerAction])

        self.TimerMode = QButtonGroup()
        rbTime = QRadioButton("Time")
        rbSunrise = QRadioButton("Sunrise ({})".format(
            self.device.p['Sunrise']))
        rbSunset = QRadioButton("Sunset ({})".format(self.device.p['Sunset']))
        self.TimerMode.addButton(rbTime, 0)
        self.TimerMode.addButton(rbSunrise, 1)
        self.TimerMode.addButton(rbSunset, 2)
        self.TimerMode.buttonClicked.connect(lambda x: self.describeTimer())
        gbTimerMode = GroupBoxH("Mode")
        gbTimerMode.addWidgets(self.TimerMode.buttons())

        hl_tmr_time = HLayout(0)
        self.cbxTimerPM = QComboBox()
        self.cbxTimerPM.addItems(["+", "-"])
        self.cbxTimerPM.currentIndexChanged.connect(
            lambda x: self.describeTimer())

        self.TimerMode.buttonClicked[int].connect(
            lambda x: self.cbxTimerPM.setEnabled(x != 0))
        self.teTimerTime = QTimeEdit()
        self.teTimerTime.setButtonSymbols(QTimeEdit.NoButtons)
        self.teTimerTime.setAlignment(Qt.AlignCenter)
        self.teTimerTime.timeChanged.connect(lambda x: self.describeTimer())

        lbWnd = QLabel("Window:")
        lbWnd.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.cbxTimerWnd = QComboBox()
        self.cbxTimerWnd.addItems([str(x).zfill(2) for x in range(0, 16)])
        self.cbxTimerWnd.currentIndexChanged.connect(
            lambda x: self.describeTimer())

        hl_tmr_days = HLayout(0)
        self.TimerWeekday = QButtonGroup()
        self.TimerWeekday.setExclusive(False)
        for i, wd in enumerate(
            ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]):
            cb = QCheckBox(wd)
            cb.clicked.connect(lambda x: self.describeTimer())
            hl_tmr_days.addWidget(cb)
            self.TimerWeekday.addButton(cb, i)

        gbTimerDesc = GroupBoxV("Timer description", 5)
        gbTimerDesc.setMinimumHeight(200)
        self.lbTimerDesc = QLabel()
        self.lbTimerDesc.setAlignment(Qt.AlignCenter)
        self.lbTimerDesc.setWordWrap(True)
        gbTimerDesc.layout().addWidget(self.lbTimerDesc)

        hl_tmr_time.addWidgets(
            [self.cbxTimerPM, self.teTimerTime, lbWnd, self.cbxTimerWnd])

        self.gbTimers.layout().addWidget(self.cbTimer)
        self.gbTimers.layout().addLayout(hl_tmr_arm_rpt)
        self.gbTimers.layout().addLayout(hl_tmr_out_act)
        self.gbTimers.layout().addWidget(gbTimerMode)
        self.gbTimers.layout().addLayout(hl_tmr_time)
        self.gbTimers.layout().addLayout(hl_tmr_days)

        btns = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Close)
        reload = btns.addButton("Reload", QDialogButtonBox.ResetRole)

        btns.accepted.connect(self.saveTimer)
        btns.rejected.connect(self.reject)
        reload.clicked.connect(
            lambda: self.loadTimer(self.cbTimer.currentText()))

        vl.addWidgets([self.gbTimers, gbTimerDesc, btns])
        self.setLayout(vl)
Beispiel #46
0
label2.setObjectName("")
gridLayout.addWidget(label2, 0, 4, 1, 1)

pushButton2 = QPushButton()
pushButton2.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
pushButton2.setText("")
gridLayout.addWidget(pushButton2, 0, 5, 1, 1)

spacerItem3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
gridLayout.addItem(spacerItem3, 0, 6, 1, 1)

groupBox = QGroupBox()
groupBox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
verticalLayout = QVBoxLayout(groupBox)

radioButton1 = QRadioButton(groupBox)
radioButton1.setText("Name")
verticalLayout.addWidget(radioButton1)

radioButton2 = QRadioButton(groupBox)
radioButton1.setText("Cost")
verticalLayout.addWidget(radioButton2)

gridLayout.addWidget(groupBox, 1, 1, 1, 2, Qt.AlignTop)

comboBox = QComboBox()
comboBox.addItem("Dokkan Belga")
comboBox.addItem("Eamon Company")
gridLayout.addWidget(comboBox, 1, 4, 1, 2, Qt.AlignTop)

btn = QPushButton("Click me")
Beispiel #47
0
    def __init__(self, parent=None):
        super(ChromAbWidget, self).__init__(parent)

        self.maxD = 20
        self.deadZ = 5
        self.isShapeRadial = True
        self.isFalloffExp = True
        self.direction = 100

        self.shapeInfo = QLabel("Shape and Direction:", self)
        self.shapeChoice = QButtonGroup(self)
        self.shapeBtn1 = QRadioButton("Radial")
        self.shapeBtn2 = QRadioButton("Linear")
        self.shapeChoice.addButton(self.shapeBtn1)
        self.shapeChoice.addButton(self.shapeBtn2)
        self.shapeBtn1.setChecked(True)
        self.shapeBtn1.pressed.connect(self.changeShape1)
        self.shapeBtn2.pressed.connect(self.changeShape2)

        self.theDial = QDial()
        self.theDial.setMinimum(0)
        self.theDial.setMaximum(359)
        self.theDial.setValue(100)
        self.theDial.setWrapping(True)
        self.theDial.valueChanged.connect(self.updateDial)

        self.maxInfo = QLabel("Max Displacement: 20px", self)
        self.maxDisplace = QSlider(Qt.Horizontal, self)
        self.maxDisplace.setRange(1, 300)
        self.maxDisplace.setValue(20)
        self.maxDisplace.valueChanged.connect(self.updateMax)

        self.falloffInfo = QLabel("Falloff:", self)
        self.falloffChoice = QButtonGroup(self)
        self.foBtn1 = QRadioButton("Exponential")
        self.foBtn2 = QRadioButton("Linear")
        self.falloffChoice.addButton(self.foBtn1)
        self.falloffChoice.addButton(self.foBtn2)
        self.foBtn1.setChecked(True)
        self.foBtn1.pressed.connect(self.changeFalloff1)
        self.foBtn2.pressed.connect(self.changeFalloff2)

        self.deadInfo = QLabel("Deadzone: 5%", self)
        self.deadzone = QSlider(Qt.Horizontal, self)
        self.deadzone.setRange(0, 100)
        self.deadzone.setValue(5)
        self.deadzone.valueChanged.connect(self.updateDead)

        vbox = QVBoxLayout()
        vbox.addWidget(self.shapeInfo)
        vbox.addWidget(self.shapeBtn1)
        vbox.addWidget(self.shapeBtn2)
        vbox.addWidget(self.theDial)
        vbox.addWidget(self.maxInfo)
        vbox.addWidget(self.maxDisplace)
        vbox.addWidget(self.falloffInfo)
        vbox.addWidget(self.foBtn1)
        vbox.addWidget(self.foBtn2)
        vbox.addWidget(self.deadInfo)
        vbox.addWidget(self.deadzone)

        self.setLayout(vbox)
        self.show()
Beispiel #48
0
    def initUI(self):
        main_layout = QVBoxLayout(self)

        self.setWindowTitle('DOCXImport')
        self.upd_layout = QVBoxLayout()
        self.update_label = QLabel()
        self.update_label.setAlignment(Qt.AlignCenter)
        self.upd_layout.addWidget(self.update_label)
        self.get_update_button = QPushButton()
        self.get_update_button.clicked.connect(self.get_update)
        self.upd_layout.addWidget(self.get_update_button)
        main_layout.addLayout(self.upd_layout)
        if not self.update:
            self.update_label.hide()
            self.get_update_button.hide()

        self.details_grid = QGridLayout()
        self.epub2_select = QRadioButton()
        self.epub2_select.setText('EPUB2')
        self.epubType = QButtonGroup()
        self.epubType.addButton(self.epub2_select)
        self.details_grid.addWidget(self.epub2_select, 0, 0, 1, 1)
        self.checkbox_get_updates = QCheckBox()
        self.details_grid.addWidget(self.checkbox_get_updates, 0, 1, 1, 1)
        self.epub3_select = QRadioButton()
        self.epub3_select.setText('EPUB3')
        self.epubType.addButton(self.epub3_select)
        self.details_grid.addWidget(self.epub3_select, 1, 0, 1, 1)
        main_layout.addLayout(self.details_grid)
        self.checkbox_get_updates.setChecked(self.prefs['check_for_updates'])
        if self.prefs['epub_version'] == '2.0':
            self.epub2_select.setChecked(True)
        elif self.prefs['epub_version'] == '3.0':
            self.epub3_select.setChecked(True)
        else:
            self.epub2_select.setChecked(True)

        self.groupBox = QGroupBox()
        self.groupBox.setTitle('')
        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.docx_grid = QGridLayout()
        self.docx_label = QLabel()
        self.docx_grid.addWidget(self.docx_label, 0, 0, 1, 1)
        self.docx_path = QLineEdit()
        self.docx_grid.addWidget(self.docx_path, 1, 0, 1, 1)
        self.choose_docx_button = QPushButton()
        self.choose_docx_button.setText('...')
        self.docx_grid.addWidget(self.choose_docx_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.docx_grid)
        self.choose_docx_button.clicked.connect(
            lambda: self.fileChooser('docx', self.docx_path))
        if len(self.prefs['lastDocxPath']):
            self.docx_path.setText(self.prefs['lastDocxPath'])
        self.docx_path.setEnabled(False)

        self.smap_grid = QGridLayout()
        self.checkbox_smap = QCheckBox(self.groupBox)
        self.smap_grid.addWidget(self.checkbox_smap, 0, 0, 1, 1)
        self.cust_smap_path = QLineEdit(self.groupBox)
        self.smap_grid.addWidget(self.cust_smap_path, 1, 0, 1, 1)
        self.choose_smap_button = QPushButton(self.groupBox)
        self.choose_smap_button.setText('...')
        self.smap_grid.addWidget(self.choose_smap_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.smap_grid)
        self.checkbox_smap.setChecked(self.prefs['useSmap'])
        self.checkbox_smap.stateChanged.connect(lambda: self.chkBoxActions(
            self.checkbox_smap, self.choose_smap_button))
        self.choose_smap_button.clicked.connect(
            lambda: self.fileChooser('smap', self.cust_smap_path, self.
                                     checkbox_smap, self.choose_smap_button))
        if len(self.prefs['useSmapPath']):
            self.cust_smap_path.setText(self.prefs['useSmapPath'])
        self.cust_smap_path.setEnabled(False)
        self.chkBoxActions(self.checkbox_smap, self.choose_smap_button)

        self.css_grid = QGridLayout()
        self.checkbox_css = QCheckBox(self.groupBox)
        self.css_grid.addWidget(self.checkbox_css, 0, 0, 1, 1)
        self.cust_css_path = QLineEdit(self.groupBox)
        self.css_grid.addWidget(self.cust_css_path, 1, 0, 1, 1)
        self.choose_css_button = QPushButton(self.groupBox)
        self.choose_css_button.setText('...')
        self.css_grid.addWidget(self.choose_css_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.css_grid)
        self.checkbox_css.setChecked(self.prefs['useCss'])
        self.checkbox_css.stateChanged.connect(lambda: self.chkBoxActions(
            self.checkbox_css, self.choose_css_button))
        self.choose_css_button.clicked.connect(
            lambda: self.fileChooser('css', self.cust_css_path, self.
                                     checkbox_css, self.choose_css_button))
        if len(self.prefs['useCssPath']):
            self.cust_css_path.setText(self.prefs['useCssPath'])
        self.cust_css_path.setEnabled(False)
        self.chkBoxActions(self.checkbox_css, self.choose_css_button)

        main_layout.addWidget(self.groupBox)
        self.checkbox_debug = QCheckBox()
        main_layout.addWidget(self.checkbox_debug)
        self.checkbox_debug.setChecked(self.prefs['debug'])

        spacerItem = QSpacerItem(20, 15, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        main_layout.addItem(spacerItem)

        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._ok_clicked)
        button_box.rejected.connect(self._cancel_clicked)
        main_layout.addWidget(button_box)
        self.retranslateUi(self)
        if self.prefs['qt_geometry'] is not None:
            try:
                self.restoreGeometry(
                    QByteArray.fromHex(
                        self.prefs['qt_geometry'].encode('ascii')))
            except:
                pass
        self.show()
Beispiel #49
0
    def __init__(self):
        # run in debug mode?
        self.rundebug = False

        # program info
        self.version = '2.1.2'
        self.version_date = '2020-05-05'
        self.author = 'Reto Trappitsch'

        # initialize the thing
        super().__init__()
        self.title = 'RIMS Scheme Drawer'
        self.left = 50
        self.top = 80
        self.width = 20
        self.height = 20

        # initialize the UI
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # settings:
        self.numberofsteps = 7
        self.lineedit_size = QSize(100, 20)

        # entries and labels necessary
        self.rbtngrp_units = QButtonGroup()
        self.rbtn_nm = QRadioButton('nm')
        self.rbtn_cm = QRadioButton()
        self.lbl_steps = []
        self.edt_level = []
        self.edt_term = []
        self.edt_gslevel = QLineEdit()
        self.edt_gsterm = QLineEdit()
        self.edt_iplevel = QLineEdit()
        self.edt_ipterm = QLineEdit()
        self.chk_lowlying = []
        self.chk_forbidden = []

        # settings line edits
        self.edt_sett_figwidth = QLineEdit()
        self.edt_sett_figheight = QLineEdit()
        self.edt_sett_fstitle = QLineEdit()
        self.edt_sett_fsaxes = QLineEdit()
        self.edt_sett_fsaxlbl = QLineEdit()
        self.chk_sett_linebreaks = QCheckBox('Line breaks?')
        self.chk_sett_showcmax = QCheckBox()  # no label -> label in layout
        self.chk_sett_showcmax.setChecked(True)
        self.chk_sett_showevax = QCheckBox('Show eV axis labels?')
        self.chk_sett_showevax.setChecked(True)
        self.edt_sett_fslbl = QLineEdit()
        self.edt_sett_headspace = QLineEdit()
        self.edt_sett_arrwidth = QLineEdit()
        self.edt_sett_arrheadwidth = QLineEdit()
        self.edt_sett_preclambda = QLineEdit()
        self.edt_sett_preclevel = QLineEdit()
        self.rbtngrp_iplabel = QButtonGroup()
        self.rbtn_iplable_top = QRadioButton('Top')
        self.rbtn_iplable_bottom = QRadioButton('Bott.')
        self.rbtngrp_sett_forbidden = QButtonGroup()
        self.rbtn_sett_xoutarrow = QRadioButton('x-out')
        self.rbtn_sett_nodisparrow = QRadioButton('Don\'t show')
        self.edt_sett_plttitle = QLineEdit()

        # push buttons
        self.btn_plot = QPushButton('Plot')
        self.btn_save = QPushButton('Save Plot')
        self.btn_load_conf = QPushButton('Load Config')
        self.btn_save_conf = QPushButton('Save Config')
        self.btn_test = QPushButton('Test')
        self.btn_about = QPushButton('About')
        self.btn_quit = QPushButton('Quit')

        # main widget
        self.mainwidget = QWidget()
        self.setCentralWidget(self.mainwidget)

        # style forms
        self.fontheader = QFont()
        self.fontheader.setBold(True)

        # initialize the UI
        self.initUI()

        # set testing values if debugging
        if self.rundebug:
            self.fill_testing_values()

        # set default values
        self.fill_default_values()

        # show the UI
        self.show()
Beispiel #50
0
class MainWindow(QMainWindow):
    receiveUpdateSignal = pyqtSignal(str)
    errorSignal = pyqtSignal(str)
    showSerialComboboxSignal = pyqtSignal()
    setDisableSettingsSignal = pyqtSignal(bool)
    isDetectSerialPort = False
    receiveCount = 0
    sendCount = 0
    isScheduledSending = False
    DataPath = "./"
    isHideSettings = False
    isHideFunctinal = True
    app = None
    isWaveOpen = False

    def __init__(self, app):
        super().__init__()
        self.app = app
        pathDirList = sys.argv[0].replace("\\", "/").split("/")
        pathDirList.pop()
        self.DataPath = os.path.abspath("/".join(str(i) for i in pathDirList))
        if not os.path.exists(self.DataPath + "/" + parameters.strDataDirName):
            pathDirList.pop()
            self.DataPath = os.path.abspath("/".join(
                str(i) for i in pathDirList))
        self.DataPath = (self.DataPath + "/" +
                         parameters.strDataDirName).replace("\\", "/")
        self.initWindow()
        self.initTool()
        self.initEvent()
        self.programStartGetSavedParameters()

    def __del__(self):
        pass

    def initTool(self):
        self.com = serial.Serial()

    def initWindow(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        # main layout
        frameWidget = QWidget()
        mainWidget = QSplitter(Qt.Horizontal)
        frameLayout = QVBoxLayout()
        self.settingWidget = QWidget()
        self.settingWidget.setProperty("class", "settingWidget")
        self.receiveSendWidget = QSplitter(Qt.Vertical)
        self.functionalWiget = QWidget()
        settingLayout = QVBoxLayout()
        sendReceiveLayout = QVBoxLayout()
        sendFunctionalLayout = QVBoxLayout()
        mainLayout = QHBoxLayout()
        self.settingWidget.setLayout(settingLayout)
        self.receiveSendWidget.setLayout(sendReceiveLayout)
        self.functionalWiget.setLayout(sendFunctionalLayout)
        mainLayout.addWidget(self.settingWidget)
        mainLayout.addWidget(self.receiveSendWidget)
        mainLayout.addWidget(self.functionalWiget)
        mainLayout.setStretch(0, 2)
        mainLayout.setStretch(1, 6)
        mainLayout.setStretch(2, 2)
        menuLayout = QHBoxLayout()
        mainWidget.setLayout(mainLayout)
        frameLayout.addLayout(menuLayout)
        frameLayout.addWidget(mainWidget)
        frameWidget.setLayout(frameLayout)
        self.setCentralWidget(frameWidget)

        # option layout
        self.settingsButton = QPushButton()
        self.skinButton = QPushButton("")
        # self.waveButton = QPushButton("")
        self.aboutButton = QPushButton()
        self.functionalButton = QPushButton()
        self.encodingCombobox = ComboBox()
        self.encodingCombobox.addItem("ASCII")
        self.encodingCombobox.addItem("UTF-8")
        self.encodingCombobox.addItem("UTF-16")
        self.encodingCombobox.addItem("GBK")
        self.encodingCombobox.addItem("GB2312")
        self.encodingCombobox.addItem("GB18030")
        self.settingsButton.setProperty("class", "menuItem1")
        self.skinButton.setProperty("class", "menuItem2")
        self.aboutButton.setProperty("class", "menuItem3")
        self.functionalButton.setProperty("class", "menuItem4")
        # self.waveButton.setProperty("class", "menuItem5")
        self.settingsButton.setObjectName("menuItem")
        self.skinButton.setObjectName("menuItem")
        self.aboutButton.setObjectName("menuItem")
        self.functionalButton.setObjectName("menuItem")
        # self.waveButton.setObjectName("menuItem")
        menuLayout.addWidget(self.settingsButton)
        menuLayout.addWidget(self.skinButton)
        # menuLayout.addWidget(self.waveButton)
        menuLayout.addWidget(self.aboutButton)
        menuLayout.addStretch(0)
        menuLayout.addWidget(self.encodingCombobox)
        menuLayout.addWidget(self.functionalButton)

        # widgets receive and send area
        self.receiveArea = QTextEdit()
        self.sendArea = QTextEdit()
        self.clearReceiveButtion = QPushButton(parameters.strClearReceive)
        self.sendButtion = QPushButton(parameters.strSend)
        self.sendHistory = ComboBox()
        sendWidget = QWidget()
        sendAreaWidgetsLayout = QHBoxLayout()
        sendWidget.setLayout(sendAreaWidgetsLayout)
        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.clearReceiveButtion)
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.sendButtion)
        sendAreaWidgetsLayout.addWidget(self.sendArea)
        sendAreaWidgetsLayout.addLayout(buttonLayout)
        sendReceiveLayout.addWidget(self.receiveArea)
        sendReceiveLayout.addWidget(sendWidget)
        sendReceiveLayout.addWidget(self.sendHistory)
        sendReceiveLayout.setStretch(0, 7)
        sendReceiveLayout.setStretch(1, 2)
        sendReceiveLayout.setStretch(2, 1)

        # widgets serial settings
        serialSettingsGroupBox = QGroupBox(parameters.strSerialSettings)
        serialSettingsLayout = QGridLayout()
        serialReceiveSettingsLayout = QGridLayout()
        serialSendSettingsLayout = QGridLayout()
        serialPortLabek = QLabel(parameters.strSerialPort)
        serailBaudrateLabel = QLabel(parameters.strSerialBaudrate)
        serailBytesLabel = QLabel(parameters.strSerialBytes)
        serailParityLabel = QLabel(parameters.strSerialParity)
        serailStopbitsLabel = QLabel(parameters.strSerialStopbits)
        self.serialPortCombobox = ComboBox()
        self.serailBaudrateCombobox = ComboBox()
        self.serailBaudrateCombobox.addItem("9600")
        self.serailBaudrateCombobox.addItem("19200")
        self.serailBaudrateCombobox.addItem("38400")
        self.serailBaudrateCombobox.addItem("57600")
        self.serailBaudrateCombobox.addItem("115200")
        self.serailBaudrateCombobox.setCurrentIndex(4)
        self.serailBaudrateCombobox.setEditable(True)
        self.serailBytesCombobox = ComboBox()
        self.serailBytesCombobox.addItem("5")
        self.serailBytesCombobox.addItem("6")
        self.serailBytesCombobox.addItem("7")
        self.serailBytesCombobox.addItem("8")
        self.serailBytesCombobox.setCurrentIndex(3)
        self.serailParityCombobox = ComboBox()
        self.serailParityCombobox.addItem("None")
        self.serailParityCombobox.addItem("Odd")
        self.serailParityCombobox.addItem("Even")
        self.serailParityCombobox.addItem("Mark")
        self.serailParityCombobox.addItem("Space")
        self.serailParityCombobox.setCurrentIndex(0)
        self.serailStopbitsCombobox = ComboBox()
        self.serailStopbitsCombobox.addItem("1")
        self.serailStopbitsCombobox.addItem("1.5")
        self.serailStopbitsCombobox.addItem("2")
        self.serailStopbitsCombobox.setCurrentIndex(0)
        self.checkBoxRts = QCheckBox("rts")
        self.checkBoxDtr = QCheckBox("dtr")
        self.serialOpenCloseButton = QPushButton(parameters.strOpen)
        serialSettingsLayout.addWidget(serialPortLabek, 0, 0)
        serialSettingsLayout.addWidget(serailBaudrateLabel, 1, 0)
        serialSettingsLayout.addWidget(serailBytesLabel, 2, 0)
        serialSettingsLayout.addWidget(serailParityLabel, 3, 0)
        serialSettingsLayout.addWidget(serailStopbitsLabel, 4, 0)
        serialSettingsLayout.addWidget(self.serialPortCombobox, 0, 1)
        serialSettingsLayout.addWidget(self.serailBaudrateCombobox, 1, 1)
        serialSettingsLayout.addWidget(self.serailBytesCombobox, 2, 1)
        serialSettingsLayout.addWidget(self.serailParityCombobox, 3, 1)
        serialSettingsLayout.addWidget(self.serailStopbitsCombobox, 4, 1)
        serialSettingsLayout.addWidget(self.checkBoxRts, 5, 0, 1, 1)
        serialSettingsLayout.addWidget(self.checkBoxDtr, 5, 1, 1, 1)
        serialSettingsLayout.addWidget(self.serialOpenCloseButton, 6, 0, 1, 2)
        serialSettingsGroupBox.setLayout(serialSettingsLayout)
        settingLayout.addWidget(serialSettingsGroupBox)

        # serial receive settings
        serialReceiveSettingsGroupBox = QGroupBox(
            parameters.strSerialReceiveSettings)
        self.receiveSettingsAscii = QRadioButton(parameters.strAscii)
        self.receiveSettingsHex = QRadioButton(parameters.strHex)
        self.receiveSettingsAscii.setChecked(True)
        self.receiveSettingsAutoLinefeed = QCheckBox(
            parameters.strAutoLinefeed)
        self.receiveSettingsAutoLinefeedTime = QLineEdit(
            parameters.strAutoLinefeedTime)
        self.receiveSettingsAutoLinefeed.setMaximumWidth(75)
        self.receiveSettingsAutoLinefeedTime.setMaximumWidth(75)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAscii, 1, 0,
                                              1, 1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsHex, 1, 1, 1,
                                              1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAutoLinefeed,
                                              2, 0, 1, 1)
        serialReceiveSettingsLayout.addWidget(
            self.receiveSettingsAutoLinefeedTime, 2, 1, 1, 1)
        serialReceiveSettingsGroupBox.setLayout(serialReceiveSettingsLayout)
        settingLayout.addWidget(serialReceiveSettingsGroupBox)

        # serial send settings
        serialSendSettingsGroupBox = QGroupBox(
            parameters.strSerialSendSettings)
        self.sendSettingsAscii = QRadioButton(parameters.strAscii)
        self.sendSettingsHex = QRadioButton(parameters.strHex)
        self.sendSettingsAscii.setChecked(True)
        self.sendSettingsScheduledCheckBox = QCheckBox(parameters.strScheduled)
        self.sendSettingsScheduled = QLineEdit(parameters.strScheduledTime)
        self.sendSettingsScheduledCheckBox.setMaximumWidth(75)
        self.sendSettingsScheduled.setMaximumWidth(75)
        self.sendSettingsCFLF = QCheckBox(parameters.strCRLF)
        self.sendSettingsCFLF.setChecked(False)
        serialSendSettingsLayout.addWidget(self.sendSettingsAscii, 1, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsHex, 1, 1, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsScheduledCheckBox,
                                           2, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsScheduled, 2, 1, 1,
                                           1)
        serialSendSettingsLayout.addWidget(self.sendSettingsCFLF, 3, 0, 1, 2)
        serialSendSettingsGroupBox.setLayout(serialSendSettingsLayout)
        settingLayout.addWidget(serialSendSettingsGroupBox)

        settingLayout.setStretch(0, 5)
        settingLayout.setStretch(1, 2.5)
        settingLayout.setStretch(2, 2.5)

        # right functional layout
        self.filePathWidget = QLineEdit()
        self.openFileButton = QPushButton("Open File")
        self.sendFileButton = QPushButton("Send File")
        self.clearHistoryButton = QPushButton("Clear History")
        self.addButton = QPushButton(parameters.strAdd)
        fileSendGroupBox = QGroupBox(parameters.strSendFile)
        fileSendGridLayout = QGridLayout()
        fileSendGridLayout.addWidget(self.filePathWidget, 0, 0, 1, 1)
        fileSendGridLayout.addWidget(self.openFileButton, 0, 1, 1, 1)
        fileSendGridLayout.addWidget(self.sendFileButton, 1, 0, 1, 2)
        fileSendGroupBox.setLayout(fileSendGridLayout)
        sendFunctionalLayout.addWidget(fileSendGroupBox)
        sendFunctionalLayout.addWidget(self.clearHistoryButton)
        sendFunctionalLayout.addWidget(self.addButton)
        sendFunctionalLayout.addStretch(1)
        self.isHideFunctinal = True
        self.hideFunctional()

        # main window
        self.statusBarStauts = QLabel()
        self.statusBarStauts.setMinimumWidth(80)
        self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                     ("#008200", parameters.strReady))
        self.statusBarSendCount = QLabel(parameters.strSend + "(bytes): " +
                                         "0")
        self.statusBarReceiveCount = QLabel(parameters.strReceive +
                                            "(bytes): " + "0")
        self.statusBar().addWidget(self.statusBarStauts)
        self.statusBar().addWidget(self.statusBarSendCount, 2)
        self.statusBar().addWidget(self.statusBarReceiveCount, 3)
        # self.statusBar()

        self.resize(800, 500)
        self.MoveToCenter()
        self.setWindowTitle(parameters.appName + " V" +
                            str(helpAbout.versionMajor) + "." +
                            str(helpAbout.versionMinor))
        icon = QIcon()
        print("icon path:" + self.DataPath + "/" + parameters.appIcon)
        icon.addPixmap(QPixmap(self.DataPath + "/" + parameters.appIcon),
                       QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        if sys.platform == "win32":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                "comtool")
        self.show()
        print("config file path:", os.getcwd() + "/comtool.settings.config")

    def initEvent(self):
        self.serialOpenCloseButton.clicked.connect(self.openCloseSerial)
        self.sendButtion.clicked.connect(self.sendData)
        self.receiveUpdateSignal.connect(self.updateReceivedDataDisplay)
        self.clearReceiveButtion.clicked.connect(self.clearReceiveBuffer)
        self.serialPortCombobox.clicked.connect(self.portComboboxClicked)
        self.sendSettingsHex.clicked.connect(self.onSendSettingsHexClicked)
        self.sendSettingsAscii.clicked.connect(self.onSendSettingsAsciiClicked)
        self.errorSignal.connect(self.errorHint)
        self.showSerialComboboxSignal.connect(self.showCombobox)
        # self.showBaudComboboxSignal.connect(self.showBaudCombobox)
        self.setDisableSettingsSignal.connect(self.setDisableSettings)
        self.sendHistory.currentIndexChanged.connect(
            self.sendHistoryIndexChanged)
        self.settingsButton.clicked.connect(self.showHideSettings)
        self.skinButton.clicked.connect(self.skinChange)
        self.aboutButton.clicked.connect(self.showAbout)
        self.openFileButton.clicked.connect(self.selectFile)
        self.sendFileButton.clicked.connect(self.sendFile)
        self.clearHistoryButton.clicked.connect(self.clearHistory)
        self.addButton.clicked.connect(self.functionAdd)
        self.functionalButton.clicked.connect(self.showHideFunctional)
        self.sendArea.currentCharFormatChanged.connect(
            self.sendAreaFontChanged)
        # self.waveButton.clicked.connect(self.openWaveDisplay)
        self.checkBoxRts.clicked.connect(self.rtsChanged)
        self.checkBoxDtr.clicked.connect(self.dtrChanged)

        self.myObject = MyClass(self)
        slotLambda = lambda: self.indexChanged_lambda(self.myObject)
        self.serialPortCombobox.currentIndexChanged.connect(slotLambda)

    # @QtCore.pyqtSlot(str)
    def indexChanged_lambda(self, obj):
        mainObj = obj.arg
        # print("item changed:",mainObj.serialPortCombobox.currentText())
        self.serialPortCombobox.setToolTip(
            mainObj.serialPortCombobox.currentText())

    def openCloseSerialProcess(self):
        try:
            if self.com.is_open:
                self.receiveProgressStop = True
                self.com.close()
                self.setDisableSettingsSignal.emit(False)
            else:
                try:
                    self.com.baudrate = int(
                        self.serailBaudrateCombobox.currentText())
                    self.com.port = self.serialPortCombobox.currentText(
                    ).split(" ")[0]
                    self.com.bytesize = int(
                        self.serailBytesCombobox.currentText())
                    self.com.parity = self.serailParityCombobox.currentText(
                    )[0]
                    self.com.stopbits = float(
                        self.serailStopbitsCombobox.currentText())
                    self.com.timeout = None
                    if self.checkBoxRts.isChecked():
                        self.com.rts = False
                    else:
                        self.com.rts = True
                    if self.checkBoxDtr.isChecked():
                        self.com.dtr = False
                    else:
                        self.com.dtr = True
                    self.com.open()
                    # print("open success")
                    # print(self.com)
                    self.setDisableSettingsSignal.emit(True)
                    self.receiveProcess = threading.Thread(
                        target=self.receiveData)
                    self.receiveProcess.setDaemon(True)
                    self.receiveProcess.start()
                except Exception as e:
                    self.com.close()
                    self.receiveProgressStop = True
                    self.errorSignal.emit(parameters.strOpenFailed + "\n" +
                                          str(e))
                    self.setDisableSettingsSignal.emit(False)
        except Exception as e:
            print(e)

    def setDisableSettings(self, disable):
        if disable:
            self.serialOpenCloseButton.setText(parameters.strClose)
            self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                         ("#008200", parameters.strReady))
            self.serialPortCombobox.setDisabled(True)
            self.serailBaudrateCombobox.setDisabled(True)
            self.serailParityCombobox.setDisabled(True)
            self.serailStopbitsCombobox.setDisabled(True)
            self.serailBytesCombobox.setDisabled(True)
            self.serialOpenCloseButton.setDisabled(False)
        else:
            self.serialOpenCloseButton.setText(parameters.strOpen)
            self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                         ("#f31414", parameters.strClosed))
            self.serialPortCombobox.setDisabled(False)
            self.serailBaudrateCombobox.setDisabled(False)
            self.serailParityCombobox.setDisabled(False)
            self.serailStopbitsCombobox.setDisabled(False)
            self.serailBytesCombobox.setDisabled(False)
            self.programExitSaveParameters()

    def openCloseSerial(self):
        t = threading.Thread(target=self.openCloseSerialProcess)
        t.setDaemon(True)
        t.start()

    def rtsChanged(self):
        if self.checkBoxRts.isChecked():
            self.com.setRTS(False)
        else:
            self.com.setRTS(True)

    def dtrChanged(self):
        if self.checkBoxDtr.isChecked():
            self.com.setDTR(False)
        else:
            self.com.setDTR(True)

    def portComboboxClicked(self):
        self.detectSerialPort()

    def getSendData(self):
        data = self.sendArea.toPlainText()
        if self.sendSettingsCFLF.isChecked():
            data = data.replace("\n", "\r\n")
        if self.sendSettingsHex.isChecked():
            if self.sendSettingsCFLF.isChecked():
                data = data.replace("\r\n", " ")
            else:
                data = data.replace("\n", " ")
            data = self.hexStringB2Hex(data)
            if data == -1:
                self.errorSignal.emit(parameters.strWriteFormatError)
                return -1
        else:
            data = data.encode(self.encodingCombobox.currentText(), "ignore")
        return data

    def sendData(self):
        try:
            if self.com.is_open:
                data = self.getSendData()
                if data == -1:
                    return
                # print(self.sendArea.toPlainText())
                # print("send:",data)
                self.sendCount += len(data)
                self.com.write(data)
                data = self.sendArea.toPlainText()
                self.sendHistoryFindDelete(data)
                self.sendHistory.insertItem(0, data)
                self.sendHistory.setCurrentIndex(0)
                self.receiveUpdateSignal.emit("")
                # scheduled send
                if self.sendSettingsScheduledCheckBox.isChecked():
                    if not self.isScheduledSending:
                        t = threading.Thread(target=self.scheduledSend)
                        t.setDaemon(True)
                        t.start()
        except Exception as e:
            self.errorSignal.emit(parameters.strWriteError)
            # print(e)

    def scheduledSend(self):
        self.isScheduledSending = True
        while self.sendSettingsScheduledCheckBox.isChecked():
            self.sendData()
            try:
                time.sleep(
                    int(self.sendSettingsScheduled.text().strip()) / 1000)
            except Exception:
                self.errorSignal.emit(parameters.strTimeFormatError)
        self.isScheduledSending = False

    def receiveData(self):
        self.receiveProgressStop = False
        self.timeLastReceive = 0
        while (not self.receiveProgressStop):
            try:
                # length = self.com.in_waiting
                length = max(1, min(2048, self.com.in_waiting))
                bytes = self.com.read(length)
                if bytes != None:

                    # if self.isWaveOpen:
                    #     self.wave.displayData(bytes)
                    self.receiveCount += len(bytes)
                    if self.receiveSettingsAutoLinefeed.isChecked():
                        if time.time() - self.timeLastReceive > int(
                                self.receiveSettingsAutoLinefeedTime.text(
                                )) / 1000:
                            if self.sendSettingsCFLF.isChecked():
                                self.receiveUpdateSignal.emit("\r\n")
                            else:
                                self.receiveUpdateSignal.emit("\n")
                            self.timeLastReceive = time.time()
                    if self.receiveSettingsHex.isChecked():
                        strReceived = self.asciiB2HexString(bytes)
                        self.receiveUpdateSignal.emit(strReceived)
                    else:
                        self.receiveUpdateSignal.emit(
                            bytes.decode(self.encodingCombobox.currentText(),
                                         "ignore"))
            except Exception as e:
                # print("receiveData error")
                # if self.com.is_open and not self.serialPortCombobox.isEnabled():
                #     self.openCloseSerial()
                #     self.serialPortCombobox.clear()
                #     self.detectSerialPort()
                if 'multiple access' in str(e):
                    self.errorSignal.emit(
                        "device disconnected or multiple access on port?")
                break
            # time.sleep(0.009)

    def updateReceivedDataDisplay(self, str):
        if str != "":
            curScrollValue = self.receiveArea.verticalScrollBar().value()
            self.receiveArea.moveCursor(QTextCursor.End)
            endScrollValue = self.receiveArea.verticalScrollBar().value()
            self.receiveArea.insertPlainText(str)
            if curScrollValue < endScrollValue:
                self.receiveArea.verticalScrollBar().setValue(curScrollValue)
            else:
                self.receiveArea.moveCursor(QTextCursor.End)
        self.statusBarSendCount.setText("%s(bytes):%d" %
                                        (parameters.strSend, self.sendCount))
        self.statusBarReceiveCount.setText(
            "%s(bytes):%d" % (parameters.strReceive, self.receiveCount))

    def onSendSettingsHexClicked(self):

        data = self.sendArea.toPlainText().replace("\n", "\r\n")
        data = self.asciiB2HexString(data.encode())
        self.sendArea.clear()
        self.sendArea.insertPlainText(data)

    def onSendSettingsAsciiClicked(self):
        try:
            data = self.sendArea.toPlainText().replace("\n", " ").strip()
            self.sendArea.clear()
            if data != "":
                data = self.hexStringB2Hex(data).decode(
                    self.encodingCombobox.currentText(), 'ignore')
                self.sendArea.insertPlainText(data)
        except Exception as e:
            # QMessageBox.information(self,parameters.strWriteFormatError,parameters.strWriteFormatError)
            print("format error")

    def sendHistoryIndexChanged(self):
        self.sendArea.clear()
        self.sendArea.insertPlainText(self.sendHistory.currentText())

    def clearReceiveBuffer(self):
        self.receiveArea.clear()
        self.receiveCount = 0
        self.sendCount = 0
        self.receiveUpdateSignal.emit(None)

    def MoveToCenter(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def errorHint(self, str):
        QMessageBox.information(self, str, str)

    def closeEvent(self, event):

        reply = QMessageBox.question(self, 'Sure To Quit?',
                                     "Are you sure to quit?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.com.close()
            self.receiveProgressStop = True
            self.programExitSaveParameters()
            event.accept()
        else:
            event.ignore()

    def findSerialPort(self):
        self.port_list = list(serial.tools.list_ports.comports())
        return self.port_list

    def portChanged(self):
        self.serialPortCombobox.setCurrentIndex(0)
        self.serialPortCombobox.setToolTip(str(self.portList[0]))

    def detectSerialPort(self):
        if not self.isDetectSerialPort:
            self.isDetectSerialPort = True
            t = threading.Thread(target=self.detectSerialPortProcess)
            t.setDaemon(True)
            t.start()

    def showCombobox(self):
        self.serialPortCombobox.showPopup()

    def detectSerialPortProcess(self):
        while (1):
            portList = self.findSerialPort()
            if len(portList) > 0:
                currText = self.serialPortCombobox.currentText()
                self.serialPortCombobox.clear()
                for i in portList:
                    showStr = str(i[0]) + " " + str(i[1])
                    self.serialPortCombobox.addItem(showStr)
                index = self.serialPortCombobox.findText(currText)
                if index >= 0:
                    self.serialPortCombobox.setCurrentIndex(index)
                else:
                    self.serialPortCombobox.setCurrentIndex(0)
                break
            time.sleep(1)
        self.showSerialComboboxSignal.emit()
        self.isDetectSerialPort = False

    def sendHistoryFindDelete(self, str):
        self.sendHistory.removeItem(self.sendHistory.findText(str))

    def asciiB2HexString(self, strB):
        strHex = binascii.b2a_hex(strB).upper()
        return re.sub(r"(?<=\w)(?=(?:\w\w)+$)", " ", strHex.decode()) + " "

    def hexStringB2Hex(self, hexString):
        dataList = hexString.split(" ")
        j = 0
        for i in dataList:
            if len(i) > 2:
                return -1
            elif len(i) == 1:
                dataList[j] = "0" + i
            j += 1
        data = "".join(dataList)
        try:
            data = bytes.fromhex(data)
        except Exception:
            return -1
        # print(data)
        return data

    def programExitSaveParameters(self):
        paramObj = parameters.ParametersToSave()
        paramObj.baudRate = self.serailBaudrateCombobox.currentIndex()
        paramObj.dataBytes = self.serailBytesCombobox.currentIndex()
        paramObj.parity = self.serailParityCombobox.currentIndex()
        paramObj.stopBits = self.serailStopbitsCombobox.currentIndex()
        paramObj.skin = self.param.skin
        if self.receiveSettingsHex.isChecked():
            paramObj.receiveAscii = False
        if not self.receiveSettingsAutoLinefeed.isChecked():
            paramObj.receiveAutoLinefeed = False
        else:
            paramObj.receiveAutoLinefeed = True
        paramObj.receiveAutoLindefeedTime = self.receiveSettingsAutoLinefeedTime.text(
        )
        if self.sendSettingsHex.isChecked():
            paramObj.sendAscii = False
        if not self.sendSettingsScheduledCheckBox.isChecked():
            paramObj.sendScheduled = False
        paramObj.sendScheduledTime = self.sendSettingsScheduled.text()
        if not self.sendSettingsCFLF.isChecked():
            paramObj.useCRLF = False
        paramObj.sendHistoryList.clear()
        for i in range(0, self.sendHistory.count()):
            paramObj.sendHistoryList.append(self.sendHistory.itemText(i))
        if self.checkBoxRts.isChecked():
            paramObj.rts = 1
        else:
            paramObj.rts = 0
        if self.checkBoxDtr.isChecked():
            paramObj.dtr = 1
        else:
            paramObj.dtr = 0
        paramObj.encodingIndex = self.encodingCombobox.currentIndex()
        f = open("comtool.settings.config", "wb")
        f.truncate()
        pickle.dump(paramObj, f)
        pickle.dump(paramObj.sendHistoryList, f)
        f.close()

    def programStartGetSavedParameters(self):
        paramObj = parameters.ParametersToSave()
        try:
            f = open("comtool.settings.config", "rb")
            paramObj = pickle.load(f)
            paramObj.sendHistoryList = pickle.load(f)
            f.close()
        except Exception as e:
            f = open("comtool.settings.config", "wb")
            f.close()
        self.serailBaudrateCombobox.setCurrentIndex(paramObj.baudRate)
        self.serailBytesCombobox.setCurrentIndex(paramObj.dataBytes)
        self.serailParityCombobox.setCurrentIndex(paramObj.parity)
        self.serailStopbitsCombobox.setCurrentIndex(paramObj.stopBits)
        if paramObj.receiveAscii == False:
            self.receiveSettingsHex.setChecked(True)
        if paramObj.receiveAutoLinefeed == False:
            self.receiveSettingsAutoLinefeed.setChecked(False)
        else:
            self.receiveSettingsAutoLinefeed.setChecked(True)
        self.receiveSettingsAutoLinefeedTime.setText(
            paramObj.receiveAutoLindefeedTime)
        if paramObj.sendAscii == False:
            self.sendSettingsHex.setChecked(True)
        if paramObj.sendScheduled == False:
            self.sendSettingsScheduledCheckBox.setChecked(False)
        else:
            self.sendSettingsScheduledCheckBox.setChecked(True)
        self.sendSettingsScheduled.setText(paramObj.sendScheduledTime)
        if paramObj.useCRLF == False:
            self.sendSettingsCFLF.setChecked(False)
        else:
            self.sendSettingsCFLF.setChecked(True)
        for i in range(0, len(paramObj.sendHistoryList)):
            str = paramObj.sendHistoryList[i]
            self.sendHistory.addItem(str)
        if paramObj.rts == 0:
            self.checkBoxRts.setChecked(False)
        else:
            self.checkBoxRts.setChecked(True)
        if paramObj.dtr == 0:
            self.checkBoxDtr.setChecked(False)
        else:
            self.checkBoxDtr.setChecked(True)
        self.encodingCombobox.setCurrentIndex(paramObj.encodingIndex)
        self.param = paramObj

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Control:
            self.keyControlPressed = True
        elif event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
            if self.keyControlPressed:
                self.sendData()
        elif event.key() == Qt.Key_L:
            if self.keyControlPressed:
                self.sendArea.clear()
        elif event.key() == Qt.Key_K:
            if self.keyControlPressed:
                self.receiveArea.clear()

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Control:
            self.keyControlPressed = False

    def sendAreaFontChanged(self, font):
        print("font changed")

    def functionAdd(self):
        QMessageBox.information(self, "On the way", "On the way")

    def showHideSettings(self):
        if self.isHideSettings:
            self.showSettings()
            self.isHideSettings = False
        else:
            self.hideSettings()
            self.isHideSettings = True

    def showSettings(self):
        self.settingWidget.show()
        self.settingsButton.setStyleSheet(
            parameters.strStyleShowHideButtonLeft.replace(
                "$DataPath", self.DataPath))

    def hideSettings(self):
        self.settingWidget.hide()
        self.settingsButton.setStyleSheet(
            parameters.strStyleShowHideButtonRight.replace(
                "$DataPath", self.DataPath))

    def showHideFunctional(self):
        if self.isHideFunctinal:
            self.showFunctional()
            self.isHideFunctinal = False
        else:
            self.hideFunctional()
            self.isHideFunctinal = True

    def showFunctional(self):
        self.functionalWiget.show()
        self.functionalButton.setStyleSheet(
            parameters.strStyleShowHideButtonRight.replace(
                "$DataPath", self.DataPath))

    def hideFunctional(self):
        self.functionalWiget.hide()
        self.functionalButton.setStyleSheet(
            parameters.strStyleShowHideButtonLeft.replace(
                "$DataPath", self.DataPath))

    def skinChange(self):
        if self.param.skin == 1:  # light
            file = open(self.DataPath + '/assets/qss/style-dark.qss', "r")
            self.param.skin = 2
        else:  # elif self.param.skin == 2: # dark
            file = open(self.DataPath + '/assets/qss/style.qss', "r")
            self.param.skin = 1
        self.app.setStyleSheet(file.read().replace("$DataPath", self.DataPath))

    def showAbout(self):
        QMessageBox.information(
            self, "About",
            "<h1 style='color:#f75a5a';margin=10px;>" + parameters.appName +
            '</h1><br><b style="color:#08c7a1;margin = 5px;">V' +
            str(helpAbout.versionMajor) + "." + str(helpAbout.versionMinor) +
            "." + str(helpAbout.versionDev) + "</b><br><br>" + helpAbout.date +
            "<br><br>" + helpAbout.strAbout())

    def selectFile(self):
        oldPath = self.filePathWidget.text()
        if oldPath == "":
            oldPath = os.getcwd()
        fileName_choose, filetype = QFileDialog.getOpenFileName(
            self, "SelectFile", oldPath, "All Files (*);;")

        if fileName_choose == "":
            return
        self.filePathWidget.setText(fileName_choose)

    def sendFile(self):
        filename = self.filePathWidget.text()
        if not os.path.exists(filename):
            self.errorSignal.emit("File path error\npath:%s" % (filename))
            return
        try:
            f = open(filename, "rb")
        except Exception as e:
            self.errorSignal.emit("Open file %s failed! \n %s" %
                                  (filename, str(e)))
            return
        self.com.write(f.read())  #TODO: optimize send in new thread
        f.close()

    def clearHistory(self):
        self.param.sendHistoryList.clear()
        self.sendHistory.clear()
        self.errorSignal.emit("History cleared!")

    def autoUpdateDetect(self):
        auto = autoUpdate.AutoUpdate()
        if auto.detectNewVersion():
            auto.OpenBrowser()

    def openDevManagement(self):
        os.system('start devmgmt.msc')
Beispiel #51
0
class SchemeDrawer(QMainWindow):
    """
    RIMSSchemeDrawer

    Developer:  Reto Trappitsch
    Version:    2.1.2
    Date:       May 27, 2020
    """
    def __init__(self):
        # run in debug mode?
        self.rundebug = False

        # program info
        self.version = '2.1.2'
        self.version_date = '2020-05-05'
        self.author = 'Reto Trappitsch'

        # initialize the thing
        super().__init__()
        self.title = 'RIMS Scheme Drawer'
        self.left = 50
        self.top = 80
        self.width = 20
        self.height = 20

        # initialize the UI
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # settings:
        self.numberofsteps = 7
        self.lineedit_size = QSize(100, 20)

        # entries and labels necessary
        self.rbtngrp_units = QButtonGroup()
        self.rbtn_nm = QRadioButton('nm')
        self.rbtn_cm = QRadioButton()
        self.lbl_steps = []
        self.edt_level = []
        self.edt_term = []
        self.edt_gslevel = QLineEdit()
        self.edt_gsterm = QLineEdit()
        self.edt_iplevel = QLineEdit()
        self.edt_ipterm = QLineEdit()
        self.chk_lowlying = []
        self.chk_forbidden = []

        # settings line edits
        self.edt_sett_figwidth = QLineEdit()
        self.edt_sett_figheight = QLineEdit()
        self.edt_sett_fstitle = QLineEdit()
        self.edt_sett_fsaxes = QLineEdit()
        self.edt_sett_fsaxlbl = QLineEdit()
        self.chk_sett_linebreaks = QCheckBox('Line breaks?')
        self.chk_sett_showcmax = QCheckBox()  # no label -> label in layout
        self.chk_sett_showcmax.setChecked(True)
        self.chk_sett_showevax = QCheckBox('Show eV axis labels?')
        self.chk_sett_showevax.setChecked(True)
        self.edt_sett_fslbl = QLineEdit()
        self.edt_sett_headspace = QLineEdit()
        self.edt_sett_arrwidth = QLineEdit()
        self.edt_sett_arrheadwidth = QLineEdit()
        self.edt_sett_preclambda = QLineEdit()
        self.edt_sett_preclevel = QLineEdit()
        self.rbtngrp_iplabel = QButtonGroup()
        self.rbtn_iplable_top = QRadioButton('Top')
        self.rbtn_iplable_bottom = QRadioButton('Bott.')
        self.rbtngrp_sett_forbidden = QButtonGroup()
        self.rbtn_sett_xoutarrow = QRadioButton('x-out')
        self.rbtn_sett_nodisparrow = QRadioButton('Don\'t show')
        self.edt_sett_plttitle = QLineEdit()

        # push buttons
        self.btn_plot = QPushButton('Plot')
        self.btn_save = QPushButton('Save Plot')
        self.btn_load_conf = QPushButton('Load Config')
        self.btn_save_conf = QPushButton('Save Config')
        self.btn_test = QPushButton('Test')
        self.btn_about = QPushButton('About')
        self.btn_quit = QPushButton('Quit')

        # main widget
        self.mainwidget = QWidget()
        self.setCentralWidget(self.mainwidget)

        # style forms
        self.fontheader = QFont()
        self.fontheader.setBold(True)

        # initialize the UI
        self.initUI()

        # set testing values if debugging
        if self.rundebug:
            self.fill_testing_values()

        # set default values
        self.fill_default_values()

        # show the UI
        self.show()

    def initUI(self):
        """
        Initialize the UI
        """
        # bottom most row:
        bottomrowindex = 12  # depends on how many settings entries there are!
        if self.numberofsteps + 2 > bottomrowindex:
            bottomrowindex = self.numberofsteps + 2

        # define the grid layout
        layout = QGridLayout()  # columns

        # ### column 1: labels for states
        # radiobuttons for nm or cm-1
        self.rbtngrp_units.addButton(self.rbtn_nm)
        self.rbtngrp_units.addButton(self.rbtn_cm)
        # set default
        self.rbtn_nm.setChecked(True)
        cmlabel = QLabel('cm<sup>-1</sup>')
        self.rbtn_nm.setToolTip('Enter steps of laser scheme in nm')
        self.rbtn_cm.setToolTip(
            'Enter steps of laser scheme in cm<sup>-1</sup>.')
        cmlabel.setToolTip('Enter steps of laser scheme in cm<sup>-1</sup>.')
        # add to layout
        rbtn_layout = QHBoxLayout()
        rbtn_layout.addWidget(self.rbtn_nm)
        rbtn_layout.addStretch()
        rbtn_layout.addWidget(self.rbtn_cm)
        # this is a workaround, since the Radiobutton cannot accept a rich text label. It works
        rbtn_layout.addWidget(cmlabel)
        layout.addLayout(rbtn_layout, 0, 0, 1, 1)

        # headers for all
        # level
        lbl_level = QLabel('Level')
        lbl_level.setFont(self.fontheader)
        layout.addWidget(lbl_level, 0, 1, 1, 1)
        # term symbol
        lbl_trmsymb = QLabel('Term Symbol')
        lbl_trmsymb.setFont(self.fontheader)
        layout.addWidget(lbl_trmsymb, 0, 2, 1, 1)
        # ground state manifold?
        lbl_gsmani = QLabel('GS Manifold?')
        lbl_gsmani.setFont(self.fontheader)
        layout.addWidget(lbl_gsmani, 0, 3, 1, 1)
        # Forbidden transition
        lbl_forbidden = QLabel('Forbidden?')
        lbl_forbidden.setFont(self.fontheader)
        layout.addWidget(lbl_forbidden, 0, 4, 1, 1)
        # Settings
        lbl_sett = QLabel('Settings')
        lbl_sett.setFont(self.fontheader)
        layout.addWidget(lbl_sett, 0, 5, 1, 1)
        # plot title
        lbl_plttit = QLabel('Plot Title')
        lbl_plttit.setFont(self.fontheader)
        layout.addWidget(lbl_plttit, 0, 7, 1, 1)

        # ground state
        lbl_gs = QLabel('Ground state (cm<sup>-1</sup>)')
        layout.addWidget(lbl_gs, 1, 0, 1, 1)
        layout.addWidget(self.edt_gslevel, 1, 1, 1, 1)
        layout.addWidget(self.edt_gsterm, 1, 2, 1, 1)
        self.edt_gslevel.setToolTip(
            'Set the ground state level in cm<sup>-1</sup>.')
        tt_termsymbol = 'For example, 2P3 for <sup>2</sup>P<sub>3</sub>. If only J-state is known, you ' \
                        'can also enter something like \'J=3\'.'
        self.edt_gsterm.setToolTip(
            'Set the term symbol for the ground state. ' + tt_termsymbol)

        # individual steps
        for it in range(self.numberofsteps):
            stepnumb = it + 1
            # make label and append
            self.lbl_steps.append(QLabel())
            layout.addWidget(self.lbl_steps[it], 2 + it, 0, 1, 1)
            # level steps
            self.edt_level.append(QLineEdit())
            self.edt_level[it].setFixedSize(self.lineedit_size)
            self.edt_level[it].setValidator(QDoubleValidator())
            self.edt_level[it].setAlignment(Qt.AlignRight)
            self.edt_level[it].setToolTip(
                'Enter the level of the given step in the selected unit.')
            layout.addWidget(self.edt_level[it], 2 + it, 1, 1, 1)
            # term symbol steps
            self.edt_term.append(QLineEdit())
            self.edt_term[it].setFixedSize(self.lineedit_size)
            self.edt_term[it].setToolTip(
                'Enter term symbol for selected step. ' + tt_termsymbol)
            layout.addWidget(self.edt_term[it], 2 + it, 2, 1, 1)
            # check boxes
            self.chk_lowlying.append(QCheckBox('Low-lying state?'))
            layout.addWidget(self.chk_lowlying[it], 2 + it, 3, 1, 1)
            self.chk_lowlying[it].toggled.connect(self.set_label_names)
            self.chk_lowlying[it].setToolTip(
                'Check if this is a low-lying state?')
            # forbidden transition
            self.chk_forbidden.append(QCheckBox())
            tmplayout = QHBoxLayout()
            tmplayout.addStretch()
            tmplayout.addWidget(self.chk_forbidden[it])
            tmplayout.addStretch()
            layout.addLayout(tmplayout, 2 + it, 4, 1, 1)
            self.chk_forbidden[it].setToolTip('Check this box to mark the\n'
                                              'transition as forbidden.')

        # name the labels
        self.set_label_names()

        # add IP label:
        ip_lbl = QLabel('IP (cm<sup>-1</sup>)')
        layout.addWidget(ip_lbl, 2 + len(self.lbl_steps), 0, 1, 1)
        layout.addWidget(self.edt_iplevel, 2 + len(self.lbl_steps), 1, 1, 1)
        layout.addWidget(self.edt_ipterm, 2 + len(self.lbl_steps), 2, 1, 1)
        self.edt_iplevel.setToolTip('Set IP level in cm<sup>-1</sup>.')
        self.edt_ipterm.setToolTip('Set term symbol of IP. ' + tt_termsymbol)

        # set sizes and validators of boxes defined outside loop
        self.edt_gslevel.setFixedSize(self.lineedit_size)
        self.edt_gslevel.setValidator(QDoubleValidator())
        self.edt_gslevel.setAlignment(Qt.AlignRight)
        self.edt_gsterm.setFixedSize(self.lineedit_size)
        self.edt_iplevel.setFixedSize(self.lineedit_size)
        self.edt_iplevel.setValidator(QDoubleValidator())
        self.edt_iplevel.setAlignment(Qt.AlignRight)
        self.edt_ipterm.setFixedSize(self.lineedit_size)

        # button group for ip label
        self.rbtngrp_iplabel.addButton(self.rbtn_iplable_top)
        self.rbtngrp_iplabel.addButton(self.rbtn_iplable_bottom)

        # button group for how to display forbidden transitions
        self.rbtngrp_sett_forbidden.addButton(self.rbtn_sett_xoutarrow)
        self.rbtngrp_sett_forbidden.addButton(self.rbtn_sett_nodisparrow)

        # labels for settings
        layout.addWidget(QLabel('Figure Width x Height:'), 1, 5, 1, 1)
        layout.addWidget(QLabel('Font size title:'), 2, 5, 1, 1)
        layout.addWidget(QLabel('Font size axes:'), 3, 5, 1, 1)
        layout.addWidget(QLabel('Font size axes label:'), 4, 5, 1, 1)
        layout.addWidget(QLabel('Font size labels:'), 5, 5, 1, 1)
        layout.addWidget(QLabel('Headspace (cm<sup>-1</sup>):'), 6, 5, 1, 1)
        layout.addWidget(QLabel('Arrow width:'), 7, 5, 1, 1)
        layout.addWidget(QLabel('Arrow head width:'), 8, 5, 1, 1)
        layout.addWidget(QLabel('Precision wavelength:'), 9, 5, 1, 1)
        layout.addWidget(QLabel('Precision level:'), 10, 5, 1, 1)
        layout.addWidget(QLabel('IP label position:'), 11, 5, 1, 1)
        layout.addWidget(QLabel('Display forbidden transitions:'), 12, 5, 1, 1)
        # line edits and buttons, include tooltips
        tmplayout = QHBoxLayout()
        tmplayout.addWidget(self.edt_sett_figwidth)
        self.edt_sett_figwidth.setToolTip('Width of figure in inches.')
        tmplayout.addStretch()
        tmplayout.addWidget(QLabel('x'))
        tmplayout.addStretch()
        tmplayout.addWidget(self.edt_sett_figheight)
        self.edt_sett_figheight.setToolTip('Height of figure in inches.')
        layout.addLayout(tmplayout, 1, 6, 1, 1)
        layout.addWidget(self.edt_sett_fstitle, 2, 6, 1, 1)
        self.edt_sett_fstitle.setToolTip('Font size of the plot title.')
        layout.addWidget(self.edt_sett_fsaxes, 3, 6, 1, 1)
        self.edt_sett_fsaxes.setToolTip('Font size of axes ticks.')
        layout.addWidget(self.edt_sett_fsaxlbl, 4, 6, 1, 1)
        self.edt_sett_fsaxlbl.setToolTip('Font size of axes labels.')
        # line breaks
        tmplayout = QHBoxLayout()
        tmplayout.addWidget(self.chk_sett_linebreaks)
        tmplayout.addStretch()
        layout.addLayout(tmplayout, 4, 7, 1, 1)
        self.chk_sett_linebreaks.setToolTip(
            'Should there be a line break between\n'
            'the state and the term symbol? Play\n'
            'with this to make the the plot look nicer.')
        layout.addWidget(self.edt_sett_fslbl, 5, 6, 1, 1)
        # check box show cm-1 axis
        tmplayout = QHBoxLayout()
        tmplayout.addWidget(self.chk_sett_showcmax)
        tmplayout.addStretch()
        tmplabel = QLabel('Show cm-1 axis labels?')
        tmplayout.addWidget(tmplabel)
        layout.addLayout(tmplayout, 5, 7, 1, 1)
        self.chk_sett_showcmax.setToolTip(
            'Show the cm<sup>-1</sup> (left) axis? You can turn this off in case you '
            'want to stich plots together afterwards! This function will also hide the '
            'ticks.')
        tmplabel.setToolTip(
            'Show the cm<sup>-1</sup> (left) axis? You can turn this off in case you '
            'want to stich plots together afterwards! This function will also hide the '
            'ticks.')
        self.edt_sett_fslbl.setToolTip('Font size of the labels.')
        layout.addWidget(self.edt_sett_headspace, 6, 6, 1, 1)
        # check box show eV axis
        tmplayout = QHBoxLayout()
        tmplayout.addWidget(self.chk_sett_showevax)
        tmplayout.addStretch()
        layout.addLayout(tmplayout, 6, 7, 1, 1)
        self.chk_sett_showevax.setToolTip(
            'Show the eV (right) axis? You can turn this\n'
            ' off in case you want to stich plots together\n'
            'afterwards! This function will also hide the\n'
            'ticks.')
        self.edt_sett_headspace.setToolTip(
            'Set how much space is added on top of the'
            'IP level: the head space. Adjust this'
            'value whenever there is not enough space'
            'on top to fit all the text in. The value'
            'is given in cm<sup>-1</sup>.')
        layout.addWidget(self.edt_sett_arrwidth, 7, 6, 1, 1)
        self.edt_sett_arrwidth.setToolTip(
            'Set the width of the arrow line in\n'
            'undefine dunits. Play to get the ideal\n'
            'settings.')
        layout.addWidget(self.edt_sett_arrheadwidth, 8, 6, 1, 1)
        self.edt_sett_arrheadwidth.setToolTip(
            'Set the width of the arrwo head in\n'
            'undefined units. Play to get the ideal\n'
            'settings.')
        layout.addWidget(self.edt_sett_preclambda, 9, 6, 1, 1)
        self.edt_sett_preclambda.setToolTip(
            'Set the precision with which the wavelength\n'
            'is displayed on the plot.')
        layout.addWidget(self.edt_sett_preclevel, 10, 6, 1, 1)
        self.edt_sett_preclevel.setToolTip(
            'Set the precision with which the wavenumber\n'
            'is displayed on the plot.')
        tmplayout = QHBoxLayout()
        tmplayout.addWidget(self.rbtn_iplable_top)
        self.rbtn_iplable_top.setChecked(True)  # set top as default
        tmplayout.addStretch()
        tmplayout.addWidget(self.rbtn_iplable_bottom)
        self.rbtn_iplable_top.setToolTip(
            'Display the IP label above the line.')
        self.rbtn_iplable_bottom.setToolTip(
            'Display the IP label below the line.')
        layout.addLayout(tmplayout, 11, 6, 1, 1)
        tmplayout = QHBoxLayout()
        tmplayout.addWidget(self.rbtn_sett_xoutarrow)
        self.rbtn_sett_xoutarrow.setChecked(True)  # set top as default
        tmplayout.addStretch()
        tmplayout.addWidget(self.rbtn_sett_nodisparrow)
        self.rbtn_sett_xoutarrow.setToolTip(
            'Show an arrow for forbidden transitions\n'
            'but cross it out.')
        self.rbtn_sett_nodisparrow.setToolTip(
            'Don\'t show arrows for forbidden\n'
            'transitions.')
        layout.addLayout(tmplayout, 12, 6, 1, 1)
        layout.addWidget(self.edt_sett_plttitle, 1, 7, 1, 1)
        self.edt_sett_plttitle.setToolTip('Title of the plot.')

        # set sizes
        self.edt_sett_plttitle.setFixedSize(self.lineedit_size)
        # validators
        self.edt_sett_figwidth.setValidator(QDoubleValidator())
        self.edt_sett_figheight.setValidator(QDoubleValidator())
        self.edt_sett_fstitle.setValidator(QIntValidator())
        self.edt_sett_fsaxes.setValidator(QIntValidator())
        self.edt_sett_fsaxlbl.setValidator(QIntValidator())
        self.edt_sett_fslbl.setValidator(QIntValidator())
        self.edt_sett_headspace.setValidator(QDoubleValidator())
        self.edt_sett_arrwidth.setValidator(QDoubleValidator())
        self.edt_sett_arrheadwidth.setValidator(QDoubleValidator())
        self.edt_sett_preclambda.setValidator(QIntValidator())
        self.edt_sett_preclevel.setValidator(QIntValidator())
        # alignment
        self.edt_sett_figwidth.setAlignment(Qt.AlignCenter)
        self.edt_sett_figheight.setAlignment(Qt.AlignCenter)
        self.edt_sett_fstitle.setAlignment(Qt.AlignRight)
        self.edt_sett_fsaxes.setAlignment(Qt.AlignRight)
        self.edt_sett_fsaxlbl.setAlignment(Qt.AlignRight)
        self.edt_sett_fslbl.setAlignment(Qt.AlignRight)
        self.edt_sett_headspace.setAlignment(Qt.AlignRight)
        self.edt_sett_arrwidth.setAlignment(Qt.AlignRight)
        self.edt_sett_arrheadwidth.setAlignment(Qt.AlignRight)
        self.edt_sett_preclambda.setAlignment(Qt.AlignRight)
        self.edt_sett_preclevel.setAlignment(Qt.AlignRight)

        # push buttons
        layout.addWidget(self.btn_plot, 2, 7, 1, 1)
        layout.addWidget(self.btn_save, 3, 7, 1, 1)
        if self.rundebug:
            layout.addWidget(self.btn_test, bottomrowindex - 4, 7, 1, 1)
        layout.addWidget(self.btn_load_conf, bottomrowindex - 3, 7, 1, 1)
        layout.addWidget(self.btn_save_conf, bottomrowindex - 2, 7, 1, 1)
        layout.addWidget(self.btn_about, bottomrowindex - 1, 7, 1, 1)
        layout.addWidget(self.btn_quit, bottomrowindex, 7, 1, 1)

        # connect it all up
        self.rbtn_nm.toggled.connect(self.set_label_names)
        self.rbtn_cm.toggled.connect(self.set_label_names)
        # buttons
        self.btn_plot.clicked.connect(self.plot)
        self.btn_plot.setToolTip('Plot the scheme.')
        self.btn_save.clicked.connect(self.save)
        self.btn_save.setToolTip(
            'Save the figure directly without plotting.\n'
            'The default format is pdf. Consider using\n'
            'the default setting, since it will result\n'
            'in a vector graphics. You can always check\n'
            'the matplotlib library documentation to find\n'
            'out what formats are possible.')
        self.btn_load_conf.clicked.connect(self.load_config)
        self.btn_load_conf.setToolTip('Load a saved configuration file.')
        self.btn_save_conf.clicked.connect(self.save_config)
        self.btn_save_conf.setToolTip(
            'Save the current configuration in a file.')
        self.btn_test.clicked.connect(self.test)
        self.btn_test.setToolTip(
            'This button should not be visible. If it is\n'
            'visible, it means that the\n'
            'self.rundebug\n'
            'value in the software is set to True. This\n'
            'is only meant for debugging and could have\n'
            'weird effects when using the software.')
        self.btn_about.clicked.connect(self.about)
        self.btn_about.setToolTip(
            'Displays an about page with info on the program')
        self.btn_quit.clicked.connect(self.close)
        self.btn_quit.setToolTip('Close the program')

        # set the layout to the widget
        self.mainwidget.setLayout(layout)

    def fill_default_values(self):
        """
        Routine to fill default values in check boxes if they are empty.
        This is such that the user can't leave required fields empty
        """
        def fillme(field, value):
            """
            Fills values of line edits, if currently empty
            """
            if field.text() == '':
                field.setText(value)

        # loop through line edits
        fillme(self.edt_sett_figwidth, '5.')
        fillme(self.edt_sett_figheight, '8.')
        fillme(self.edt_sett_fstitle, '14')
        fillme(self.edt_sett_fsaxes, '12')
        fillme(self.edt_sett_fslbl, '14')
        fillme(self.edt_sett_fsaxlbl, '12')
        fillme(self.edt_sett_headspace, '2000')
        fillme(self.edt_sett_arrwidth, '0.2')
        fillme(self.edt_sett_arrheadwidth, '0.6')
        fillme(self.edt_sett_preclambda, '3')
        fillme(self.edt_sett_preclevel, '0')

    def fill_testing_values(self):
        """
        For testing: Ti scheme
        """
        self.edt_gslevel.setText('0')
        self.edt_level[0].setText('465.777')

        # low lying states cm-1
        self.chk_lowlying[1].setChecked(True)
        self.chk_lowlying[2].setChecked(True)
        self.edt_level[1].setText('170')
        self.edt_level[2].setText('387')

        # higher states
        self.edt_level[3].setText('416.158')
        self.edt_level[4].setText('881.399')
        self.edt_gslevel.setText('0')
        self.edt_iplevel.setText('55072')

        self.edt_gsterm.setText('3F2')
        self.edt_term[0].setText('3F3')
        self.edt_term[1].setText('3F4')
        self.edt_term[2].setText('3G3')
        self.edt_term[3].setText('3G4')

        # headspace
        self.edt_sett_headspace.setText('3000')

    def set_label_names(self):
        # get the unit
        unit = self.get_unit()
        # set the labels
        stepnumb = 0
        for it in range(self.numberofsteps):
            stepnumb += 1
            # appendix for step number in label
            app = 'th'
            if stepnumb == 1:
                app = 'st'
            elif stepnumb == 2:
                app = 'nd'
            elif stepnumb == 3:
                app = 'rd'
            # set the namestring according to if low lying is toggled or not
            if self.chk_lowlying[it].isChecked():
                stepnumb -= 1
                namestring = 'Low lying st (cm<sup>-1</sup>)'
            else:
                namestring = str(stepnumb) + app + ' step ' + '(' + unit + '):'
            self.lbl_steps[it].setText(namestring)

    def get_unit(self):
        """
        Returns the current unit
        :return unit:   <str>   'nm' or 'cm<sup>-1</sup>'
        """
        if self.rbtn_nm.isChecked():
            return 'nm'
        else:
            return 'cm<sup>-1</sup>'

    def check_fields(self):
        """
        Check if the required fields are filled in.
        """
        # throw an error if not at least one box is filled
        if self.edt_level[0].text() == '':
            QMessageBox.warning(self, 'No entries',
                                'Need at least one level to make a plot!',
                                QMessageBox.Ok)
            return False

        # ip value
        try:
            ipvalue = float(self.edt_iplevel.text())
        except ValueError:
            QMessageBox.warning(
                self, 'Enter IP',
                'Please enter an ionization potential as a number and try again.',
                QMessageBox.Ok)
            return False
        return True

    # buttons
    def plot(self):
        """
        Call the plotting window
        """
        if self.rundebug:
            print('Plotting...')
        if not self.check_fields():
            return

        # fill default values - if not already there
        self.fill_default_values()

        # open the plotting window
        plotwindow = Plotter(self)
        plotwindow.show()

    def save(self):
        """
        Save the figure, default is pdf.
        """
        if self.rundebug:
            print('Save figure directly')
        plotwindow = Plotter(self, saveplt=True)

    def load_config(self):
        """
        Load a configuration file that has previously been saved
        """
        # get the filename
        # home folder of user platform independent
        home = expanduser('~')
        # options
        options = QFileDialog.Options()
        # options |= QFileDialog.DontUseNativeDialog
        filename, _ = QFileDialog.getOpenFileName(
            self,
            'QFileDialog.getOpenFileName()',
            home,
            filter='JSON Files (*.json);;All Files (*.*)',
            options=options)
        # user pressed cancel
        if filename is '':
            return

        # load the json file
        with open(filename, 'r') as read_file:
            savedict = json.load(read_file)

        # function for setting line edits
        def set_line_edits(category, entry, lineedit):
            """
            Sets a given line edit from the dictionary, but also checks if available.
            :param category:    <string>    Category the entry is in
            :param entry:       <string>    Entry with the value
            :param lineedit:    <QLineEdit> The object where the text should be set
            """
            try:
                lineedit.setText(savedict[category][entry])
            except KeyError:
                pass

        # set the settings for the levels
        try:
            if savedict['scheme']['unit'] == 'nm':
                self.rbtn_nm.setChecked(True)
            else:
                self.rbtn_cm.setChecked(True)
        except KeyError:
            pass

        set_line_edits('scheme', 'gs_level', self.edt_gslevel)
        set_line_edits('scheme', 'gs_term', self.edt_gsterm)
        for it in range(len(self.edt_level)
                        ):  # only loop through as many entries as there are
            set_line_edits('scheme', 'step_level' + str(it),
                           self.edt_level[it])
            set_line_edits('scheme', 'step_term' + str(it), self.edt_term[it])
            try:
                if savedict['scheme']['step_lowlying' + str(it)]:
                    self.chk_lowlying[it].setChecked(True)
                else:
                    self.chk_lowlying[it].setChecked(False)
            except KeyError:
                pass
            try:
                if savedict['scheme']['step_forbidden' + str(it)]:
                    self.chk_forbidden[it].setChecked(True)
                else:
                    self.chk_forbidden[it].setChecked(False)
            except KeyError:
                pass
        set_line_edits('scheme', 'ip_level', self.edt_iplevel)
        set_line_edits('scheme', 'ip_term', self.edt_ipterm)

        # program settings - alphabetically
        set_line_edits('settings', 'arrow_head_width',
                       self.edt_sett_arrheadwidth)
        set_line_edits('settings', 'arrow_width', self.edt_sett_arrwidth)
        set_line_edits('settings', 'fig_height', self.edt_sett_figheight)
        set_line_edits('settings', 'fig_width', self.edt_sett_figwidth)
        set_line_edits('settings', 'fs_axes', self.edt_sett_fsaxes)
        set_line_edits('settings', 'fs_axes_labels', self.edt_sett_fsaxlbl)
        set_line_edits('settings', 'fs_labels', self.edt_sett_fslbl)
        set_line_edits('settings', 'fs_title', self.edt_sett_fstitle)
        set_line_edits('settings', 'headspace', self.edt_sett_headspace)
        try:
            if savedict['settings']['ip_label_pos'] == 'Top':
                self.rbtn_iplable_top.setChecked(True)
            else:
                self.rbtn_iplable_bottom.setChecked(True)
        except KeyError:
            pass
        # how to display forbidden transitions
        try:
            if savedict['settings']['show_forbidden_transitions'] == 'x-out':
                self.rbtn_sett_xoutarrow.setChecked(True)
            else:
                self.rbtn_sett_nodisparrow.setChecked(True)
        except KeyError:
            pass
        # line breaks
        try:
            if savedict['settings']['line_breaks']:
                self.chk_sett_linebreaks.setChecked(True)
            else:
                self.chk_sett_linebreaks.setChecked(False)
        except KeyError:
            pass
        # show cm-1 axis
        try:
            if savedict['settings']['show_cm-1_axis']:
                self.chk_sett_showcmax.setChecked(True)
            else:
                self.chk_sett_showcmax.setChecked(False)
        except KeyError:
            pass
        # show eV axis
        try:
            if savedict['settings']['show_eV_axis']:
                self.chk_sett_showevax.setChecked(True)
            else:
                self.chk_sett_showevax.setChecked(False)
        except KeyError:
            pass
        set_line_edits('settings', 'plot_title', self.edt_sett_plttitle)
        set_line_edits('settings', 'prec_level', self.edt_sett_preclevel)
        set_line_edits('settings', 'prec_wavelength', self.edt_sett_preclambda)

    def save_config(self):
        """
        Save the current configuration as a .json file the user defines
        """
        # ask for the filename
        # home folder of user platform independent
        home = expanduser('~')
        # options
        options = QFileDialog.Options()
        # options |= QFileDialog.DontUseNativeDialog
        filename, _ = QFileDialog.getSaveFileName(
            self,
            'QFileDialog.getOpenFileName()',
            home,
            filter='JSON Files (*.json);;All Files (*.*)',
            options=options)
        # user pressed cancel
        if filename is '':
            return
        if filename[-5:len(filename)] != '.json':
            filename += '.json'

        # create the dictionary to save
        savedict = {}
        savedict['scheme'] = {}
        savedict['settings'] = {}

        # save the levels
        savedict['scheme']['unit'] = self.get_unit()
        savedict['scheme']['gs_level'] = self.edt_gslevel.text()
        savedict['scheme']['gs_term'] = self.edt_gsterm.text()
        for it in range(len(self.lbl_steps)):
            savedict['scheme']['step_level' +
                               str(it)] = self.edt_level[it].text()
            savedict['scheme']['step_term' +
                               str(it)] = self.edt_term[it].text()
            savedict['scheme']['step_lowlying' +
                               str(it)] = self.chk_lowlying[it].isChecked()
            savedict['scheme']['step_forbidden' +
                               str(it)] = self.chk_forbidden[it].isChecked()
        savedict['scheme']['ip_level'] = self.edt_iplevel.text()
        savedict['scheme']['ip_term'] = self.edt_ipterm.text()

        # save the settings
        savedict['settings']['fig_width'] = self.edt_sett_figwidth.text()
        savedict['settings']['fig_height'] = self.edt_sett_figheight.text()
        savedict['settings']['fs_title'] = self.edt_sett_fstitle.text()
        savedict['settings']['fs_axes'] = self.edt_sett_fsaxes.text()
        savedict['settings']['fs_axes_labels'] = self.edt_sett_fsaxlbl.text()
        savedict['settings']['fs_labels'] = self.edt_sett_fslbl.text()
        savedict['settings']['headspace'] = self.edt_sett_headspace.text()
        savedict['settings']['arrow_width'] = self.edt_sett_arrwidth.text()
        savedict['settings'][
            'arrow_head_width'] = self.edt_sett_arrheadwidth.text()
        savedict['settings'][
            'prec_wavelength'] = self.edt_sett_preclambda.text()
        savedict['settings']['prec_level'] = self.edt_sett_preclevel.text()
        if self.rbtn_iplable_top.isChecked():
            iptablepos = 'Top'
        else:
            iptablepos = 'Bottom'
        savedict['settings']['ip_label_pos'] = iptablepos
        if self.rbtn_sett_xoutarrow.isChecked():
            dispforbidden = 'x-out'
        else:
            dispforbidden = 'noshow'
        savedict['settings']['show_forbidden_transitions'] = dispforbidden
        savedict['settings']['plot_title'] = self.edt_sett_plttitle.text()
        savedict['settings'][
            'line_breaks'] = self.chk_sett_linebreaks.isChecked()
        savedict['settings'][
            'show_cm-1_axis'] = self.chk_sett_showcmax.isChecked()
        savedict['settings'][
            'show_eV_axis'] = self.chk_sett_showevax.isChecked()

        with open(filename, 'w') as write_file:
            json.dump(savedict, write_file, indent=4, sort_keys=True)

    def about(self):
        """
        Gives a QMessagebox with an about thing
        :return:
        """
        about_msg = '<center>' \
                    '<h1>RIMS Scheme drawer program</h1>' \
                    '<br>Version: ' + self.version + \
                    '<br>Date: ' + self.version_date + \
                    '<p>Author: ' + self.author + \
                    '<p>Please see the github repository for bug reports, feature requests, and for contacting the ' \
                    'author.' \
                    '<p>Many tooltips are implemented that can help you with the software. Hover over entries ' \
                    'with the mouse and check those tooltips out.'
        QMessageBox.about(self, 'About', about_msg)

    def test(self):
        """
        Development testing routine, with the according button
        """
        self.set_label_names()
Beispiel #52
0
class AddWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Tenant{}s Information'.format("'")  # Window Title
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, 400, 300)  # Window Size
        self.setFixedSize(self.size())

        self.background = QLabel(self)
        self.backgroundLoc = QPixmap('heyo.jpg')
        self.background.setPixmap(self.backgroundLoc)
        self.background.move(0, 0)
        self.background.resize(400, 300)
        self.background.setScaledContents(True)

        self.firstnamelabel = QLabel(self)
        self.firstnamelabel.setText('First Name:')
        self.firstnamelabel.move(0, 0)
        self.firstnamelabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.firstnamelabel.adjustSize()

        self.firstname = QLineEdit(self)
        self.firstname.move(150, 0)
        self.firstname.resize(140, 20)
        self.firstname.setMaxLength(15)
        self.firstname.setStyleSheet(
            "font: 11pt Arial Rounded MT Bold; color:black")

        self.lastnamelabel = QLabel(self)
        self.lastnamelabel.setText('Last Name:')
        self.lastnamelabel.move(0, 50)
        self.lastnamelabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.lastnamelabel.adjustSize()

        self.lastname = QLineEdit(self)
        self.lastname.move(150, 50)
        self.lastname.resize(140, 20)
        self.lastname.setMaxLength(15)
        self.lastname.setStyleSheet(
            "font: 11pt Arial Rounded MT Bold; color:black")

        self.genderlabel = QLabel(self)
        self.genderlabel.setText('Gender: female   male')
        self.genderlabel.move(0, 90)
        self.genderlabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.genderlabel.adjustSize()

        self.radiobutton1 = QRadioButton(self)
        self.radiobutton1.move(150, 95)

        self.radiobutton2 = QRadioButton(self)
        self.radiobutton2.move(230, 95)

        self.agelabel = QLabel(self)
        self.agelabel.setText('Age:')
        self.agelabel.move(0, 130)
        self.agelabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.agelabel.adjustSize()

        self.age = QLineEdit(self)
        self.age.move(150, 130)
        self.age.resize(140, 20)
        self.age.setMaxLength(3)
        self.age.setValidator(QIntValidator())
        self.age.setStyleSheet("font: 11pt Arial Rounded MT Bold; color:black")

        self.addresslabel = QLabel(self)
        self.addresslabel.setText('Address:')
        self.addresslabel.move(0, 170)
        self.addresslabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.addresslabel.adjustSize()

        self.address = QLineEdit(self)
        self.address.move(150, 170)
        self.address.resize(140, 20)
        self.address.setMaxLength(15)
        self.address.setStyleSheet(
            "font: 11pt Arial Rounded MT Bold; color:black")

        self.contactlabel = QLabel(self)
        self.contactlabel.setText('Contact:')
        self.contactlabel.move(0, 210)
        self.contactlabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.contactlabel.adjustSize()

        self.contact = QLineEdit(self)
        self.contact.move(150, 210)
        self.contact.resize(140, 20)
        self.contact.setMaxLength(12)
        #self.contact.setValidator(QIntValidator())
        self.contact.setStyleSheet(
            "font: 11pt Arial Rounded MT Bold; color:black")

        self.submitbutton = QPushButton('Submit', self)
        self.submitbutton.move(70, 250)
        self.submitbutton.resize(120, 30)
        self.submitbutton.clicked.connect(self.Submit)
        self.submitbutton.setStyleSheet(
            "font: 10pt Arial Rounded MT Bold; background-color: #a6e3e3; border-style: outset; border-radius: 5px; padding: 2px;"
        )

    def Submit(self):
        Gender = ''
        if (self.radiobutton1.isChecked()):
            Gender = 'Female'
        elif (self.radiobutton2.isChecked()):
            Gender = 'Male'
        FirstName = self.firstname.text()
        LastName = self.lastname.text()
        Age = self.age.text()
        Address = self.address.text()
        ContactNo = self.contact.text()
        Information = (Gender, FirstName, LastName, Age, Address, ContactNo)

        NotBlank = True

        for i in Information:
            if (len(i) == 0):
                NotBlank = False
                self.msgBox = QMessageBox()
                self.msgBox.setIcon(QMessageBox.Information)
                self.msgBox.setText('Please do not leave an entry blank!')
                self.msgBox.setWindowTitle('Warning!')
                self.msgBox.show()
                break

        if (NotBlank):
            Age = int(Age)
            connection = pymysql.connect(
                host='localhost',
                user='******',
                password='',
                db='dormdb',
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor,
                port=3306)
            with connection.cursor() as cursor:
                cursor.execute(
                    'insert into tenants (FirstName,LastName,Gender,Age,Address,ContactNo) values (%s,%s,%s,%s,%s,%s)',
                    (FirstName, LastName, Gender, Age, Address, ContactNo))
                connection.commit()
                self.msgBox = QMessageBox()
                self.msgBox.setIcon(QMessageBox.Information)
                self.msgBox.setText('Thank you! Added Succesfully')
                self.msgBox.setWindowTitle('Add Success!')
                self.msgBox.show()
                self.hide()
                self.newWindow = home()
                self.newWindow.hide()
                self.newWindow.show()
Beispiel #53
0
class App(QWidget):
    def __init__(self, bk, prefs):
        super().__init__()

        self.bk = bk
        self.prefs = prefs
        self.update = False

        # Install translator for the DOCXImport plugin dialog.
        # Use the Sigil language setting unless manually overridden.
        plugin_translator = QTranslator()
        if prefs['language_override'] is not None:
            print('Plugin preferences language override in effect')
            qmf = '{}_{}'.format(bk._w.plugin_name.lower(),
                                 prefs['language_override'])
        else:
            qmf = '{}_{}'.format(bk._w.plugin_name.lower(), bk.sigil_ui_lang)
        print(
            qmf,
            os.path.join(bk._w.plugin_dir, bk._w.plugin_name, 'translations'))
        plugin_translator.load(
            qmf,
            os.path.join(bk._w.plugin_dir, bk._w.plugin_name, 'translations'))
        print(QCoreApplication.instance().installTranslator(plugin_translator))

        self._ok_to_close = False

        self.FTYPE_MAP = {
            'smap': {
                'title': _translate('App', 'Select custom style-map file'),
                'defaultextension': '.txt',
                'filetypes': 'Text Files (*.txt);;All files (*.*)',
            },
            'css': {
                'title': _translate('App', 'Select custom CSS file'),
                'defaultextension': '.css',
                'filetypes': 'CSS Files (*.css)',
            },
            'docx': {
                'title': _translate('App', 'Select DOCX file'),
                'defaultextension': '.docx',
                'filetypes': 'DOCX Files (*.docx)',
            },
        }

        # Check online github files for newer version
        if self.prefs['check_for_updates']:
            self.update, self.newversion = self.check_for_update()
        self.initUI()

    def initUI(self):
        main_layout = QVBoxLayout(self)

        self.setWindowTitle('DOCXImport')
        self.upd_layout = QVBoxLayout()
        self.update_label = QLabel()
        self.update_label.setAlignment(Qt.AlignCenter)
        self.upd_layout.addWidget(self.update_label)
        self.get_update_button = QPushButton()
        self.get_update_button.clicked.connect(self.get_update)
        self.upd_layout.addWidget(self.get_update_button)
        main_layout.addLayout(self.upd_layout)
        if not self.update:
            self.update_label.hide()
            self.get_update_button.hide()

        self.details_grid = QGridLayout()
        self.epub2_select = QRadioButton()
        self.epub2_select.setText('EPUB2')
        self.epubType = QButtonGroup()
        self.epubType.addButton(self.epub2_select)
        self.details_grid.addWidget(self.epub2_select, 0, 0, 1, 1)
        self.checkbox_get_updates = QCheckBox()
        self.details_grid.addWidget(self.checkbox_get_updates, 0, 1, 1, 1)
        self.epub3_select = QRadioButton()
        self.epub3_select.setText('EPUB3')
        self.epubType.addButton(self.epub3_select)
        self.details_grid.addWidget(self.epub3_select, 1, 0, 1, 1)
        main_layout.addLayout(self.details_grid)
        self.checkbox_get_updates.setChecked(self.prefs['check_for_updates'])
        if self.prefs['epub_version'] == '2.0':
            self.epub2_select.setChecked(True)
        elif self.prefs['epub_version'] == '3.0':
            self.epub3_select.setChecked(True)
        else:
            self.epub2_select.setChecked(True)

        self.groupBox = QGroupBox()
        self.groupBox.setTitle('')
        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.docx_grid = QGridLayout()
        self.docx_label = QLabel()
        self.docx_grid.addWidget(self.docx_label, 0, 0, 1, 1)
        self.docx_path = QLineEdit()
        self.docx_grid.addWidget(self.docx_path, 1, 0, 1, 1)
        self.choose_docx_button = QPushButton()
        self.choose_docx_button.setText('...')
        self.docx_grid.addWidget(self.choose_docx_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.docx_grid)
        self.choose_docx_button.clicked.connect(
            lambda: self.fileChooser('docx', self.docx_path))
        if len(self.prefs['lastDocxPath']):
            self.docx_path.setText(self.prefs['lastDocxPath'])
        self.docx_path.setEnabled(False)

        self.smap_grid = QGridLayout()
        self.checkbox_smap = QCheckBox(self.groupBox)
        self.smap_grid.addWidget(self.checkbox_smap, 0, 0, 1, 1)
        self.cust_smap_path = QLineEdit(self.groupBox)
        self.smap_grid.addWidget(self.cust_smap_path, 1, 0, 1, 1)
        self.choose_smap_button = QPushButton(self.groupBox)
        self.choose_smap_button.setText('...')
        self.smap_grid.addWidget(self.choose_smap_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.smap_grid)
        self.checkbox_smap.setChecked(self.prefs['useSmap'])
        self.checkbox_smap.stateChanged.connect(lambda: self.chkBoxActions(
            self.checkbox_smap, self.choose_smap_button))
        self.choose_smap_button.clicked.connect(
            lambda: self.fileChooser('smap', self.cust_smap_path, self.
                                     checkbox_smap, self.choose_smap_button))
        if len(self.prefs['useSmapPath']):
            self.cust_smap_path.setText(self.prefs['useSmapPath'])
        self.cust_smap_path.setEnabled(False)
        self.chkBoxActions(self.checkbox_smap, self.choose_smap_button)

        self.css_grid = QGridLayout()
        self.checkbox_css = QCheckBox(self.groupBox)
        self.css_grid.addWidget(self.checkbox_css, 0, 0, 1, 1)
        self.cust_css_path = QLineEdit(self.groupBox)
        self.css_grid.addWidget(self.cust_css_path, 1, 0, 1, 1)
        self.choose_css_button = QPushButton(self.groupBox)
        self.choose_css_button.setText('...')
        self.css_grid.addWidget(self.choose_css_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.css_grid)
        self.checkbox_css.setChecked(self.prefs['useCss'])
        self.checkbox_css.stateChanged.connect(lambda: self.chkBoxActions(
            self.checkbox_css, self.choose_css_button))
        self.choose_css_button.clicked.connect(
            lambda: self.fileChooser('css', self.cust_css_path, self.
                                     checkbox_css, self.choose_css_button))
        if len(self.prefs['useCssPath']):
            self.cust_css_path.setText(self.prefs['useCssPath'])
        self.cust_css_path.setEnabled(False)
        self.chkBoxActions(self.checkbox_css, self.choose_css_button)

        main_layout.addWidget(self.groupBox)
        self.checkbox_debug = QCheckBox()
        main_layout.addWidget(self.checkbox_debug)
        self.checkbox_debug.setChecked(self.prefs['debug'])

        spacerItem = QSpacerItem(20, 15, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        main_layout.addItem(spacerItem)

        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._ok_clicked)
        button_box.rejected.connect(self._cancel_clicked)
        main_layout.addWidget(button_box)
        self.retranslateUi(self)
        if self.prefs['qt_geometry'] is not None:
            try:
                self.restoreGeometry(
                    QByteArray.fromHex(
                        self.prefs['qt_geometry'].encode('ascii')))
            except:
                pass
        self.show()

    def retranslateUi(self, App):
        self.update_label.setText(_translate('App', 'Plugin Update Available'))
        self.get_update_button.setText(_translate('App',
                                                  'Go to download page'))
        self.checkbox_get_updates.setText(
            _translate('App', 'Check for plugin updates'))
        self.docx_label.setText(_translate('App', 'DOCX File to import'))
        self.checkbox_smap.setText(_translate('App', 'Use Custom Style Map'))
        self.checkbox_css.setText(_translate('App', 'Use Custom CSS'))
        self.checkbox_debug.setText(
            _translate('App',
                       'Debug Mode (change takes effect next plugin run)'))

    def fileChooser(self, ftype, qlineedit, qcheck=None, qbutton=None):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        title = self.FTYPE_MAP[ftype]['title']
        startfolder = self.prefs['lastDir'][ftype]
        ffilter = self.FTYPE_MAP[ftype]['filetypes']
        inpath, _ = QFileDialog.getOpenFileName(self,
                                                title,
                                                startfolder,
                                                ffilter,
                                                options=options)
        if len(inpath):
            qlineedit.setEnabled(True)
            qlineedit.setText(os.path.normpath(inpath))
            self.prefs['lastDir'][ftype] = os.path.dirname(inpath)
            qlineedit.setEnabled(False)
        else:
            if qcheck is not None:
                qcheck.setChecked(False)
            if qbutton is not None:
                qbutton.setEnabled(False)

    def chkBoxActions(self, chk, btn):
        btn.setEnabled(chk.isChecked())

    def cmdDo(self):
        global _DETAILS
        self.prefs['qt_geometry'] = self.saveGeometry().toHex().data().decode(
            'ascii')
        self.prefs['check_for_updates'] = self.checkbox_get_updates.isChecked()
        self.prefs['epub_version'] = self.epubType.checkedButton().text(
        )[-1] + '.0'
        self.prefs['debug'] = self.checkbox_debug.isChecked()
        _DETAILS['vers'] = self.epubType.checkedButton().text()[-1] + '.0'
        self.prefs['useSmap'] = self.checkbox_smap.isChecked()
        if self.checkbox_smap.isChecked():
            if len(self.cust_smap_path.text()):
                self.prefs['useSmapPath'] = self.cust_smap_path.text()
                _DETAILS['smap'] = (self.checkbox_smap.isChecked(),
                                    self.cust_smap_path.text())
            else:
                # Message box that no file is selected
                return
        self.prefs['useCss'] = self.checkbox_css.isChecked()
        if self.checkbox_css.isChecked():
            if len(self.cust_css_path.text()):
                self.prefs['useCssPath'] = self.cust_css_path.text()
                _DETAILS['css'] = (self.checkbox_css.isChecked(),
                                   self.cust_css_path.text())
            else:
                # Message box that no file is selected
                return
        if len(self.docx_path.text()):
            self.prefs['lastDocxPath'] = self.docx_path.text()
            _DETAILS['docx'] = self.docx_path.text()
        else:
            # Message box that no file is selected
            return

    def check_for_update(self):
        '''Use updatecheck.py to check for newer versions of the plugin'''
        chk = UpdateChecker(self.prefs['last_time_checked'], self.bk._w)
        update_available, online_version, time = chk.update_info()
        # update preferences with latest date/time/version
        self.prefs['last_time_checked'] = time
        if online_version is not None:
            self.prefs['last_online_version'] = online_version
        if update_available:
            return (True, online_version)
        return (False, online_version)

    def get_update(self):
        url = DOWNLOAD_PAGE
        if self.update:
            latest = '/tag/v{}'.format(self.newversion)
            url = url + latest
        webbrowser.open_new_tab(url)

    def _ok_clicked(self):
        self._ok_to_close = True
        self.cmdDo()
        self.bk.savePrefs(self.prefs)
        QCoreApplication.instance().quit()

    def _cancel_clicked(self):
        self._ok_to_close = True
        '''Close aborting any changes'''
        self.prefs['qt_geometry'] = self.saveGeometry().toHex().data().decode(
            'ascii')
        self.prefs['check_for_updates'] = self.checkbox_get_updates.isChecked()
        self.prefs['debug'] = self.checkbox_debug.isChecked()
        self.bk.savePrefs(self.prefs)
        QCoreApplication.instance().quit()

    def closeEvent(self, event):
        if self._ok_to_close:
            event.accept()  # let the window close
        else:
            self._cancel_clicked()
class App(QWidget):
    
    def __init__(self):
        super().__init__()
        self.title = 'Meshtastic data show'
        self.interceptor = Interceptor()
        self.initUI()
        
    def initUI(self):
        self.labels = ['data ora','origine','destinazione','tipo messaggio','payload','utente', \
            'da_id','a_id','altitudine','latitudine','longitudine','rxSnr','distanza','rilevamento']
        self.labels1 = ['data ora','user','altitudine','latitudine','longitudine','batteria%', \
            'rxsnr','distanza','rilevamento']
        self.csvFile = open('meshtastic_data.csv','wt')
        mylatlbl = QLabel("Home lat:")
        mylonlbl = QLabel("Home lon:")
        voidlbl = QLabel("")
        voidlbl.setMinimumWidth(320)
        self.mylat = QLineEdit()
        self.mylon = QLineEdit()
        #mylatlbl.setMaximumWidth(60)
        #mylonlbl.setMaximumWidth(60)
        mapbtn =  QPushButton("SHOW MAP",self)
        #mapbtn.setMaximumWidth(110)
        self.radiob = QRadioButton('Storico giorno:')
        #self.setMaximumWidth(100)
        self.combobox = QComboBox(self)
        self.combobox.setMinimumWidth(90)
        fra = QLabel("fra")
        self.fragiorno = QLineEdit()
        self.fragiorno.setText('21/01/01')
        #self.fragiorno.setMaximumSize(70,24)
        et = QLabel("e")
        self.egiorno = QLineEdit()
        oggi = datetime.datetime.now().strftime("%y/%m/%d")
        self.egiorno.setText(oggi)
        #self.egiorno.setMaximumSize(70,24)
        mapbtn.clicked.connect(self.showMap)
        #self.mylat.setMaximumWidth(80)
        #self.mylon.setMaximumWidth(80)
        self.mylat.setText('45.641174')
        self.mylon.setText('9.114828')
        lblmap = QLabel("Tipo Map")
        self.combomap = QComboBox(self)
        self.combomap.addItem("OpenStreetMap")
      # self.combomap.addItem("Mapbox Bright")
        self.combomap.addItem('Stamen Terrain')
        self.combomap.addItem("Stamen Toner")
        self.combomap.addItem("CartoDB positron")
        self.combomap.addItem("CartoDB dark_matter")
        hhome = QHBoxLayout()
        hhome.addWidget(mylatlbl)
        hhome.addWidget(self.mylat)
        hhome.addWidget(mylonlbl)
        hhome.addWidget(self.mylon)
        hhome.addWidget(mapbtn)
        hhome.addWidget(self.radiob)
        hhome.addWidget(self.combobox)
        hhome.addWidget(fra)
        hhome.addWidget(self.fragiorno)
        hhome.addWidget(et)
        hhome.addWidget(self.egiorno)
        hhome.addWidget(lblmap)
        hhome.addWidget(self.combomap)
        hhome.addWidget(voidlbl)
        self.layout = QVBoxLayout(self)
        self.setWindowTitle(self.title)
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.inText = QLineEdit()
        self.inText.setMaximumWidth(250)
        self.inText.setText("cq de I1LOZ")
        label2 = QLabel("Dati inviati: ")
        label2.setMaximumWidth(70)
        self.rbtn1 = QCheckBox('Solo ricezione') 
        self.rbtn2 = QCheckBox('Genera csv file')
        self.rbtn1.setMaximumWidth(150)
        self.rbtn2.setMinimumWidth(600)
        startb = QPushButton("START",self)
        startb.clicked.connect(self.start_click)
        hbox = QHBoxLayout()
        hbox.addWidget(startb)
        hbox.addWidget(label2)
        hbox.addWidget(self.inText) 
        hbox.addWidget(self.rbtn1)
        hbox.addWidget(self.rbtn2)
        # Add tabs
        self.tabs.addTab(self.tab1,"Messaggi")
        self.tabs.addTab(self.tab2,"Connessi")
        self.tabs.addTab(self.tab3,"GeoMap")
        
        self.table = QTableWidget()
        self.table.setColumnCount(len(self.labels))
        self.table.setHorizontalHeaderLabels(self.labels)
        self.tab1.layout = QVBoxLayout()
        self.tab1.layout.addWidget(self.table)
        self.tab1.setLayout(self.tab1.layout)

        self.table1 = QTableWidget()
        self.table1.setColumnCount(len(self.labels1))
        self.table1.setHorizontalHeaderLabels(self.labels1)
        self.tab2.layout = QVBoxLayout()
        self.tab2.layout.addWidget(self.table1)
        self.tab2.setLayout(self.tab2.layout)
        label = QLabel("Log dati ricevuti")
        self.log = QTextEdit()
        self.log.setMaximumHeight(180)
        self.rbtn2.clicked.connect(self.handleFile)
        self.layout.addLayout(hhome)
        self.layout.addWidget(self.tabs)
        self.layout.addWidget(label)
        self.layout.addWidget(self.log)
        self.layout.addLayout(hbox)
        self.setGeometry(100, 50, 1200,640)
        self.show()


    def showMap(self):
        homeLoc['lat'] = float(self.mylat.text())
        homeLoc['lon'] = float(self.mylon.text())
        # tiles = 'OpenStreetMap'
        # tiles = 'Stamen Terrain'
        # tiles = 'Stamen Toner'
        # tiles = 'CartoDB dark_matter'
        # tiles = "CartoDB positron"
        self.map1 = folium.Map(
            location=[homeLoc['lat'],homeLoc['lon']], tiles=self.combomap.currentText(), \
                zoom_start=13
        )
        folium.Marker([homeLoc['lat'],homeLoc['lon']],
            #Make color/style changes here
            icon = folium.Icon(color='blue'),
            popup = 'Home node',
          ).add_to(self.map1)
        if(self.radiob.isChecked()):
            #read connessioni in meshDB and mark all record = combobox selected
            qr = "select user,lat,lon,dist,ora,snr from connessioni where data = '"+self.combobox.currentText()+ \
                "' and dist is not null"
            conn = dba.connect('meshDB.db')
            cur = conn.cursor()
            rows = cur.execute(qr)
            datas = rows.fetchall()
            prevd = 0
            for row in datas:
                user = row[0]
                lat = row[1]
                lon = row[2]
                dist = row[3]
                ora = row[4]
                snr = row[5]
                dist = round(dist)
                dist = dist/1000
                if(abs(dist-prevd)>0.01):
                    prevd = dist
                    folium.Marker([lat,lon],
                        icon = folium.Icon(color='red'),
                        popup = user+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;<br>ora: '+ \
                            ora+'<br>snr: '+str(snr)+'<br>Km: '+str(dist),
                    ).add_to(self.map1)
                    folium.Marker([lat,lon],
                        icon=folium.DivIcon(html=f"""<div style='font-size: 22px; font-weight: bold;'>{user}</div>""")
                    ).add_to(self.map1)
                    print("Mark added")
            cur.close()
            conn.close()
        else:
            #add a marker for each node in nodeInfo
            for node in nodeInfo:
                if('lat' in node):
                    dist = haversine([homeLoc['lat'],homeLoc['lon']],[node['lat'],node['lon']])
                    dist = round(dist)
                    dist = dist/1000
                    ora = node['time'].split(' ')[1]
                    if(dist > 0.01):
                        folium.Marker([node['lat'],node['lon']],
                            icon = folium.Icon(color='red'),
                            popup = node['user']+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;<br>ora: '+ \
                                ora+'<br>snr: '+str(node['snr'])+'<br>Km: '+str(dist),
                        ).add_to(self.map1)
                        folium.Marker([node['lat'],node['lon']],
                        icon=folium.DivIcon(html=f"""<div style='font-size: 22px; font-weight: bold;'>{node['user']}</div>""")
                    ).add_to(self.map1)
        data = io.BytesIO()
        self.map1.save(data, close_file=False)
        self.map1 = QtWebEngineWidgets.QWebEngineView()
        self.map1.setHtml(data.getvalue().decode())
        self.map1.page().profile().setUrlRequestInterceptor(self.interceptor)
        self.tabs.removeTab(2)
        self.tab3.destroy()
        self.tab3 = QWidget()
        self.tabs.addTab(self.tab3,"GeoMap")
        self.tab3.layout = QVBoxLayout()
        self.tab3.layout.addWidget(self.map1)
        self.tab3.setLayout(self.tab3.layout)
        self.map1.show()


    def start_click(self):
        global RUNNING,interface
        if(RUNNING==True):
            return
        interface = meshtastic.SerialInterface()
        RUNNING = True


    def handleFile(self):
        if(self.rbtn2.isChecked()):
            if(self.csvFile.closed):
                self.csvFile = open('meshtastic_data.csv','wt')
            l = 0
            while(l < len(self.labels)-1):
                self.csvFile.write(self.labels[l]+';')
                l += 1
            self.csvFile.write(self.labels[l]+'\n')
        else:
            self.csvFile.close()
Beispiel #55
0
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, 400, 300)  # Window Size
        self.setFixedSize(self.size())

        self.background = QLabel(self)
        self.backgroundLoc = QPixmap('heyo.jpg')
        self.background.setPixmap(self.backgroundLoc)
        self.background.move(0, 0)
        self.background.resize(400, 300)
        self.background.setScaledContents(True)

        self.firstnamelabel = QLabel(self)
        self.firstnamelabel.setText('First Name:')
        self.firstnamelabel.move(0, 0)
        self.firstnamelabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.firstnamelabel.adjustSize()

        self.firstname = QLineEdit(self)
        self.firstname.move(150, 0)
        self.firstname.resize(140, 20)
        self.firstname.setMaxLength(15)
        self.firstname.setStyleSheet(
            "font: 11pt Arial Rounded MT Bold; color:black")

        self.lastnamelabel = QLabel(self)
        self.lastnamelabel.setText('Last Name:')
        self.lastnamelabel.move(0, 50)
        self.lastnamelabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.lastnamelabel.adjustSize()

        self.lastname = QLineEdit(self)
        self.lastname.move(150, 50)
        self.lastname.resize(140, 20)
        self.lastname.setMaxLength(15)
        self.lastname.setStyleSheet(
            "font: 11pt Arial Rounded MT Bold; color:black")

        self.genderlabel = QLabel(self)
        self.genderlabel.setText('Gender: female   male')
        self.genderlabel.move(0, 90)
        self.genderlabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.genderlabel.adjustSize()

        self.radiobutton1 = QRadioButton(self)
        self.radiobutton1.move(150, 95)

        self.radiobutton2 = QRadioButton(self)
        self.radiobutton2.move(230, 95)

        self.agelabel = QLabel(self)
        self.agelabel.setText('Age:')
        self.agelabel.move(0, 130)
        self.agelabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.agelabel.adjustSize()

        self.age = QLineEdit(self)
        self.age.move(150, 130)
        self.age.resize(140, 20)
        self.age.setMaxLength(3)
        self.age.setValidator(QIntValidator())
        self.age.setStyleSheet("font: 11pt Arial Rounded MT Bold; color:black")

        self.addresslabel = QLabel(self)
        self.addresslabel.setText('Address:')
        self.addresslabel.move(0, 170)
        self.addresslabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.addresslabel.adjustSize()

        self.address = QLineEdit(self)
        self.address.move(150, 170)
        self.address.resize(140, 20)
        self.address.setMaxLength(15)
        self.address.setStyleSheet(
            "font: 11pt Arial Rounded MT Bold; color:black")

        self.contactlabel = QLabel(self)
        self.contactlabel.setText('Contact:')
        self.contactlabel.move(0, 210)
        self.contactlabel.setStyleSheet(
            "font: 16pt Arial Rounded MT Bold; color:white")
        self.contactlabel.adjustSize()

        self.contact = QLineEdit(self)
        self.contact.move(150, 210)
        self.contact.resize(140, 20)
        self.contact.setMaxLength(12)
        #self.contact.setValidator(QIntValidator())
        self.contact.setStyleSheet(
            "font: 11pt Arial Rounded MT Bold; color:black")

        self.submitbutton = QPushButton('Submit', self)
        self.submitbutton.move(70, 250)
        self.submitbutton.resize(120, 30)
        self.submitbutton.clicked.connect(self.Submit)
        self.submitbutton.setStyleSheet(
            "font: 10pt Arial Rounded MT Bold; background-color: #a6e3e3; border-style: outset; border-radius: 5px; padding: 2px;"
        )
Beispiel #56
0
    def __init__(self, parent):
        super(FontCommandWidget, self).__init__(parent)

        self._cmd = {'lily': '', 'oll': ''}
        self._full_cmd = {'lily': '', 'oll': ''}
        self.approach = 'lily'

        self.font_labels = {}

        mainWidget = QWidget()
        self.setWidgetResizable(True)
        self.setWidget(mainWidget)
        self.setFrameShape(QScrollArea.NoFrame)
        layout = QVBoxLayout()
        mainWidget.setLayout(layout)
        col_layout = QHBoxLayout()
        layout.addLayout(col_layout)
        layout.addStretch()

        # Left column holding the options
        self.option_widget = QWidget()
        opt_layout = QVBoxLayout(margin=0)
        self.option_widget.setLayout(opt_layout)
        col_layout.addWidget(self.option_widget)

        # TextEdit to display the generated command
        self.command_edit = ce = QTextEdit()
        ce.setReadOnly(True)
        col_layout.addWidget(self.command_edit)

        # Which text font families to integrate?
        self.family_group = QGroupBox()
        opt_layout.addWidget(self.family_group)
        family_layout = QGridLayout()
        self.family_group.setLayout(family_layout)
        self.cb_roman = QCheckBox()
        self.font_labels['roman'] = QLabel(parent.selected_font('roman'))
        family_layout.addWidget(self.cb_roman, 0, 0)
        family_layout.addWidget(self.font_labels['roman'], 0, 1)

        self.cb_sans = QCheckBox()
        self.font_labels['sans'] = QLabel(parent.selected_font('sans'))
        family_layout.addWidget(self.cb_sans, 1, 0)
        family_layout.addWidget(self.font_labels['sans'], 1, 1)

        self.cb_typewriter = QCheckBox()
        self.font_labels['typewriter'] = QLabel(
            parent.selected_font('typewriter'))
        family_layout.addWidget(self.cb_typewriter, 2, 0)
        family_layout.addWidget(self.font_labels['typewriter'], 2, 1)

        # Choice between traditional and openLilyLib approach
        self.approach_group = QGroupBox()
        approach_layout = QVBoxLayout()
        self.approach_group.setLayout(approach_layout)
        self.approach_tab = QTabWidget()
        approach_layout.addWidget(self.approach_tab)
        opt_layout.addWidget(self.approach_group)

        self.trad_widget = QWidget()
        trad_layout = QVBoxLayout()
        self.trad_widget.setLayout(trad_layout)
        self.approach_tab.addTab(self.trad_widget, "")

        self.oll_widget = QWidget()
        oll_layout = QVBoxLayout()
        self.oll_widget.setLayout(oll_layout)
        self.approach_tab.addTab(self.oll_widget, "")

        # Configure traditional approach
        self.cb_music = QCheckBox()
        self.font_labels['music'] = QLabel(parent.selected_font('music'))
        trad_music_layout = QHBoxLayout()
        trad_music_layout.addWidget(self.cb_music)
        trad_music_layout.addWidget(self.font_labels['music'])
        trad_layout.addLayout(trad_music_layout)

        self.cb_paper_block = QCheckBox()
        trad_layout.addWidget(self.cb_paper_block)
        trad_layout.addStretch()

        # Configure openLilyLib approach
        self.cb_oll_music = QCheckBox()
        self.cb_oll_music.setChecked(True)
        self.cb_oll_music.setEnabled(False)
        self.font_labels['oll_music'] = QLabel(parent.selected_font('music'))
        oll_music_layout = QHBoxLayout()
        oll_music_layout.addWidget(self.cb_oll_music)
        oll_music_layout.addWidget(self.font_labels['oll_music'])
        oll_layout.addLayout(oll_music_layout)
        self.cb_oll = QCheckBox()
        oll_layout.addWidget(self.cb_oll)
        self.cb_loadpackage = QCheckBox()
        oll_layout.addWidget(self.cb_loadpackage)
        self.cb_extensions = QCheckBox()
        oll_layout.addWidget(self.cb_extensions)
        # Configure handling of stylesheet
        self.stylesheet_group = QGroupBox()
        self.stylesheet_buttons = QButtonGroup()
        oll_layout.addWidget(self.stylesheet_group)
        stylesheet_layout = QVBoxLayout()
        self.stylesheet_group.setLayout(stylesheet_layout)
        self.style_buttons = [QRadioButton() for i in range(3)]
        for i in range(3):
            b = self.style_buttons[i]
            stylesheet_layout.addWidget(b)
            self.stylesheet_buttons.addButton(b)
            self.stylesheet_buttons.setId(b, i)
        self.le_stylesheet = QLineEdit()
        stylesheet_layout.addWidget(self.le_stylesheet)
        oll_layout.addStretch()
        # enable line edit when custom stylesheet is selected
        self.stylesheet_buttons.buttonClicked.connect(
            lambda: self.le_stylesheet.setEnabled(self.stylesheet_buttons.
                                                  checkedId() == 2))

        self.loadSettings()
        self.window().finished.connect(self.saveSettings)
        # Connect widgets that trigger re-generation of the command
        # Map widget base classes to signal names
        signal_map = {
            QAbstractButton: 'toggled',
            QButtonGroup: 'buttonClicked',
            QTabWidget: 'currentChanged',
            QLineEdit: 'editingFinished'
        }
        trigger_widgets = [
            self.cb_roman,
            self.cb_sans,
            self.cb_typewriter,
            self.cb_music,
            self.cb_paper_block,
        ]
        trigger_widgets.extend([
            self.approach_tab, self.cb_oll, self.cb_loadpackage,
            self.cb_extensions, self.stylesheet_buttons, self.le_stylesheet
        ])
        for w in trigger_widgets:
            # For the current widget determine a supported base class
            # and connect the appropriate signal.
            # NOTE: When a new widget is added to the list it has to be
            # ensured it has a supported base class.
            for base_class in signal_map:
                if isinstance(w, base_class):
                    signal = getattr(w, signal_map[base_class])
                    signal.connect(self.invalidate_command)
                    break

        app.translateUI(self)
    def init_ui(self):
        print("@ Final Survey : init_ui")
        self.setMinimumHeight(400)
        self.setMinimumWidth(900)
        self.move(QApplication.desktop().rect().center() -
                  self.rect().center())

        layout = QGridLayout()

        rating_prompt = QLabel()
        rating_prompt.setText(
            "From a scale of 1 for “why would you waste my time” to 7 for \n"
            "“Perfection incarnate,” how was your experience with the application:"
        )
        layout.addWidget(rating_prompt, 0, 0)

        rating_buttons = [QRadioButton(str(i + 1)) for i in range(7)]
        rating_buttons[0].setChecked(True)
        self.rating_group = QButtonGroup()
        rating_group_layout = QHBoxLayout()
        for b in range(len(rating_buttons)):
            rating_group_layout.addWidget(rating_buttons[b])
            self.rating_group.addButton(rating_buttons[b])
            rating_buttons[b].clicked.connect(self.rating_set)
        layout.addLayout(rating_group_layout, 0, 1)

        productivity_prompt = QLabel()
        productivity_prompt.setText(
            "From a -3 for “damn, it made it worse, what the f**k is this” \n"
            "to 3 for “Oh my God I was in the clouds, it’s better than cocaine”, \n"
            "how did you feel your productivity was affected through the application:"
        )
        layout.addWidget(productivity_prompt, 1, 0)

        productivity_buttons = [QRadioButton(str(i - 3)) for i in range(7)]
        productivity_buttons[3].setChecked(True)
        self.productivity_group = QButtonGroup()
        productivity_group_layout = QHBoxLayout()
        for b in range(len(rating_buttons)):
            productivity_group_layout.addWidget(productivity_buttons[b])
            self.productivity_group.addButton(productivity_buttons[b])
            productivity_buttons[b].clicked.connect(self.productivity_set)
        layout.addLayout(productivity_group_layout, 1, 1)

        comments_prompt = QLabel()
        comments_prompt.setText(
            "Any bugs you experienced, suggestions, comments? Write ‘em here; \n"
            "be nice, or not, I just want an A...")
        layout.addWidget(comments_prompt, 2, 0)

        self.comments.setPlaceholderText("Enter comments here...")
        layout.addWidget(self.comments, 3, 0)

        final_picture = QLabel()
        final_picture.setPixmap(QPixmap("happy.png"))
        layout.addWidget(final_picture, 3, 1)

        submit_button = QPushButton()
        submit_button.setText("Submit")
        submit_button.clicked.connect(self.submit_survey)
        layout.addWidget(submit_button, 4, 1)

        self.setLayout(layout)
Beispiel #58
0
    def request_trezor_init_settings(self, wizard, method, model):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        gb = QGroupBox()
        hbox1 = QHBoxLayout()
        gb.setLayout(hbox1)
        vbox.addWidget(gb)
        gb.setTitle(_("Select your seed length:"))
        bg_numwords = QButtonGroup()
        for i, count in enumerate([12, 18, 24]):
            rb = QRadioButton(gb)
            rb.setText(_("%d words") % count)
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, i)
            hbox1.addWidget(rb)
            rb.setChecked(True)
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)

        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        if method == TIM_RECOVER and not model == 'T':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX)
            hbox_rectype.addWidget(rb2)
        else:
            bg_rectype = None

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        item = bg_numwords.checkedId()
        pin = cb_pin.isChecked()
        recovery_type = bg_rectype.checkedId() if bg_rectype else None

        return (item, name.text(), pin, cb_phrase.isChecked(), recovery_type)
    def initUI(self):
        self.labels = ['data ora','origine','destinazione','tipo messaggio','payload','utente', \
            'da_id','a_id','altitudine','latitudine','longitudine','rxSnr','distanza','rilevamento']
        self.labels1 = ['data ora','user','altitudine','latitudine','longitudine','batteria%', \
            'rxsnr','distanza','rilevamento']
        self.csvFile = open('meshtastic_data.csv','wt')
        mylatlbl = QLabel("Home lat:")
        mylonlbl = QLabel("Home lon:")
        voidlbl = QLabel("")
        voidlbl.setMinimumWidth(320)
        self.mylat = QLineEdit()
        self.mylon = QLineEdit()
        #mylatlbl.setMaximumWidth(60)
        #mylonlbl.setMaximumWidth(60)
        mapbtn =  QPushButton("SHOW MAP",self)
        #mapbtn.setMaximumWidth(110)
        self.radiob = QRadioButton('Storico giorno:')
        #self.setMaximumWidth(100)
        self.combobox = QComboBox(self)
        self.combobox.setMinimumWidth(90)
        fra = QLabel("fra")
        self.fragiorno = QLineEdit()
        self.fragiorno.setText('21/01/01')
        #self.fragiorno.setMaximumSize(70,24)
        et = QLabel("e")
        self.egiorno = QLineEdit()
        oggi = datetime.datetime.now().strftime("%y/%m/%d")
        self.egiorno.setText(oggi)
        #self.egiorno.setMaximumSize(70,24)
        mapbtn.clicked.connect(self.showMap)
        #self.mylat.setMaximumWidth(80)
        #self.mylon.setMaximumWidth(80)
        self.mylat.setText('45.641174')
        self.mylon.setText('9.114828')
        lblmap = QLabel("Tipo Map")
        self.combomap = QComboBox(self)
        self.combomap.addItem("OpenStreetMap")
      # self.combomap.addItem("Mapbox Bright")
        self.combomap.addItem('Stamen Terrain')
        self.combomap.addItem("Stamen Toner")
        self.combomap.addItem("CartoDB positron")
        self.combomap.addItem("CartoDB dark_matter")
        hhome = QHBoxLayout()
        hhome.addWidget(mylatlbl)
        hhome.addWidget(self.mylat)
        hhome.addWidget(mylonlbl)
        hhome.addWidget(self.mylon)
        hhome.addWidget(mapbtn)
        hhome.addWidget(self.radiob)
        hhome.addWidget(self.combobox)
        hhome.addWidget(fra)
        hhome.addWidget(self.fragiorno)
        hhome.addWidget(et)
        hhome.addWidget(self.egiorno)
        hhome.addWidget(lblmap)
        hhome.addWidget(self.combomap)
        hhome.addWidget(voidlbl)
        self.layout = QVBoxLayout(self)
        self.setWindowTitle(self.title)
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.inText = QLineEdit()
        self.inText.setMaximumWidth(250)
        self.inText.setText("cq de I1LOZ")
        label2 = QLabel("Dati inviati: ")
        label2.setMaximumWidth(70)
        self.rbtn1 = QCheckBox('Solo ricezione') 
        self.rbtn2 = QCheckBox('Genera csv file')
        self.rbtn1.setMaximumWidth(150)
        self.rbtn2.setMinimumWidth(600)
        startb = QPushButton("START",self)
        startb.clicked.connect(self.start_click)
        hbox = QHBoxLayout()
        hbox.addWidget(startb)
        hbox.addWidget(label2)
        hbox.addWidget(self.inText) 
        hbox.addWidget(self.rbtn1)
        hbox.addWidget(self.rbtn2)
        # Add tabs
        self.tabs.addTab(self.tab1,"Messaggi")
        self.tabs.addTab(self.tab2,"Connessi")
        self.tabs.addTab(self.tab3,"GeoMap")
        
        self.table = QTableWidget()
        self.table.setColumnCount(len(self.labels))
        self.table.setHorizontalHeaderLabels(self.labels)
        self.tab1.layout = QVBoxLayout()
        self.tab1.layout.addWidget(self.table)
        self.tab1.setLayout(self.tab1.layout)

        self.table1 = QTableWidget()
        self.table1.setColumnCount(len(self.labels1))
        self.table1.setHorizontalHeaderLabels(self.labels1)
        self.tab2.layout = QVBoxLayout()
        self.tab2.layout.addWidget(self.table1)
        self.tab2.setLayout(self.tab2.layout)
        label = QLabel("Log dati ricevuti")
        self.log = QTextEdit()
        self.log.setMaximumHeight(180)
        self.rbtn2.clicked.connect(self.handleFile)
        self.layout.addLayout(hhome)
        self.layout.addWidget(self.tabs)
        self.layout.addWidget(label)
        self.layout.addWidget(self.log)
        self.layout.addLayout(hbox)
        self.setGeometry(100, 50, 1200,640)
        self.show()
Beispiel #60
0
    class WMChannelGUI(QWidget):
        def __init__(self, parent=None, data=None):
            self.parent = parent
            self.data = data
            super().__init__(parent=self.parent)
            main_layout = QVBoxLayout()

            layout1 = QHBoxLayout()
            self.btn_w = QRadioButton('nm')
            self.btn_w.setChecked(self.data.unit == 'nm')
            self.btn_w.toggled.connect(self.unitChanged)  # (lambda:self.unitChange(self.btn_w))
            layout1.addWidget(self.btn_w)
            self.btn_f = QRadioButton('THz')
            self.btn_f.setChecked(self.data.unit != 'nm')
            # self.btn_f.toggled.connect(self.unitChanged)  # (lambda: self.unitChange(self.btn_f))
            layout1.addWidget(self.btn_f)
            self.show_sp_chbx = QCheckBox()
            self.show_sp_chbx.setChecked(self.data.show_spectrum)
            self.show_sp_chbx.toggled.connect(self.showSpectrum)
            layout1.addWidget(self.show_sp_chbx)

            self.col_btn = QPushButton()
            self.col_btn.setMinimumWidth(25)
            self.col_btn.setMaximumWidth(25)
            # print('background-color: rgb(%i,%i,%i)' % self.data.color.getRgb()[:3])
            # self.col_btn.setStyleSheet('background-color: rgb(%i,%i,%i)' % self.data.color.getRgb()[:3])
            self.col_btn.setStyleSheet("QWidget { background-color: %s }"% self.data.color.name())
            self.col_btn.clicked.connect(self.changeColor)
            layout1.addWidget(self.col_btn)
            layout1.addStretch(1)
            # implemented in main window
            # self.show_box = QCheckBox('Show')
            # self.show_box.setChecked(False)
            # self.show_box.stateChanged.connect(lambda:self.showSpectrum(self.show_box.checkState()))
            # layout1.addWidget(self.show_box)

            main_layout.addLayout(layout1)

            self.name_line = QLabel(self.data.name)
            self.name_line.setFont(QFont("Times", 25, QFont.Bold))
            self.name_line.setStyleSheet("QWidget { color: %s }"% self.data.color.name())
            main_layout.addWidget(self.name_line)

            self.value = QLabel()
            self.value.setFont(QFont("Times",65))#,QFont.Bold
            self.setValueText()
            self.value.setStyleSheet("QWidget { color: %s }"% self.data.color.name())
            main_layout.addWidget(self.value)
            self.setLayout(main_layout)
            # print('Min Width ', self.width())

        def changeColor(self):
            col = QColorDialog.getColor()
            if col.isValid():
                self.data.color = col#.setStyleSheet("QWidget { background-color: %s }"% col.name())
            self.parent.data.save()

        def unitChanged(self):
            if self.btn_w.isChecked():
                self.data.unit = 'nm'
            else:
                self.data.unit = 'THz'
            self.parent.data.save()

        def setValueText(self):
            if self.data.unit == 'nm':
                self.value.setText("%.5f nm" % self.data.wavelength)
            else:
                self.value.setText("%.5f THz" % self.data.frequency)

        def showSpectrum(self, b):
            print('Show spectrum', b)
            self.data.show_spectrum = b
            self.parent.data.save()