コード例 #1
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout())
        self.layout().setAlignment(Qt.AlignTop)

        self.behaviorsGroup = QGroupBox(self)
        self.behaviorsGroup.setTitle('Default behaviors')
        self.behaviorsGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.behaviorsGroup)

        self.showPlaying = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showPlaying)

        self.showDbMeters = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showDbMeters)

        self.showAccurate = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showAccurate)

        self.showSeek = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showSeek)

        self.autoNext = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.autoNext)

        self.retranslateUi()
コード例 #2
0
    def __init__(self, parent=None):
        """Initiate the abstract widget that is displayed in the preferences dialog."""
        super(Playback, self).__init__(parent)
        self.user_config_file = os.path.join(AppDirs('mosaic', 'Mandeep').user_config_dir,
                                             'settings.toml')

        with open(self.user_config_file) as conffile:
            config = toml.load(conffile)

        playback_config = QGroupBox('Playback Configuration')
        playback_config_layout = QVBoxLayout()
        playback_config_layout.setAlignment(Qt.AlignTop)

        self.cover_art_playback = QCheckBox('Cover Art Playback')
        self.playlist_save_checkbox = QCheckBox('Save Playlist on Close')

        playback_config_layout.addWidget(self.cover_art_playback)
        playback_config_layout.addWidget(self.playlist_save_checkbox)

        playback_config.setLayout(playback_config_layout)

        main_layout = QVBoxLayout()
        main_layout.addWidget(playback_config)

        self.setLayout(main_layout)

        self.check_playback_setting(config)
        self.check_playlist_save(config)
        self.cover_art_playback.clicked.connect(lambda: self.cover_art_playback_setting(config))
        self.playlist_save_checkbox.clicked.connect(lambda: self.playlist_save_setting(config))
コード例 #3
0
ファイル: gui_z2.py プロジェクト: koduj-z-klasa/python101
class Ui_Widget(object):
    """ Klasa definiująca GUI """

    def setupUi(self, Widget):

        # widgety rysujące kształty, instancje klasy Ksztalt
        self.ksztalt1 = Ksztalt(self, Ksztalty.Polygon)
        self.ksztalt2 = Ksztalt(self, Ksztalty.Ellipse)
        self.ksztaltAktywny = self.ksztalt1

        # przyciski CheckBox ###
        uklad = QVBoxLayout()  # układ pionowy
        self.grupaChk = QButtonGroup()
        for i, v in enumerate(('Kwadrat', 'Koło', 'Trójkąt', 'Linia')):
            self.chk = QCheckBox(v)
            self.grupaChk.addButton(self.chk, i)
            uklad.addWidget(self.chk)
        self.grupaChk.buttons()[self.ksztaltAktywny.ksztalt].setChecked(True)
        # CheckBox do wyboru aktywnego kształtu
        self.ksztaltChk = QCheckBox('<=')
        self.ksztaltChk.setChecked(True)
        uklad.addWidget(self.ksztaltChk)

        # układ poziomy dla kształtów oraz przycisków CheckBox
        ukladH1 = QHBoxLayout()
        ukladH1.addWidget(self.ksztalt1)
        ukladH1.addLayout(uklad)
        ukladH1.addWidget(self.ksztalt2)
        # koniec CheckBox ###

        self.setLayout(ukladH1)  # przypisanie układu do okna głównego
        self.setWindowTitle('Widżety')
コード例 #4
0
ファイル: misc_db.py プロジェクト: Pewpews/happypanda
 def __init__(self, parent=None):
     super().__init__(parent, blur=False)
     main_layout = QFormLayout(self.main_widget)
     self.name_edit = QLineEdit(self)
     main_layout.addRow("Name:", self.name_edit)
     self.filter_edit = QPlainTextEdit(self)
     self.filter_edit.setPlaceholderText("tag1, namespace:tag2, namespace2:[tag1, tag2] ...")
     self.filter_edit.setFixedHeight(100)
     what_is_filter = misc.ClickedLabel("What is Filter/Enforce? (Hover)")
     what_is_filter.setToolTip(app_constants.WHAT_IS_FILTER)
     what_is_filter.setToolTipDuration(9999999999)
     self.enforce = QCheckBox(self)
     self.regex = QCheckBox(self)
     self.case = QCheckBox(self)
     self.strict = QCheckBox(self)
     main_layout.addRow(what_is_filter)
     main_layout.addRow("Filter", self.filter_edit)
     main_layout.addRow("Enforce", self.enforce)
     main_layout.addRow("Regex", self.regex)
     main_layout.addRow("Case sensitive", self.case)
     main_layout.addRow("Match whole terms", self.strict)
     main_layout.addRow(self.buttons_layout)
     self.add_buttons("Close")[0].clicked.connect(self.hide)
     self.add_buttons("Apply")[0].clicked.connect(self.accept)
     old_v = self.width()
     self.adjustSize()
     self.resize(old_v, self.height())
コード例 #5
0
    def tab5UI(self):
        """Tab where the raw data can be exported to a text file."""
        self.tab5.setLayout(self.grid4)

        self.checkboxdict = {"mean_score": "Mean Score",
                             "hbond_percentage": "HBond Percentage", "median_score": "Median Score",
                             "contactTypeAsShortcut": "Contact Type",
                             "getScoreArray": "Score List", "hbondFramesScan": "Hydrogen Bond Frames"}
        # let's define the key order ourselves
        self.keys = ["contactTypeAsShortcut", "mean_score", "median_score", "hbond_percentage", "getScoreArray", "hbondFramesScan"]

        propertyLabel = QLabel("Select properties to export")
        self.grid4.addWidget(propertyLabel, 0, 0)

        startLine = 1
        for box in self.keys:
            checkBox = QCheckBox()
            checkBox.setChecked(True)
            boxLabel = QLabel(self.checkboxdict[box])
            self.grid4.addWidget(boxLabel, startLine, 0)
            self.grid4.addWidget(checkBox, startLine, 1)
            self.checkboxes.append(checkBox)
            startLine += 1

        self.tab5.button = QPushButton("Export to text")
        self.tab5.button.clicked.connect(self.saveText)
        self.grid4.addWidget(self.tab5.button, startLine, 5)
コード例 #6
0
ファイル: errorgb.py プロジェクト: faouellet/CorrectUS
    def setErrors(self, errors):
        self.errors = errors

        for idx, err_key in enumerate(sorted(self.errors)):
            err = self.errors[err_key]
            id_item = QTableWidgetItem(err.id)
            id_item.setFlags(Qt.ItemIsEnabled)

            desc_item = QTableWidgetItem(err.check)
            desc_item.setFlags(Qt.ItemIsEnabled)

            penalty_item = QTableWidgetItem(str(err.penalty))
            penalty_item.setTextAlignment(Qt.AlignCenter)

            cell_widget = QWidget()
            chk_box = QCheckBox()
            if err.is_enabled:
                chk_box.setCheckState(Qt.Checked)
            else:
                chk_box.setCheckState(Qt.Unchecked)
            chk_box.stateChanged.connect(lambda state, err=err: self.chkboxClicked(err, state))
            layout = QHBoxLayout(cell_widget)
            layout.addWidget(chk_box)
            layout.setAlignment(Qt.AlignCenter)
            cell_widget.setLayout(layout)

            self.table.setItem(idx, 0, id_item)
            self.table.setItem(idx, 1, desc_item)
            self.table.setItem(idx, 2, penalty_item)
            self.table.setCellWidget(idx, 3, cell_widget)
コード例 #7
0
ファイル: PrintSetup.py プロジェクト: colchuck/pySchlageGen
 def initUI(self):
     #icon
     app_icon = QIcon()
     app_icon.addFile("key.png", QSize(256, 256))
     self.setWindowIcon(app_icon)
     #text preview
     self.Gen = self.parent.getGen()
     self.preview = QTextEdit()
     self.preview.setReadOnly(True)
     #gui elements
     pntBtn = QPushButton("Print", self)
     pntBtn.clicked.connect(self.printMKS)
     previewBtn = QPushButton("Preview", self)
     previewBtn.clicked.connect(self.previewMKS)
     #showBittings = QCheckBox("Master Bittings")
     #showTitlePage = QCheckBox("Title Page")
     showContact = QCheckBox("Contact Information")
     showContact.setEnabled(False)
     vert = QVBoxLayout()
     self.setLayout(vert)
     #vert.addWidget(showBittings)
     #vert.addWidget(showTitlePage)
     vert.addWidget(showContact)
     vert.addWidget(self.preview)
     vert.addWidget(pntBtn)
     vert.addWidget(previewBtn)
     self.setGeometry(300, 300, 290, 150)
     self.setWindowTitle('Print')
     self.formatPrint()
     self.show()
コード例 #8
0
    def _initUi(self, name, baseDate):
        self.setWindowTitle('行业对比[{0}]-基准日期[{1}]'.format(name, baseDate))
 
        # 控件
        forwardNTDaysLabel = QLabel('向前N日涨幅(%)')
        self._forwardNTDaysLineEdit = QLineEdit('30')

        self._industry2CheckBox = QCheckBox('行业二级分级')
        #self._industry2CheckBox.setChecked(True)

        self._industry3CheckBox = QCheckBox('行业三级分级')
        self._industry3CheckBox.setChecked(True)

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

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

        grid.addWidget(self._industry2CheckBox, 1, 0)
        grid.addWidget(self._industry3CheckBox, 1, 1)

        grid.addWidget(okPushButton, 2, 1)
        grid.addWidget(cancelPushButton, 2, 0)
 
        self.setLayout(grid)

        self.setMinimumWidth(QApplication.desktop().size().width()//5)
コード例 #9
0
ファイル: tools.py プロジェクト: 19joho66/frescobaldi
    def __init__(self, page):
        super(LogTool, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

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

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

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

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

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

        app.translateUI(self)
コード例 #10
0
    def _createEncodingBox(self):
        groupbox = QGroupBox(_("File Encoding"))
        layout = QGridLayout()


        self._autoEncoding = QCheckBox(_("Auto input encoding"), self)
        self._inputEncoding = QComboBox(self)
        self._inputEncoding.addItems(ALL_ENCODINGS)
        self._inputEncoding.setDisabled(self._autoEncoding.isChecked())
        inputLabel = QLabel(_("Input encoding"))

        self._changeEncoding = QCheckBox(_("Change encoding on save"), self)
        self._outputEncoding = QComboBox(self)
        self._outputEncoding.addItems(ALL_ENCODINGS)
        self._outputEncoding.setEnabled(self._changeEncoding.isChecked())
        outputLabel = QLabel(_("Output encoding"))

        layout.addWidget(self._autoEncoding, 0, 0)
        layout.addWidget(self._inputEncoding, 1, 0)
        layout.addWidget(inputLabel, 1, 1)
        layout.addWidget(self._changeEncoding, 2, 0)
        layout.addWidget(self._outputEncoding, 3, 0)
        layout.addWidget(outputLabel, 3, 1)
        groupbox.setLayout(layout)
        return groupbox
コード例 #11
0
ファイル: stop_all.py プロジェクト: chippey/linux-show-player
class StopAllSettings(SettingsPage):
    Name = 'Cue Settings'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.setLayout(QVBoxLayout(self))

        self.group = QGroupBox(self)
        self.group.setTitle('Mode')
        self.group.setLayout(QHBoxLayout(self.group))

        self.pauseMode = QCheckBox(self.group)
        self.pauseMode.setText('Pause mode')
        self.group.layout().addWidget(self.pauseMode)

        self.layout().addWidget(self.group)
        self.layout().addSpacing(self.height() - 100)

    def enable_check(self, enabled):
        self.group.setCheckable(enabled)
        self.group.setChecked(False)

    def get_settings(self):
        conf = {}

        if not (self.group.isCheckable() and not self.group.isChecked()):
            conf['pause_mode'] = self.pauseMode.isChecked()

        return conf

    def load_settings(self, settings):
        if 'pause_mode' in settings:
            self.pauseMode.setChecked(settings['pause_mode'])
コード例 #12
0
ファイル: formlayout5.py プロジェクト: elcritch/formlayout5
 def __init__(self, value, parent=None):
     QGridLayout.__init__(self)
     font = tuple_to_qfont(value)
     assert font is not None
     
     # Font family
     self.family = QFontComboBox(parent)
     self.family.setCurrentFont(font)
     self.addWidget(self.family, 0, 0, 1, -1)
     
     # Font size
     self.size = QComboBox(parent)
     self.size.setEditable(True)
     sizelist = list(range(6, 12)) + list(range(12, 30, 2)) + [36, 48, 72]
     size = font.pointSize()
     if size not in sizelist:
         sizelist.append(size)
         sizelist.sort()
     self.size.addItems([str(s) for s in sizelist])
     self.size.setCurrentIndex(sizelist.index(size))
     self.addWidget(self.size, 1, 0)
     
     # Italic or not
     self.italic = QCheckBox(self.tr("Italic"), parent)
     self.italic.setChecked(font.italic())
     self.addWidget(self.italic, 1, 1)
     
     # Bold or not
     self.bold = QCheckBox(self.tr("Bold"), parent)
     self.bold.setChecked(font.bold())
     self.addWidget(self.bold, 1, 2)
コード例 #13
0
ファイル: protoGUI.py プロジェクト: tomcatz85/photo-lazy
    def initUI(self):

       self.OpenButton = QPushButton('Open Folder')
       self.OpenButton.clicked.connect(self.OpenFolder)

       self.ConvertButton = QPushButton('Convert')
       self.ConvertButton.clicked.connect(self.PreConvert)

       self.CheckBoxInst = QCheckBox('Instagram', self)
       self.CheckBoxVK = QCheckBox('VK.com', self)

#       self.progressBar = QProgressBar(self)
#       self.progressBar.setRange(0, 1)
#       self.statusBar = QStatusBar(self)
#       self.statusBar.addWidget(self.progressBar)
       #self.statusBar.showMessage('Ready')

       HBox = QHBoxLayout()
       HBox.addWidget(self.OpenButton)
       HBox.addWidget(self.CheckBoxInst)
       HBox.addWidget(self.CheckBoxVK)

       VBox = QVBoxLayout()
       VBox.addLayout(HBox)
       VBox.addWidget(self.ConvertButton)

       self.setLayout(VBox)

       self.setGeometry(500, 500, 500, 500)
       self.setWindowTitle('protoGUI')
       self.show()
コード例 #14
0
ファイル: style_window.py プロジェクト: mintoo/NetDim
class StyleWindow(QWidget):
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Styles')
        
        self.original_palette = QApplication.palette()
        
        styles = QLabel('Styles :')
        self.style_list = QComboBox()
        self.style_list.addItems(QStyleFactory.keys())
        self.style_list.setCurrentIndex(3)
        self.style_list.activated[str].connect(self.change_style)
        
        self.standard_palette = QCheckBox("Standard palette")
        self.standard_palette.setChecked(False)
        self.standard_palette.toggled.connect(self.change_palette)
        
        self.change_style('Fusion')
        
        grid = QGridLayout()
        grid.addWidget(styles, 0, 0, 1, 1)
        grid.addWidget(self.style_list, 0, 1, 1, 1)
        grid.addWidget(self.standard_palette, 1, 0, 1, 2)
        self.setLayout(grid)
        
    def change_style(self, name):
        QApplication.setStyle(QStyleFactory.create(name))
        self.change_palette()

    def change_palette(self):
        if self.standard_palette.isChecked():
            QApplication.setPalette(QApplication.style().standardPalette())
        else:
            QApplication.setPalette(self.original_palette)
コード例 #15
0
    def dialogExtract2csv(self):
        d = QDialog(self)
        d.setFixedWidth(450)
        d.setWindowTitle("Extract data to Csv")
        d.setVisible(True)
        vbox = QVBoxLayout()
        tabWidget = QTabWidget()
        for name, mod in list(self.moduleDict.items()):
            wid = QWidget()
            grid = QGridLayout()
            grid.setSpacing(20)
            wid.dateStart = QLineEdit('%s00:00' % dt.datetime.now().strftime("%Y-%m-%dT"))
            wid.dateEnd = QLineEdit("Now")
            grid.addWidget(QLabel("From"), 0, 0)
            grid.addWidget(wid.dateStart, 0, 1)
            grid.addWidget(QLabel("To"), 0, 2)
            grid.addWidget(wid.dateEnd, 0, 3)
            for i, device in enumerate(mod.devices):
                checkbox = QCheckBox(device.deviceLabel)
                checkbox.stateChanged.connect(partial(self.csvUpdateTab, name, checkbox, device))
                checkbox.setCheckState(2)
                grid.addWidget(checkbox, 1 + i, 0, 1, 3)

            wid.setLayout(grid)
            tabWidget.addTab(wid, name)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.button(QDialogButtonBox.Ok).clicked.connect(partial(self.extract2csv, tabWidget, d))
        buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(d.close)

        vbox.addWidget(tabWidget)
        vbox.addWidget(buttonBox)
        d.setLayout(vbox)
コード例 #16
0
ファイル: find_in_files.py プロジェクト: ninja-ide/ninja-ide
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored)
        self._scope = QComboBox()
        self._scope.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.ninjaide = IDE.get_service('ide')
        self.ninjaide.filesAndProjectsLoaded.connect(
            self._update_combo_projects)

        main_layout = QVBoxLayout(self)
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(translations.TR_SEARCH_SCOPE))
        hbox.addWidget(self._scope)
        main_layout.addLayout(hbox)
        widgets_layout = QGridLayout()
        widgets_layout.setContentsMargins(0, 0, 0, 0)
        self._line_search = QLineEdit()
        self._line_search.setPlaceholderText(translations.TR_SEARCH_FOR)
        main_layout.addWidget(self._line_search)
        # TODO: replace
        self._check_cs = QCheckBox(translations.TR_SEARCH_CASE_SENSITIVE)
        self._check_cs.setChecked(True)
        widgets_layout.addWidget(self._check_cs, 2, 0)
        self._check_wo = QCheckBox(translations.TR_SEARCH_WHOLE_WORDS)
        widgets_layout.addWidget(self._check_wo, 2, 1)
        self._check_re = QCheckBox(translations.TR_SEARCH_REGEX)
        widgets_layout.addWidget(self._check_re, 3, 0)
        self._check_recursive = QCheckBox('Recursive')
        widgets_layout.addWidget(self._check_recursive, 3, 1)
        main_layout.addLayout(widgets_layout)
        main_layout.addStretch(1)

        # Connections
        self._line_search.returnPressed.connect(self.search_requested)
コード例 #17
0
ファイル: routing_panel.py プロジェクト: mintoo/NetDim
 def __init__(self, controller):
     super().__init__(controller)
     self.controller = controller
     self.setTitle('Routing')
     
     select_all_button = QPushButton()
     select_all_button.setText('Select / Unselect all')
     select_all_button.clicked.connect(self.selection)
     
     self.actions = (
                     'Update AS topology',
                     'Creation of all virtual connections',
                     'Names / addresses interface allocation',
                     'Creation of all ARP / MAC tables',
                     'Creation of all routing tables',
                     'Path finding procedure',
                     'Refresh the display'
                     )
                     
     layout = QGridLayout(self)
     layout.addWidget(select_all_button, 0, 1, 1, 1)
     self.checkboxes = []
     for index, action in enumerate(self.actions, 1):
         checkbox = QCheckBox(action)
         checkbox.setChecked(True)
         self.checkboxes.append(checkbox)
         layout.addWidget(checkbox, index, 1, 1, 1)
     self.setLayout(layout)
コード例 #18
0
 def __init__(self, parent, styler):
     QCheckBox.__init__(self, _(styler.friendly_name), parent)
     self.styler = styler
     if styler.is_active:
         self.toggle()
     self.stateChanged.connect(self.switch_state)
     self.parent = parent
コード例 #19
0
    def save_all(self):
        if self.num_frames == 0:
            return

        settings = constants.SETTINGS
        try:
            not_show = settings.value('not_show_save_dialog', type=bool, defaultValue=False)
        except TypeError:
            not_show = False

        if not not_show:
            cb = QCheckBox("Don't ask me again.")
            msg_box = QMessageBox(QMessageBox.Question, self.tr("Confirm saving all signals"),
                                  self.tr("All changed signal files will be overwritten. OK?"))
            msg_box.addButton(QMessageBox.Yes)
            msg_box.addButton(QMessageBox.No)
            msg_box.setCheckBox(cb)

            reply = msg_box.exec()
            not_show_again = cb.isChecked()
            settings.setValue("not_show_save_dialog", not_show_again)
            self.not_show_again_changed.emit()

            if reply != QMessageBox.Yes:
                return

        for f in self.signal_frames:
            if f.signal is None or f.signal.filename == "":
                continue
            f.signal.save()
コード例 #20
0
    def __init__(self,parent=None):
        super().__init__(parent)
        label = QLabel(self.tr("Find &what:"))
        self.lineEdit = QLineEdit()
        label.setBuddy(self.lineEdit)

        self.caseCheckBox=QCheckBox(self.tr("Match &case"))
        self.backwardCheckBox=QCheckBox(self.tr("Search &backward"))
        self.findButton = QPushButton(self.tr("&Find"))
        self.findButton.setDefault(True)
        self.findButton.setEnabled(False)
        closeButton=QPushButton(self.tr("Close"))

        self.lineEdit.textChanged.connect(self.enableFindButton)
        self.findButton.clicked.connect(self.findClicked)
        closeButton.clicked.connect(self.close)

        topLeftLayout=QHBoxLayout()
        topLeftLayout.addWidget(label)
        topLeftLayout.addWidget(self.lineEdit)
        leftLayout=QVBoxLayout()
        leftLayout.addLayout(topLeftLayout)
        leftLayout.addWidget(self.caseCheckBox)
        leftLayout.addWidget(self.backwardCheckBox)
        rightLayout = QVBoxLayout()
        rightLayout.addWidget(self.findButton)
        rightLayout.addWidget(closeButton)
        rightLayout.addStretch()
        mainLayout=QHBoxLayout()
        mainLayout.addLayout(leftLayout)
        mainLayout.addLayout(rightLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle(self.tr("Find"))
        self.setFixedHeight(self.sizeHint().height())
コード例 #21
0
ファイル: deletion_options.py プロジェクト: atiarda/dupeguru
 def _setupUi(self):
     self.setWindowTitle(tr("Deletion Options"))
     self.resize(400, 270)
     self.verticalLayout = QVBoxLayout(self)
     self.msgLabel = QLabel()
     self.verticalLayout.addWidget(self.msgLabel)
     self.linkCheckbox = QCheckBox(tr("Link deleted files"))
     self.verticalLayout.addWidget(self.linkCheckbox)
     text = tr(
         "After having deleted a duplicate, place a link targeting the reference file "
         "to replace the deleted file."
     )
     self.linkMessageLabel = QLabel(text)
     self.linkMessageLabel.setWordWrap(True)
     self.verticalLayout.addWidget(self.linkMessageLabel)
     self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False)
     self.verticalLayout.addWidget(self.linkTypeRadio)
     if not self.model.supports_links():
         self.linkCheckbox.setEnabled(False)
         self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)"))
     self.directCheckbox = QCheckBox(tr("Directly delete files"))
     self.verticalLayout.addWidget(self.directCheckbox)
     text = tr(
         "Instead of sending files to trash, delete them directly. This option is usually "
         "used as a workaround when the normal deletion method doesn't work."
     )
     self.directMessageLabel = QLabel(text)
     self.directMessageLabel.setWordWrap(True)
     self.verticalLayout.addWidget(self.directMessageLabel)
     self.buttonBox = QDialogButtonBox()
     self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole)
     self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole)
     self.verticalLayout.addWidget(self.buttonBox)
コード例 #22
0
ファイル: stop_all.py プロジェクト: tornel/linux-show-player
class StopAllSettings(SettingsSection):

    Name = 'Cue Settings'

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

        self.setLayout(QVBoxLayout(self))

        self.group = QGroupBox(self)
        self.group.setTitle('Mode')
        self.group.setLayout(QHBoxLayout(self.group))

        self.pauseMode = QCheckBox(self.group)
        self.pauseMode.setText('Pause mode')
        self.group.layout().addWidget(self.pauseMode)

        self.layout().addWidget(self.group)
        self.layout().addSpacing(self.height() - 100)

    def enable_check(self, enable):
        self.group.setCheckable(enable)
        self.group.setChecked(False)

    def get_configuration(self):
        conf = {}

        if not (self.group.isCheckable() and not self.group.isChecked()):
            conf['pause_mode'] = self.pauseMode.isChecked()

        return conf

    def set_configuration(self, conf):
        if 'pause_mode' in conf:
            self.pauseMode.setChecked(conf['pause_mode'])
コード例 #23
0
    def _setup_general_ui(self):
        """
        Create everything related to the general tab
        """

        layout = QFormLayout()
        layout.setSpacing(20)
        layout.setVerticalSpacing(20)

        self.device_dialog_checkbox = QCheckBox(self)
        device_dialog_label = QLabel("Open device dialog on start:")
        layout.addRow(device_dialog_label,
                      self.device_dialog_checkbox)

        self.reopen_device_checkbox = QCheckBox(self)
        reopen_device_label = QLabel("Reopen device on start(ignores device dialog):", self)
        layout.addRow(reopen_device_label,
                      self.reopen_device_checkbox)

        self.use_dutils_checkbox = QCheckBox(self)
        self.use_dutils_label = QLabel("Use tiscamera dutils, if present:", self)
        layout.addRow(self.use_dutils_label,
                      self.use_dutils_checkbox)

        if not self.enabled_dutils:
            self.use_dutils_label.setToolTip("Enabled when tiscamera-dutils are installed")
            self.use_dutils_label.setEnabled(False)
            self.use_dutils_checkbox.setToolTip("Enabled when tiscamera-dutils are installed")
            self.use_dutils_checkbox.setEnabled(False)

        self.general_widget.setLayout(layout)
コード例 #24
0
 def __init__(self, parent=None):
     QCheckBox.__init__(self, parent)
     self.stateChanged.connect(self.submit)
     self._column = Outline.compile
     self._index = None
     self._indexes = None
     self._model = None
     self._updating = False
コード例 #25
0
ファイル: game.py プロジェクト: kobso1245/Don-t-get-angry
 def __add_checkbox(self, index):
     box = QVBoxLayout()
     checkbox = QCheckBox(str(index), self)
     self.checkboxes.append(checkbox)
     checkbox.stateChanged.connect(self.signal_for_figure)
     checkbox.setCheckable(False)
     box.addWidget(checkbox)
     self.boxes[index].setLayout(box)
コード例 #26
0
class General(SettingsPage):

    NAME = 'General'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout())
        self.layout().setAlignment(Qt.AlignTop)

        # Startup layout
        self.layoutGroup = QGroupBox(self)
        self.layoutGroup.setTitle('Startup layout')
        self.layoutGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.layoutGroup)

        self.startupDialogCheck = QCheckBox(self.layoutGroup)
        self.startupDialogCheck.setText('Use startup dialog')
        self.layoutGroup.layout().addWidget(self.startupDialogCheck)

        self.layoutCombo = QComboBox(self.layoutGroup)
        self.layoutCombo.addItems([lay.NAME for lay in layouts.get_layouts()])
        self.layoutGroup.layout().addWidget(self.layoutCombo)

        self.startupDialogCheck.clicked.connect(
            lambda check: self.layoutCombo.setEnabled(not check))

        # Application style
        self.themeGroup = QGroupBox(self)
        self.themeGroup.setTitle('Application theme')
        self.themeGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.themeGroup)

        self.themeCombo = QComboBox(self.themeGroup)
        self.themeCombo.addItems(styles.get_styles())
        self.themeGroup.layout().addWidget(self.themeCombo)

    def get_settings(self):
        conf = {'Layout': {}, 'Theme': {}}

        if self.startupDialogCheck.isChecked():
            conf['Layout']['default'] = 'NoDefault'
        else:
            conf['Layout']['default'] = self.layoutCombo.currentText()

        conf['Theme']['theme'] = self.themeCombo.currentText()
        styles.apply_style(self.themeCombo.currentText())

        return conf

    def load_settings(self, settings):
        if 'default' in settings['Layout']:
            if settings['Layout']['default'].lower() == 'nodefault':
                self.startupDialogCheck.setChecked(True)
                self.layoutCombo.setEnabled(False)
            else:
                self.layoutCombo.setCurrentText(settings['Layout']['default'])
        if 'theme' in settings['Theme']:
            self.themeCombo.setCurrentText(settings['Theme']['theme'])
コード例 #27
0
class DyStockDataHistTicksVerifyDlg(QDialog):

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

        self._data = data

        self._initUi()

    def _initUi(self):
        self.setWindowTitle('历史分笔数据校验')
 
        # 控件
        startDateLable = QLabel('开始日期')
        self._startDateLineEdit = QLineEdit(datetime.now().strftime("%Y-%m-%d"))

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

        self._addCheckBox = QCheckBox('校验缺失历史分笔数据')
        self._addCheckBox.setChecked(True)
        self._deleteCheckBox = QCheckBox('校验无效历史分笔数据')
        #self._deleteCheckBox.setChecked(True)

        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(self._addCheckBox, 2, 0)
        grid.addWidget(self._deleteCheckBox, 2, 1)

        grid.addWidget(okPushButton, 3, 1)
        grid.addWidget(cancelPushButton, 3, 0)
 
        self.setLayout(grid)

    def _ok(self):
        self._data['startDate'] = self._startDateLineEdit.text()
        self._data['endDate'] = self._endDateLineEdit.text()

        self._data['verifyMissing'] = self._addCheckBox.isChecked()
        self._data['verifyInvalid'] = self._deleteCheckBox.isChecked()

        self.accept()

    def _cancel(self):
        self.reject()
コード例 #28
0
ファイル: find_in_files.py プロジェクト: ninja-ide/ninja-ide
class FindInFilesActions(QWidget):

    searchRequested = pyqtSignal('QString', bool, bool, bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored)
        self._scope = QComboBox()
        self._scope.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.ninjaide = IDE.get_service('ide')
        self.ninjaide.filesAndProjectsLoaded.connect(
            self._update_combo_projects)

        main_layout = QVBoxLayout(self)
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(translations.TR_SEARCH_SCOPE))
        hbox.addWidget(self._scope)
        main_layout.addLayout(hbox)
        widgets_layout = QGridLayout()
        widgets_layout.setContentsMargins(0, 0, 0, 0)
        self._line_search = QLineEdit()
        self._line_search.setPlaceholderText(translations.TR_SEARCH_FOR)
        main_layout.addWidget(self._line_search)
        # TODO: replace
        self._check_cs = QCheckBox(translations.TR_SEARCH_CASE_SENSITIVE)
        self._check_cs.setChecked(True)
        widgets_layout.addWidget(self._check_cs, 2, 0)
        self._check_wo = QCheckBox(translations.TR_SEARCH_WHOLE_WORDS)
        widgets_layout.addWidget(self._check_wo, 2, 1)
        self._check_re = QCheckBox(translations.TR_SEARCH_REGEX)
        widgets_layout.addWidget(self._check_re, 3, 0)
        self._check_recursive = QCheckBox('Recursive')
        widgets_layout.addWidget(self._check_recursive, 3, 1)
        main_layout.addLayout(widgets_layout)
        main_layout.addStretch(1)

        # Connections
        self._line_search.returnPressed.connect(self.search_requested)

    def _update_combo_projects(self):
        projects = self.ninjaide.get_projects()
        for nproject in projects.values():
            self._scope.addItem(nproject.name, nproject.path)

    @property
    def current_project_path(self):
        """Returns NProject.path of current project"""
        return self._scope.itemData(self._scope.currentIndex())

    def search_requested(self):
        text = self._line_search.text()
        if not text.strip():
            return
        has_search = self._line_search.text()
        cs = self._check_cs.isChecked()
        regex = self._check_re.isChecked()
        wo = self._check_wo.isChecked()
        self.searchRequested.emit(has_search, cs, regex, wo)
コード例 #29
0
ファイル: copy2image.py プロジェクト: 19joho66/frescobaldi
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self._filename = None
        self._page = None
        self._rect = None
        self.imageViewer = widgets.imageviewer.ImageViewer()
        self.dpiLabel = QLabel()
        self.dpiCombo = QComboBox(insertPolicy=QComboBox.NoInsert, editable=True)
        self.dpiCombo.lineEdit().setCompleter(None)
        self.dpiCombo.setValidator(QDoubleValidator(10.0, 1200.0, 4, self.dpiCombo))
        self.dpiCombo.addItems([format(i) for i in (72, 100, 200, 300, 600, 1200)])

        self.colorButton = widgets.colorbutton.ColorButton()
        self.colorButton.setColor(QColor(Qt.white))
        self.grayscale = QCheckBox(checked=False)
        self.crop = QCheckBox()
        self.antialias = QCheckBox(checked=True)
        self.scaleup = QCheckBox(checked=False)
        self.dragfile = QPushButton(icons.get("image-x-generic"), None, None)
        self.fileDragger = FileDragger(self.dragfile)
        self.buttons = QDialogButtonBox(QDialogButtonBox.Close)
        self.copyButton = self.buttons.addButton('', QDialogButtonBox.ApplyRole)
        self.copyButton.setIcon(icons.get('edit-copy'))
        self.saveButton = self.buttons.addButton('', QDialogButtonBox.ApplyRole)
        self.saveButton.setIcon(icons.get('document-save'))

        layout = QVBoxLayout()
        self.setLayout(layout)

        layout.addWidget(self.imageViewer)

        controls = QHBoxLayout()
        layout.addLayout(controls)
        controls.addWidget(self.dpiLabel)
        controls.addWidget(self.dpiCombo)
        controls.addWidget(self.colorButton)
        controls.addWidget(self.grayscale)
        controls.addWidget(self.crop)
        controls.addWidget(self.antialias)
        controls.addWidget(self.scaleup)
        controls.addStretch()
        controls.addWidget(self.dragfile)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        self.readSettings()
        self.finished.connect(self.writeSettings)
        self.dpiCombo.editTextChanged.connect(self.drawImage)
        self.colorButton.colorChanged.connect(self.drawImage)
        self.grayscale.toggled.connect(self.drawImage)
        self.antialias.toggled.connect(self.drawImage)
        self.scaleup.toggled.connect(self.drawImage)
        self.crop.toggled.connect(self.cropImage)
        self.buttons.rejected.connect(self.reject)
        self.copyButton.clicked.connect(self.copyToClipboard)
        self.saveButton.clicked.connect(self.saveAs)
        qutil.saveDialogSize(self, "copy_image/dialog/size", QSize(480, 320))
コード例 #30
0
ファイル: editable_objects.py プロジェクト: spacejump163/ai2
 def to_editor(self, modify_callback, current_name):
     w = QCheckBox()
     w.setChecked(self._v)
     def changed():
         nv = w.isChecked()
         self._v = nv
         modify_callback(current_name, self, w)
     w.stateChanged.connect(changed)
     return w
コード例 #31
0
class ComicsProjectSetupWizard():
    setupDictionary = {}
    projectDirectory = ""

    def __init__(self):
        # super().__init__(parent)
        # Search the location of the script for the two lists that are used with the projectname generator.
        mainP = Path(__file__).parent
        self.generateListA = []
        self.generateListB = []
        if Path(mainP / "projectGenLists" / "listA.txt").exists():
            for l in open(str(mainP / "projectGenLists" / "listA.txt"), "r"):
                if l.isspace() == False:
                    self.generateListA.append(l.strip("\n"))
        if Path(mainP / "projectGenLists" / "listB.txt").exists():
            for l in open(str(mainP / "projectGenLists" / "listB.txt"), "r"):
                if l.isspace() == False:
                    self.generateListB.append(l.strip("\n"))

    def showDialog(self):
        # Initialise the setup directory empty toavoid exceptions.
        self.setupDictionary = {}

        # ask for a project directory.
        self.projectDirectory = QFileDialog.getExistingDirectory(
            caption=i18n("Where should the comic project go?"),
            options=QFileDialog.ShowDirsOnly)
        if os.path.exists(self.projectDirectory) is False:
            return
        self.pagesDirectory = os.path.relpath(self.projectDirectory,
                                              self.projectDirectory)
        self.exportDirectory = os.path.relpath(self.projectDirectory,
                                               self.projectDirectory)

        wizard = QWizard()
        wizard.setWindowTitle(i18n("Comic Project Setup"))
        wizard.setOption(QWizard.IndependentPages, True)

        # Set up the UI for the wizard
        basicsPage = QWizardPage()
        basicsPage.setTitle(i18n("Basic Comic Project Settings"))
        formLayout = QFormLayout()
        basicsPage.setLayout(formLayout)
        projectLayout = QHBoxLayout()
        self.lnProjectName = QLineEdit()
        basicsPage.registerField("Project Name*", self.lnProjectName)
        self.lnProjectName.setToolTip(
            i18n(
                "A Project name. This can be different from the eventual title"
            ))
        btnRandom = QPushButton()
        btnRandom.setText(i18n("Generate"))
        btnRandom.setToolTip(
            i18n(
                "If you cannot come up with a project name, our highly sophisticated project name generator will serve to give a classy yet down to earth name."
            ))
        btnRandom.clicked.connect(self.slot_generate)
        projectLayout.addWidget(self.lnProjectName)
        projectLayout.addWidget(btnRandom)
        lnConcept = QLineEdit()
        lnConcept.setToolTip(
            i18n(
                "What is your comic about? This is mostly for your own convenience so do not worry about what it says too much."
            ))
        self.cmbLanguage = comics_metadata_dialog.language_combo_box()
        self.cmbLanguage.setToolTip(i18n("The main language the comic is in"))
        self.cmbLanguage.setEntryToCode(
            str(QLocale.system().name()).split("_")[0])
        self.cmbCountry = comics_metadata_dialog.country_combo_box()
        if QLocale.system() != QLocale.c():
            self.cmbCountry.setEntryToCode(
                str(QLocale.system().name()).split("_")[-1])
        else:
            self.slot_update_countries()
        self.cmbLanguage.currentIndexChanged.connect(
            self.slot_update_countries)
        self.lnProjectDirectory = QLabel(self.projectDirectory)
        self.chkMakeProjectDirectory = QCheckBox()
        labelDirectory = QLabel(
            i18n("Make a new directory with the project name."))
        labelDirectory.setWordWrap(True)
        stringDirectoryTooltip = i18n(
            "This allows you to select a generic comics project directory, in which a new folder will be made for the project using the given project name."
        )
        self.chkMakeProjectDirectory.setToolTip(stringDirectoryTooltip)
        labelDirectory.setToolTip(stringDirectoryTooltip)
        self.chkMakeProjectDirectory.setChecked(True)
        self.lnPagesDirectory = QLineEdit()
        self.lnPagesDirectory.setText(i18n("pages"))
        self.lnPagesDirectory.setToolTip(
            i18n(
                "The name for the folder where the pages are contained. If it does not exist, it will be created."
            ))
        self.lnExportDirectory = QLineEdit()
        self.lnExportDirectory.setText(i18n("export"))
        self.lnExportDirectory.setToolTip(
            i18n(
                "The name for the folder where the export is put. If it does not exist, it will be created."
            ))
        self.lnTemplateLocation = QLineEdit()
        self.lnTemplateLocation.setText(i18n("templates"))
        self.lnTemplateLocation.setToolTip(
            i18n(
                "The name for the folder where the page templates are sought in."
            ))

        self.lnTranslationLocation = QLineEdit()
        self.lnTranslationLocation.setText(i18n("translations"))
        self.lnTranslationLocation.setToolTip(
            "This is the location that POT files will be stored to and PO files will be read from."
        )
        formLayout.addRow(i18n("Comic concept:"), lnConcept)
        formLayout.addRow(i18n("Project name:"), projectLayout)
        formLayout.addRow(i18n("Main language:"), self.cmbLanguage)
        formLayout.addRow("", self.cmbCountry)

        buttonMetaData = QPushButton(i18n("Meta Data"))
        buttonMetaData.clicked.connect(self.slot_edit_meta_data)

        wizard.addPage(basicsPage)

        foldersPage = QWizardPage()
        foldersPage.setTitle(i18n("Folder names and other."))
        folderFormLayout = QFormLayout()
        foldersPage.setLayout(folderFormLayout)
        folderFormLayout.addRow(i18n("Project directory:"),
                                self.lnProjectDirectory)
        folderFormLayout.addRow(self.chkMakeProjectDirectory, labelDirectory)
        folderFormLayout.addRow(i18n("Pages directory"), self.lnPagesDirectory)
        folderFormLayout.addRow(i18n("Export directory"),
                                self.lnExportDirectory)
        folderFormLayout.addRow(i18n("Template directory"),
                                self.lnTemplateLocation)
        folderFormLayout.addRow(i18n("Translation directory"),
                                self.lnTranslationLocation)
        folderFormLayout.addRow("", buttonMetaData)
        wizard.addPage(foldersPage)

        # Execute the wizard, and after wards...
        if (wizard.exec_()):

            # First get the directories, check if the directories exist, and otherwise make them.
            self.pagesDirectory = self.lnPagesDirectory.text()
            self.exportDirectory = self.lnExportDirectory.text()
            self.templateLocation = self.lnTemplateLocation.text()
            self.translationLocation = self.lnTranslationLocation.text()
            projectPath = Path(self.projectDirectory)
            # Only make a project directory if the checkbox for that has been checked.
            if self.chkMakeProjectDirectory.isChecked():
                projectPath = projectPath / self.lnProjectName.text()
                if projectPath.exists() is False:
                    projectPath.mkdir()
                self.projectDirectory = str(projectPath)
            if Path(projectPath / self.pagesDirectory).exists() is False:
                Path(projectPath / self.pagesDirectory).mkdir()
            if Path(projectPath / self.exportDirectory).exists() is False:
                Path(projectPath / self.exportDirectory).mkdir()
            if Path(projectPath / self.templateLocation).exists() is False:
                Path(projectPath / self.templateLocation).mkdir()
            if Path(projectPath / self.translationLocation).exists() is False:
                Path(projectPath / self.translationLocation).mkdir()

            # Then store the information into the setup diactionary.
            self.setupDictionary["projectName"] = self.lnProjectName.text()
            self.setupDictionary["concept"] = lnConcept.text()
            self.setupDictionary["language"] = str(
                self.cmbLanguage.codeForCurrentEntry())
            self.setupDictionary["pagesLocation"] = self.pagesDirectory
            self.setupDictionary["exportLocation"] = self.exportDirectory
            self.setupDictionary["templateLocation"] = self.templateLocation
            self.setupDictionary[
                "translationLocation"] = self.translationLocation

            # Finally, write the dictionary into the json file.
            self.writeConfig()

    """
    This calls up the metadata dialog, for if people already have information they want to type in
    at the setup stage. Not super likely, but the organisation and management aspect of the comic
    manager means we should give the option to organise as smoothly as possible.
    """

    def slot_edit_meta_data(self):
        dialog = comics_metadata_dialog.comic_meta_data_editor()
        self.setupDictionary["language"] = str(
            self.cmbLanguage.codeForCurrentEntry())
        dialog.setConfig(self.setupDictionary)
        dialog.setConfig(self.setupDictionary)
        if (dialog.exec_() == QDialog.Accepted):
            self.setupDictionary = dialog.getConfig(self.setupDictionary)
            self.cmbLanguage.setEntryToCode(self.setupDictionary["language"])

    """
    Update the country list when the language list changes.
    """

    def slot_update_countries(self):
        code = self.cmbLanguage.codeForCurrentEntry()
        self.cmbCountry.set_country_for_locale(code)

    """
    Write the actual config to the chosen project directory.
    """

    def writeConfig(self):
        print("CPMT: writing comic configuration...")
        print(self.projectDirectory)
        configFile = open(os.path.join(self.projectDirectory,
                                       "comicConfig.json"),
                          "w",
                          newline="",
                          encoding="utf-16")
        json.dump(self.setupDictionary,
                  configFile,
                  indent=4,
                  sort_keys=True,
                  ensure_ascii=False)
        configFile.close()
        print("CPMT: done")

    """
    As you may be able to tell, the random projectname generator is hardly sophisticated.
    It picks a word from a list of names of figures from Greek Mythology, and a name from a list
    of vegetables and fruits and combines the two camelcased.
    It makes for good codenames at the least.
    """

    def slot_generate(self):
        if len(self.generateListA) > 0 and len(self.generateListB) > 0:
            nameA = self.generateListA[random.randint(
                0,
                len(self.generateListA) - 1)]
            nameB = self.generateListB[random.randint(
                0,
                len(self.generateListB) - 1)]
            self.lnProjectName.setText(str(nameA.title() + nameB.title()))
コード例 #32
0
    def showDialog(self):
        # Initialise the setup directory empty toavoid exceptions.
        self.setupDictionary = {}

        # ask for a project directory.
        self.projectDirectory = QFileDialog.getExistingDirectory(
            caption=i18n("Where should the comic project go?"),
            options=QFileDialog.ShowDirsOnly)
        if os.path.exists(self.projectDirectory) is False:
            return
        self.pagesDirectory = os.path.relpath(self.projectDirectory,
                                              self.projectDirectory)
        self.exportDirectory = os.path.relpath(self.projectDirectory,
                                               self.projectDirectory)

        wizard = QWizard()
        wizard.setWindowTitle(i18n("Comic Project Setup"))
        wizard.setOption(QWizard.IndependentPages, True)

        # Set up the UI for the wizard
        basicsPage = QWizardPage()
        basicsPage.setTitle(i18n("Basic Comic Project Settings"))
        formLayout = QFormLayout()
        basicsPage.setLayout(formLayout)
        projectLayout = QHBoxLayout()
        self.lnProjectName = QLineEdit()
        basicsPage.registerField("Project Name*", self.lnProjectName)
        self.lnProjectName.setToolTip(
            i18n(
                "A Project name. This can be different from the eventual title"
            ))
        btnRandom = QPushButton()
        btnRandom.setText(i18n("Generate"))
        btnRandom.setToolTip(
            i18n(
                "If you cannot come up with a project name, our highly sophisticated project name generator will serve to give a classy yet down to earth name."
            ))
        btnRandom.clicked.connect(self.slot_generate)
        projectLayout.addWidget(self.lnProjectName)
        projectLayout.addWidget(btnRandom)
        lnConcept = QLineEdit()
        lnConcept.setToolTip(
            i18n(
                "What is your comic about? This is mostly for your own convenience so do not worry about what it says too much."
            ))
        self.cmbLanguage = comics_metadata_dialog.language_combo_box()
        self.cmbLanguage.setToolTip(i18n("The main language the comic is in"))
        self.cmbLanguage.setEntryToCode(
            str(QLocale.system().name()).split("_")[0])
        self.cmbCountry = comics_metadata_dialog.country_combo_box()
        if QLocale.system() != QLocale.c():
            self.cmbCountry.setEntryToCode(
                str(QLocale.system().name()).split("_")[-1])
        else:
            self.slot_update_countries()
        self.cmbLanguage.currentIndexChanged.connect(
            self.slot_update_countries)
        self.lnProjectDirectory = QLabel(self.projectDirectory)
        self.chkMakeProjectDirectory = QCheckBox()
        labelDirectory = QLabel(
            i18n("Make a new directory with the project name."))
        labelDirectory.setWordWrap(True)
        stringDirectoryTooltip = i18n(
            "This allows you to select a generic comics project directory, in which a new folder will be made for the project using the given project name."
        )
        self.chkMakeProjectDirectory.setToolTip(stringDirectoryTooltip)
        labelDirectory.setToolTip(stringDirectoryTooltip)
        self.chkMakeProjectDirectory.setChecked(True)
        self.lnPagesDirectory = QLineEdit()
        self.lnPagesDirectory.setText(i18n("pages"))
        self.lnPagesDirectory.setToolTip(
            i18n(
                "The name for the folder where the pages are contained. If it does not exist, it will be created."
            ))
        self.lnExportDirectory = QLineEdit()
        self.lnExportDirectory.setText(i18n("export"))
        self.lnExportDirectory.setToolTip(
            i18n(
                "The name for the folder where the export is put. If it does not exist, it will be created."
            ))
        self.lnTemplateLocation = QLineEdit()
        self.lnTemplateLocation.setText(i18n("templates"))
        self.lnTemplateLocation.setToolTip(
            i18n(
                "The name for the folder where the page templates are sought in."
            ))

        self.lnTranslationLocation = QLineEdit()
        self.lnTranslationLocation.setText(i18n("translations"))
        self.lnTranslationLocation.setToolTip(
            "This is the location that POT files will be stored to and PO files will be read from."
        )
        formLayout.addRow(i18n("Comic concept:"), lnConcept)
        formLayout.addRow(i18n("Project name:"), projectLayout)
        formLayout.addRow(i18n("Main language:"), self.cmbLanguage)
        formLayout.addRow("", self.cmbCountry)

        buttonMetaData = QPushButton(i18n("Meta Data"))
        buttonMetaData.clicked.connect(self.slot_edit_meta_data)

        wizard.addPage(basicsPage)

        foldersPage = QWizardPage()
        foldersPage.setTitle(i18n("Folder names and other."))
        folderFormLayout = QFormLayout()
        foldersPage.setLayout(folderFormLayout)
        folderFormLayout.addRow(i18n("Project directory:"),
                                self.lnProjectDirectory)
        folderFormLayout.addRow(self.chkMakeProjectDirectory, labelDirectory)
        folderFormLayout.addRow(i18n("Pages directory"), self.lnPagesDirectory)
        folderFormLayout.addRow(i18n("Export directory"),
                                self.lnExportDirectory)
        folderFormLayout.addRow(i18n("Template directory"),
                                self.lnTemplateLocation)
        folderFormLayout.addRow(i18n("Translation directory"),
                                self.lnTranslationLocation)
        folderFormLayout.addRow("", buttonMetaData)
        wizard.addPage(foldersPage)

        # Execute the wizard, and after wards...
        if (wizard.exec_()):

            # First get the directories, check if the directories exist, and otherwise make them.
            self.pagesDirectory = self.lnPagesDirectory.text()
            self.exportDirectory = self.lnExportDirectory.text()
            self.templateLocation = self.lnTemplateLocation.text()
            self.translationLocation = self.lnTranslationLocation.text()
            projectPath = Path(self.projectDirectory)
            # Only make a project directory if the checkbox for that has been checked.
            if self.chkMakeProjectDirectory.isChecked():
                projectPath = projectPath / self.lnProjectName.text()
                if projectPath.exists() is False:
                    projectPath.mkdir()
                self.projectDirectory = str(projectPath)
            if Path(projectPath / self.pagesDirectory).exists() is False:
                Path(projectPath / self.pagesDirectory).mkdir()
            if Path(projectPath / self.exportDirectory).exists() is False:
                Path(projectPath / self.exportDirectory).mkdir()
            if Path(projectPath / self.templateLocation).exists() is False:
                Path(projectPath / self.templateLocation).mkdir()
            if Path(projectPath / self.translationLocation).exists() is False:
                Path(projectPath / self.translationLocation).mkdir()

            # Then store the information into the setup diactionary.
            self.setupDictionary["projectName"] = self.lnProjectName.text()
            self.setupDictionary["concept"] = lnConcept.text()
            self.setupDictionary["language"] = str(
                self.cmbLanguage.codeForCurrentEntry())
            self.setupDictionary["pagesLocation"] = self.pagesDirectory
            self.setupDictionary["exportLocation"] = self.exportDirectory
            self.setupDictionary["templateLocation"] = self.templateLocation
            self.setupDictionary[
                "translationLocation"] = self.translationLocation

            # Finally, write the dictionary into the json file.
            self.writeConfig()
コード例 #33
0
    def _initUi(self):
        self.setWindowTitle('配置-股票历史日线数据源')

        # 控件
        label = QLabel('股票历史日线数据源')

        self._windCheckBox = QCheckBox('Wind')
        self._windCheckBox.clicked.connect(self._windCheckBoxClicked)

        self._tuShareCheckBox = QCheckBox('TuShare')
        self._tuShareCheckBox.clicked.connect(self._tuShareCheckBoxClicked)

        self._tuShareProCheckBox = QCheckBox('TuSharePro')

        tuShareProTokenLabel = QLabel('TuSharePro token')
        self._tuShareProTokenLineEdit = QLineEdit()

        description = """默认使用Wind

只选Wind:更新交易日数据,股票代码表和股票历史日线数据到Wind对应的数据库

只选TuShare:更新交易日数据,股票代码表和股票历史日线数据到TuShare对应的数据库

选两个:更新交易日数据,股票代码表和股票历史日线数据到Wind对应的数据库,并同时做两个源的数据验证

交易日数据,股票代码表和股票历史日线数据的载入也是基于上面选择的数据库
        """
        textEdit = QTextEdit()
        textEdit.setPlainText(description)
        textEdit.setReadOnly(True)

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

        self._tradeDaysComboBox = QComboBox()
        descriptionTradeDays = "Wind有时交易日数据可能出错,所以选Wind时,总是跟TuShare做验证,由用户选择该如何做。"
        tradeDaysTextEdit = QTextEdit()
        tradeDaysTextEdit.setPlainText(descriptionTradeDays)
        tradeDaysTextEdit.setReadOnly(True)

        self._tuShareDaysIntervalLineEdit = QLineEdit(
        )  # TuShare日线数据每次下载间隔时间(秒)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(label, 0, 0)
        grid.addWidget(self._windCheckBox, 1, 0)
        grid.addWidget(self._tuShareCheckBox, 2, 0)
        grid.addWidget(self._tuShareProCheckBox, 3, 0)
        grid.addWidget(tuShareProTokenLabel, 4, 0)
        grid.addWidget(self._tuShareProTokenLineEdit, 5, 0)

        grid.addWidget(textEdit, 6, 0)

        grid.addWidget(
            QLabel(
                "                                                                 "
            ), 7, 0)
        grid.addWidget(QLabel("交易日数据模式"), 8, 0)
        grid.addWidget(self._tradeDaysComboBox, 9, 0)
        grid.addWidget(tradeDaysTextEdit, 10, 0)

        grid.addWidget(
            QLabel(
                "                                                                 "
            ), 11, 0)
        grid.addWidget(QLabel("TuShare日线数据下载间隔时间(秒)"), 12, 0)
        grid.addWidget(self._tuShareDaysIntervalLineEdit, 13, 0)

        grid.addWidget(okPushButton, 0, 1)
        grid.addWidget(cancelPushButton, 1, 1)

        self.setLayout(grid)

        # set data source to UI
        if self._data.get('Wind'):
            self._windCheckBox.setChecked(True)

        if sys.platform != 'win32':  # Wind only supported at Windows.
            self._windCheckBox.setEnabled(False)
            self._windCheckBox.setChecked(False)

        enableTuSharePro = False
        if self._data.get('TuShare'):
            self._tuShareCheckBox.setChecked(True)
            enableTuSharePro = True

        self._tuShareProCheckBox.setEnabled(enableTuSharePro)

        # set tushare pro
        enableTushareProToken = False
        if self._tuShareProData.get('TuSharePro'):
            self._tuShareProCheckBox.setChecked(True)
            enableTushareProToken = True

        if self._tuShareProData.get('Token'):
            self._tuShareProTokenLineEdit.setText(
                self._tuShareProData.get('Token'))

        # set according to days source checkbox
        self._tradeDaysComboBox.addItems(list(self.tradeDaysMode))
        self._enableTradeDaysComboBox()

        for k, v in self.tradeDaysMode.items():
            if v == self._tradeDaysModeData["tradeDaysMode"]:
                self._tradeDaysComboBox.setCurrentText(k)
                break

        # tushare days downloading interval
        self._tuShareDaysIntervalLineEdit.setText(
            str(self._tuShareDaysIntervalData['interval']))

        self.resize(QApplication.desktop().size().width() // 2,
                    QApplication.desktop().size().height() // 4 * 3)
コード例 #34
0
 def __create_check_box_for_tag(self, tag: str):
     check_box = QCheckBox(tag)
     # check_box.clicked.connect(self.__on_checkbox_clicked())
     self.__flow_layout.addWidget(check_box)
     self.__check_tags.append(check_box)
コード例 #35
0
ファイル: qt.py プロジェクト: Cessaa/electrum-doge
    def request_safe_t_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)
            vbox.addWidget(gb)
            gb.setTitle(_("Select your seed length:"))
            bg = QButtonGroup()
            for i, count in enumerate([12, 18, 24]):
                rb = QRadioButton(gb)
                rb.setText(_("{:d} 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.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())
コード例 #36
0
class NetworkChoiceLayout(object):
    def __init__(self, network, config, wizard=False):
        self.network = network
        self.config = config
        self.protocol = None
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        server_tab = QWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(server_tab, _('Server'))
        tabs.addTab(proxy_tab, _('Proxy'))

        if wizard:
            tabs.setCurrentIndex(1)

        # server tab
        grid = QGridLayout(server_tab)
        grid.setSpacing(8)

        self.server_host = QLineEdit()
        self.server_host.setFixedWidth(200)
        self.server_port = QLineEdit()
        self.server_port.setFixedWidth(60)
        self.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))

        self.server_host.editingFinished.connect(self.set_server)
        self.server_port.editingFinished.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)

        msg = ' '.join([
            _("If auto-connect is enabled, ElectrumSV will always use a server that "
              "is on the longest blockchain."),
            _("If it is disabled, you have to choose a server you want to use. "
              "ElectrumSV will warn you if your server is lagging.")
        ])
        grid.addWidget(self.autoconnect_cb, 0, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_host, 1, 1, 1, 2)
        grid.addWidget(self.server_port, 1, 3)

        label = _('Server peers') if network.is_connected() else _(
            'Default Servers')
        grid.addWidget(QLabel(label), 2, 0, 1, 5)
        self.servers_list = ServerListWidget(self)
        grid.addWidget(self.servers_list, 3, 0, 1, 5)

        # Proxy tab
        grid = QGridLayout(proxy_tab)
        grid.setSpacing(8)

        # proxy setting
        self.proxy_cb = QCheckBox(_('Use proxy'))
        self.proxy_cb.clicked.connect(self.check_disable_proxy)
        self.proxy_cb.clicked.connect(self.set_proxy)

        self.proxy_mode = QComboBox()
        self.proxy_mode.addItems(['SOCKS4', 'SOCKS5', 'HTTP'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(200)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(100)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_user.setFixedWidth(self.proxy_host.width())
        self.proxy_password = PasswordLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))

        self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
        self.proxy_host.editingFinished.connect(self.set_proxy)
        self.proxy_port.editingFinished.connect(self.set_proxy)
        self.proxy_user.editingFinished.connect(self.set_proxy)
        self.proxy_password.editingFinished.connect(self.set_proxy)

        self.proxy_mode.currentIndexChanged.connect(
            self.proxy_settings_changed)
        self.proxy_host.textEdited.connect(self.proxy_settings_changed)
        self.proxy_port.textEdited.connect(self.proxy_settings_changed)
        self.proxy_user.textEdited.connect(self.proxy_settings_changed)
        self.proxy_password.textEdited.connect(self.proxy_settings_changed)

        self.tor_cb = QCheckBox(_("Use Tor Proxy"))
        self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_cb.hide()
        self.tor_cb.clicked.connect(self.use_tor_proxy)

        grid.addWidget(self.tor_cb, 1, 0, 1, 3)
        grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
        grid.addWidget(
            HelpButton(
                _('Proxy settings apply to all connections: both '
                  'ElectrumSV servers and third-party services.')), 2, 4)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)
        grid.addWidget(self.proxy_user, 5, 2, Qt.AlignTop)
        grid.addWidget(self.proxy_password, 5, 3, Qt.AlignTop)
        grid.setRowStretch(7, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg = ' '.join([
            _("ElectrumSV connects to several nodes in order to download block headers "
              "and find out the longest blockchain."),
            _("This blockchain is used to verify the transactions sent by your "
              "transaction server.")
        ])
        self.status_label = QLabel('')
        grid.addWidget(QLabel(_('Status') + ':'), 0, 0)
        grid.addWidget(self.status_label, 0, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        self.server_label = QLabel('')
        msg = _(
            "ElectrumSV sends your wallet addresses to a single server, in order to "
            "receive your transaction history.")
        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_label, 1, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.height_label = QLabel('')
        msg = _('This is the height of your local copy of the blockchain.')
        grid.addWidget(QLabel(_('Blockchain') + ':'), 2, 0)
        grid.addWidget(self.height_label, 2, 1)
        grid.addWidget(HelpButton(msg), 2, 4)

        self.split_label = QLabel('')
        grid.addWidget(self.split_label, 3, 0, 1, 3)

        self.nodes_list_widget = NodesListWidget(self)
        grid.addWidget(self.nodes_list_widget, 5, 0, 1, 5)

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.layout_ = vbox
        # tor detector
        self.td = td = TorDetector()
        td.found_proxy.connect(self.suggest_proxy)
        td.start()

        self.fill_in_proxy_settings()
        self.update()

    def check_disable_proxy(self, b):
        if not self.config.is_modifiable('proxy'):
            b = False
        for w in [
                self.proxy_mode, self.proxy_host, self.proxy_port,
                self.proxy_user, self.proxy_password
        ]:
            w.setEnabled(b)

    def enable_set_server(self):
        if self.config.is_modifiable('server'):
            enabled = not self.autoconnect_cb.isChecked()
            self.server_host.setEnabled(enabled)
            self.server_port.setEnabled(enabled)
            self.servers_list.setEnabled(enabled)
        else:
            for w in [
                    self.autoconnect_cb, self.server_host, self.server_port,
                    self.servers_list
            ]:
                w.setEnabled(False)

    def update(self):
        host, port, protocol, proxy_config, auto_connect = self.network.get_parameters(
        )
        self.server_host.setText(host)
        self.server_port.setText(port)
        self.autoconnect_cb.setChecked(auto_connect)

        host = self.network.interface.host if self.network.interface else _(
            'None')
        self.server_label.setText(host)

        self.set_protocol(protocol)
        self.servers = self.network.get_servers()
        self.servers_list.update(self.servers, self.protocol,
                                 self.tor_cb.isChecked())
        self.enable_set_server()

        height_str = "%d " % (self.network.get_local_height()) + _('blocks')
        self.height_label.setText(height_str)
        n = len(self.network.get_interfaces())
        status = _("Connected to %d nodes.") % n if n else _("Not connected")
        self.status_label.setText(status)
        if self.network.blockchain_count() > 1:
            chain = self.network.blockchain()
            heights = set()
            for blockchain in self.network.interfaces_by_blockchain():
                if blockchain != chain:
                    heights.add(chain.common_height(blockchain) + 1)
            msg = _('Chain split detected at height(s) {}\n').format(','.join(
                f'{height:,d}' for height in sorted(heights)))
        else:
            msg = ''
        self.split_label.setText(msg)
        self.nodes_list_widget.update(self.network)

    def fill_in_proxy_settings(self):
        host, port, protocol, proxy_config, auto_connect = self.network.get_parameters(
        )
        if not proxy_config:
            proxy_config = {
                "mode": "none",
                "host": "localhost",
                "port": "9050"
            }

        b = proxy_config.get('mode') != "none"
        self.check_disable_proxy(b)
        if b:
            self.proxy_cb.setChecked(True)
            self.proxy_mode.setCurrentIndex(
                self.proxy_mode.findText(str(
                    proxy_config.get("mode").upper())))

        self.proxy_host.setText(proxy_config.get("host"))
        self.proxy_port.setText(proxy_config.get("port"))
        self.proxy_user.setText(proxy_config.get("user", ""))
        self.proxy_password.setText(proxy_config.get("password", ""))

    def layout(self):
        return self.layout_

    def set_protocol(self, protocol):
        if protocol != self.protocol:
            self.protocol = protocol

    def change_protocol(self, use_ssl):
        p = 's' if use_ssl else 't'
        host = self.server_host.text()
        pp = self.servers.get(host, Net.DEFAULT_PORTS)
        if p not in pp.keys():
            p = list(pp.keys())[0]
        port = pp[p]
        self.server_host.setText(host)
        self.server_port.setText(port)
        self.set_protocol(p)
        self.set_server()

    def follow_server(self, server):
        self.network.switch_to_interface(server)
        host, port, protocol, proxy, auto_connect = self.network.get_parameters(
        )
        host, port, protocol = deserialize_server(server)
        self.network.set_parameters(host, port, protocol, proxy, auto_connect)
        self.update()

    def server_changed(self, x):
        if x:
            self.change_server(str(x.text(0)), self.protocol)

    def change_server(self, host, protocol):
        pp = self.servers.get(host, Net.DEFAULT_PORTS)
        if protocol and protocol not in protocol_letters:
            protocol = None
        if protocol:
            port = pp.get(protocol)
            if port is None:
                protocol = None
        if not protocol:
            if 's' in pp.keys():
                protocol = 's'
                port = pp.get(protocol)
            else:
                protocol = list(pp.keys())[0]
                port = pp.get(protocol)
        self.server_host.setText(host)
        self.server_port.setText(port)

    def accept(self):
        pass

    def set_server(self):
        host, port, protocol, proxy, auto_connect = self.network.get_parameters(
        )
        host = str(self.server_host.text())
        port = str(self.server_port.text())
        auto_connect = self.autoconnect_cb.isChecked()
        self.network.set_parameters(host, port, protocol, proxy, auto_connect)

    def set_proxy(self):
        host, port, protocol, proxy, auto_connect = self.network.get_parameters(
        )
        if self.proxy_cb.isChecked():
            proxy = {
                'mode': str(self.proxy_mode.currentText()).lower(),
                'host': str(self.proxy_host.text()),
                'port': str(self.proxy_port.text()),
                'user': str(self.proxy_user.text()),
                'password': str(self.proxy_password.text())
            }
        else:
            proxy = None
            self.tor_cb.setChecked(False)
        self.network.set_parameters(host, port, protocol, proxy, auto_connect)

    def suggest_proxy(self, found_proxy):
        self.tor_proxy = found_proxy
        self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
        if (self.proxy_mode.currentIndex()
                == self.proxy_mode.findText('SOCKS5')
                and self.proxy_host.text() == "127.0.0.1"
                and self.proxy_port.text() == str(found_proxy[1])):
            self.tor_cb.setChecked(True)
        self.tor_cb.show()

    def use_tor_proxy(self, use_it):
        if not use_it:
            self.proxy_cb.setChecked(False)
        else:
            socks5_mode_index = self.proxy_mode.findText('SOCKS5')
            if socks5_mode_index == -1:
                logger.error("can't find proxy_mode 'SOCKS5'")
                return
            self.proxy_mode.setCurrentIndex(socks5_mode_index)
            self.proxy_host.setText("127.0.0.1")
            self.proxy_port.setText(str(self.tor_proxy[1]))
            self.proxy_user.setText("")
            self.proxy_password.setText("")
            self.tor_cb.setChecked(True)
            self.proxy_cb.setChecked(True)
        self.check_disable_proxy(use_it)
        self.set_proxy()

    def proxy_settings_changed(self):
        self.tor_cb.setChecked(False)
コード例 #37
0
    def __init__(self, network, config, wizard=False):
        self.network = network
        self.config = config
        self.protocol = None
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        server_tab = QWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(server_tab, _('Server'))
        tabs.addTab(proxy_tab, _('Proxy'))

        if wizard:
            tabs.setCurrentIndex(1)

        # server tab
        grid = QGridLayout(server_tab)
        grid.setSpacing(8)

        self.server_host = QLineEdit()
        self.server_host.setFixedWidth(200)
        self.server_port = QLineEdit()
        self.server_port.setFixedWidth(60)
        self.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))

        self.server_host.editingFinished.connect(self.set_server)
        self.server_port.editingFinished.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)

        msg = ' '.join([
            _("If auto-connect is enabled, ElectrumSV will always use a server that "
              "is on the longest blockchain."),
            _("If it is disabled, you have to choose a server you want to use. "
              "ElectrumSV will warn you if your server is lagging.")
        ])
        grid.addWidget(self.autoconnect_cb, 0, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_host, 1, 1, 1, 2)
        grid.addWidget(self.server_port, 1, 3)

        label = _('Server peers') if network.is_connected() else _(
            'Default Servers')
        grid.addWidget(QLabel(label), 2, 0, 1, 5)
        self.servers_list = ServerListWidget(self)
        grid.addWidget(self.servers_list, 3, 0, 1, 5)

        # Proxy tab
        grid = QGridLayout(proxy_tab)
        grid.setSpacing(8)

        # proxy setting
        self.proxy_cb = QCheckBox(_('Use proxy'))
        self.proxy_cb.clicked.connect(self.check_disable_proxy)
        self.proxy_cb.clicked.connect(self.set_proxy)

        self.proxy_mode = QComboBox()
        self.proxy_mode.addItems(['SOCKS4', 'SOCKS5', 'HTTP'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(200)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(100)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_user.setFixedWidth(self.proxy_host.width())
        self.proxy_password = PasswordLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))

        self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
        self.proxy_host.editingFinished.connect(self.set_proxy)
        self.proxy_port.editingFinished.connect(self.set_proxy)
        self.proxy_user.editingFinished.connect(self.set_proxy)
        self.proxy_password.editingFinished.connect(self.set_proxy)

        self.proxy_mode.currentIndexChanged.connect(
            self.proxy_settings_changed)
        self.proxy_host.textEdited.connect(self.proxy_settings_changed)
        self.proxy_port.textEdited.connect(self.proxy_settings_changed)
        self.proxy_user.textEdited.connect(self.proxy_settings_changed)
        self.proxy_password.textEdited.connect(self.proxy_settings_changed)

        self.tor_cb = QCheckBox(_("Use Tor Proxy"))
        self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_cb.hide()
        self.tor_cb.clicked.connect(self.use_tor_proxy)

        grid.addWidget(self.tor_cb, 1, 0, 1, 3)
        grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
        grid.addWidget(
            HelpButton(
                _('Proxy settings apply to all connections: both '
                  'ElectrumSV servers and third-party services.')), 2, 4)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)
        grid.addWidget(self.proxy_user, 5, 2, Qt.AlignTop)
        grid.addWidget(self.proxy_password, 5, 3, Qt.AlignTop)
        grid.setRowStretch(7, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg = ' '.join([
            _("ElectrumSV connects to several nodes in order to download block headers "
              "and find out the longest blockchain."),
            _("This blockchain is used to verify the transactions sent by your "
              "transaction server.")
        ])
        self.status_label = QLabel('')
        grid.addWidget(QLabel(_('Status') + ':'), 0, 0)
        grid.addWidget(self.status_label, 0, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        self.server_label = QLabel('')
        msg = _(
            "ElectrumSV sends your wallet addresses to a single server, in order to "
            "receive your transaction history.")
        grid.addWidget(QLabel(_('Server') + ':'), 1, 0)
        grid.addWidget(self.server_label, 1, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.height_label = QLabel('')
        msg = _('This is the height of your local copy of the blockchain.')
        grid.addWidget(QLabel(_('Blockchain') + ':'), 2, 0)
        grid.addWidget(self.height_label, 2, 1)
        grid.addWidget(HelpButton(msg), 2, 4)

        self.split_label = QLabel('')
        grid.addWidget(self.split_label, 3, 0, 1, 3)

        self.nodes_list_widget = NodesListWidget(self)
        grid.addWidget(self.nodes_list_widget, 5, 0, 1, 5)

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.layout_ = vbox
        # tor detector
        self.td = td = TorDetector()
        td.found_proxy.connect(self.suggest_proxy)
        td.start()

        self.fill_in_proxy_settings()
        self.update()
コード例 #38
0
class GeoduckDialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(604, 522)
        font = QtGui.QFont()
        font.setPointSize(12)
        Dialog.setFont(font)
        self.AllSurveys = QCheckBox(Dialog)
        self.AllSurveys.setGeometry(QtCore.QRect(20, 210, 141, 41))
        self.AllSurveys.setStyleSheet(
            _fromUtf8("font: 12pt \"MS Shell Dlg 2\";"))
        self.AllSurveys.setObjectName(_fromUtf8("AllSurveys"))
        self.label = QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(30, 10, 241, 31))
        self.label.setObjectName(_fromUtf8("label"))
        self.NumberBootstrapLabel = QLabel(Dialog)
        self.NumberBootstrapLabel.setGeometry(QtCore.QRect(430, 120, 131, 41))
        self.NumberBootstrapLabel.setWordWrap(True)
        self.NumberBootstrapLabel.setObjectName(
            _fromUtf8("NumberBootstrapLabel"))
        self.NumberBootstrap = QPlainTextEdit(Dialog)
        self.NumberBootstrap.setGeometry(QtCore.QRect(320, 120, 101, 31))
        self.NumberBootstrap.setObjectName(_fromUtf8("NumberBootstrap"))
        self.RandomSeed = QPlainTextEdit(Dialog)
        self.RandomSeed.setGeometry(QtCore.QRect(320, 170, 101, 31))
        self.RandomSeed.setObjectName(_fromUtf8("RandomSeed"))
        self.RandomSeedLabel = QLabel(Dialog)
        self.RandomSeedLabel.setGeometry(QtCore.QRect(430, 170, 131, 31))
        self.RandomSeedLabel.setObjectName(_fromUtf8("RandomSeedLabel"))
        self.AvailSurveys = QListWidget(Dialog)
        self.AvailSurveys.setGeometry(QtCore.QRect(21, 40, 251, 161))
        self.AvailSurveys.setObjectName(_fromUtf8("AvailSurveys"))
        self.DoCalcs = QPushButton(Dialog)
        self.DoCalcs.setGeometry(QtCore.QRect(190, 380, 91, 41))
        self.DoCalcs.setObjectName(_fromUtf8("DoCalcs"))
        font = QtGui.QFont()
        font.setPointSize(8)
        self.DoCalcs.setFont(font)
        self.QuitBttn = QPushButton(Dialog)
        self.QuitBttn.setGeometry(QtCore.QRect(320, 380, 91, 41))
        self.QuitBttn.setObjectName(_fromUtf8("QuitBttn"))
        self.MinDepthLabel = QLabel(Dialog)
        self.MinDepthLabel.setGeometry(QtCore.QRect(300, 280, 131, 31))
        self.MinDepthLabel.setWordWrap(True)
        self.MinDepthLabel.setObjectName(_fromUtf8("MinDepthLabel"))
        self.MinDepth = QPlainTextEdit(Dialog)
        self.MinDepth.setGeometry(QtCore.QRect(190, 280, 101, 31))
        self.MinDepth.setObjectName(_fromUtf8("MinDepth"))
        self.MaxDepth = QPlainTextEdit(Dialog)
        self.MaxDepth.setGeometry(QtCore.QRect(190, 330, 101, 31))
        self.MaxDepth.setObjectName(_fromUtf8("MaxDepth"))
        self.MaxDepthLabel = QLabel(Dialog)
        self.MaxDepthLabel.setGeometry(QtCore.QRect(300, 330, 131, 31))
        self.MaxDepthLabel.setWordWrap(True)
        self.MaxDepthLabel.setObjectName(_fromUtf8("MaxDepthLabel"))
        self.label_3 = QLabel(Dialog)
        self.label_3.setGeometry(QtCore.QRect(330, 0, 241, 31))
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.RunComments = QPlainTextEdit(Dialog)
        self.RunComments.setGeometry(QtCore.QRect(320, 40, 251, 51))
        self.RunComments.setObjectName(_fromUtf8("RunComments"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(
            _translate("Dialog", "Geoduck Analysis Program", None))
        self.AllSurveys.setText(_translate("Dialog", "Do All Projects?", None))
        self.label.setText(
            _translate(
                "Dialog",
                "<html><head/><body><p align=\"center\">Available Projects</p></body></html>",
                None))
        self.NumberBootstrapLabel.setText(
            _translate(
                "Dialog",
                "<html><head/><body><p><span style=\" font-size:8pt;\">Number of Bootstrap Repetitions</span></p></body></html>",
                None))
        self.RandomSeedLabel.setText(
            _translate(
                "Dialog",
                "<html><head/><body><p><span style=\" font-size:8pt;\">Random Seed</span></p></body></html>",
                None))
        self.DoCalcs.setText(_translate("Dialog", "Do\nCalculations", None))
        self.QuitBttn.setText(_translate("Dialog", "Quit", None))
        self.MinDepthLabel.setText(
            _translate(
                "Dialog",
                "<html><head/><body><p><span style=\" font-size:8pt;\">Minimum Depth (m)</span></p></body></html>",
                None))
        self.MaxDepthLabel.setText(
            _translate(
                "Dialog",
                "<html><head/><body><p><span style=\" font-size:8pt;\">Maximum Depth (m)</span></p></body></html>",
                None))
        self.label_3.setText(
            _translate(
                "Dialog",
                "<html><head/><body><p align=\"center\">Run Comments</p></body></html>",
                None))
コード例 #39
0
ファイル: gui.py プロジェクト: Flperez/ComparePose3d
    def initUI(self,map):
        ### initialize
        self.filename = map

        # Estimated
        self.pose3dEstimated = []
        self.pose3dReal = []
        self.error = []

        self.loadpathXYZ()


        ### Text out
        self.textbox = QLineEdit(self)
        self.textbox.move(20,480+10)
        self.textbox.resize(640,80)



        ### To select a different graph
        self.showNow = "showXYZ"
        
        ## XYZ
        self.cbxyz = QCheckBox('Show XYZ', self)
        self.cbxyz.move(640+40, 100)
        self.cbxyz.toggle()
        self.cbxyz.setChecked(True)
        self.cbxyz.stateChanged.connect(self.showXYZ)

        ## RPY
        self.cbRPY = QCheckBox('Show RPY', self)
        self.cbRPY.move(640+40, 200)
        self.cbRPY.toggle()
        self.cbRPY.setChecked(False)
        self.cbRPY.stateChanged.connect(self.showRPY)

        ## Error
        self.cbError = QCheckBox('Show Error', self)
        self.cbError.move(640+40, 300)
        self.cbError.toggle()
        self.cbError.setChecked(False)
        self.cbError.stateChanged.connect(self.showError)



        ### Saving results
        ButtonSave = QPushButton('Save results', self)
        ButtonSave.setCheckable(True)
        ButtonSave.move(640+50, 480+30)
        ButtonSave.clicked[bool].connect(self.savingResult)

        # Plot map
        self.main_widget = QWidget(self)
        l = QVBoxLayout(self.main_widget)
        self.dc = MyDynamicMplCanvas(parent=self.main_widget,option=self.showNow,
                                        map=self.map, xsim=self.xestimated, ysim=self.yestimated,
                                        xreal=self.xreal, yreal=self.yreal,interface=self.interface)
        l.addWidget(self.dc)




        self.setGeometry(600, 600, 250, 150)
        self.setWindowTitle('Compare')
        self.setFixedSize(10+640+20+150,600)
コード例 #40
0
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(604, 522)
        font = QtGui.QFont()
        font.setPointSize(12)
        Dialog.setFont(font)
        self.AllSurveys = QCheckBox(Dialog)
        self.AllSurveys.setGeometry(QtCore.QRect(20, 210, 141, 41))
        self.AllSurveys.setStyleSheet(
            _fromUtf8("font: 12pt \"MS Shell Dlg 2\";"))
        self.AllSurveys.setObjectName(_fromUtf8("AllSurveys"))
        self.label = QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(30, 10, 241, 31))
        self.label.setObjectName(_fromUtf8("label"))
        self.NumberBootstrapLabel = QLabel(Dialog)
        self.NumberBootstrapLabel.setGeometry(QtCore.QRect(430, 120, 131, 41))
        self.NumberBootstrapLabel.setWordWrap(True)
        self.NumberBootstrapLabel.setObjectName(
            _fromUtf8("NumberBootstrapLabel"))
        self.NumberBootstrap = QPlainTextEdit(Dialog)
        self.NumberBootstrap.setGeometry(QtCore.QRect(320, 120, 101, 31))
        self.NumberBootstrap.setObjectName(_fromUtf8("NumberBootstrap"))
        self.RandomSeed = QPlainTextEdit(Dialog)
        self.RandomSeed.setGeometry(QtCore.QRect(320, 170, 101, 31))
        self.RandomSeed.setObjectName(_fromUtf8("RandomSeed"))
        self.RandomSeedLabel = QLabel(Dialog)
        self.RandomSeedLabel.setGeometry(QtCore.QRect(430, 170, 131, 31))
        self.RandomSeedLabel.setObjectName(_fromUtf8("RandomSeedLabel"))
        self.AvailSurveys = QListWidget(Dialog)
        self.AvailSurveys.setGeometry(QtCore.QRect(21, 40, 251, 161))
        self.AvailSurveys.setObjectName(_fromUtf8("AvailSurveys"))
        self.DoCalcs = QPushButton(Dialog)
        self.DoCalcs.setGeometry(QtCore.QRect(190, 380, 91, 41))
        self.DoCalcs.setObjectName(_fromUtf8("DoCalcs"))
        font = QtGui.QFont()
        font.setPointSize(8)
        self.DoCalcs.setFont(font)
        self.QuitBttn = QPushButton(Dialog)
        self.QuitBttn.setGeometry(QtCore.QRect(320, 380, 91, 41))
        self.QuitBttn.setObjectName(_fromUtf8("QuitBttn"))
        self.MinDepthLabel = QLabel(Dialog)
        self.MinDepthLabel.setGeometry(QtCore.QRect(300, 280, 131, 31))
        self.MinDepthLabel.setWordWrap(True)
        self.MinDepthLabel.setObjectName(_fromUtf8("MinDepthLabel"))
        self.MinDepth = QPlainTextEdit(Dialog)
        self.MinDepth.setGeometry(QtCore.QRect(190, 280, 101, 31))
        self.MinDepth.setObjectName(_fromUtf8("MinDepth"))
        self.MaxDepth = QPlainTextEdit(Dialog)
        self.MaxDepth.setGeometry(QtCore.QRect(190, 330, 101, 31))
        self.MaxDepth.setObjectName(_fromUtf8("MaxDepth"))
        self.MaxDepthLabel = QLabel(Dialog)
        self.MaxDepthLabel.setGeometry(QtCore.QRect(300, 330, 131, 31))
        self.MaxDepthLabel.setWordWrap(True)
        self.MaxDepthLabel.setObjectName(_fromUtf8("MaxDepthLabel"))
        self.label_3 = QLabel(Dialog)
        self.label_3.setGeometry(QtCore.QRect(330, 0, 241, 31))
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.RunComments = QPlainTextEdit(Dialog)
        self.RunComments.setGeometry(QtCore.QRect(320, 40, 251, 51))
        self.RunComments.setObjectName(_fromUtf8("RunComments"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
コード例 #41
0
ファイル: config_ui.py プロジェクト: shengtu0328/djc_helper
def create_checkbox(val=False, name="") -> QCheckBox:
    checkbox = QCheckBox(name)

    checkbox.setChecked(val)

    return checkbox
コード例 #42
0
class MainWindow(QMainWindow):
    """
        Объявление чекбокса и иконки системного трея.
        Инициализироваться будут в конструкторе.
    """
    check_box = None
    tray_icon = None

    # Переопределяем конструктор класса
    def __init__(self):
        # Обязательно нужно вызвать метод супер класса
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(480, 80))  # Устанавливаем размеры
        self.setWindowTitle(
            "System Tray Application")  # Устанавливаем заголовок окна
        central_widget = QWidget(self)  # Создаём центральный виджет
        self.setCentralWidget(
            central_widget)  # Устанавливаем центральный виджет

        grid_layout = QGridLayout(self)  # Создаём QGridLayout
        central_widget.setLayout(
            grid_layout
        )  # Устанавливаем данное размещение в центральный виджет
        grid_layout.addWidget(
            QLabel("Application, which can minimize to Tray", self), 0, 0)

        # Добавляем чекбокс, от которого будет зависеть поведение программы при закрытии окна
        self.check_box = QCheckBox('Minimize to Tray')
        grid_layout.addWidget(self.check_box, 1, 0)
        grid_layout.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding), 2,
            0)

        # Инициализируем QSystemTrayIcon
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.style().standardIcon(
            QStyle.SP_ComputerIcon))
        '''
            Объявим и добавим действия для работы с иконкой системного трея
            show - показать окно
            hide - скрыть окно
            exit - выход из программы
        '''
        show_action = QAction("Показать", self)
        quit_action = QAction("Выход", self)
        hide_action = QAction("Скрыть", self)
        show_action.triggered.connect(self.show)
        hide_action.triggered.connect(self.hide)
        quit_action.triggered.connect(qApp.quit)
        tray_menu = QMenu()
        tray_menu.addAction(show_action)
        tray_menu.addAction(hide_action)
        tray_menu.addAction(quit_action)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()

    # Переопределение метода closeEvent, для перехвата события закрытия окна
    # Окно будет закрываться только в том случае, если нет галочки в чекбоксе
    def closeEvent(self, event):
        if self.check_box.isChecked():
            event.ignore()
            self.hide()
            self.tray_icon.showMessage("Tray Program",
                                       "Application was minimized to Tray",
                                       QSystemTrayIcon.Information, 2000)
コード例 #43
0
    def create_ui(self):
        # 1.文字标签
        # QLabel(显示的文字, 父标签/放到哪个窗口上)
        label1 = QLabel('用户名:', self)
        # 一般不常用的移动坐标
        label1.move(50, 10)

        # 2.按钮
        btn1 = QPushButton('登录', self)
        btn1.move(50, 50)
        # css语法:选择器{属性1:属性值1; 属性2:属性值2;..}
        # color - 字体颜色,对应的值:颜色单词, rbg(255, 0, 0)
        #
        btn1.setStyleSheet('QPushButton{}')
        btn2 = QRadioButton('男', self)
        btn2.move(50, 100)
        btn3 = QCheckBox('篮球', self)
        btn3.move(50, 150)
        btn4 = QCommandLinkButton('hello', 'hellowword', self)
        btn4.move(50, 200)

        b1 = QDialogButtonBox.StandardButton.Ok
        b2 = QDialogButtonBox.StandardButton.Cancel
        btn5 = QDialogButtonBox(b2, self)
        btn5.move(50, 300)

        # 3.输入框
        input1 = QLineEdit(self)
        input1.move(150, 10)
        input2 = QLineEdit('admin', self)
        input2.move(150, 50)
        input1.setText('张三')
        # 富文本
        input3 = QTextEdit('张三', self)
        input3.move(50, 300)
        # 设置成只读
        input3.setReadOnly(True)
        # 只能显示纯文本
        input4 = QPlainTextEdit(self)
        input4.move(300, 10)
        # 输入数值
        input5 = QSpinBox(self)
        input5.move(100, 100)
        input5.setMinimum(10)
        input5.setMaximum(20)
        input5.setValue(15)
        print(input5.value())  # 获取当前值
        # 输入小数
        input6 = QDoubleSpinBox(self)
        input6.move(100, 150)
        # 下拉菜单
        input7 = QComboBox(self)
        input7.addItems(['item1', 'item2'])
        input7.move(150, 200)
        print(input7.currentText())  # 获取当前选中的选项,适用input8
        input8 = QFontComboBox(self)
        input8.move(350, 300)
        input8.setCurrentIndex(2)
        print(input8.currentText())
        label1.setFont(input8.currentFont())
        # 日期选择
        input9 = QDateEdit(date.today(), self)
        input9.move(300, 400)
        # 选择颜色
        input10 = QColorDialog(self)
        input10.move(400, 400)
        # input10.show()

        input11 = QDial(self)
        input11.move(300, 200)

        input12 = QSlider(self)
        input12.move(430, 350)
        input12.setMaximum(100)
        input12.setMinimum(-100)
        input12.setValue(20)
        input12.setOrientation(Qt.Horizontal)  # 设置为水平方向
コード例 #44
0
ファイル: settings.py プロジェクト: bastonc/linlog_v1.262
    def initUI(self):

        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('LinLog | Settings')

        self.setWindowIcon(QIcon('logo.png'))
        style = "QWidget{background-color:" + self.settingsDict[
            'background-color'] + "; color:" + self.settingsDict['color'] + ";}"
        self.setStyleSheet(style)
        # declaration tab
        self.tab = QtWidgets.QTabWidget()
        self.general_tab = QWidget()
        self.cluster_tab = QWidget()
        self.tci_tab = QWidget()
        self.io_tab = QWidget()
        self.service_widget = QWidget()
        #
        self.tab.addTab(self.general_tab, "General")
        self.tab.addTab(self.cluster_tab, "Cluster")
        self.tab.addTab(self.tci_tab, "TCI")
        self.tab.addTab(self.io_tab, "Log file")
        self.tab.addTab(self.service_widget, "Services")
        # create General Tab
        formstyle = "background: "+self.settingsDict['form-background']+"; color: "+\
                    self.settingsDict['color-table']+"; "
        self.general_tab.layout = QVBoxLayout(self)  # create vertical lay
        self.call_label = QLabel("You Callsign")
        self.call_input = QLineEdit()
        self.call_input.setFixedWidth(100)
        self.call_input.setStyleSheet(formstyle)
        # Chekbox SWL
        self.swl_chekbox = QCheckBox("Enable SWL mode")
        self.swl_chekbox.setStyleSheet("QCheckBox{ color:" +
                                       self.settingsDict['color'] +
                                       "; font-size: 12px;}")
        self.dlg = QColorDialog(self)
        self.back_color_label = QLabel("Window color")
        self.back_color_label.setStyleSheet(self.label_style)
        self.back_color_input = QPushButton()
        self.back_color_input.clicked.connect(self.back_color_select)
        self.back_color_input.setFixedWidth(70)
        self.back_color_input.setStyleSheet(
            "background:" + self.settingsDict['background-color'] +
            "; color:" + self.settingsDict['background-color'] + ";")
        self.back_color_input.setText(self.settingsDict['background-color'])
        #self.back_color_input.setStyleSheet(formstyle)
        self.text_color_label = QLabel("Text color")
        self.text_color_label.setStyleSheet(self.label_style)
        self.text_color_input = QPushButton()
        self.text_color_input.clicked.connect(self.text_color_select)
        self.text_color_input.setFixedWidth(70)
        self.text_color_input.setStyleSheet("background:" +
                                            self.settingsDict['color'] +
                                            "; color:" +
                                            self.settingsDict['color'] + ";")
        self.text_color_input.setText(self.settingsDict['color'])

        #self.text_color_input.setStyleSheet(formstyle)
        self.form_color_label = QLabel("Form background color")
        self.form_color_label.setStyleSheet(self.label_style)
        self.form_color_input = QPushButton()
        self.form_color_input.clicked.connect(self.form_color_select)
        self.form_color_input.setFixedWidth(70)
        self.form_color_input.setStyleSheet(
            "background: " + self.settingsDict['form-background'] +
            "; color:" + self.settingsDict['form-background'] + ";")
        self.form_color_input.setText(self.settingsDict['form-background'])
        #
        self.text_form_color_label = QLabel("Form text color")
        self.text_form_color_label.setStyleSheet(self.label_style)
        self.text_form_color_button = QPushButton()
        self.text_form_color_button.clicked.connect(
            self.form_text_color_select)
        self.text_form_color_button.setFixedWidth(70)
        self.text_form_color_button.setStyleSheet(
            "background: " + self.settingsDict['color-table'] + "; color: " +
            self.settingsDict['color-table'] + ";")
        self.text_form_color_button.setText(self.settingsDict['color-table'])

        # setup all elements to vertical lay
        self.general_tab.layout.addWidget(self.call_label)
        self.general_tab.layout.addWidget(self.call_input)
        self.general_tab.layout.addSpacing(20)
        self.general_tab.layout.addWidget(self.swl_chekbox)
        self.general_tab.layout.addWidget(self.back_color_label)
        self.general_tab.layout.addWidget(self.back_color_input)
        self.general_tab.layout.addSpacing(20)
        self.general_tab.layout.addWidget(self.text_color_label)
        self.general_tab.layout.addWidget(self.text_color_input)
        self.general_tab.layout.addSpacing(20)
        self.general_tab.layout.addWidget(self.form_color_label)
        self.general_tab.layout.addWidget(self.form_color_input)
        self.general_tab.layout.addWidget(self.text_form_color_label)
        self.general_tab.layout.addWidget(self.text_form_color_button)

        self.general_tab.setLayout(self.general_tab.layout)

        # create Cluster tab

        self.cluster_tab.layout = QVBoxLayout(self)
        self.cluster_host = QLabel("Cluster host:")
        self.cluster_host_input = QLineEdit()
        self.cluster_host_input.setFixedWidth(150)
        self.cluster_host_input.setStyleSheet(formstyle)
        self.cluster_port = QLabel("Cluster port:")
        self.cluster_port_input = QLineEdit()
        self.cluster_port_input.setFixedWidth(50)
        self.cluster_port_input.setStyleSheet(formstyle)
        self.host_port_lay = QHBoxLayout()
        # create host:port lay
        self.host_lay = QVBoxLayout()
        self.host_lay.addWidget(self.cluster_host)
        self.host_lay.addWidget(self.cluster_host_input)

        self.port_lay = QVBoxLayout()
        self.port_lay.addWidget(self.cluster_port)
        self.port_lay.addWidget(self.cluster_port_input)

        self.host_port_lay.addLayout(self.host_lay)
        self.host_port_lay.addLayout(self.port_lay)

        # Create calibrate cluster
        self.calibrate_lay = QHBoxLayout()
        ## Create text label
        self.text_and_button_Vlay = QVBoxLayout()
        text = "Press \"Start claibrate\" and select Callsign and Freq \n" \
               "from the received line from the telnet cluster"
        self.message_label = QLabel(text)
        self.message_label.setStyleSheet("font: 12px;")
        self.text_and_button_Vlay.addWidget(self.message_label)

        self.button_and_combo = QHBoxLayout()
        ## Create group from button and combobox
        self.cluster_start_calibrate_button = QPushButton(
            "Start \n callibrate")
        self.cluster_start_calibrate_button.setFixedWidth(100)
        self.cluster_start_calibrate_button.setFixedHeight(60)
        self.button_and_combo.addWidget(self.cluster_start_calibrate_button)
        self.combo_lay = QVBoxLayout()
        self.call_H = QHBoxLayout()
        self.call_H.setAlignment(Qt.AlignRight)
        self.cluster_call_label = QLabel("Call:")

        self.cluster_combo_call = QComboBox()

        self.freq_H = QHBoxLayout()
        self.freq_H.setAlignment(Qt.AlignRight)
        self.cluster_freq_label = QLabel("Freq:")
        self.cluster_combo_freq = QComboBox()
        self.call_H.addWidget(self.cluster_call_label)
        self.call_H.addWidget(self.cluster_combo_call)
        self.freq_H.addWidget(self.cluster_freq_label)
        self.freq_H.addWidget(self.cluster_combo_freq)
        self.combo_lay.addLayout(self.call_H)
        self.combo_lay.addLayout(self.freq_H)
        self.button_and_combo.addLayout(self.combo_lay)
        self.text_and_button_Vlay.addLayout(self.button_and_combo)

        self.calibrate_lay.addLayout(self.text_and_button_Vlay)

        ## Create filter band
        self.cluster_filter_band_combo = QCheckBox("Filter BAND")
        self.cluster_filter_band_combo.setStyleSheet(
            "QCheckBox{ color:" + self.settingsDict['color'] +
            "; font-size: 12px;}")
        self.cluster_filter_band_input = QLineEdit()
        self.cluster_filter_band_input.setFixedWidth(80)
        self.cluster_filter_band_input.setFixedHeight(20)
        self.cluster_filter_band_input.setStyleSheet(
            "background-color:" + self.settingsDict['form-background'] +
            "; font-size: 12px")
        text = "Bands in m."
        self.message_label_band = QLabel(text)
        self.message_label_band.setStyleSheet("font: 12px;")

        self.filter_band_lay = QVBoxLayout()
        self.filter_band_lay.addWidget(self.cluster_filter_band_combo)
        self.filter_band_lay.addWidget(self.message_label_band)
        self.filter_band_lay.addWidget(self.cluster_filter_band_input)

        ## Create filter spot
        self.cluster_filter_spot_combo = QCheckBox("Filter SPOT")
        self.cluster_filter_spot_combo.setStyleSheet(
            "QCheckBox{ color:" + self.settingsDict['color'] +
            "; font-size: 12px;}")
        self.cluster_filter_spot_input = QLineEdit()
        self.cluster_filter_spot_input.setFixedWidth(80)
        self.cluster_filter_spot_input.setFixedHeight(20)
        self.cluster_filter_spot_input.setStyleSheet(
            "background-color:" + self.settingsDict['form-background'] +
            "; font-size: 12px")
        text = "Spot prefixes"
        self.message_label_spot = QLabel(text)
        self.message_label_spot.setStyleSheet("font: 12px;")

        self.filter_spot_lay = QVBoxLayout()
        self.filter_spot_lay.addWidget(self.cluster_filter_spot_combo)
        self.filter_spot_lay.addWidget(self.message_label_spot)
        self.filter_spot_lay.addWidget(self.cluster_filter_spot_input)

        ## create filter spotter
        self.cluster_filter_spotter_combo = QCheckBox("Filter SPOTTER")
        self.cluster_filter_spotter_combo.setStyleSheet(
            "QCheckBox{ color:" + self.settingsDict['color'] +
            "; font-size: 12px;}")
        self.cluster_filter_spotter_input = QLineEdit()
        self.cluster_filter_spotter_input.setFixedWidth(80)
        self.cluster_filter_spotter_input.setFixedHeight(20)
        self.cluster_filter_spotter_input.setStyleSheet(
            "background-color:" + self.settingsDict['form-background'] +
            "; font-size: 12px")
        text = "Spotter prefixes"
        self.message_label_spotter = QLabel(text)
        self.message_label_spotter.setStyleSheet("font: 12px;")

        self.filter_spotter_lay = QVBoxLayout()
        self.filter_spotter_lay.addWidget(self.cluster_filter_spotter_combo)
        self.filter_spotter_lay.addWidget(self.message_label_spotter)
        self.filter_spotter_lay.addWidget(self.cluster_filter_spotter_input)

        text = "All value separate by comma"
        self.filter_message_label = QLabel(text)
        self.filter_message_label.setStyleSheet("font: 12px;")

        self.filters_Hlay = QHBoxLayout()
        self.filters_Hlay.addLayout(self.filter_band_lay)
        self.filters_Hlay.addLayout(self.filter_spot_lay)
        self.filters_Hlay.addLayout(self.filter_spotter_lay)

        self.filters_lay = QVBoxLayout()
        self.filters_lay.addSpacing(10)
        self.filters_lay.setAlignment(Qt.AlignCenter)
        self.filters_lay.addLayout(self.filters_Hlay)
        self.filters_lay.addWidget(self.filter_message_label)
        self.filters_lay.addSpacing(10)
        Separador = QFrame()
        Separador.setFrameShape(QFrame.HLine)
        Separador.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        Separador.setLineWidth(1)
        self.filters_lay.addWidget(Separador)

        ## Create List view for input string from cluster

        self.line_text = QLabel()

        self.line_text.setFixedHeight(50)
        # Set all layers to window
        self.cluster_tab.layout.addLayout(self.host_port_lay)
        self.cluster_tab.layout.addSpacing(10)
        self.cluster_tab.layout.addLayout(self.filters_lay)
        self.cluster_tab.layout.addLayout(self.calibrate_lay)
        self.cluster_tab.layout.addWidget(self.line_text)

        ## install lay to main tab (Cluster)
        self.cluster_tab.setLayout(self.cluster_tab.layout)

        # create TCI Tab

        self.tci_enable_combo_lay = QHBoxLayout()
        self.tci_enable_combo_lay.setAlignment(Qt.AlignCenter)
        self.tci_enable_combo = QCheckBox("TCI Enable")
        self.tci_enable_combo.setStyleSheet("QCheckBox{" +
                                            self.settingsDict['color'] + "}")
        self.tci_enable_combo_lay.addWidget(self.tci_enable_combo)
        self.tci_tab.layout = QVBoxLayout(self)
        self.tci_host = QLabel("TCI host:")
        self.tci_host_input = QLineEdit()
        self.tci_host_input.setFixedWidth(150)
        self.tci_host_input.setStyleSheet(formstyle)
        self.tci_port = QLabel("TCI port:")
        self.tci_port_input = QLineEdit()
        self.tci_port_input.setFixedWidth(50)
        self.tci_port_input.setStyleSheet(formstyle)
        self.host_port_lay = QHBoxLayout()
        # create host:port lay
        self.host_lay = QVBoxLayout()
        self.host_lay.addWidget(self.tci_host)
        self.host_lay.addWidget(self.tci_host_input)

        self.port_lay = QVBoxLayout()
        self.port_lay.addWidget(self.tci_port)
        self.port_lay.addWidget(self.tci_port_input)

        self.host_port_lay.addLayout(self.host_lay)
        self.host_port_lay.addLayout(self.port_lay)

        self.tci_tab.layout.addLayout(self.tci_enable_combo_lay)
        self.tci_tab.layout.addLayout(self.host_port_lay)
        self.tci_tab.layout.addSpacing(250)
        self.tci_tab.setLayout(self.tci_tab.layout)

        # Create io_tab
        self.io_tab_lay = QVBoxLayout()
        self.io_tab_lay.setAlignment(Qt.AlignCenter)
        self.import_button = QPushButton("Import")
        self.import_button.setFixedSize(100, 30)
        self.import_button.clicked.connect(self.import_adi)
        self.import_button.setStyleSheet("width: 100px;")
        self.export_button = QPushButton("Export")
        self.export_button.clicked.connect(self.export_adi)
        self.export_button.setFixedSize(100, 30)
        self.io_tab_lay.addWidget(self.import_button)
        self.io_tab_lay.addWidget(self.export_button)
        self.io_tab.setLayout(self.io_tab_lay)

        # Create Services tab

        self.service_tab = QVBoxLayout()
        self.service_tab.setAlignment(Qt.AlignCenter)

        # create elements form
        self.eqsl_lay = QVBoxLayout()
        self.eqsl_lay.setAlignment(Qt.AlignCenter)
        self.eqsl_activate = QHBoxLayout()
        self.eqsl_chekBox = QCheckBox("Auto sent eQSL after QSO")
        self.eqsl_chekBox.setStyleSheet(
            "{ color:" + self.settingsDict['color'] +
            "; font-size: 12px; border-color: white }")

        self.eqsl_activate.addWidget(self.eqsl_chekBox)
        #self.eqsl_activate.addWidget(QLabel("eQSL.cc"))
        self.eqsl_lay.addLayout(self.eqsl_activate)
        self.text_eqsl_small = QLabel("Automatic send eQSL after enter QSO")
        self.text_eqsl_small.setStyleSheet("font: 10px; font-style: italic;")
        self.eqsl_lay.addWidget(self.text_eqsl_small)
        self.eqsl_form = QVBoxLayout()
        self.login = QHBoxLayout()

        self.login.addWidget(QLabel("Login:"******"Password:"******"Color for eQSL complited: ")
        self.color_label_eqsl.setStyleSheet(style)
        self.color_button_eqsl = QPushButton()
        self.color_button_eqsl.setStyleSheet(
            "background:" + self.settingsDict['eqsl-sent-color'] + "; color:" +
            self.settingsDict['eqsl-sent-color'])
        self.color_button_eqsl.setText(self.settingsDict['eqsl-sent-color'])
        self.color_button_eqsl.setFixedWidth(120)
        self.color_button_eqsl.setFixedHeight(40)
        self.color_button_eqsl.clicked.connect(self.select_eqsl_color)
        self.color_button_layer = QHBoxLayout()
        self.color_button_layer.setAlignment(Qt.AlignLeft)
        self.color_button_layer.addWidget(self.color_label_eqsl)
        self.color_button_layer.addWidget(self.color_button_eqsl)
        self.eqsl_lay.addLayout(self.color_button_layer)
        self.service_tab.addLayout(self.eqsl_lay)
        self.service_widget.setLayout(self.service_tab)

        # button panel
        self.button_panel = QHBoxLayout()
        button_style = "font: 12px;"
        self.button_save = QPushButton("Save and Exit")
        self.button_save.setStyleSheet(button_style)
        self.button_save.clicked.connect(self.save_and_exit_button)
        self.button_apply = QPushButton("Apply")
        self.button_apply.setStyleSheet(button_style)
        self.button_apply.clicked.connect(self.apply_button)
        self.button_cancel = QPushButton("Cancel")
        self.button_cancel.setStyleSheet(button_style)
        self.button_cancel.clicked.connect(self.cancel_button)
        self.button_cancel.setFixedWidth(60)
        self.button_panel.addWidget(self.button_cancel)
        self.button_panel.addWidget(self.button_apply)
        self.button_panel.addWidget(self.button_save)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.tab)
        self.mainLayout.addLayout(self.button_panel)
        #self.mainLayout.addWidget(self.tab)
        self.setLayout(self.mainLayout)
コード例 #45
0
class management(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.video_size = QSize(460, 460)
        #self._Knowface=self._load_data_fromPickle()
        self.dataSrc = {}
        self.dataSrc_img = {}

        self.dirSrc = ""

        self.setup_ui()

    def _load_data_fromFaceLog(self, fileDIR):

        pickle_in = open(fileDIR, 'rb')
        data = pickle.load(pickle_in)
        return data, fileDIR

    def _load_data_fromPickle(self, fileDIR):
        data = {}
        data_img = {}
        #print("2",self._KnowfaceDIR)
        if "_img" in fileDIR:
            modelFeature = fileDIR.replace("_img", "")
            modelFeature_img = fileDIR

            print("_img", fileDIR, "modelFeature: " + modelFeature)

        else:
            modelFeature_img = fileDIR.replace(".pickle", "_img.pickle")
            modelFeature = fileDIR

            print(" ", modelFeature_img, "modelFeature: " + fileDIR)

        pickle_in_img = open(modelFeature_img, 'rb')
        pickle_in = open(modelFeature, 'rb')

        data_img = pickle.load(pickle_in_img)
        data = pickle.load(pickle_in)
        return data, data_img, modelFeature, modelFeature_img

    def draw_Src(self):
        try:

            if len(self.lbl_img) >= 1:
                i = 0
                while 1:
                    #print(self.formLayout.rowCount())
                    self.formLayout.removeRow(i)
                    del self.lbl_img[i]
                    del self.tbox_name[i]
                    del self.btn_copy[i]
                    del self.btn_delete[i]
                    if len(self.lbl_img) == 0:
                        break

            for key, value in self.dataSrc_img.items():
                i = list(self.dataSrc_img.keys()).index(key)
                frame = cv2.cvtColor(value, cv2.COLOR_BGR2RGB)
                image = qimage2ndarray.array2qimage(frame)

                self.lbl_img.append(QLabel())
                self.lbl_img[i].setPixmap(
                    QPixmap.fromImage(image).scaled(100, 100,
                                                    Qt.KeepAspectRatio,
                                                    Qt.FastTransformation))
                self.lbl_img[i].setFixedSize(QSize(100, 100))

                self.tbox_name.append(QLineEdit())
                self.tbox_name[i].setText(key)

                vlay = QVBoxLayout()
                vlay.addWidget(self.tbox_name[i])
                if not self.checkBox.isChecked():
                    self.btn_copy.append(QPushButton("Copy"))
                    self.btn_copy[i].installEventFilter(self)

                    self.btn_delete.append(QPushButton("Delete"))
                    self.btn_delete[i].installEventFilter(self)

                    vlay.addWidget(self.btn_delete[i])
                    vlay.addWidget(self.btn_copy[i])

                hlayout = QHBoxLayout()
                hlayout.addWidget(self.lbl_img[i])
                hlayout.addLayout(vlay)

                self.formLayout.addRow(hlayout)

        except Exception as e:
            print("Management/draw_match_pair_box: ", e)

    def setup_ui(self):

        lbl_src = QLabel("File 1:")
        lbl_dst = QLabel("File 2:")

        self.tbox_srcFile = QLineEdit()
        self.tbox_srcFile.setEnabled(False)
        self.tbox_dstFile = QLineEdit()
        self.tbox_dstFile.setEnabled(False)

        self.checkBox = QCheckBox("View Only this is for debug and testing")

        self.btn_browseSrc = QPushButton("...")
        self.btn_browseSrc.setFixedSize(
            QSize(monitorWidth * 0.02, monitorHeight * 0.02))
        self.btn_browseSrc.clicked.connect(self._browseSrc)

        self.btn_browseDst = QPushButton("...")
        self.btn_browseDst.setFixedSize(
            QSize(monitorWidth * 0.02, monitorHeight * 0.02))
        self.btn_browseSrc.clicked.connect(self._browseDst)

        self.btn_back = QPushButton("<< Back")
        self.btn_back.clicked.connect(self._back)

        self.btn_quit = QPushButton("Quit")
        self.btn_quit.clicked.connect(self._quit)

        self.btn_save = QPushButton("Save")
        self.btn_save.clicked.connect(self._save)

        ## groupBox
        self.lbl_img = []
        self.tbox_name = []
        self.btn_delete = []
        self.btn_copy = []

        self.groupBoxSrc = QGroupBox()

        # lay output
        self.gridBox = QGridLayout()
        self.formLayout = QFormLayout()
        self.groupBoxSrc.setLayout(self.formLayout)

        scroll = QScrollArea()
        scroll.setWidget(self.groupBoxSrc)
        scroll.setWidgetResizable(True)
        scroll.setFixedHeight(monitorHeight * 0.5)
        scroll.setFixedWidth(monitorWidth * 0.12)

        hlaysrc = QHBoxLayout()
        hlaysrc.addWidget(lbl_src)
        hlaysrc.addWidget(self.tbox_srcFile)
        hlaysrc.addWidget(self.btn_browseSrc)

        vlaysrc = QVBoxLayout()
        vlaysrc.addLayout(hlaysrc)
        vlaysrc.addWidget(self.checkBox)
        vlaysrc.addWidget(scroll)

        hBtnLayout = QHBoxLayout()
        hBtnLayout.addWidget(self.btn_back)
        hBtnLayout.addWidget(self.btn_save)
        hBtnLayout.addWidget(self.btn_quit)

        vMain = QVBoxLayout()
        vMain.addLayout(vlaysrc)
        vMain.addLayout(hBtnLayout)

        self.setLayout(vMain)
        #self.show()

    def browseFileDialog(self):
        options = QFileDialog.Options()
        fileName, a = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getSaveFileName()",
            "",
            "Text Files (*.pickle)",
            options=options)
        print(fileName, a)
        if fileName:
            return fileName

    def eventFilter(self, ob, event):
        try:
            for i in range(0, len(self.btn_copy)):
                if ob is self.btn_copy[i] and event.type() == 2:
                    print("Copy: ", i)
                    self.copy_Item(i)
                    return False
                elif ob is self.btn_delete[i] and event.type() == 2:
                    print("Delete: ", i)
                    self.del_Item(i)
                    return False

            return False
        except Exception as e:
            print("eventFilter: ", e)

    def del_Item(self, idx):
        del self.dataSrc[self.tbox_name[idx].text()]
        del self.dataSrc_img[self.tbox_name[idx].text()]
        self.btn_copy[idx].removeEventFilter(self)
        self.btn_delete[idx].removeEventFilter(self)
        self.formLayout.removeRow(idx)
        del self.lbl_img[idx]
        del self.tbox_name[idx]
        del self.btn_copy[idx]
        del self.btn_delete[idx]

    def copy_Item(self, idx):

        filename = self.browseFileDialog()
        data, data_img, dir, dir_img = self._load_data_fromPickle(filename)
        for k in data:
            if self.tbox_name[idx].text() == k:
                QMessageBox.about(self, "Error",
                                  " This person is already exit ")
                return False

        key = list(self.dataSrc.keys())[idx]

        print(dir, dir_img)
        data[key] = self.dataSrc[key]
        data_img[key] = self.dataSrc_img[key]
        print(data)
        pickle_out = open(
            dir, 'wb')  ## for training data, contain the feature of the face
        pickle_out_img = open(dir_img, 'wb')  ## for the image of known people
        pickle.dump(data, pickle_out)
        pickle.dump(data_img, pickle_out_img)
        QMessageBox.about(self, "Notification", " Done and Done ")

    def saveData(self, flag):
        if flag == 1:  # this is for file 1
            i = 0
            temp = {}
            temp_img = {}
            for k in self.dataSrc.copy():
                i = list(self.dataSrc.keys()).index(k)
                newName = self.tbox_name[i].text()
                temp[newName] = self.dataSrc[k]
                temp_img[newName] = self.dataSrc_img[k]
                # newkey=self.tbox_name[i].text()
                # print(newkey,k)
                # if newkey !=k:
                #     self.dataSrc[newkey]=self.dataSrc.pop(k)
                #     self.dataSrc_img[newkey]=self.dataSrc_img.pop(k)
                # i+=1
                # print(self.dataSrc)
            del self.dataSrc
            del self.dataSrc_img
            self.dataSrc = temp
            self.dataSrc_img = temp_img

            dir = self.dirSrc
            dir_img = self.dirSrc.replace(".pickle", "_img.pickle")
            print("copy_Items", dir, dir_img)
            pickle_out = open(
                dir,
                'wb')  ## for training data, contain the feature of the face
            pickle_out_img = open(dir_img,
                                  'wb')  ## for the image of known people
            pickle.dump(self.dataSrc, pickle_out)
            pickle.dump(self.dataSrc_img, pickle_out_img)
            del temp
            del temp_img
            QMessageBox.about(self, "Notification", " Done and Done ")

    @pyqtSlot()
    def _save(self):
        try:
            if self.warningMsg("the old file will be Overwritten"):
                self.saveData(1)
        except Exception as e:
            print("management/_save: ", e)

    def warningMsg(self, strmsg):
        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setText(strmsg)
        msgBox.setWindowTitle("# WARNING: ")
        msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

        returnValue = msgBox.exec()
        if returnValue == QMessageBox.Ok:
            return True

    def _quit(self):
        pass

    def _back(self):
        pass

    def _browseSrc(self):
        try:
            filename = self.browseFileDialog()
            self.dirSrc = filename
            if filename is not None:
                self.tbox_srcFile.setText(filename)
                if self.checkBox.isChecked():
                    self.btn_save.setEnabled(False)
                    self.dataSrc_img, _ = self._load_data_fromFaceLog(filename)
                else:
                    self.dataSrc, self.dataSrc_img, _, _ = self._load_data_fromPickle(
                        filename)
                self.draw_Src()
        except Exception as e:
            print(e)

    def _browseDst(self):
        pass
コード例 #46
0
ファイル: settings.py プロジェクト: bastonc/linlog_v1.262
class Menu(QWidget):
    def __init__(self,
                 settingsDict,
                 telnetCluster,
                 logForm,
                 logSearch,
                 logWindow,
                 internetSearch,
                 tci_class,
                 parent=None):
        super(Menu, self).__init__(parent)
        self.settingsDict = settingsDict
        self.label_style = "font: 12px;"
        self.initUI()
        self.initData()
        self.telnetCluster = telnetCluster
        self.logForm = logForm
        self.logSearch = logSearch
        self.logWindow = logWindow
        self.internetSearch = internetSearch
        self.tci_class = tci_class
        #print ("Menu init tci class:", self.tci_class.currentThreadId())
        #self.initUI()

    def initUI(self):

        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('LinLog | Settings')

        self.setWindowIcon(QIcon('logo.png'))
        style = "QWidget{background-color:" + self.settingsDict[
            'background-color'] + "; color:" + self.settingsDict['color'] + ";}"
        self.setStyleSheet(style)
        # declaration tab
        self.tab = QtWidgets.QTabWidget()
        self.general_tab = QWidget()
        self.cluster_tab = QWidget()
        self.tci_tab = QWidget()
        self.io_tab = QWidget()
        self.service_widget = QWidget()
        #
        self.tab.addTab(self.general_tab, "General")
        self.tab.addTab(self.cluster_tab, "Cluster")
        self.tab.addTab(self.tci_tab, "TCI")
        self.tab.addTab(self.io_tab, "Log file")
        self.tab.addTab(self.service_widget, "Services")
        # create General Tab
        formstyle = "background: "+self.settingsDict['form-background']+"; color: "+\
                    self.settingsDict['color-table']+"; "
        self.general_tab.layout = QVBoxLayout(self)  # create vertical lay
        self.call_label = QLabel("You Callsign")
        self.call_input = QLineEdit()
        self.call_input.setFixedWidth(100)
        self.call_input.setStyleSheet(formstyle)
        # Chekbox SWL
        self.swl_chekbox = QCheckBox("Enable SWL mode")
        self.swl_chekbox.setStyleSheet("QCheckBox{ color:" +
                                       self.settingsDict['color'] +
                                       "; font-size: 12px;}")
        self.dlg = QColorDialog(self)
        self.back_color_label = QLabel("Window color")
        self.back_color_label.setStyleSheet(self.label_style)
        self.back_color_input = QPushButton()
        self.back_color_input.clicked.connect(self.back_color_select)
        self.back_color_input.setFixedWidth(70)
        self.back_color_input.setStyleSheet(
            "background:" + self.settingsDict['background-color'] +
            "; color:" + self.settingsDict['background-color'] + ";")
        self.back_color_input.setText(self.settingsDict['background-color'])
        #self.back_color_input.setStyleSheet(formstyle)
        self.text_color_label = QLabel("Text color")
        self.text_color_label.setStyleSheet(self.label_style)
        self.text_color_input = QPushButton()
        self.text_color_input.clicked.connect(self.text_color_select)
        self.text_color_input.setFixedWidth(70)
        self.text_color_input.setStyleSheet("background:" +
                                            self.settingsDict['color'] +
                                            "; color:" +
                                            self.settingsDict['color'] + ";")
        self.text_color_input.setText(self.settingsDict['color'])

        #self.text_color_input.setStyleSheet(formstyle)
        self.form_color_label = QLabel("Form background color")
        self.form_color_label.setStyleSheet(self.label_style)
        self.form_color_input = QPushButton()
        self.form_color_input.clicked.connect(self.form_color_select)
        self.form_color_input.setFixedWidth(70)
        self.form_color_input.setStyleSheet(
            "background: " + self.settingsDict['form-background'] +
            "; color:" + self.settingsDict['form-background'] + ";")
        self.form_color_input.setText(self.settingsDict['form-background'])
        #
        self.text_form_color_label = QLabel("Form text color")
        self.text_form_color_label.setStyleSheet(self.label_style)
        self.text_form_color_button = QPushButton()
        self.text_form_color_button.clicked.connect(
            self.form_text_color_select)
        self.text_form_color_button.setFixedWidth(70)
        self.text_form_color_button.setStyleSheet(
            "background: " + self.settingsDict['color-table'] + "; color: " +
            self.settingsDict['color-table'] + ";")
        self.text_form_color_button.setText(self.settingsDict['color-table'])

        # setup all elements to vertical lay
        self.general_tab.layout.addWidget(self.call_label)
        self.general_tab.layout.addWidget(self.call_input)
        self.general_tab.layout.addSpacing(20)
        self.general_tab.layout.addWidget(self.swl_chekbox)
        self.general_tab.layout.addWidget(self.back_color_label)
        self.general_tab.layout.addWidget(self.back_color_input)
        self.general_tab.layout.addSpacing(20)
        self.general_tab.layout.addWidget(self.text_color_label)
        self.general_tab.layout.addWidget(self.text_color_input)
        self.general_tab.layout.addSpacing(20)
        self.general_tab.layout.addWidget(self.form_color_label)
        self.general_tab.layout.addWidget(self.form_color_input)
        self.general_tab.layout.addWidget(self.text_form_color_label)
        self.general_tab.layout.addWidget(self.text_form_color_button)

        self.general_tab.setLayout(self.general_tab.layout)

        # create Cluster tab

        self.cluster_tab.layout = QVBoxLayout(self)
        self.cluster_host = QLabel("Cluster host:")
        self.cluster_host_input = QLineEdit()
        self.cluster_host_input.setFixedWidth(150)
        self.cluster_host_input.setStyleSheet(formstyle)
        self.cluster_port = QLabel("Cluster port:")
        self.cluster_port_input = QLineEdit()
        self.cluster_port_input.setFixedWidth(50)
        self.cluster_port_input.setStyleSheet(formstyle)
        self.host_port_lay = QHBoxLayout()
        # create host:port lay
        self.host_lay = QVBoxLayout()
        self.host_lay.addWidget(self.cluster_host)
        self.host_lay.addWidget(self.cluster_host_input)

        self.port_lay = QVBoxLayout()
        self.port_lay.addWidget(self.cluster_port)
        self.port_lay.addWidget(self.cluster_port_input)

        self.host_port_lay.addLayout(self.host_lay)
        self.host_port_lay.addLayout(self.port_lay)

        # Create calibrate cluster
        self.calibrate_lay = QHBoxLayout()
        ## Create text label
        self.text_and_button_Vlay = QVBoxLayout()
        text = "Press \"Start claibrate\" and select Callsign and Freq \n" \
               "from the received line from the telnet cluster"
        self.message_label = QLabel(text)
        self.message_label.setStyleSheet("font: 12px;")
        self.text_and_button_Vlay.addWidget(self.message_label)

        self.button_and_combo = QHBoxLayout()
        ## Create group from button and combobox
        self.cluster_start_calibrate_button = QPushButton(
            "Start \n callibrate")
        self.cluster_start_calibrate_button.setFixedWidth(100)
        self.cluster_start_calibrate_button.setFixedHeight(60)
        self.button_and_combo.addWidget(self.cluster_start_calibrate_button)
        self.combo_lay = QVBoxLayout()
        self.call_H = QHBoxLayout()
        self.call_H.setAlignment(Qt.AlignRight)
        self.cluster_call_label = QLabel("Call:")

        self.cluster_combo_call = QComboBox()

        self.freq_H = QHBoxLayout()
        self.freq_H.setAlignment(Qt.AlignRight)
        self.cluster_freq_label = QLabel("Freq:")
        self.cluster_combo_freq = QComboBox()
        self.call_H.addWidget(self.cluster_call_label)
        self.call_H.addWidget(self.cluster_combo_call)
        self.freq_H.addWidget(self.cluster_freq_label)
        self.freq_H.addWidget(self.cluster_combo_freq)
        self.combo_lay.addLayout(self.call_H)
        self.combo_lay.addLayout(self.freq_H)
        self.button_and_combo.addLayout(self.combo_lay)
        self.text_and_button_Vlay.addLayout(self.button_and_combo)

        self.calibrate_lay.addLayout(self.text_and_button_Vlay)

        ## Create filter band
        self.cluster_filter_band_combo = QCheckBox("Filter BAND")
        self.cluster_filter_band_combo.setStyleSheet(
            "QCheckBox{ color:" + self.settingsDict['color'] +
            "; font-size: 12px;}")
        self.cluster_filter_band_input = QLineEdit()
        self.cluster_filter_band_input.setFixedWidth(80)
        self.cluster_filter_band_input.setFixedHeight(20)
        self.cluster_filter_band_input.setStyleSheet(
            "background-color:" + self.settingsDict['form-background'] +
            "; font-size: 12px")
        text = "Bands in m."
        self.message_label_band = QLabel(text)
        self.message_label_band.setStyleSheet("font: 12px;")

        self.filter_band_lay = QVBoxLayout()
        self.filter_band_lay.addWidget(self.cluster_filter_band_combo)
        self.filter_band_lay.addWidget(self.message_label_band)
        self.filter_band_lay.addWidget(self.cluster_filter_band_input)

        ## Create filter spot
        self.cluster_filter_spot_combo = QCheckBox("Filter SPOT")
        self.cluster_filter_spot_combo.setStyleSheet(
            "QCheckBox{ color:" + self.settingsDict['color'] +
            "; font-size: 12px;}")
        self.cluster_filter_spot_input = QLineEdit()
        self.cluster_filter_spot_input.setFixedWidth(80)
        self.cluster_filter_spot_input.setFixedHeight(20)
        self.cluster_filter_spot_input.setStyleSheet(
            "background-color:" + self.settingsDict['form-background'] +
            "; font-size: 12px")
        text = "Spot prefixes"
        self.message_label_spot = QLabel(text)
        self.message_label_spot.setStyleSheet("font: 12px;")

        self.filter_spot_lay = QVBoxLayout()
        self.filter_spot_lay.addWidget(self.cluster_filter_spot_combo)
        self.filter_spot_lay.addWidget(self.message_label_spot)
        self.filter_spot_lay.addWidget(self.cluster_filter_spot_input)

        ## create filter spotter
        self.cluster_filter_spotter_combo = QCheckBox("Filter SPOTTER")
        self.cluster_filter_spotter_combo.setStyleSheet(
            "QCheckBox{ color:" + self.settingsDict['color'] +
            "; font-size: 12px;}")
        self.cluster_filter_spotter_input = QLineEdit()
        self.cluster_filter_spotter_input.setFixedWidth(80)
        self.cluster_filter_spotter_input.setFixedHeight(20)
        self.cluster_filter_spotter_input.setStyleSheet(
            "background-color:" + self.settingsDict['form-background'] +
            "; font-size: 12px")
        text = "Spotter prefixes"
        self.message_label_spotter = QLabel(text)
        self.message_label_spotter.setStyleSheet("font: 12px;")

        self.filter_spotter_lay = QVBoxLayout()
        self.filter_spotter_lay.addWidget(self.cluster_filter_spotter_combo)
        self.filter_spotter_lay.addWidget(self.message_label_spotter)
        self.filter_spotter_lay.addWidget(self.cluster_filter_spotter_input)

        text = "All value separate by comma"
        self.filter_message_label = QLabel(text)
        self.filter_message_label.setStyleSheet("font: 12px;")

        self.filters_Hlay = QHBoxLayout()
        self.filters_Hlay.addLayout(self.filter_band_lay)
        self.filters_Hlay.addLayout(self.filter_spot_lay)
        self.filters_Hlay.addLayout(self.filter_spotter_lay)

        self.filters_lay = QVBoxLayout()
        self.filters_lay.addSpacing(10)
        self.filters_lay.setAlignment(Qt.AlignCenter)
        self.filters_lay.addLayout(self.filters_Hlay)
        self.filters_lay.addWidget(self.filter_message_label)
        self.filters_lay.addSpacing(10)
        Separador = QFrame()
        Separador.setFrameShape(QFrame.HLine)
        Separador.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        Separador.setLineWidth(1)
        self.filters_lay.addWidget(Separador)

        ## Create List view for input string from cluster

        self.line_text = QLabel()

        self.line_text.setFixedHeight(50)
        # Set all layers to window
        self.cluster_tab.layout.addLayout(self.host_port_lay)
        self.cluster_tab.layout.addSpacing(10)
        self.cluster_tab.layout.addLayout(self.filters_lay)
        self.cluster_tab.layout.addLayout(self.calibrate_lay)
        self.cluster_tab.layout.addWidget(self.line_text)

        ## install lay to main tab (Cluster)
        self.cluster_tab.setLayout(self.cluster_tab.layout)

        # create TCI Tab

        self.tci_enable_combo_lay = QHBoxLayout()
        self.tci_enable_combo_lay.setAlignment(Qt.AlignCenter)
        self.tci_enable_combo = QCheckBox("TCI Enable")
        self.tci_enable_combo.setStyleSheet("QCheckBox{" +
                                            self.settingsDict['color'] + "}")
        self.tci_enable_combo_lay.addWidget(self.tci_enable_combo)
        self.tci_tab.layout = QVBoxLayout(self)
        self.tci_host = QLabel("TCI host:")
        self.tci_host_input = QLineEdit()
        self.tci_host_input.setFixedWidth(150)
        self.tci_host_input.setStyleSheet(formstyle)
        self.tci_port = QLabel("TCI port:")
        self.tci_port_input = QLineEdit()
        self.tci_port_input.setFixedWidth(50)
        self.tci_port_input.setStyleSheet(formstyle)
        self.host_port_lay = QHBoxLayout()
        # create host:port lay
        self.host_lay = QVBoxLayout()
        self.host_lay.addWidget(self.tci_host)
        self.host_lay.addWidget(self.tci_host_input)

        self.port_lay = QVBoxLayout()
        self.port_lay.addWidget(self.tci_port)
        self.port_lay.addWidget(self.tci_port_input)

        self.host_port_lay.addLayout(self.host_lay)
        self.host_port_lay.addLayout(self.port_lay)

        self.tci_tab.layout.addLayout(self.tci_enable_combo_lay)
        self.tci_tab.layout.addLayout(self.host_port_lay)
        self.tci_tab.layout.addSpacing(250)
        self.tci_tab.setLayout(self.tci_tab.layout)

        # Create io_tab
        self.io_tab_lay = QVBoxLayout()
        self.io_tab_lay.setAlignment(Qt.AlignCenter)
        self.import_button = QPushButton("Import")
        self.import_button.setFixedSize(100, 30)
        self.import_button.clicked.connect(self.import_adi)
        self.import_button.setStyleSheet("width: 100px;")
        self.export_button = QPushButton("Export")
        self.export_button.clicked.connect(self.export_adi)
        self.export_button.setFixedSize(100, 30)
        self.io_tab_lay.addWidget(self.import_button)
        self.io_tab_lay.addWidget(self.export_button)
        self.io_tab.setLayout(self.io_tab_lay)

        # Create Services tab

        self.service_tab = QVBoxLayout()
        self.service_tab.setAlignment(Qt.AlignCenter)

        # create elements form
        self.eqsl_lay = QVBoxLayout()
        self.eqsl_lay.setAlignment(Qt.AlignCenter)
        self.eqsl_activate = QHBoxLayout()
        self.eqsl_chekBox = QCheckBox("Auto sent eQSL after QSO")
        self.eqsl_chekBox.setStyleSheet(
            "{ color:" + self.settingsDict['color'] +
            "; font-size: 12px; border-color: white }")

        self.eqsl_activate.addWidget(self.eqsl_chekBox)
        #self.eqsl_activate.addWidget(QLabel("eQSL.cc"))
        self.eqsl_lay.addLayout(self.eqsl_activate)
        self.text_eqsl_small = QLabel("Automatic send eQSL after enter QSO")
        self.text_eqsl_small.setStyleSheet("font: 10px; font-style: italic;")
        self.eqsl_lay.addWidget(self.text_eqsl_small)
        self.eqsl_form = QVBoxLayout()
        self.login = QHBoxLayout()

        self.login.addWidget(QLabel("Login:"******"Password:"******"Color for eQSL complited: ")
        self.color_label_eqsl.setStyleSheet(style)
        self.color_button_eqsl = QPushButton()
        self.color_button_eqsl.setStyleSheet(
            "background:" + self.settingsDict['eqsl-sent-color'] + "; color:" +
            self.settingsDict['eqsl-sent-color'])
        self.color_button_eqsl.setText(self.settingsDict['eqsl-sent-color'])
        self.color_button_eqsl.setFixedWidth(120)
        self.color_button_eqsl.setFixedHeight(40)
        self.color_button_eqsl.clicked.connect(self.select_eqsl_color)
        self.color_button_layer = QHBoxLayout()
        self.color_button_layer.setAlignment(Qt.AlignLeft)
        self.color_button_layer.addWidget(self.color_label_eqsl)
        self.color_button_layer.addWidget(self.color_button_eqsl)
        self.eqsl_lay.addLayout(self.color_button_layer)
        self.service_tab.addLayout(self.eqsl_lay)
        self.service_widget.setLayout(self.service_tab)

        # button panel
        self.button_panel = QHBoxLayout()
        button_style = "font: 12px;"
        self.button_save = QPushButton("Save and Exit")
        self.button_save.setStyleSheet(button_style)
        self.button_save.clicked.connect(self.save_and_exit_button)
        self.button_apply = QPushButton("Apply")
        self.button_apply.setStyleSheet(button_style)
        self.button_apply.clicked.connect(self.apply_button)
        self.button_cancel = QPushButton("Cancel")
        self.button_cancel.setStyleSheet(button_style)
        self.button_cancel.clicked.connect(self.cancel_button)
        self.button_cancel.setFixedWidth(60)
        self.button_panel.addWidget(self.button_cancel)
        self.button_panel.addWidget(self.button_apply)
        self.button_panel.addWidget(self.button_save)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.tab)
        self.mainLayout.addLayout(self.button_panel)
        #self.mainLayout.addWidget(self.tab)
        self.setLayout(self.mainLayout)

        #self.setLayout(self.mainLayout)
        #self.show()
        #print("Menu() initUi")
    def select_eqsl_color(self):
        color_eqsl = QColorDialog.getColor(initial=QColor(
            self.color_button_eqsl.text()),
                                           parent=None,
                                           title="Select color for sent eQSL")

        if color_eqsl.isValid():
            # self.back_color_input.setText()
            self.color_button_eqsl.setStyleSheet("background:" +
                                                 color_eqsl.name() + ";")
            self.color_button_eqsl.setText(color_eqsl.name())
            self.color_button_eqsl.autoFillBackground()

    def initData(self):
        #init data in general tab
        self.call_input.setText(self.settingsDict["my-call"])
        #self.text_color_input.setText(self.settingsDict['color'])
        #self.form_color_input.setText(self.settingsDict['form-background'])
        #self.back_color_input.setText(self.settingsDict['background-color'])
        #init data in cluster tab
        self.cluster_host_input.setText(self.settingsDict['telnet-host'])
        self.cluster_port_input.setText(self.settingsDict['telnet-port'])
        if self.settingsDict['filter_by_band'] == 'enable':
            self.cluster_filter_band_combo.setChecked(True)
        self.cluster_filter_band_input.setText(
            self.settingsDict['list-by-band'])
        if self.settingsDict['filter-by-prefix'] == 'enable':
            self.cluster_filter_spot_combo.setChecked(True)
        self.cluster_filter_spot_input.setText(
            self.settingsDict['filter-prefix'])
        if self.settingsDict['filter-by-prefix-spotter'] == 'enable':
            self.cluster_filter_spotter_combo.setChecked(True)
        self.cluster_filter_spotter_input.setText(
            self.settingsDict['filter-prefix-spotter'])
        self.cluster_start_calibrate_button.clicked.connect(
            self.start_calibrate_cluster)
        #init data in tci tab
        if self.settingsDict['tci'] == 'enable':
            self.tci_enable_combo.setChecked(True)
        host = self.settingsDict['tci-server'].replace("ws://", '')
        self.tci_host_input.setText(host)
        self.tci_port_input.setText(self.settingsDict['tci-port'])
        self.eqsl_login.setText(self.settingsDict['eqsl_user'])
        self.eqsl_password.setText(self.settingsDict['eqsl_password'])
        if self.settingsDict['eqsl'] == 'enable':
            self.eqsl_chekBox.setChecked(True)
        if self.settingsDict['mode-swl'] == 'enable':
            self.swl_chekbox.setChecked(True)

    def closeEvent(self, e):
        #print("Close menu", e)
        self.close()

    def import_adi(self):
        fileimport = QFileDialog()
        options = QFileDialog.Options()
        #options |= QFileDialog.DontUseNativeDialog
        #fileimport.setNameFilter("Adi file(*.adi)")
        #fileimport.setFilter()
        fname = fileimport.getOpenFileName(self,
                                           'Import adi file',
                                           '/home',
                                           "*.adi",
                                           options=options)[0]
        if fname:
            # print(fname)
            self.allCollumn = [
                'records_number', 'QSO_DATE', 'TIME_ON', 'BAND', 'CALL',
                'FREQ', 'MODE', 'RST_RCVD', 'RST_SENT', 'NAME', 'QTH',
                'COMMENTS', 'TIME_OFF', 'eQSL_QSL_RCVD', 'OPERATOR'
            ]
            try:
                allRecords = parse.getAllRecord(self.allCollumn,
                                                fname,
                                                key="import")
                main.Adi_file.record_dict_qso(self, allRecords)
                self.logWindow.refresh_data()
                std.std.message(self, "Import complete!", "Ok")
            except Exception:
                std.std.message(self, "Can't import\nUnknown problem", "STOP!")

    def export_adi(self):
        # print("export_adi")
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, _ = QFileDialog.getSaveFileName(self,
                                                   "Export adi",
                                                   "",
                                                   "Adi (*.adi)",
                                                   options=options)
        if file_name:
            # print(file_name)
            copy_file = shutil.copyfile('log.adi', file_name + '.adi')

            if copy_file != '':
                #print("Export complete")
                std.std.message(self,
                                "Export to\n" + copy_file + "\n completed",
                                "Export complited")
            else:
                std.std.message(self, "Can't export to file", "Sorry")

    def start_calibrate_cluster(self):
        # print("start_calibrate_cluster:_>", self.settingsDict)
        self.telnetCluster.stop_cluster()
        self.cluster = cluster_in_Thread(
            self.cluster_host_input.text().strip(),
            self.cluster_port_input.text().strip(),
            self.call_input.text().strip(),
            settingsDict=self.settingsDict,
            parent_window=self)
        self.cluster.start()

    def refresh_interface(self):

        self.update_color_schemes()

    def text_color_select(self):
        color = QColorDialog.getColor(initial=QColor(
            self.text_color_input.text()),
                                      parent=None,
                                      title="Select color for text in window")

        if color.isValid():
            self.text_color_input.setText(color.name())
            self.text_color_input.setStyleSheet("background:" + color.name() +
                                                ";")
            self.text_color_input.autoFillBackground()

    def form_color_select(self):
        color = QColorDialog.getColor(initial=QColor(
            self.form_color_input.text()),
                                      parent=None,
                                      title="Select color for text in tables")

        if color.isValid():
            self.form_color_input.setText(color.name())
            self.form_color_input.setStyleSheet("background:" + color.name() +
                                                ";")
            self.form_color_input.autoFillBackground()

    def form_text_color_select(self):
        color = QColorDialog.getColor(initial=QColor(
            self.text_form_color_button.text()),
                                      parent=None,
                                      title="Select color for text in tables")

        if color.isValid():
            self.text_form_color_button.setText(color.name())
            self.text_form_color_button.setStyleSheet("background:" +
                                                      color.name() + ";")
            self.text_form_color_button.autoFillBackground()

    #self.back_color_input.clicked.connect(self.text_color_select)

    def back_color_select(self):
        #self.dlg.show()
        color = QColorDialog.getColor(
            initial=QColor(self.back_color_input.text()),
            parent=None,
            title="Select color for background color")

        if color.isValid():
            #self.back_color_input.setText()
            self.back_color_input.setStyleSheet("background:" + color.name() +
                                                ";")
            self.back_color_input.setText(color.name())
            self.back_color_input.autoFillBackground()

    def update_color_schemes(self):
        style = "QWidget{background-color:" + self.settingsDict['background-color'] + "; color:" + \
                self.settingsDict['color'] + ";}"

        self.setStyleSheet(style)

    def store_new_settingsDict(self):
        call = self.settingsDict['my-call']
        self.settingsDict['my-call'] = self.call_input.text()
        self.settingsDict['background-color'] = self.back_color_input.text()
        self.settingsDict['color'] = self.text_color_input.text()
        self.settingsDict['form-background'] = self.form_color_input.text()
        self.settingsDict['color-table'] = self.text_form_color_button.text()
        self.settingsDict['telnet-host'] = self.cluster_host_input.text()
        self.settingsDict['telnet-port'] = self.cluster_port_input.text()
        self.settingsDict[
            'list-by-band'] = self.cluster_filter_band_input.text()
        self.settingsDict[
            'filter-prefix'] = self.cluster_filter_spot_input.text()
        self.settingsDict[
            'filter-prefix-spotter'] = self.cluster_filter_spotter_input.text(
            )
        if self.cluster_combo_call.currentText() != '':
            self.settingsDict[
                'telnet-call-position'] = self.cluster_combo_call.currentText(
                ).split(":")[0]
        if self.cluster_combo_freq.currentText() != '':
            self.settingsDict[
                'telnet-freq-position'] = self.cluster_combo_freq.currentText(
                ).split(":")[0]
        self.settingsDict['tci-server'] = "ws://" + self.tci_host_input.text(
        ).strip()
        self.settingsDict['tci-port'] = self.tci_port_input.text().strip()
        self.settingsDict['eqsl_user'] = self.eqsl_login.text()
        self.settingsDict['eqsl_password'] = self.eqsl_password.text()
        self.settingsDict['eqsl-sent-color'] = self.color_button_eqsl.text()
        if self.eqsl_chekBox.isChecked():
            self.settingsDict['eqsl'] = 'enable'
        else:
            self.settingsDict['eqsl'] = 'disable'
        if self.swl_chekbox.isChecked():
            self.settingsDict['mode-swl'] = 'enable'

        else:
            self.settingsDict['mode-swl'] = "disable"
        if self.tci_enable_combo.isChecked():
            self.settingsDict['tci'] = 'enable'
        else:
            self.settingsDict['tci'] = 'disable'

        cluster_change_flag = 0
        if self.cluster_filter_band_combo.isChecked():
            if self.settingsDict['filter_by_band'] != "enable":
                self.settingsDict['filter_by_band'] = "enable"
                cluster_change_flag = 1
        else:
            if self.settingsDict['filter_by_band'] != "disable":
                self.settingsDict['filter_by_band'] = "disable"
                cluster_change_flag = 1

        if self.cluster_filter_spot_combo.isChecked():
            if self.settingsDict['filter-by-prefix'] != "enable":
                self.settingsDict['filter-by-prefix'] = "enable"
                cluster_change_flag = 1
        else:
            if self.settingsDict['filter-by-prefix'] != "disable":
                self.settingsDict['filter-by-prefix'] = "disable"
                cluster_change_flag = 1

        if self.cluster_filter_spotter_combo.isChecked():
            if self.settingsDict['filter-by-prefix-spotter'] != "enable":
                self.settingsDict['filter-by-prefix-spotter'] = "enable"
                cluster_change_flag = 1
        else:
            if self.settingsDict['filter-by-prefix-spotter'] != "disable":
                self.settingsDict['filter-by-prefix-spotter'] = "disable"
                cluster_change_flag = 1

        return cluster_change_flag

    def apply_button(self):

        cluster_change_flag = self.store_new_settingsDict(
        )  # save all lines from menu window \
        # to dictionary settingsDict
        if self.settingsDict['tci'] == 'enable':
            self.tci_class.stop_tci()
            self.tci_class.start_tci(self.settingsDict['tci-server'],
                                     self.settingsDict['tci-port'])
            #self.logForm.update_settings(self.settingsDict)
        else:
            self.tci_class.stop_tci()

        self.logForm.refresh_interface()
        #self.logSearch.update_settings(self.settingsDict)
        self.logSearch.refresh_interface()
        #self.logWindow.update_settings(self.settingsDict)
        self.logWindow.refresh_interface()
        #self.internetSearch.update_settings(self.settingsDict)
        self.internetSearch.refresh_interface()
        #self.telnetCluster.update_settings(self.settingsDict)
        self.telnetCluster.refresh_interface()
        self.refresh_interface()
        if cluster_change_flag == 1:
            self.telnetCluster.stop_cluster()
            self.telnetCluster.start_cluster()

    def save_and_exit_button(self):

        cluster_change_flag = self.store_new_settingsDict()

        filename = 'settings.cfg'
        with open(filename, 'r') as f:
            old_data = f.readlines()
        for index, line in enumerate(old_data):
            key_from_line = line.split('=')[0]
            #print ("key_from_line:",key_from_line)
            for key in self.settingsDict:

                if key_from_line == key:
                    #print("key",key , "line", line)
                    old_data[index] = key + "=" + self.settingsDict[key] + "\n"
        with open(filename, 'w') as f:
            f.writelines(old_data)
        #print ("Save_and_Exit_button: ", old_data)
        Menu.close(self)

    def cancel_button(self):
        self.close()
コード例 #47
0
    def setup_ui(self):

        lbl_src = QLabel("File 1:")
        lbl_dst = QLabel("File 2:")

        self.tbox_srcFile = QLineEdit()
        self.tbox_srcFile.setEnabled(False)
        self.tbox_dstFile = QLineEdit()
        self.tbox_dstFile.setEnabled(False)

        self.checkBox = QCheckBox("View Only this is for debug and testing")

        self.btn_browseSrc = QPushButton("...")
        self.btn_browseSrc.setFixedSize(
            QSize(monitorWidth * 0.02, monitorHeight * 0.02))
        self.btn_browseSrc.clicked.connect(self._browseSrc)

        self.btn_browseDst = QPushButton("...")
        self.btn_browseDst.setFixedSize(
            QSize(monitorWidth * 0.02, monitorHeight * 0.02))
        self.btn_browseSrc.clicked.connect(self._browseDst)

        self.btn_back = QPushButton("<< Back")
        self.btn_back.clicked.connect(self._back)

        self.btn_quit = QPushButton("Quit")
        self.btn_quit.clicked.connect(self._quit)

        self.btn_save = QPushButton("Save")
        self.btn_save.clicked.connect(self._save)

        ## groupBox
        self.lbl_img = []
        self.tbox_name = []
        self.btn_delete = []
        self.btn_copy = []

        self.groupBoxSrc = QGroupBox()

        # lay output
        self.gridBox = QGridLayout()
        self.formLayout = QFormLayout()
        self.groupBoxSrc.setLayout(self.formLayout)

        scroll = QScrollArea()
        scroll.setWidget(self.groupBoxSrc)
        scroll.setWidgetResizable(True)
        scroll.setFixedHeight(monitorHeight * 0.5)
        scroll.setFixedWidth(monitorWidth * 0.12)

        hlaysrc = QHBoxLayout()
        hlaysrc.addWidget(lbl_src)
        hlaysrc.addWidget(self.tbox_srcFile)
        hlaysrc.addWidget(self.btn_browseSrc)

        vlaysrc = QVBoxLayout()
        vlaysrc.addLayout(hlaysrc)
        vlaysrc.addWidget(self.checkBox)
        vlaysrc.addWidget(scroll)

        hBtnLayout = QHBoxLayout()
        hBtnLayout.addWidget(self.btn_back)
        hBtnLayout.addWidget(self.btn_save)
        hBtnLayout.addWidget(self.btn_quit)

        vMain = QVBoxLayout()
        vMain.addLayout(vlaysrc)
        vMain.addLayout(hBtnLayout)

        self.setLayout(vMain)
コード例 #48
0
class ReferenceDataPidget(PidgetStub):
    def __init__(self, param, parent_instance):
        super().__init__(param, parent_instance)

        self.title_label = QLabel(param.label)
        self.grid.addWidget(self.title_label, 0, 0, 1, 2)

        self.buffer_btn = QPushButton()
        self.buffer_btn.clicked.connect(self.__buffer_btn_clicked)
        self.grid.addWidget(self.buffer_btn, 1, 0, 1, 1)

        self.load_btn = QPushButton()
        self.load_btn.clicked.connect(self.__load_btn_clicked)
        self.grid.addWidget(self.load_btn, 1, 1, 1, 1)

        self.info_label = QLabel()
        self.grid.addWidget(self.info_label, 2, 0, 1, 2)

        self.use_cb = QCheckBox("Enable", self)
        self.use_cb.setTristate(False)
        self.use_cb.stateChanged.connect(self.__use_cb_state_changed)
        self.grid.addWidget(self.use_cb, 3, 0, 1, 2)

        self.update()

    def _update(self, *args, **kwargs):
        super()._update(*args, **kwargs)

        config = self._get_param_value()

        if config.is_loaded:
            enabled = config.source == "buffer"
            text = "Save" if enabled else "Already saved"
        else:
            enabled = config.has_buffered

            if config.has_buffered:
                text = "Use measured"
            else:
                if self._parent_instance._state == cb.Config.State.LIVE:
                    text = "Measuring..."
                else:
                    text = "Waiting..."

        self.buffer_btn.setEnabled(enabled)
        self.buffer_btn.setText(text)

        text = "Unload" if config.is_loaded else "Load from file"
        self.load_btn.setText(text)

        if config.is_loaded:
            if config.source == "file":
                text = "Loaded {}".format(config.source_file)
            else:
                text = "Loaded measured data"
        else:
            text = ""

        self.info_label.setText(text)
        self.info_label.setVisible(config.is_loaded)

        self.use_cb.setEnabled(not config.error)
        self.use_cb.setChecked(False if config.error else config.use)
        self.use_cb.setVisible(config.is_loaded)

        if config.error:
            self._set_alert(cb.Error(None, config.error))
        else:
            self._set_alert(None)

    def __buffer_btn_clicked(self):
        config = self._get_param_value()

        if config.is_loaded:
            filename = self.__file_dialog(save=True)
            if filename:
                config.save_to_file(filename)
        else:
            config.load_buffered()

    def __load_btn_clicked(self):
        config = self._get_param_value()

        if config.is_loaded:
            config.unload()
        else:
            filename = self.__file_dialog(save=False)
            if filename:
                config.load_from_file(filename)

    def __use_cb_state_changed(self, state):
        config = self._get_param_value()
        config.use = bool(state)

    def __file_dialog(self, save=True):
        caption = "Save" if save else "Load"
        caption = caption + " " + self.param.label.lower().strip()
        suggested_filename = self.param.label.lower().strip().replace(
            " ", "_") + ".npy"
        file_types = "NumPy data files (*.npy)"

        if save:
            filename, info = QFileDialog.getSaveFileName(
                self,
                caption,
                suggested_filename,
                file_types,
            )
        else:
            filename, info = QFileDialog.getOpenFileName(
                self,
                caption,
                suggested_filename,
                file_types,
            )

        return filename
コード例 #49
0
    def __init__(self, count_data):

        super(Choose, self).__init__()

        self.resize(250, 200)
        self.setWindowTitle("提示信息")

        # 初始化数据
        self.jiaLableSort = QLabel("假")
        self.jiaLableCount = QLabel("数量: %d" % count_data["jia"]["count"])
        self.jiaLablePrice = QLabel("总价: %.2f" % count_data["jia"]["price"])

        self.siLableSort = QLabel("私")
        self.siLableCount = QLabel("数量: %d" % count_data["si"]["count"])
        self.siLablePrice = QLabel("总价: %.2f" % count_data["si"]["price"])

        self.feiLableSort = QLabel("非")
        self.feiLableCount = QLabel("数量: %d" % count_data["fei"]["count"])
        self.feiLablePrice = QLabel("总价: %.2f" % count_data["fei"]["price"])

        # self.totalPrice = QLabel(str(count_data["price"]))


        # 装载布局
        layout = QGridLayout()
        layout.addWidget(self.jiaLableSort, 0, 0)
        layout.addWidget(self.jiaLableCount, 0, 1)
        layout.addWidget(self.jiaLablePrice, 0, 2)
        layout.addWidget(self.siLableSort, 1, 0)
        layout.addWidget(self.siLableCount, 1, 1)
        layout.addWidget(self.siLablePrice, 1, 2)
        layout.addWidget(self.feiLableSort, 2, 0)
        layout.addWidget(self.feiLableCount, 2, 1)
        layout.addWidget(self.feiLablePrice, 2, 2)
        # layout.addWidget(self.totalPrice, 3, 0, 1, 3)

        self.anjian_type = 0  # 案件的类型 0零盒 1小微 2一般

        # 根据数量的不同,选择类型
        if count_data["is_tiao"]:  # 以条为单位
            if count_data["jia"]["count"] > 0:
                self.anjian_type = 2
            else:
                all_count = count_data["jia"]["count"] + count_data["si"]["count"] + count_data["fei"]["count"]
                price_count = count_data["price"]
                if all_count > 50 or float(price_count) > 10000:
                    self.anjian_type = 2
                else:
                    self.anjian_type = 1
        else:  # 以支为单位
            if count_data["jia"]["count"] > 0:
                self.anjian_type = 2
            else:
                all_count = count_data["jia"]["count"] + count_data["si"]["count"] + count_data["fei"]["count"]
                if all_count > 800:
                    self.anjian_type = 2
                else:
                    self.anjian_type = 0

        self.confirm_btn = QPushButton("确定")
        self.confirm_btn.clicked.connect(self.func_confirm)

        if self.anjian_type == 0:  # 零盒案件
            self.checkbox1 = QCheckBox("当事人无异议")
            self.checkbox2 = QCheckBox("涉案烟未销售")
            layout.addWidget(self.checkbox1, 4, 0, 1, 2)
            layout.addWidget(self.checkbox2, 5, 0, 1, 2)
            layout.addWidget(self.confirm_btn, 6, 0, 1, 2)
        elif self.anjian_type == 1:  # 小微案件
            self.checkbox1 = QCheckBox("当事人无异议")
            layout.addWidget(self.checkbox1, 4, 0, 1, 2)
            layout.addWidget(self.confirm_btn, 5, 0, 1, 2)
        else:  # 一般案件不处理
            layout.addWidget(self.confirm_btn, 4, 0, 1, 2)

        self.setLayout(layout)
        style_str = "QLabel{font-size: 30px;}" + "QLineEdit{font-size: 30px;}" + \
                    "QPushButton{font-size: 25px; background-color: green; min-height: 50px}" + \
                    "QComboBox{font-size: 30px;}" + "QCheckBox{font-size: 30px;}"
        self.setStyleSheet(style_str)
コード例 #50
0
class FloatSpinBoxPidget(PidgetStub):
    def __init__(self, param, parent_instance):
        assert isinstance(param, cb.FloatParameter)

        super().__init__(param, parent_instance)

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

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

        self.spin_box = wrap_qwidget(QDoubleSpinBox)(self)
        self.spin_box.setDecimals(param.decimals)
        self.spin_box.setSingleStep(10**(-param.decimals))
        self.spin_box.setKeyboardTracking(False)
        self.spin_box.setRange(*_limits_for_qt(param.limits))

        if param.is_optional:
            self.checkbox = QCheckBox(param.optional_label, self)
            self.checkbox.setTristate(False)
            self.checkbox.stateChanged.connect(self.__checkbox_event_handler)

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

            self.grid.setColumnStretch(2, 1)
            self.grid.addWidget(self.spin_box, 0, 2, 1, 1)

            self.spin_box.setValue(self.param.optional_default_set_value)
        else:
            self.checkbox = None
            self.grid.addWidget(self.spin_box, 0, 1, 1, 1)

        self.spin_box.valueChanged.connect(self.__spin_box_event_handler)

        self.update()

    def _update(self, *args, **kwargs):
        super()._update(*args, **kwargs)
        value = self._get_param_value()
        is_set = value is not None

        if is_set:
            self.spin_box.setValue(value)

        self.spin_box.setEnabled(is_set)

        if self.checkbox is not None:
            self.checkbox.setChecked(is_set)

    def __checkbox_event_handler(self, val):
        if val:
            val = self.spin_box.value()
        else:
            val = None

        self._subwidget_event_handler(val)

    def __spin_box_event_handler(self, val):
        if self.param.is_optional:
            if not self.checkbox.isChecked():
                val = None

        self._subwidget_event_handler(val)
コード例 #51
0
class DyStockHistDaysDataSourceConfigDlg(QDialog):
    tradeDaysMode = OrderedDict\
                    ([
                        ('Wind和TuShare相互验证(默认)', 'Verify'),
                        ('若冲突,则以Wind为主', 'Wind'),
                        ('若冲突,则以TuShare为主', 'TuShare'),
                    ])

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

        self._read()
        self._initUi()

    def _initUi(self):
        self.setWindowTitle('配置-股票历史日线数据源')

        # 控件
        label = QLabel('股票历史日线数据源')

        self._windCheckBox = QCheckBox('Wind')
        self._windCheckBox.clicked.connect(self._windCheckBoxClicked)

        self._tuShareCheckBox = QCheckBox('TuShare')
        self._tuShareCheckBox.clicked.connect(self._tuShareCheckBoxClicked)

        self._tuShareProCheckBox = QCheckBox('TuSharePro')

        tuShareProTokenLabel = QLabel('TuSharePro token')
        self._tuShareProTokenLineEdit = QLineEdit()

        description = """默认使用Wind

只选Wind:更新交易日数据,股票代码表和股票历史日线数据到Wind对应的数据库

只选TuShare:更新交易日数据,股票代码表和股票历史日线数据到TuShare对应的数据库

选两个:更新交易日数据,股票代码表和股票历史日线数据到Wind对应的数据库,并同时做两个源的数据验证

交易日数据,股票代码表和股票历史日线数据的载入也是基于上面选择的数据库
        """
        textEdit = QTextEdit()
        textEdit.setPlainText(description)
        textEdit.setReadOnly(True)

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

        self._tradeDaysComboBox = QComboBox()
        descriptionTradeDays = "Wind有时交易日数据可能出错,所以选Wind时,总是跟TuShare做验证,由用户选择该如何做。"
        tradeDaysTextEdit = QTextEdit()
        tradeDaysTextEdit.setPlainText(descriptionTradeDays)
        tradeDaysTextEdit.setReadOnly(True)

        self._tuShareDaysIntervalLineEdit = QLineEdit(
        )  # TuShare日线数据每次下载间隔时间(秒)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(label, 0, 0)
        grid.addWidget(self._windCheckBox, 1, 0)
        grid.addWidget(self._tuShareCheckBox, 2, 0)
        grid.addWidget(self._tuShareProCheckBox, 3, 0)
        grid.addWidget(tuShareProTokenLabel, 4, 0)
        grid.addWidget(self._tuShareProTokenLineEdit, 5, 0)

        grid.addWidget(textEdit, 6, 0)

        grid.addWidget(
            QLabel(
                "                                                                 "
            ), 7, 0)
        grid.addWidget(QLabel("交易日数据模式"), 8, 0)
        grid.addWidget(self._tradeDaysComboBox, 9, 0)
        grid.addWidget(tradeDaysTextEdit, 10, 0)

        grid.addWidget(
            QLabel(
                "                                                                 "
            ), 11, 0)
        grid.addWidget(QLabel("TuShare日线数据下载间隔时间(秒)"), 12, 0)
        grid.addWidget(self._tuShareDaysIntervalLineEdit, 13, 0)

        grid.addWidget(okPushButton, 0, 1)
        grid.addWidget(cancelPushButton, 1, 1)

        self.setLayout(grid)

        # set data source to UI
        if self._data.get('Wind'):
            self._windCheckBox.setChecked(True)

        if sys.platform != 'win32':  # Wind only supported at Windows.
            self._windCheckBox.setEnabled(False)
            self._windCheckBox.setChecked(False)

        enableTuSharePro = False
        if self._data.get('TuShare'):
            self._tuShareCheckBox.setChecked(True)
            enableTuSharePro = True

        self._tuShareProCheckBox.setEnabled(enableTuSharePro)

        # set tushare pro
        enableTushareProToken = False
        if self._tuShareProData.get('TuSharePro'):
            self._tuShareProCheckBox.setChecked(True)
            enableTushareProToken = True

        if self._tuShareProData.get('Token'):
            self._tuShareProTokenLineEdit.setText(
                self._tuShareProData.get('Token'))

        # set according to days source checkbox
        self._tradeDaysComboBox.addItems(list(self.tradeDaysMode))
        self._enableTradeDaysComboBox()

        for k, v in self.tradeDaysMode.items():
            if v == self._tradeDaysModeData["tradeDaysMode"]:
                self._tradeDaysComboBox.setCurrentText(k)
                break

        # tushare days downloading interval
        self._tuShareDaysIntervalLineEdit.setText(
            str(self._tuShareDaysIntervalData['interval']))

        self.resize(QApplication.desktop().size().width() // 2,
                    QApplication.desktop().size().height() // 4 * 3)

    def _read(self):
        # data source
        file = DyStockConfig.getStockHistDaysDataSourceFileName()

        try:
            with open(file) as f:
                self._data = json.load(f)
        except:
            self._data = DyStockConfig.getDefaultHistDaysDataSource()

        # tushare pro
        file = DyStockConfig.getStockHistDaysTuShareProFileName()

        try:
            with open(file) as f:
                self._tuShareProData = json.load(f)
        except:
            self._tuShareProData = DyStockConfig.getDefaultHistDaysTuSharePro()

        # trade days mode
        file = DyStockConfig.getStockTradeDaysModeFileName()

        try:
            with open(file) as f:
                self._tradeDaysModeData = json.load(f)
        except:
            self._tradeDaysModeData = DyStockConfig.defaultTradeDaysMode

        # interval of tushare days downloading
        file = DyStockConfig.getStockTuShareDaysIntervalFileName()

        try:
            with open(file) as f:
                self._tuShareDaysIntervalData = json.load(f)
        except:
            self._tuShareDaysIntervalData = DyStockConfig.defaultTuShareDaysInterval

    def _ok(self):
        # data source
        data = {'Wind': False, 'TuShare': False}
        if self._windCheckBox.isChecked():
            data['Wind'] = True

        if self._tuShareCheckBox.isChecked():
            data['TuShare'] = True

        # config to variables
        DyStockConfig.configStockHistDaysDataSource(data)

        # save config
        file = DyStockConfig.getStockHistDaysDataSourceFileName()
        with open(file, 'w') as f:
            f.write(json.dumps(data, indent=4))

        # tushare pro
        data = {'TuSharePro': False, 'Token': None}
        if self._tuShareProCheckBox.isChecked():
            data['TuSharePro'] = True

        data['Token'] = self._tuShareProTokenLineEdit.text()

        DyStockConfig.configStockHistDaysTuSharePro(data)

        file = DyStockConfig.getStockHistDaysTuShareProFileName()
        with open(file, 'w') as f:
            f.write(json.dumps(data, indent=4))

        # trade days mode
        data = {}
        data["tradeDaysMode"] = self.tradeDaysMode[
            self._tradeDaysComboBox.currentText()]

        DyStockConfig.configStockTradeDaysMode(data)

        file = DyStockConfig.getStockTradeDaysModeFileName()
        with open(file, 'w') as f:
            f.write(json.dumps(data, indent=4))

        # tushare days downloading interval
        data = {}
        text = self._tuShareDaysIntervalLineEdit.text()
        try:
            data["interval"] = int(text)
        except:
            try:
                data["interval"] = float(text)
            except:
                data = DyStockConfig.defaultTuShareDaysInterval

        DyStockConfig.configStockTuShareDaysInterval(data)

        file = DyStockConfig.getStockTuShareDaysIntervalFileName()
        with open(file, 'w') as f:
            f.write(json.dumps(data, indent=4))

        self.accept()

    def _cancel(self):
        self.reject()

    def _enableTradeDaysComboBox(self):
        if self._windCheckBox.isChecked():
            self._tradeDaysComboBox.setEnabled(True)
        else:
            self._tradeDaysComboBox.setEnabled(False)

    def _checkBoxClicked(self):
        if not self._windCheckBox.isChecked(
        ) and not self._tuShareCheckBox.isChecked():
            if sys.platform == 'win32':
                self._windCheckBox.setChecked(True)
            else:
                self._tuShareCheckBox.setChecked(True)

        self._enableTradeDaysComboBox()

    def _windCheckBoxClicked(self):
        self._checkBoxClicked()

    def _tuShareCheckBoxClicked(self):
        self._checkBoxClicked()

        enable = self._tuShareCheckBox.isChecked()
        self._tuShareProCheckBox.setEnabled(enable)
コード例 #52
0
ファイル: linkUI.py プロジェクト: panghaibin/shuClient
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(433, 291)
        font = QFont()
        font.setPointSize(11)
        MainWindow.setFont(font)

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.groupBox = QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QRect(10, 70, 231, 131))
        self.groupBox.setTitle("")
        self.groupBox.setObjectName("groupBox")
        self.gridLayoutWidget = QWidget(self.groupBox)
        self.gridLayoutWidget.setGeometry(QRect(9, 10, 213, 91))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.input_user = QLineEdit(self.gridLayoutWidget)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.input_user.setFont(font)
        self.input_user.setText("")
        self.input_user.setAlignment(Qt.AlignLeading | Qt.AlignLeft
                                     | Qt.AlignVCenter)
        self.input_user.setObjectName("input_user")
        self.gridLayout.addWidget(self.input_user, 0, 1, 1, 1)
        self.user = QLabel(self.gridLayoutWidget)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.user.setFont(font)
        self.user.setAlignment(Qt.AlignCenter)
        self.user.setObjectName("user")
        self.gridLayout.addWidget(self.user, 0, 0, 1, 1)
        self.input_passwd = QLineEdit(self.gridLayoutWidget)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.input_passwd.setFont(font)
        self.input_passwd.setFocusPolicy(Qt.StrongFocus)
        self.input_passwd.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.input_passwd.setText("")
        self.input_passwd.setEchoMode(QLineEdit.Password)
        self.input_passwd.setAlignment(Qt.AlignLeading | Qt.AlignLeft
                                       | Qt.AlignVCenter)
        self.input_passwd.setObjectName("input_passwd")
        self.gridLayout.addWidget(self.input_passwd, 1, 1, 1, 1)
        self.passwd = QLabel(self.gridLayoutWidget)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.passwd.setFont(font)
        self.passwd.setAlignment(Qt.AlignCenter)
        self.passwd.setObjectName("passwd")
        self.gridLayout.addWidget(self.passwd, 1, 0, 1, 1)
        self.horizontalLayoutWidget = QWidget(self.groupBox)
        self.horizontalLayoutWidget.setGeometry(QRect(10, 102, 211, 26))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout_7 = QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout_7.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.passwdCB = QCheckBox(self.horizontalLayoutWidget)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.passwdCB.setFont(font)
        self.passwdCB.setObjectName("passwdCB")
        self.horizontalLayout_7.addWidget(self.passwdCB)
        self.auto_login = QCheckBox(self.horizontalLayoutWidget)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.auto_login.setFont(font)
        self.auto_login.setObjectName("auto_login")
        self.horizontalLayout_7.addWidget(self.auto_login)
        self.groupBox_2 = QGroupBox(self.centralwidget)
        self.groupBox_2.setGeometry(QRect(240, 70, 181, 131))
        self.groupBox_2.setTitle("")
        self.groupBox_2.setObjectName("groupBox_2")
        self.verticalLayoutWidget = QWidget(self.groupBox_2)
        self.verticalLayoutWidget.setGeometry(QRect(10, 10, 161, 111))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.status_lable = QLabel(self.verticalLayoutWidget)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.status_lable.setFont(font)
        self.status_lable.setAlignment(Qt.AlignCenter)
        self.status_lable.setObjectName("status_lable")
        self.verticalLayout.addWidget(self.status_lable)
        self.status = QTextBrowser(self.verticalLayoutWidget)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(9)
        self.status.setFont(font)
        self.status.setObjectName("status")
        self.verticalLayout.addWidget(self.status)
        self.groupBox_3 = QGroupBox(self.centralwidget)
        self.groupBox_3.setGeometry(QRect(10, 250, 411, 31))
        self.groupBox_3.setTitle("")
        self.groupBox_3.setObjectName("groupBox_3")
        self.updateLabel = QLabel(self.groupBox_3)
        self.updateLabel.setGeometry(QRect(150, 0, 111, 31))
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(10)
        self.updateLabel.setFont(font)
        self.updateLabel.setCursor(QCursor(Qt.PointingHandCursor))
        self.updateLabel.setToolTip("")
        self.updateLabel.setAlignment(Qt.AlignCenter)
        self.updateLabel.setObjectName("updateLabel")
        self.groupBox_4 = QGroupBox(self.centralwidget)
        self.groupBox_4.setGeometry(QRect(10, 0, 411, 71))
        self.groupBox_4.setTitle("")
        self.groupBox_4.setObjectName("groupBox_4")
        self.logo = QLabel(self.groupBox_4)
        self.logo.setGeometry(QRect(80, 10, 250, 51))
        self.logo.setText("")
        self.logo.setPixmap(QPixmap(linkpath + r'\timg.png'))
        self.logo.setObjectName("logo")
        self.text = QLabel(self.groupBox_4)
        self.text.setGeometry(QRect(180, 10, 122, 49))
        palette = QPalette()
        brush = QBrush(QColor(0, 85, 255))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Text, brush)
        brush = QBrush(QColor(0, 85, 255, 128))
        brush.setStyle(Qt.NoBrush)
        palette.setBrush(QPalette.Active, QPalette.PlaceholderText, brush)
        brush = QBrush(QColor(0, 85, 255))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Text, brush)
        brush = QBrush(QColor(0, 85, 255, 128))
        brush.setStyle(Qt.NoBrush)
        palette.setBrush(QPalette.Inactive, QPalette.PlaceholderText, brush)
        brush = QBrush(QColor(120, 120, 120))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Text, brush)
        brush = QBrush(QColor(0, 85, 255, 128))
        brush.setStyle(Qt.NoBrush)
        palette.setBrush(QPalette.Disabled, QPalette.PlaceholderText, brush)
        self.text.setPalette(palette)
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(14)
        self.text.setFont(font)
        self.text.setAlignment(Qt.AlignCenter)
        self.text.setObjectName("text")
        self.groupBox_5 = QGroupBox(self.centralwidget)
        self.groupBox_5.setGeometry(QRect(240, 200, 181, 51))
        self.groupBox_5.setTitle("")
        self.groupBox_5.setObjectName("groupBox_5")
        self.login = QPushButton(self.groupBox_5)
        self.login.setGeometry(QRect(10, 10, 91, 28))
        font = QFont()
        font.setFamily("微软雅黑")
        self.login.setFont(font)
        self.login.setObjectName("login")
        self.logout = QPushButton(self.groupBox_5)
        self.logout.setGeometry(QRect(110, 10, 61, 28))
        font = QFont()
        font.setFamily("微软雅黑")
        self.logout.setFont(font)
        self.logout.setObjectName("logout")
        self.groupBox_6 = QGroupBox(self.centralwidget)
        self.groupBox_6.setGeometry(QRect(10, 200, 231, 51))
        self.groupBox_6.setTitle("")
        self.groupBox_6.setObjectName("groupBox_6")
        self.linkStyle = QLabel(self.groupBox_6)
        self.linkStyle.setGeometry(QRect(10, 0, 71, 41))
        font = QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        self.linkStyle.setFont(font)
        self.linkStyle.setCursor(QCursor(Qt.ArrowCursor))
        self.linkStyle.setToolTip("")
        self.linkStyle.setAlignment(Qt.AlignCenter)
        self.linkStyle.setObjectName("linkStyle")
        self.comboBox = QComboBox(self.groupBox_6)
        self.comboBox.setGeometry(QRect(80, 10, 131, 26))
        font = QFont()
        font.setFamily("微软雅黑")
        self.comboBox.setFont(font)
        self.comboBox.setLayoutDirection(Qt.LeftToRight)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
コード例 #53
0
 def ff4_left_binding_cb () :
   fu4_cb = QCheckBox ('Left binding')
   fu4_cb .setVisible (False)
   fu4_cb .setChecked (True)
   return fu4_cb
コード例 #54
0
    def __init__(self, parent: 'ElectrumWindow', config: 'SimpleConfig'):
        WindowModalDialog.__init__(self, parent, _('Preferences'))
        self.config = config
        self.window = parent
        self.need_restart = False
        self.fx = self.window.fx
        self.wallet = self.window.wallet

        vbox = QVBoxLayout()
        tabs = QTabWidget()
        gui_widgets = []
        fee_widgets = []
        tx_widgets = []
        oa_widgets = []
        services_widgets = []

        # language
        lang_help = _(
            'Select which language is used in the GUI (after restart).')
        lang_label = HelpLabel(_('Language') + ':', lang_help)
        lang_combo = QComboBox()
        lang_combo.addItems(list(languages.values()))
        lang_keys = list(languages.keys())
        lang_cur_setting = self.config.get("language", '')
        try:
            index = lang_keys.index(lang_cur_setting)
        except ValueError:  # not in list
            index = 0
        lang_combo.setCurrentIndex(index)
        if not self.config.is_modifiable('language'):
            for w in [lang_combo, lang_label]:
                w.setEnabled(False)

        def on_lang(x):
            lang_request = list(languages.keys())[lang_combo.currentIndex()]
            if lang_request != self.config.get('language'):
                self.config.set_key("language", lang_request, True)
                self.need_restart = True

        lang_combo.currentIndexChanged.connect(on_lang)
        gui_widgets.append((lang_label, lang_combo))

        nz_help = _(
            'Number of zeros displayed after the decimal point. For example, if this is set to 2, "1." will be displayed as "1.00"'
        )
        nz_label = HelpLabel(_('Zeros after decimal point') + ':', nz_help)
        nz = QSpinBox()
        nz.setMinimum(0)
        nz.setMaximum(self.window.decimal_point)
        nz.setValue(self.window.num_zeros)
        if not self.config.is_modifiable('num_zeros'):
            for w in [nz, nz_label]:
                w.setEnabled(False)

        def on_nz():
            value = nz.value()
            if self.window.num_zeros != value:
                self.window.num_zeros = value
                self.config.set_key('num_zeros', value, True)
                self.window.history_list.update()
                self.window.address_list.update()

        nz.valueChanged.connect(on_nz)
        gui_widgets.append((nz_label, nz))

        msg = '\n'.join([
            _('Time based: fee rate is based on average confirmation time estimates'
              ),
            _('Mempool based: fee rate is targeting a depth in the memory pool'
              )
        ])
        fee_type_label = HelpLabel(_('Fee estimation') + ':', msg)
        fee_type_combo = QComboBox()
        fee_type_combo.addItems([_('Static'), _('ETA'), _('Mempool')])
        fee_type_combo.setCurrentIndex((2 if self.config.use_mempool_fees(
        ) else 1) if self.config.is_dynfee() else 0)

        def on_fee_type(x):
            self.config.set_key('mempool_fees', x == 2)
            self.config.set_key('dynamic_fees', x > 0)

        fee_type_combo.currentIndexChanged.connect(on_fee_type)
        fee_widgets.append((fee_type_label, fee_type_combo))

        use_rbf = bool(self.config.get('use_rbf', True))
        use_rbf_cb = QCheckBox(_('Use Replace-By-Fee'))
        use_rbf_cb.setChecked(use_rbf)
        use_rbf_cb.setToolTip(
            _('If you check this box, your transactions will be marked as non-final,') + '\n' + \
            _('and you will have the possibility, while they are unconfirmed, to replace them with transactions that pay higher fees.') + '\n' + \
            _('Note that some merchants do not accept non-final transactions until they are confirmed.'))

        def on_use_rbf(x):
            self.config.set_key('use_rbf', bool(x))
            batch_rbf_cb.setEnabled(bool(x))

        use_rbf_cb.stateChanged.connect(on_use_rbf)
        fee_widgets.append((use_rbf_cb, None))

        batch_rbf_cb = QCheckBox(_('Batch RBF transactions'))
        batch_rbf_cb.setChecked(bool(self.config.get('batch_rbf', False)))
        batch_rbf_cb.setEnabled(use_rbf)
        batch_rbf_cb.setToolTip(
            _('If you check this box, your unconfirmed transactions will be consolidated into a single transaction.') + '\n' + \
            _('This will save fees.'))

        def on_batch_rbf(x):
            self.config.set_key('batch_rbf', bool(x))

        batch_rbf_cb.stateChanged.connect(on_batch_rbf)
        fee_widgets.append((batch_rbf_cb, None))

        msg = _('OpenAlias record, used to receive coins and to sign payment requests.') + '\n\n'\
              + _('The following alias providers are available:') + '\n'\
              + '\n'.join(['https://cryptoname.co/', 'http://xmr.link']) + '\n\n'\
              + 'For more information, see https://openalias.org'
        alias_label = HelpLabel(_('OpenAlias') + ':', msg)
        alias = self.config.get('alias', '')
        self.alias_e = QLineEdit(alias)
        self.set_alias_color()
        self.alias_e.editingFinished.connect(self.on_alias_edit)
        oa_widgets.append((alias_label, self.alias_e))

        # Services
        ssl_cert = self.config.get('ssl_certfile')
        ssl_cert_label = HelpLabel(
            _('SSL cert file') + ':',
            'certificate file, with intermediate certificates if needed')
        self.ssl_cert_e = QPushButton(ssl_cert)
        self.ssl_cert_e.clicked.connect(self.select_ssl_certfile)
        services_widgets.append((ssl_cert_label, self.ssl_cert_e))

        ssl_privkey = self.config.get('ssl_keyfile')
        ssl_privkey_label = HelpLabel(_('SSL key file') + ':', '')
        self.ssl_privkey_e = QPushButton(ssl_privkey)
        self.ssl_privkey_e.clicked.connect(self.select_ssl_privkey)
        services_widgets.append((ssl_privkey_label, self.ssl_privkey_e))

        ssl_domain_label = HelpLabel(_('SSL domain') + ':', '')
        self.ssl_domain_e = QLineEdit('')
        self.ssl_domain_e.setReadOnly(True)
        services_widgets.append((ssl_domain_label, self.ssl_domain_e))

        self.check_ssl_config()

        hostname = self.config.get('services_hostname', 'localhost')
        hostname_label = HelpLabel(
            _('Hostname') + ':', 'must match your SSL domain')
        self.hostname_e = QLineEdit(hostname)
        self.hostname_e.editingFinished.connect(self.on_hostname)
        services_widgets.append((hostname_label, self.hostname_e))

        payserver_cb = QCheckBox(_("Run PayServer"))
        payserver_cb.setToolTip("Configure a port")
        payserver_cb.setChecked(bool(self.config.get('run_payserver', False)))

        def on_payserver_checked(x):
            self.config.set_key('run_payserver', bool(x))
            self.payserver_port_e.setEnabled(bool(x))

        payserver_cb.stateChanged.connect(on_payserver_checked)
        payserver_port = self.config.get('payserver_port', 8002)
        self.payserver_port_e = QLineEdit(str(payserver_port))
        self.payserver_port_e.editingFinished.connect(self.on_payserver_port)
        self.payserver_port_e.setEnabled(
            self.config.get('run_payserver', False))
        services_widgets.append((payserver_cb, self.payserver_port_e))

        help_local_wt = _(
            """To setup a local watchtower, you must run Electrum on a machine
that is always connected to the internet. Configure a port if you want it to be public."""
        )
        local_wt_cb = QCheckBox(_("Run Watchtower"))
        local_wt_cb.setToolTip(help_local_wt)
        local_wt_cb.setChecked(bool(self.config.get('run_watchtower', False)))

        def on_local_wt_checked(x):
            self.config.set_key('run_watchtower', bool(x))
            self.local_wt_port_e.setEnabled(bool(x))

        local_wt_cb.stateChanged.connect(on_local_wt_checked)
        watchtower_port = self.config.get('watchtower_port', '')
        self.local_wt_port_e = QLineEdit(str(watchtower_port))
        self.local_wt_port_e.setEnabled(
            self.config.get('run_watchtower', False))
        self.local_wt_port_e.editingFinished.connect(self.on_watchtower_port)
        services_widgets.append((local_wt_cb, self.local_wt_port_e))

        # units
        units = base_units_list
        msg = (_(
            'Base unit of your wallet.'
        ) + '\n1 BTC = 1000 mBTC. 1 mBTC = 1000 bits. 1 bit = 100 sat.\n' + _(
            'This setting affects the Send tab, and all balance related fields.'
        ))
        unit_label = HelpLabel(_('Base unit') + ':', msg)
        unit_combo = QComboBox()
        unit_combo.addItems(units)
        unit_combo.setCurrentIndex(units.index(self.window.base_unit()))

        def on_unit(x, nz):
            unit_result = units[unit_combo.currentIndex()]
            if self.window.base_unit() == unit_result:
                return
            edits = self.window.amount_e, self.window.receive_amount_e
            amounts = [edit.get_amount() for edit in edits]
            self.window.decimal_point = base_unit_name_to_decimal_point(
                unit_result)
            self.config.set_key('decimal_point', self.window.decimal_point,
                                True)
            nz.setMaximum(self.window.decimal_point)
            self.window.history_list.update()
            self.window.request_list.update()
            self.window.address_list.update()
            for edit, amount in zip(edits, amounts):
                edit.setAmount(amount)
            self.window.update_status()

        unit_combo.currentIndexChanged.connect(lambda x: on_unit(x, nz))
        gui_widgets.append((unit_label, unit_combo))

        system_cameras = qrscanner._find_system_cameras()
        qr_combo = QComboBox()
        qr_combo.addItem("Default", "default")
        for camera, device in system_cameras.items():
            qr_combo.addItem(camera, device)
        #combo.addItem("Manually specify a device", config.get("video_device"))
        index = qr_combo.findData(self.config.get("video_device"))
        qr_combo.setCurrentIndex(index)
        msg = _("Install the zbar package to enable this.")
        qr_label = HelpLabel(_('Video Device') + ':', msg)
        qr_combo.setEnabled(qrscanner.libzbar is not None)
        on_video_device = lambda x: self.config.set_key(
            "video_device", qr_combo.itemData(x), True)
        qr_combo.currentIndexChanged.connect(on_video_device)
        gui_widgets.append((qr_label, qr_combo))

        colortheme_combo = QComboBox()
        colortheme_combo.addItem(_('Light'), 'default')
        colortheme_combo.addItem(_('Dark'), 'dark')
        index = colortheme_combo.findData(
            self.config.get('qt_gui_color_theme', 'default'))
        colortheme_combo.setCurrentIndex(index)
        colortheme_label = QLabel(_('Color theme') + ':')

        def on_colortheme(x):
            self.config.set_key('qt_gui_color_theme',
                                colortheme_combo.itemData(x), True)
            self.need_restart = True

        colortheme_combo.currentIndexChanged.connect(on_colortheme)
        gui_widgets.append((colortheme_label, colortheme_combo))

        updatecheck_cb = QCheckBox(
            _("Automatically check for software updates"))
        updatecheck_cb.setChecked(bool(self.config.get('check_updates',
                                                       False)))

        def on_set_updatecheck(v):
            self.config.set_key('check_updates', v == Qt.Checked, save=True)

        updatecheck_cb.stateChanged.connect(on_set_updatecheck)
        gui_widgets.append((updatecheck_cb, None))

        filelogging_cb = QCheckBox(_("Write logs to file"))
        filelogging_cb.setChecked(bool(self.config.get('log_to_file', False)))

        def on_set_filelogging(v):
            self.config.set_key('log_to_file', v == Qt.Checked, save=True)
            self.need_restart = True

        filelogging_cb.stateChanged.connect(on_set_filelogging)
        filelogging_cb.setToolTip(
            _('Debug logs can be persisted to disk. These are useful for troubleshooting.'
              ))
        gui_widgets.append((filelogging_cb, None))

        preview_cb = QCheckBox(_('Advanced preview'))
        preview_cb.setChecked(bool(self.config.get('advanced_preview', False)))
        preview_cb.setToolTip(
            _("Open advanced transaction preview dialog when 'Pay' is clicked."
              ))

        def on_preview(x):
            self.config.set_key('advanced_preview', x == Qt.Checked)

        preview_cb.stateChanged.connect(on_preview)
        tx_widgets.append((preview_cb, None))

        usechange_cb = QCheckBox(_('Use change addresses'))
        usechange_cb.setChecked(self.window.wallet.use_change)
        if not self.config.is_modifiable('use_change'):
            usechange_cb.setEnabled(False)

        def on_usechange(x):
            usechange_result = x == Qt.Checked
            if self.window.wallet.use_change != usechange_result:
                self.window.wallet.use_change = usechange_result
                self.window.wallet.storage.put('use_change',
                                               self.window.wallet.use_change)
                multiple_cb.setEnabled(self.window.wallet.use_change)

        usechange_cb.stateChanged.connect(on_usechange)
        usechange_cb.setToolTip(
            _('Using change addresses makes it more difficult for other people to track your transactions.'
              ))
        tx_widgets.append((usechange_cb, None))

        def on_multiple(x):
            multiple = x == Qt.Checked
            if self.wallet.multiple_change != multiple:
                self.wallet.multiple_change = multiple
                self.wallet.storage.put('multiple_change', multiple)

        multiple_change = self.wallet.multiple_change
        multiple_cb = QCheckBox(_('Use multiple change addresses'))
        multiple_cb.setEnabled(self.wallet.use_change)
        multiple_cb.setToolTip('\n'.join([
            _('In some cases, use up to 3 change addresses in order to break '
              'up large coin amounts and obfuscate the recipient address.'),
            _('This may result in higher transactions fees.')
        ]))
        multiple_cb.setChecked(multiple_change)
        multiple_cb.stateChanged.connect(on_multiple)
        tx_widgets.append((multiple_cb, None))

        def fmt_docs(key, klass):
            lines = [ln.lstrip(" ") for ln in klass.__doc__.split("\n")]
            return '\n'.join([key, "", " ".join(lines)])

        choosers = sorted(coinchooser.COIN_CHOOSERS.keys())
        if len(choosers) > 1:
            chooser_name = coinchooser.get_name(self.config)
            msg = _(
                'Choose coin (UTXO) selection method.  The following are available:\n\n'
            )
            msg += '\n\n'.join(
                fmt_docs(*item) for item in coinchooser.COIN_CHOOSERS.items())
            chooser_label = HelpLabel(_('Coin selection') + ':', msg)
            chooser_combo = QComboBox()
            chooser_combo.addItems(choosers)
            i = choosers.index(chooser_name) if chooser_name in choosers else 0
            chooser_combo.setCurrentIndex(i)

            def on_chooser(x):
                chooser_name = choosers[chooser_combo.currentIndex()]
                self.config.set_key('coin_chooser', chooser_name)

            chooser_combo.currentIndexChanged.connect(on_chooser)
            tx_widgets.append((chooser_label, chooser_combo))

        def on_unconf(x):
            self.config.set_key('confirmed_only', bool(x))

        conf_only = bool(self.config.get('confirmed_only', False))
        unconf_cb = QCheckBox(_('Spend only confirmed coins'))
        unconf_cb.setToolTip(_('Spend only confirmed inputs.'))
        unconf_cb.setChecked(conf_only)
        unconf_cb.stateChanged.connect(on_unconf)
        tx_widgets.append((unconf_cb, None))

        def on_outrounding(x):
            self.config.set_key('coin_chooser_output_rounding', bool(x))

        enable_outrounding = bool(
            self.config.get('coin_chooser_output_rounding', False))
        outrounding_cb = QCheckBox(_('Enable output value rounding'))
        outrounding_cb.setToolTip(
            _('Set the value of the change output so that it has similar precision to the other outputs.'
              ) + '\n' + _('This might improve your privacy somewhat.') +
            '\n' +
            _('If enabled, at most 100 satoshis might be lost due to this, per transaction.'
              ))
        outrounding_cb.setChecked(enable_outrounding)
        outrounding_cb.stateChanged.connect(on_outrounding)
        tx_widgets.append((outrounding_cb, None))

        block_explorers = sorted(util.block_explorer_info().keys())
        msg = _(
            'Choose which online block explorer to use for functions that open a web browser'
        )
        block_ex_label = HelpLabel(_('Online Block Explorer') + ':', msg)
        block_ex_combo = QComboBox()
        block_ex_combo.addItems(block_explorers)
        block_ex_combo.setCurrentIndex(
            block_ex_combo.findText(util.block_explorer(self.config)))

        def on_be(x):
            be_result = block_explorers[block_ex_combo.currentIndex()]
            self.config.set_key('block_explorer', be_result, True)

        block_ex_combo.currentIndexChanged.connect(on_be)
        tx_widgets.append((block_ex_label, block_ex_combo))

        # Fiat Currency
        hist_checkbox = QCheckBox()
        hist_capgains_checkbox = QCheckBox()
        fiat_address_checkbox = QCheckBox()
        ccy_combo = QComboBox()
        ex_combo = QComboBox()

        def update_currencies():
            if not self.window.fx: return
            currencies = sorted(
                self.fx.get_currencies(self.fx.get_history_config()))
            ccy_combo.clear()
            ccy_combo.addItems([_('None')] + currencies)
            if self.fx.is_enabled():
                ccy_combo.setCurrentIndex(
                    ccy_combo.findText(self.fx.get_currency()))

        def update_history_cb():
            if not self.fx: return
            hist_checkbox.setChecked(self.fx.get_history_config())
            hist_checkbox.setEnabled(self.fx.is_enabled())

        def update_fiat_address_cb():
            if not self.fx: return
            fiat_address_checkbox.setChecked(self.fx.get_fiat_address_config())

        def update_history_capgains_cb():
            if not self.fx: return
            hist_capgains_checkbox.setChecked(
                self.fx.get_history_capital_gains_config())
            hist_capgains_checkbox.setEnabled(hist_checkbox.isChecked())

        def update_exchanges():
            if not self.fx: return
            b = self.fx.is_enabled()
            ex_combo.setEnabled(b)
            if b:
                h = self.fx.get_history_config()
                c = self.fx.get_currency()
                exchanges = self.fx.get_exchanges_by_ccy(c, h)
            else:
                exchanges = self.fx.get_exchanges_by_ccy('USD', False)
            ex_combo.blockSignals(True)
            ex_combo.clear()
            ex_combo.addItems(sorted(exchanges))
            ex_combo.setCurrentIndex(
                ex_combo.findText(self.fx.config_exchange()))
            ex_combo.blockSignals(False)

        def on_currency(hh):
            if not self.fx: return
            b = bool(ccy_combo.currentIndex())
            ccy = str(ccy_combo.currentText()) if b else None
            self.fx.set_enabled(b)
            if b and ccy != self.fx.ccy:
                self.fx.set_currency(ccy)
            update_history_cb()
            update_exchanges()
            self.window.update_fiat()

        def on_exchange(idx):
            exchange = str(ex_combo.currentText())
            if self.fx and self.fx.is_enabled(
            ) and exchange and exchange != self.fx.exchange.name():
                self.fx.set_exchange(exchange)

        def on_history(checked):
            if not self.fx: return
            self.fx.set_history_config(checked)
            update_exchanges()
            self.window.history_model.refresh('on_history')
            if self.fx.is_enabled() and checked:
                self.fx.trigger_update()
            update_history_capgains_cb()

        def on_history_capgains(checked):
            if not self.fx: return
            self.fx.set_history_capital_gains_config(checked)
            self.window.history_model.refresh('on_history_capgains')

        def on_fiat_address(checked):
            if not self.fx: return
            self.fx.set_fiat_address_config(checked)
            self.window.address_list.refresh_headers()
            self.window.address_list.update()

        update_currencies()
        update_history_cb()
        update_history_capgains_cb()
        update_fiat_address_cb()
        update_exchanges()
        ccy_combo.currentIndexChanged.connect(on_currency)
        hist_checkbox.stateChanged.connect(on_history)
        hist_capgains_checkbox.stateChanged.connect(on_history_capgains)
        fiat_address_checkbox.stateChanged.connect(on_fiat_address)
        ex_combo.currentIndexChanged.connect(on_exchange)

        fiat_widgets = []
        fiat_widgets.append((QLabel(_('Fiat currency')), ccy_combo))
        fiat_widgets.append((QLabel(_('Source')), ex_combo))
        fiat_widgets.append((QLabel(_('Show history rates')), hist_checkbox))
        fiat_widgets.append((QLabel(_('Show capital gains in history')),
                             hist_capgains_checkbox))
        fiat_widgets.append((QLabel(_('Show Fiat balance for addresses')),
                             fiat_address_checkbox))

        tabs_info = [
            (gui_widgets, _('General')),
            (fee_widgets, _('Fees')),
            (tx_widgets, _('Transactions')),
            (fiat_widgets, _('Fiat')),
            (services_widgets, _('Services')),
            (oa_widgets, _('OpenAlias')),
        ]
        for widgets, name in tabs_info:
            tab = QWidget()
            tab_vbox = QVBoxLayout(tab)
            grid = QGridLayout()
            for a, b in widgets:
                i = grid.rowCount()
                if b:
                    if a:
                        grid.addWidget(a, i, 0)
                    grid.addWidget(b, i, 1)
                else:
                    grid.addWidget(a, i, 0, 1, 2)
            tab_vbox.addLayout(grid)
            tab_vbox.addStretch(1)
            tabs.addTab(tab, name)

        vbox.addWidget(tabs)
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CloseButton(self)))
        self.setLayout(vbox)
コード例 #55
0
ファイル: addlink.py プロジェクト: unnoisy-gypsy/persepolis
    def __init__(self, callback, flashgot_add_link_dictionary={}):
        super().__init__()
        self.callback = callback
        self.flashgot_add_link_dictionary = flashgot_add_link_dictionary

        #add change_name field
        self.change_name_horizontalLayout = QHBoxLayout()
        self.change_name_checkBox = QCheckBox(self.link_frame)
        self.change_name_checkBox.setText('Change File Name : ')
        self.change_name_horizontalLayout.addWidget(self.change_name_checkBox)

        self.change_name_lineEdit = QLineEdit(self.link_frame)
        self.change_name_horizontalLayout.addWidget(self.change_name_lineEdit)

        self.link_verticalLayout.addLayout(self.change_name_horizontalLayout)

        #entry initialization

        f = Open(setting_file)
        setting_file_lines = f.readlines()
        f.close()
        setting_dict_str = str(setting_file_lines[0].strip())
        setting_dict = ast.literal_eval(setting_dict_str)
        global connections
        connections = int(setting_dict['connections'])
        global download_path
        download_path = str(setting_dict['download_path'])

        global init_file
        init_file = str(
            home_address
        ) + "/.config/persepolis_download_manager/addlink_init_file"
        os.system("touch " + init_file)
        f = Open(init_file)
        init_file_lines = f.readlines()
        f.close()

        #initialization
        self.connections_spinBox.setValue(connections)
        self.download_folder_lineEdit.setText(download_path)
        self.download_folder_lineEdit.setEnabled(False)

        self.ok_pushButton.setEnabled(False)
        self.link_lineEdit.textChanged.connect(self.linkLineChanged)
        #AddLink - checking clipboard for link!
        if 'link' in self.flashgot_add_link_dictionary:
            self.link_lineEdit.setText(
                str(self.flashgot_add_link_dictionary['link']))
            del self.flashgot_add_link_dictionary['link']
        else:
            clipboard = QApplication.clipboard()
            text = clipboard.text()
            try:
                if ("tp:/" in text[2:6]) or ("tps:/" in text[2:7]):
                    self.link_lineEdit.setText(str(text))
            except:
                pass
#ip_lineEdit initialization
        try:
            self.ip_lineEdit.setText(init_file_lines[0].strip())
        except:
            pass

#proxy user lineEdit initialization
        try:
            self.proxy_user_lineEdit.setText(init_file_lines[2].strip())
        except:
            pass

#port_spinBox initialization
        try:
            self.port_spinBox.setValue(int(init_file_lines[1].strip()))
        except:
            pass

#download UserName initialization
        try:
            self.download_user_lineEdit.setText(init_file_lines[3].strip())
        except:
            pass
#connect folder_pushButton
        self.folder_pushButton.clicked.connect(self.changeFolder)

        #connect OK and canel button

        self.cancel_pushButton.clicked.connect(self.cancelButtonPressed)
        self.ok_pushButton.clicked.connect(self.okButtonPressed)
        #frames and checkBoxes
        self.proxy_frame.setEnabled(False)
        self.proxy_checkBox.toggled.connect(self.proxyFrame)

        self.download_frame.setEnabled(False)
        self.download_checkBox.toggled.connect(self.downloadFrame)

        self.limit_frame.setEnabled(False)
        self.limit_checkBox.toggled.connect(self.limitFrame)

        self.start_frame.setEnabled(False)
        self.start_checkBox.toggled.connect(self.startFrame)

        self.end_frame.setEnabled(False)
        self.end_checkBox.toggled.connect(self.endFrame)

        self.change_name_lineEdit.setEnabled(False)
        self.change_name_checkBox.toggled.connect(self.changeName)

        #check name of flashgot link
        if 'out' in self.flashgot_add_link_dictionary:
            self.change_name_lineEdit.setText(
                str(self.flashgot_add_link_dictionary['out']))
            self.change_name_checkBox.setChecked(True)
            del self.flashgot_add_link_dictionary['out']
コード例 #56
0
ファイル: addlink.py プロジェクト: unnoisy-gypsy/persepolis
class AddLinkWindow(AddLinkWindow_Ui):
    def __init__(self, callback, flashgot_add_link_dictionary={}):
        super().__init__()
        self.callback = callback
        self.flashgot_add_link_dictionary = flashgot_add_link_dictionary

        #add change_name field
        self.change_name_horizontalLayout = QHBoxLayout()
        self.change_name_checkBox = QCheckBox(self.link_frame)
        self.change_name_checkBox.setText('Change File Name : ')
        self.change_name_horizontalLayout.addWidget(self.change_name_checkBox)

        self.change_name_lineEdit = QLineEdit(self.link_frame)
        self.change_name_horizontalLayout.addWidget(self.change_name_lineEdit)

        self.link_verticalLayout.addLayout(self.change_name_horizontalLayout)

        #entry initialization

        f = Open(setting_file)
        setting_file_lines = f.readlines()
        f.close()
        setting_dict_str = str(setting_file_lines[0].strip())
        setting_dict = ast.literal_eval(setting_dict_str)
        global connections
        connections = int(setting_dict['connections'])
        global download_path
        download_path = str(setting_dict['download_path'])

        global init_file
        init_file = str(
            home_address
        ) + "/.config/persepolis_download_manager/addlink_init_file"
        os.system("touch " + init_file)
        f = Open(init_file)
        init_file_lines = f.readlines()
        f.close()

        #initialization
        self.connections_spinBox.setValue(connections)
        self.download_folder_lineEdit.setText(download_path)
        self.download_folder_lineEdit.setEnabled(False)

        self.ok_pushButton.setEnabled(False)
        self.link_lineEdit.textChanged.connect(self.linkLineChanged)
        #AddLink - checking clipboard for link!
        if 'link' in self.flashgot_add_link_dictionary:
            self.link_lineEdit.setText(
                str(self.flashgot_add_link_dictionary['link']))
            del self.flashgot_add_link_dictionary['link']
        else:
            clipboard = QApplication.clipboard()
            text = clipboard.text()
            try:
                if ("tp:/" in text[2:6]) or ("tps:/" in text[2:7]):
                    self.link_lineEdit.setText(str(text))
            except:
                pass
#ip_lineEdit initialization
        try:
            self.ip_lineEdit.setText(init_file_lines[0].strip())
        except:
            pass

#proxy user lineEdit initialization
        try:
            self.proxy_user_lineEdit.setText(init_file_lines[2].strip())
        except:
            pass

#port_spinBox initialization
        try:
            self.port_spinBox.setValue(int(init_file_lines[1].strip()))
        except:
            pass

#download UserName initialization
        try:
            self.download_user_lineEdit.setText(init_file_lines[3].strip())
        except:
            pass
#connect folder_pushButton
        self.folder_pushButton.clicked.connect(self.changeFolder)

        #connect OK and canel button

        self.cancel_pushButton.clicked.connect(self.cancelButtonPressed)
        self.ok_pushButton.clicked.connect(self.okButtonPressed)
        #frames and checkBoxes
        self.proxy_frame.setEnabled(False)
        self.proxy_checkBox.toggled.connect(self.proxyFrame)

        self.download_frame.setEnabled(False)
        self.download_checkBox.toggled.connect(self.downloadFrame)

        self.limit_frame.setEnabled(False)
        self.limit_checkBox.toggled.connect(self.limitFrame)

        self.start_frame.setEnabled(False)
        self.start_checkBox.toggled.connect(self.startFrame)

        self.end_frame.setEnabled(False)
        self.end_checkBox.toggled.connect(self.endFrame)

        self.change_name_lineEdit.setEnabled(False)
        self.change_name_checkBox.toggled.connect(self.changeName)

        #check name of flashgot link
        if 'out' in self.flashgot_add_link_dictionary:
            self.change_name_lineEdit.setText(
                str(self.flashgot_add_link_dictionary['out']))
            self.change_name_checkBox.setChecked(True)
            del self.flashgot_add_link_dictionary['out']

#activate frames if checkBoxes checked

    def proxyFrame(self, checkBox):

        if self.proxy_checkBox.isChecked() == True:
            self.proxy_frame.setEnabled(True)
        else:
            self.proxy_frame.setEnabled(False)

    def downloadFrame(self, checkBox):

        if self.download_checkBox.isChecked() == True:
            self.download_frame.setEnabled(True)
        else:
            self.download_frame.setEnabled(False)

    def limitFrame(self, checkBox):

        if self.limit_checkBox.isChecked() == True:
            self.limit_frame.setEnabled(True)
        else:
            self.limit_frame.setEnabled(False)

    def startFrame(self, checkBox):

        if self.start_checkBox.isChecked() == True:
            self.start_frame.setEnabled(True)
        else:
            self.start_frame.setEnabled(False)

    def endFrame(self, checkBox):

        if self.end_checkBox.isChecked() == True:
            self.end_frame.setEnabled(True)
        else:
            self.end_frame.setEnabled(False)

    def changeFolder(self, button):
        fname = QFileDialog.getExistingDirectory(self, 'Open f', download_path)
        if os.path.isdir(fname):
            self.download_folder_lineEdit.setText(fname)

    def linkLineChanged(self, lineEdit):
        if str(self.link_lineEdit.text()) == '':
            self.ok_pushButton.setEnabled(False)
        else:
            self.ok_pushButton.setEnabled(True)

    def changeName(self, checkBoxes):
        if self.change_name_checkBox.isChecked() == True:
            self.change_name_lineEdit.setEnabled(True)
        else:
            self.change_name_lineEdit.setEnabled(False)

#close window if cancelButton Pressed

    def cancelButtonPressed(self, button):
        self.close()

    def okButtonPressed(self, button):
        global init_file
        f = Open(init_file, "w")
        #writing user's input data to init file
        for i in self.ip_lineEdit.text(), self.port_spinBox.value(
        ), self.proxy_user_lineEdit.text(), self.download_user_lineEdit.text():
            f.writelines(str(i) + "\n")
        f.close()

        if self.proxy_checkBox.isChecked() == False:
            ip = None
            port = None
            proxy_user = None
            proxy_passwd = None
        else:
            ip = self.ip_lineEdit.text()
            if not (ip):
                ip = None
            port = self.port_spinBox.value()
            if not (port):
                port = None
            proxy_user = self.proxy_user_lineEdit.text()
            if not (proxy_user):
                proxy_user = None
            proxy_passwd = self.proxy_pass_lineEdit.text()
            if not (proxy_passwd):
                proxy_passwd = None

        if self.download_checkBox.isChecked() == False:
            download_user = None
            download_passwd = None
        else:
            download_user = self.download_user_lineEdit.text()
            if not (download_user):
                download_user = None
            download_passwd = self.download_pass_lineEdit.text()
            if not (download_passwd):
                download_passwd = None

        if self.limit_checkBox.isChecked() == False:
            limit = 0
        else:
            if self.limit_comboBox.currentText() == "KB/S":
                limit = str(self.limit_spinBox.value()) + str("K")
            else:
                limit = str(self.limit_spinBox.value()) + str("M")

        if self.start_checkBox.isChecked() == False:
            start_hour = None
            start_minute = None
        else:
            start_hour = str(self.start_hour_spinBox.value())
            start_minute = str(self.start_minute_spinBox.value())

        if self.end_checkBox.isChecked() == False:
            end_hour = None
            end_minute = None
        else:
            end_hour = str(self.end_hour_spinBox.value())
            end_minute = str(self.end_minute_spinBox.value())

        if self.change_name_checkBox.isChecked() == False:
            out = None
        else:
            out = str(self.change_name_lineEdit.text())

        link = self.link_lineEdit.text()

        connections = self.connections_spinBox.value()
        download_path = self.download_folder_lineEdit.text()

        if not ('referer' in self.flashgot_add_link_dictionary):
            self.flashgot_add_link_dictionary['referer'] = None

        if not ('header' in self.flashgot_add_link_dictionary):
            self.flashgot_add_link_dictionary['header'] = None

        if not ('user-agent' in self.flashgot_add_link_dictionary):
            self.flashgot_add_link_dictionary['user-agent'] = None

        if not ('load-cookies' in self.flashgot_add_link_dictionary):
            self.flashgot_add_link_dictionary['load-cookies'] = None

        final_download_path = None
        self.add_link_dictionary = {
            'out': out,
            'final_download_path': final_download_path,
            'start_hour': start_hour,
            'start_minute': start_minute,
            'end_hour': end_hour,
            'end_minute': end_minute,
            'link': link,
            'ip': ip,
            'port': port,
            'proxy_user': proxy_user,
            'proxy_passwd': proxy_passwd,
            'download_user': download_user,
            'download_passwd': download_passwd,
            'connections': connections,
            'limit': limit,
            'download_path': download_path
        }
        for i in self.flashgot_add_link_dictionary.keys():
            self.add_link_dictionary[i] = self.flashgot_add_link_dictionary[i]

        del self.flashgot_add_link_dictionary
        self.callback(self.add_link_dictionary)

        self.close()
コード例 #57
0
class ControlWindow(QWidget):
    def __init__(self, mainWindow=None, handler=None, parent=None):
        super(ControlWindow, self).__init__(parent=parent)
        self.handler = handler
        self.mainWindow = mainWindow
        self.activeFrames = []
        self.activeGaussians = []
        self.frame_toggle = True
        self.gaussian_toggle = True
        self.heatmap_toggle = True
        self.AOIs_toggle = True
        self.AOILines_toggle = True
        self.gaze_paths_toggle = True

        self.horizontalLayout = QHBoxLayout(self)

        self.sliderX = Slider(0, self.handler.aois[0][:, -1].max())
        self.sliderX.slider.setValue(0)
        self.horizontalLayout.addWidget(self.sliderX)
        self.sliderX.slider.valueChanged.connect(
            lambda: self.translateX(self.sliderX.slider.value()))
        #

        self.sliderY = Slider(0, self.handler.frame_size[1])
        v = .5 * self.handler.frame_size[1]
        self.sliderY.slider.setValue(v)
        self.translateY(v)
        self.horizontalLayout.addWidget(self.sliderY)
        self.sliderY.slider.valueChanged.connect(
            lambda: self.translateY(self.sliderY.slider.value()))
        #

        self.sliderZ = Slider(0, self.handler.frame_size[0])
        v = .5 * self.handler.frame_size[0]
        self.sliderZ.slider.setValue(v)
        self.translateZ(v)
        self.horizontalLayout.addWidget(self.sliderZ)
        self.sliderZ.slider.valueChanged.connect(
            lambda: self.translateZ(self.sliderZ.slider.value()))
        #

        # vertical button layout
        self.buttonLayout = QVBoxLayout()
        spacer = QSpacerItem(10, 30)
        self.buttonLayout.addItem(spacer)

        # button to de/activate aois:
        self.buttonAOIs = QCheckBox('aois (volume)')
        self.buttonAOIs.setChecked(True)
        self.buttonAOIs.clicked.connect(self.toggleAOIs)
        self.buttonLayout.addWidget(self.buttonAOIs)

        # button to de/activate aois:
        self.buttonAOIs = QCheckBox('aois (line)')
        self.buttonAOIs.setChecked(True)
        self.buttonAOIs.clicked.connect(self.toggleAOILines)
        self.buttonLayout.addWidget(self.buttonAOIs)

        # button to de/activate gaze paths:
        self.buttonGaze = QCheckBox('gaze paths')
        self.buttonGaze.setChecked(True)
        self.buttonGaze.clicked.connect(self.toggleGaze)
        self.buttonLayout.addWidget(self.buttonGaze)

        # button to de/activate heatmaps:
        self.buttonHeatmap = QCheckBox('heatmaps')
        self.buttonHeatmap.setChecked(True)
        self.buttonHeatmap.clicked.connect(self.toggleHeatmaps)
        self.buttonLayout.addWidget(self.buttonHeatmap)

        # button to de/activate gaussians:
        self.buttonGaussian = QCheckBox('gaze points')
        self.buttonGaussian.setChecked(True)
        self.buttonGaussian.clicked.connect(self.toggleGaussians)
        self.buttonLayout.addWidget(self.buttonGaussian)

        # button to de/activate gaussians:
        self.buttonFrame = QCheckBox('video frames')
        self.buttonFrame.setChecked(True)
        self.buttonFrame.clicked.connect(self.toggleFrames)
        self.buttonLayout.addWidget(self.buttonFrame)

        self.buttonLayout.addStretch()
        self.horizontalLayout.addLayout(self.buttonLayout)

        # vertical selection box layout
        self.selectionLayout = QVBoxLayout()
        spacer = QSpacerItem(10, 30)
        self.selectionLayout.addItem(spacer)

        self.aoiSelection = QToolButton()
        self.aoiSelection.setText('select AOI (volume)')
        self.aoiSelectionMenu = QMenu()
        for t in self.handler.aoi_titles:
            a = self.aoiSelectionMenu.addAction(t)
            a.setCheckable(True)
            a.setChecked(True)
            a.changed.connect(self.toggleSingleAOIs)
        self.aoiSelection.setMenu(self.aoiSelectionMenu)
        self.aoiSelection.setPopupMode(QToolButton.InstantPopup)
        self.selectionLayout.addWidget(self.aoiSelection)

        self.aoiLineSelection = QToolButton()
        self.aoiLineSelection.setText('select AOI (lines)')
        self.aoiLineSelectionMenu = QMenu()
        for t in self.handler.aoi_titles:
            a = self.aoiLineSelectionMenu.addAction(t)
            a.setCheckable(True)
            a.setChecked(True)
            a.changed.connect(self.toggleSingleAOILines)
        self.aoiLineSelection.setMenu(self.aoiLineSelectionMenu)
        self.aoiLineSelection.setPopupMode(QToolButton.InstantPopup)
        self.selectionLayout.addWidget(self.aoiLineSelection)

        self.gazePathsSelection = QToolButton()
        self.gazePathsSelection.setText('select gaze paths')
        self.gazePathsSelectionMenu = QMenu()
        for t in self.handler.gp_titles:
            a = self.gazePathsSelectionMenu.addAction(t)
            a.setCheckable(True)
            a.setChecked(True)
            a.changed.connect(self.toggleSingleGazePath)
        self.gazePathsSelection.setMenu(self.gazePathsSelectionMenu)
        self.gazePathsSelection.setPopupMode(QToolButton.InstantPopup)
        self.selectionLayout.addWidget(self.gazePathsSelection)

        self.label = QLabel('specify key frames')
        self.lineEdit = QLineEdit()
        self.lineEditButton = QPushButton('ok')
        self.lineEditButton.clicked.connect(self.updateKeyFrames)
        self.selectionLayout.addWidget(self.label)
        self.selectionLayout.addWidget(self.lineEdit)
        self.selectionLayout.addWidget(self.lineEditButton)

        self.selectionLayout.addStretch()
        self.horizontalLayout.addLayout(self.selectionLayout)

        spacer = QSpacerItem(0, 0, QSizePolicy.Expanding,
                             QSizePolicy.Expanding)
        #self.horizontalLayout.addItem(spacer)
        self.show()

    def updateKeyFrames(self):
        if not self.handler.keyFrames == []:
            for kf in self.handler.keyFrames:
                self.mainWindow.plotWindow.removeItem(kf)
                del kf
        text = re.split(' | , ; ', self.lineEdit.text())
        key_frames = [int(t) for t in text if t.isnumeric()]
        self.handler.loadKeyFrames(key_frames)
        for kf in self.handler.keyFrames:
            self.mainWindow.plotWindow.addItem(kf)

    def toggleFrames(self):
        self.frame_toggle = not self.frame_toggle
        for fx in self.activeFrames:
            frame = self.handler.frames[fx]
            frame.setVisible(self.frame_toggle)

    def toggleGaussians(self):
        self.gaussian_toggle = not self.gaussian_toggle
        for gx in self.activeGaussians:
            gaussian = self.handler.gaussians[gx]
            gaussian.setVisible(self.gaussian_toggle)

    def toggleAllGaussians(self):
        self.gaussian_toggle = not self.gaussian_toggle
        for gx in self.handler.gaussians:
            gx.setVisible(self.gaussian_toggle)

    # gaze paths
    def toggleGaze(self):
        self.gaze_paths_toggle = not self.gaze_paths_toggle
        self.toggleSingleGazePath()

    def toggleSingleGazePath(self):
        for a in self.gazePathsSelectionMenu.actions():
            idx = self.handler.gp_titles.index(a.text())
            self.handler.gazePointsLinePlotItems[idx].setVisible(
                a.isChecked() * self.gaze_paths_toggle)

    # AOI meshes
    def toggleAOIs(self):
        self.AOIs_toggle = not self.AOIs_toggle
        self.toggleSingleAOIs()

    def toggleSingleAOIs(self):
        for a in self.aoiSelectionMenu.actions():
            idx = self.handler.aoi_titles.index(a.text())
            self.handler.aoiMeshes[idx].setVisible(a.isChecked() *
                                                   self.AOIs_toggle)

    # AOI lines
    def toggleAOILines(self):
        self.AOILines_toggle = not self.AOILines_toggle
        self.toggleSingleAOILines()

    def toggleSingleAOILines(self):
        for a in self.aoiLineSelectionMenu.actions():
            idx = self.handler.aoi_titles.index(a.text())
            for line in self.handler.aoiLines[idx]:
                line.setVisible(a.isChecked() * self.AOILines_toggle)

    def toggleHeatmaps(self):
        self.heatmap_toggle = not self.heatmap_toggle
        self.handler.XYHeatmap.setVisible(self.heatmap_toggle)
        self.handler.XZHeatmap.setVisible(self.heatmap_toggle)

    def translateX(self, value):
        self.mainWindow.plotWindow.opts['center'].setX(
            value * self.handler.image_spacing)
        if value < len(self.handler.frames):
            self.showFrameNum(value)
            self.showGaussianNum(value)
        self.mainWindow.plotWindow.update()

    def translateY(self, value):
        self.mainWindow.plotWindow.opts['center'].setY(value)
        self.mainWindow.plotWindow.update()

    def translateZ(self, value):
        self.mainWindow.plotWindow.opts['center'].setZ(-value)
        self.mainWindow.plotWindow.update()

    def showFrameNum(self, value):
        for frame in self.handler.frames:
            frame.setVisible(False)
        if self.frame_toggle:
            self.handler.frames[value].setVisible(True)
        self.activeFrames = [value]

    def showGaussianNum(self, value):
        for gaussian in self.handler.gaussians:
            gaussian.setVisible(False)
        if self.gaussian_toggle:
            self.handler.gaussians[value].setVisible(True)
        self.activeGaussians = [value]

    def showGazePointLines(self, line_idxs):
        for line in self.handler.gazePointsLinePlotItems:
            line.setVisible(False)
        for idx in line_idxs:
            self.handler.gazePointsLinePlotItems[idx].setVisible(True)
コード例 #58
0
ファイル: HeartDock.py プロジェクト: behollis/pyQt-muView
    def init(self,pView,_pmesh,_smesh,_fdata,parent):
        self.dfield = 0
        self.pdata  = 0
        self.pmesh  = _pmesh
        self.tdata  = _smesh
        self.fdata  = _fdata
        
        self.vp_widget = QSplitter( Qt.Vertical )
        self.sp_widget = QSplitter( Qt.Horizontal )
    
        sp0 = QSplitter( Qt.Horizontal )
        sp1 = QSplitter( Qt.Horizontal )
    
        #self.pr_widget = ParallelCoordinates( 0 )
        
        self.tb_widget = QTabWidget()
        
        #sp0.addWidget( self.render_engine.re )
        #sp0.addWidget( self.render_engine.pca )
    
        '''
        sp1.addWidget( self.render_engine.re2[0]) )
        sp1.addWidget( self.render_engine.re2[1]) )
        sp1.addWidget( self.render_engine.re2[2]) )
        '''
        
        self.vp_widget.addWidget( sp0 )
        self.vp_widget.addWidget( sp1 )
#        self.vp_widget.addWidget( self.pr_widget )
        self.sp_widget.addWidget( self.vp_widget )
        self.sp_widget.addWidget( self.tb_widget )
                
        self.setWidget( self.sp_widget )
    
        drawBoxWidget = QControlWidget.QGroupControlWidget()

        draw0 = drawBoxWidget.addRadioButton('Points')
        draw1 = drawBoxWidget.addRadioButton('Network')
        draw2 = drawBoxWidget.addRadioButton('Volume Rendering')
        draw3 = drawBoxWidget.addRadioButton('Isosurfacing')
        draw4 = drawBoxWidget.addRadioButton('Distance Field')

        draw0.setChecked(True)

        '''
        draw0.clicked.connect(&(render_engine).setDrawModePoints)
        draw1.clicked.connect(&(render_engine).setDrawModeNetwork)
        draw2.clicked.connect(&(render_engine).setDrawModeVolumeRendering)
        draw3.clicked.connect(&(render_engine).setDrawModeIsosurfacing)
        draw4.clicked.connect(&(render_engine).setDrawModeDistanceField)
        '''

        colorBoxWidget = QWidget()
    
        color0 = QRadioButton( 'Dimension Value' )
        color7 = QRadioButton( 'Min Value' )
        color1 = QRadioButton( 'Mean Value' )
        color8 = QRadioButton( 'Max Value' )
        color2 = QRadioButton( 'St Dev' )
        color3 = QRadioButton( 'Clustering' )
        color4 = QRadioButton( 'Isovalue' )
        color5 = QRadioButton( 'PCA Painting' )
        color6 = QRadioButton( 'Fiber Direction' )
        color0.setChecked(True)

        dimension_label = QLabel('Dimension')
        dimension_spinner = QSpinBox()  
        dimension_spinner.setRange(0,40)
        dimension_spinner.setValue(0)
        

        cluster_count_label = QLabel('Clusters')
        cluster_count_spinner = QSpinBox( )
        cluster_count_spinner.setRange(2,40)
        cluster_count_spinner.setValue( 12 )

        cluster_type = QControlWidget.QControlWidget()
    
        ct0 = cluster_type.addRadioButton( 'L2 Norm' )
        ct1 = cluster_type.addRadioButton( 'Pearson Correlation' )
        ct2 = cluster_type.addRadioButton( 'Histogram Difference' )
        ct0.setChecked( True )
        
        '''
        ct0.clicked.connect(&(render_engine).setClusterTypeL2Norm)
        ct1.clicked.connect(&(render_engine).setClusterTypePearson)
        ct2.clicked.connect(&(render_engine).setClusterTypeHistogram)
        '''

        cluster_iteration_label = QLabel( 'Iterations' )
        cluster_iteration_spinner = QSpinBox( )
        cluster_iteration_spinner.setRange(1,40)
        cluster_iteration_spinner.setValue( 5 )

        cluster_histogram = QCheckBox( 'Histogram' )
        cluster_histogram.setChecked( True )

        cluster_recalculate = QPushButton( self.tr('Recalculate') )
        pca_sel_color = QPushButton( self.tr('PCA: Select Paint Color') )

        pca_dim0_label = QLabel(self.tr('PCA X Dimension'))
        pca_dim0_spinner = QSpinBox( )
        pca_dim0_spinner.setRange(0,100)
        pca_dim0_spinner.setValue( 0 )

        pca_dim1_label = QLabel(self.tr('PCA Y Dimension'))
        pca_dim1_spinner = QSpinBox( )
        pca_dim1_spinner.setRange(0,100)
        pca_dim1_spinner.setValue( 1 )

        '''
        color0.clicked.connect(&(render_engine).setColorModeDimension)
        color1.clicked.connect(&(render_engine).setColorModeMedian)
        color2.clicked.connect(&(render_engine).setColorModeStDev)
        color3.clicked.connect(&(render_engine).setColorModeCluster)
        color4.clicked.connect(&(render_engine).setColorModeIsovalue)
        color5.clicked.connect(&(render_engine).setColorModePCA)
        color6.clicked.connect(&(render_engine).setColorModeFibers)
        color7.clicked.connect(&(render_engine).setColorModeMin)
        color8.clicked.connect(&(render_engine).setColorModeMax)

        pca_sel_color.clicked.connect(&(render_engine.pca).selectPaintColor)
        dimension_spinner.valueChanged.connect(&(render_engine).setDimension)

        cluster_count_spinner.valueChanged.connect(&(render_engine).setClusterCount)
        cluster_iteration_spinner.valueChanged.connect(&(render_engine).setClusterIterations)
        cluster_recalculate.clicked.connect(&(render_engine).setClusterRecalculate)
        cluster_histogram.clicked.connect(&(render_engine).setClusterHistogram)
        '''

        '''
        color0.clicked.connect(self.pr_widget.Reset)
        color1.clicked.connect(self.pr_widget.Reset)
        color2.clicked.connect(self.pr_widget.Reset)
        color3.clicked.connect(self.pr_widget.Reset)
        color4.clicked.connect(self.pr_widget.Reset)
        color5.clicked.connect(self.pr_widget.Reset)
        color6.clicked.connect(self.pr_widget.Reset)
        color7.clicked.connect(self.pr_widget.Reset)
        color8.clicked.connect(self.pr_widget.Reset)
        '''

        #dimension_spinner.valueChanged.connect(self.pr_widget.Reset)

        #cluster_count_spinner.valueChanged.connect(self.pr_widget.Reset)
        #cluster_iteration_spinner.valueChanged.connect(self.pr_widget.Reset)
        #cluster_recalculate.clicked.connect(self.pr_widget.Reset)
        #cluster_histogram.clicked.connect(self.pr_widget.Reset)

#        pca_dim0_spinner.valueChanged.connect(&(render_engine.pca).ModifyPCADim0)
#        pca_dim1_spinner.valueChanged.connect(&(render_engine.pca).ModifyPCADim1)

        row = 0
        colorLayout = QGridLayout( )
        
        row+=1;colorLayout.addWidget( color0,             row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( dimension_label,            row,   1, 1, 1 )
        row+=1;colorLayout.addWidget( dimension_spinner,          row, 2, 1, 1 )
        row+=1;colorLayout.addWidget( color1,                     row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( color7,                     row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( color8,                     row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( color2,                     row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( color3,                     row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( cluster_histogram,          row, 1, 1, 2 )
        colorLayout.addWidget( cluster_count_label,        row,   1, 1, 1 )
        row+=1;colorLayout.addWidget( cluster_count_spinner,      row, 2, 1, 1 )
        #row+=1;colorLayout.addWidget( cluster_type,               row, 1, 1, 1 )
        colorLayout.addWidget( cluster_iteration_label,    row,   1, 1, 1 )
        row+=1;colorLayout.addWidget( cluster_iteration_spinner,  row, 2, 1, 1 )
        row+=1;colorLayout.addWidget( cluster_recalculate,        row, 1, 1, 2 )
        row+=1;colorLayout.addWidget( color4,                     row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( color5,                     row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( pca_sel_color,              row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( color6,                     row, 0, 1, 3 )
        row+=1;colorLayout.addWidget( pca_dim0_label,             row,   1, 1, 1 )
        row+=1;colorLayout.addWidget( pca_dim0_spinner,           row, 2, 1, 1 )
        colorLayout.addWidget( pca_dim1_label,             row,   1, 1, 1 )
        row+=1;colorLayout.addWidget( pca_dim1_spinner,           row, 2, 1, 1 )
        colorLayout.setRowStretch( row, 1 )
        colorBoxWidget.setLayout( colorLayout )
        
        
        #render_engine.SetParallelCoordinateView( self.pr_widget )
        #render_engine.SetData( self.pdata, self.pmesh, self.tdata )
        #render_engine.SetFiberData( selffdata );
        
        self.tb_widget.setTabPosition( self.tb_widget.West )
        self.tb_widget.addTab( drawBoxWidget, self.tr( 'Draw Mode' ) )
        self.tb_widget.addTab( colorBoxWidget, self.tr( 'Color Mode' ) )
コード例 #59
0
    def __init__(self, mainWindow=None, handler=None, parent=None):
        super(ControlWindow, self).__init__(parent=parent)
        self.handler = handler
        self.mainWindow = mainWindow
        self.activeFrames = []
        self.activeGaussians = []
        self.frame_toggle = True
        self.gaussian_toggle = True
        self.heatmap_toggle = True
        self.AOIs_toggle = True
        self.AOILines_toggle = True
        self.gaze_paths_toggle = True

        self.horizontalLayout = QHBoxLayout(self)

        self.sliderX = Slider(0, self.handler.aois[0][:, -1].max())
        self.sliderX.slider.setValue(0)
        self.horizontalLayout.addWidget(self.sliderX)
        self.sliderX.slider.valueChanged.connect(
            lambda: self.translateX(self.sliderX.slider.value()))
        #

        self.sliderY = Slider(0, self.handler.frame_size[1])
        v = .5 * self.handler.frame_size[1]
        self.sliderY.slider.setValue(v)
        self.translateY(v)
        self.horizontalLayout.addWidget(self.sliderY)
        self.sliderY.slider.valueChanged.connect(
            lambda: self.translateY(self.sliderY.slider.value()))
        #

        self.sliderZ = Slider(0, self.handler.frame_size[0])
        v = .5 * self.handler.frame_size[0]
        self.sliderZ.slider.setValue(v)
        self.translateZ(v)
        self.horizontalLayout.addWidget(self.sliderZ)
        self.sliderZ.slider.valueChanged.connect(
            lambda: self.translateZ(self.sliderZ.slider.value()))
        #

        # vertical button layout
        self.buttonLayout = QVBoxLayout()
        spacer = QSpacerItem(10, 30)
        self.buttonLayout.addItem(spacer)

        # button to de/activate aois:
        self.buttonAOIs = QCheckBox('aois (volume)')
        self.buttonAOIs.setChecked(True)
        self.buttonAOIs.clicked.connect(self.toggleAOIs)
        self.buttonLayout.addWidget(self.buttonAOIs)

        # button to de/activate aois:
        self.buttonAOIs = QCheckBox('aois (line)')
        self.buttonAOIs.setChecked(True)
        self.buttonAOIs.clicked.connect(self.toggleAOILines)
        self.buttonLayout.addWidget(self.buttonAOIs)

        # button to de/activate gaze paths:
        self.buttonGaze = QCheckBox('gaze paths')
        self.buttonGaze.setChecked(True)
        self.buttonGaze.clicked.connect(self.toggleGaze)
        self.buttonLayout.addWidget(self.buttonGaze)

        # button to de/activate heatmaps:
        self.buttonHeatmap = QCheckBox('heatmaps')
        self.buttonHeatmap.setChecked(True)
        self.buttonHeatmap.clicked.connect(self.toggleHeatmaps)
        self.buttonLayout.addWidget(self.buttonHeatmap)

        # button to de/activate gaussians:
        self.buttonGaussian = QCheckBox('gaze points')
        self.buttonGaussian.setChecked(True)
        self.buttonGaussian.clicked.connect(self.toggleGaussians)
        self.buttonLayout.addWidget(self.buttonGaussian)

        # button to de/activate gaussians:
        self.buttonFrame = QCheckBox('video frames')
        self.buttonFrame.setChecked(True)
        self.buttonFrame.clicked.connect(self.toggleFrames)
        self.buttonLayout.addWidget(self.buttonFrame)

        self.buttonLayout.addStretch()
        self.horizontalLayout.addLayout(self.buttonLayout)

        # vertical selection box layout
        self.selectionLayout = QVBoxLayout()
        spacer = QSpacerItem(10, 30)
        self.selectionLayout.addItem(spacer)

        self.aoiSelection = QToolButton()
        self.aoiSelection.setText('select AOI (volume)')
        self.aoiSelectionMenu = QMenu()
        for t in self.handler.aoi_titles:
            a = self.aoiSelectionMenu.addAction(t)
            a.setCheckable(True)
            a.setChecked(True)
            a.changed.connect(self.toggleSingleAOIs)
        self.aoiSelection.setMenu(self.aoiSelectionMenu)
        self.aoiSelection.setPopupMode(QToolButton.InstantPopup)
        self.selectionLayout.addWidget(self.aoiSelection)

        self.aoiLineSelection = QToolButton()
        self.aoiLineSelection.setText('select AOI (lines)')
        self.aoiLineSelectionMenu = QMenu()
        for t in self.handler.aoi_titles:
            a = self.aoiLineSelectionMenu.addAction(t)
            a.setCheckable(True)
            a.setChecked(True)
            a.changed.connect(self.toggleSingleAOILines)
        self.aoiLineSelection.setMenu(self.aoiLineSelectionMenu)
        self.aoiLineSelection.setPopupMode(QToolButton.InstantPopup)
        self.selectionLayout.addWidget(self.aoiLineSelection)

        self.gazePathsSelection = QToolButton()
        self.gazePathsSelection.setText('select gaze paths')
        self.gazePathsSelectionMenu = QMenu()
        for t in self.handler.gp_titles:
            a = self.gazePathsSelectionMenu.addAction(t)
            a.setCheckable(True)
            a.setChecked(True)
            a.changed.connect(self.toggleSingleGazePath)
        self.gazePathsSelection.setMenu(self.gazePathsSelectionMenu)
        self.gazePathsSelection.setPopupMode(QToolButton.InstantPopup)
        self.selectionLayout.addWidget(self.gazePathsSelection)

        self.label = QLabel('specify key frames')
        self.lineEdit = QLineEdit()
        self.lineEditButton = QPushButton('ok')
        self.lineEditButton.clicked.connect(self.updateKeyFrames)
        self.selectionLayout.addWidget(self.label)
        self.selectionLayout.addWidget(self.lineEdit)
        self.selectionLayout.addWidget(self.lineEditButton)

        self.selectionLayout.addStretch()
        self.horizontalLayout.addLayout(self.selectionLayout)

        spacer = QSpacerItem(0, 0, QSizePolicy.Expanding,
                             QSizePolicy.Expanding)
        #self.horizontalLayout.addItem(spacer)
        self.show()
コード例 #60
0
ファイル: gui.py プロジェクト: Flperez/ComparePose3d
class Gui(QWidget):
    def __init__(self,map,interface):
        super(Gui, self).__init__()

        # Estimated
        self.xestimated = []
        self.yestimated = []
        self.zestimated = []
        self.Restimated = []
        self.Yestimated = []
        self.Pestimated = []

        self.xreal = []
        self.yreal = []
        self.zreal = []
        self.Rreal = []
        self.Yreal = []
        self.Preal = []
        self.interface = interface
        self.initUI(map=map)


    def initUI(self,map):
        ### initialize
        self.filename = map

        # Estimated
        self.pose3dEstimated = []
        self.pose3dReal = []
        self.error = []

        self.loadpathXYZ()


        ### Text out
        self.textbox = QLineEdit(self)
        self.textbox.move(20,480+10)
        self.textbox.resize(640,80)



        ### To select a different graph
        self.showNow = "showXYZ"
        
        ## XYZ
        self.cbxyz = QCheckBox('Show XYZ', self)
        self.cbxyz.move(640+40, 100)
        self.cbxyz.toggle()
        self.cbxyz.setChecked(True)
        self.cbxyz.stateChanged.connect(self.showXYZ)

        ## RPY
        self.cbRPY = QCheckBox('Show RPY', self)
        self.cbRPY.move(640+40, 200)
        self.cbRPY.toggle()
        self.cbRPY.setChecked(False)
        self.cbRPY.stateChanged.connect(self.showRPY)

        ## Error
        self.cbError = QCheckBox('Show Error', self)
        self.cbError.move(640+40, 300)
        self.cbError.toggle()
        self.cbError.setChecked(False)
        self.cbError.stateChanged.connect(self.showError)



        ### Saving results
        ButtonSave = QPushButton('Save results', self)
        ButtonSave.setCheckable(True)
        ButtonSave.move(640+50, 480+30)
        ButtonSave.clicked[bool].connect(self.savingResult)

        # Plot map
        self.main_widget = QWidget(self)
        l = QVBoxLayout(self.main_widget)
        self.dc = MyDynamicMplCanvas(parent=self.main_widget,option=self.showNow,
                                        map=self.map, xsim=self.xestimated, ysim=self.yestimated,
                                        xreal=self.xreal, yreal=self.yreal,interface=self.interface)
        l.addWidget(self.dc)




        self.setGeometry(600, 600, 250, 150)
        self.setWindowTitle('Compare')
        self.setFixedSize(10+640+20+150,600)

    def setInterface(self,interface):
        self.interface = interface

    def showXYZ(self,state):
        if state == Qt.Checked:
            self.textbox.setText("You have selected show XYZ graph")
            self.showNow = "showXYZ"
            self.dc.setOption(self.showNow)

            self.cbRPY.setChecked(False)
            self.cbError.setChecked(False)

    def showRPY(self, state):
        if state == Qt.Checked:
            self.textbox.setText("You have selected show RPY graph")
            self.showNow = "showRPY"
            self.cbxyz.setChecked(False)
            self.cbError.setChecked(False)
            self.dc.setOption(self.showNow)



            

    def showError(self, state):
        if state == Qt.Checked:
            self.textbox.setText("You have selected show error graph")
            self.showNow = "showError"
            self.dc.setOption(self.showNow)
            self.cbxyz.setChecked(False)
            self.cbRPY.setChecked(False)

            
    def savingResult(self):
        self.textbox.setText("Saving result...")
        ## Save real and sim xyzRYP
        np.save(os.path.join("result", "xestimated.npy"), np.array(self.xestimated))

        np.save(os.path.join("result", "yestimated.npy"), np.array(self.yestimated))
        np.save(os.path.join("result", "xreal.npy"), np.array(self.xreal))
        np.save(os.path.join("result", "yreal.npy"), np.array(self.yreal))

        self.textbox.setText("Done!")


    def update(self):
        ###### Estimated ########
        pose3dEstimated = PosXYZRPY(self.interface.getsimPose3D())

        self.xestimated.append(pose3dEstimated.x)
        self.yestimated.append(pose3dEstimated.y)
        self.zestimated.append(pose3dEstimated.z)
        self.Restimated.append(pose3dEstimated.R)
        self.Yestimated.append(pose3dEstimated.Y)
        self.Pestimated.append(pose3dEstimated.P)

        ###### Real ########
        pose3dReal = PosXYZRPY(self.interface.getPose3D())

        self.xreal.append(pose3dReal.x)
        self.yreal.append(pose3dReal.y)
        self.zreal.append(pose3dReal.z)
        self.Rreal.append(pose3dReal.R)
        self.Yreal.append(pose3dReal.Y)
        self.Preal.append(pose3dReal.P)



    def loadpathXYZ(self):
        a=[]

        for line in open(self.filename, 'r').readlines():
            line = line.rstrip('\n')
            linelist = line.split()
            if len(linelist)>1:
                pose = jderobot.Pose3DData()
                pose.x = float(linelist[0])
                pose.y = float(linelist[1])
                pose.z = float(linelist[2])
                a.append(pose)

        self.map = list(a)