コード例 #1
1
ファイル: newUser.py プロジェクト: oferlitver/DataConsultant
class ExperimentSetup(QWidget):
    """ Class for setting-up the experiment: choosing condition"""

    def __init__(self, parent=None):
        super(ExperimentSetup, self).__init__(parent)
        self.title = QLabel("EXPERIMENTER ONLY")
        # titleFont = QFont()
        # titleFont.setPointSize(36)
        # titleFont.setItalic(True)
        # self.title.setFont(titleFont)
        import os
        print(os.getcwd())
        self.mypixmap = QPixmap(os.getcwd() + "/ido.jpg")
        self.title.setPixmap(self.mypixmap)
        self.title.setGeometry(10, 10, 10, 10)

        # conditions list
        self.conditions_combo = QComboBox()
        conditions_list = config.CONDITIONS['condition']
        self.conditions_combo.addItems(conditions_list)

        # layout
        formLayout = QGridLayout()
        formLayout.setSpacing(20)
        formLayout.setColumnStretch(0, 5)
        formLayout.setColumnStretch(1, 2)
        formLayout.setColumnStretch(2, 5)
        formLayout.setRowStretch(0, 1)
        formLayout.setRowStretch(3, 1)

        formLayout.addWidget(self.title, 1, 1, 1, 2)
        formLayout.setRowMinimumHeight(2, 5)
        formLayout.addWidget(self.conditions_combo, 2, 1)

        self.setLayout(formLayout)
コード例 #2
1
ファイル: formlayout5.py プロジェクト: elcritch/formlayout5
class FormComboWidget(QWidget):
    def __init__(self, datalist, comment="", parent=None):
        QWidget.__init__(self, parent)
        layout = QVBoxLayout()
        self.setLayout(layout)
        self.combobox = QComboBox()
        layout.addWidget(self.combobox)
        
        self.stackwidget = QStackedWidget(self)
        layout.addWidget(self.stackwidget)
        self.combobox.currentIndexChanged[int].connect(self.stackwidget,setCurrentIndex)
        
        self.widgetlist = []
        for data, title, comment in datalist:
            self.combobox.addItem(title)
            widget = FormWidget(data, comment=comment, parent=self)
            self.stackwidget.addWidget(widget)
            self.widgetlist.append(widget)
            
    def setup(self):
        for widget in self.widgetlist:
            widget.setup()

    def get(self):
        return [ widget.get() for widget in self.widgetlist]
コード例 #3
0
ファイル: parse.py プロジェクト: KirillUdod/test_rebranch
    def create_main_window(self):

        lbl1 = QLabel("Choose needed section", self)
        lbl1.setGeometry(40, 0, 200, 35)

        self.sections_combo = QComboBox(self)
        for ref in _SECTIONS_REF:
            self.sections_combo.addItem(ref)
        self.sections_combo.setGeometry(40, 35, 200, 35)

        lbl2 = QLabel("Choose needed format", self)
        lbl2.setGeometry(40, 70, 200, 35)

        self.format_combo = QComboBox(self)
        for form in _FORMAT:
            self.format_combo.addItem(form)
        self.format_combo.setGeometry(40, 105, 200, 35)

        self.sections_combo.activated[str].connect(self.sections_combo_Activated)
        self.sections_combo.setCurrentIndex(int(self.sections_combo.findText('За сутки')))

        self.format_combo.activated[str].connect(self.format_combo_Activated)
        self.format_combo.setCurrentIndex(int(self.format_combo.findText('JSON')))

        btn1 = QPushButton("GO", self)
        btn1.setGeometry(40, 140, 200, 35)

        btn1.clicked.connect(self.buttonClicked)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Main')
        self.show()
コード例 #4
0
ファイル: search_window.py プロジェクト: mintoo/NetDim
 def __init__(self, controller):
     super().__init__()
     self.controller = controller
     self.setWindowTitle('Search window')
     self.setMinimumSize(300, 200)
     
     self.subtypes_list = QComboBox()
     self.subtypes_list.addItems(name_to_obj)
     self.subtypes_list.activated.connect(self.update_properties)
     
     self.property_list = QComboBox()
     self.checkbox_regex = QCheckBox('Regex search')
     self.entry_search = QLineEdit()
     
     button_OK = QPushButton()
     button_OK.setText('OK')
     button_OK.clicked.connect(self.search)
     
     # position in the grid
     layout = QGridLayout()
     layout.addWidget(self.subtypes_list, 0, 0, 1, 2)
     layout.addWidget(self.property_list, 1, 0, 1, 2)
     layout.addWidget(self.checkbox_regex, 2, 0, 1, 1)
     layout.addWidget(self.entry_search, 3, 0, 1, 1)
     layout.addWidget(button_OK, 4, 0, 1, 1)
     self.setLayout(layout)
     
     # update property with first value of the list
     self.update_properties()
コード例 #5
0
class DocumentTab(QWidget):
    def __init__(self, parent):
        self.parent = parent
        super(DocumentTab, self).__init__(parent)
        self.name = 'Documents'
        self.formats = config.document_formats

        convertQL = QLabel(self.tr('Convert to:'))
        self.extQCB = QComboBox()
        final_layout = utils.add_to_layout('h', convertQL, self.extQCB, None)
        self.setLayout(final_layout)

    def fill_extension_combobox(self, extraformats):
        self.extQCB.clear()
        self.extQCB.addItems(sorted(self.formats + extraformats))

    def ok_to_continue(self):
        """
        Check if everything is ok with documenttab to continue conversion.

        Checks if:
        - unoconv is missing.

        Return True if all tests pass, else False.
        """
        if not self.parent.unoconv:
            QMessageBox.warning(self, 'FF Multi Converter - ' + self.tr('Error!'),
                    self.tr('Unocov is not installed!'))
            return False
        return True
コード例 #6
0
ファイル: rosconfigdialog.py プロジェクト: Diegojnb/JdeRobot
    def __init__(self):
        super(QWidget, self).__init__()
        self.config = None
        self.count = 0
        self.topicRows = {}

        self.nameEdit = QLineEdit()
        self.dataTypeComboBox = QComboBox()
        self.fillDataTypes()
        self.opTypeComboBox = QComboBox()
        self.opTypeComboBox.addItem('sub', 'Subscribe')
        self.opTypeComboBox.addItem('pub', 'Publish')
        self.addButton = QPushButton('Add')
        self.addButton.clicked.connect(self.addClicked)

        self.mainLayout = QVBoxLayout()
        rowLayout = QHBoxLayout()
        rowLayout.addWidget(self.nameEdit)
        rowLayout.addWidget(self.dataTypeComboBox)
        rowLayout.addWidget(self.opTypeComboBox)
        rowLayout.addWidget(self.addButton)
        rowContainer = QWidget()
        rowContainer.setLayout(rowLayout)
        rowContainer.setObjectName('titleRow')
        self.mainLayout.addWidget(rowContainer)
        self.setLayout(self.mainLayout)
コード例 #7
0
ファイル: area_operations.py プロジェクト: mintoo/NetDim
    def __init__(self, mode, obj, AS=set(), controller=None):
        super().__init__()
        
        title = 'Add to area' if mode == 'add' else 'Remove from area'
        self.setWindowTitle(title)

        values = tuple(map(str, AS))
        
        # list of existing AS
        self.AS_list = QComboBox()
        self.AS_list.addItems(values)
        self.AS_list.activated.connect(self.update_value)
        
        # list of areas
        self.area_list = QComboBox()
        self.update_value()
        
        # confirmation button
        button_area_operation = QPushButton()
        button_area_operation.setText('OK')
        button_area_operation.clicked.connect(lambda: self.area_operation(mode, *obj))
        
        # position in the grid
        layout = QGridLayout()
        layout.addWidget(self.AS_list, 0, 0, 1, 2)
        layout.addWidget(self.area_list, 1, 0, 1, 2)
        layout.addWidget(button_area_operation, 2, 0, 1, 1)
        layout.addWidget(cancel_button, 2, 1, 1, 1)
        self.setLayout(layout)
コード例 #8
0
    def __init__(self, tr_action, target, ta_action, cue_dialog, **kwargs):
        super().__init__(**kwargs)

        self.target = target
        self.cue_dialog = cue_dialog
        self.target_actions = {a.name: a.value for a in target.CueActions}

        self.setLayout(QHBoxLayout(self))
        self.layout().setContentsMargins(2, 1, 2, 1)

        self.triggerActions = QComboBox(self)
        # MediaTriggers members names and values are equals
        self.triggerActions.addItems([a.value for a in CueTriggers])
        self.triggerActions.setCurrentText(tr_action)
        self.layout().addWidget(self.triggerActions)

        self.selectButton = QPushButton(self)
        self.selectButton.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        self.selectButton.setText(target.name)
        self.selectButton.setToolTip(target.name)
        self.selectButton.clicked.connect(self.select_target)
        self.layout().addWidget(self.selectButton)

        self.targetActionCombo = QComboBox(self)
        self.targetActionCombo.addItems(self.target_actions.keys())
        self.targetActionCombo.setCurrentText(CueAction(ta_action).name)
        self.layout().addWidget(self.targetActionCombo)

        self.layout().setStretch(0, 1)
        self.layout().setStretch(1, 3)
        self.layout().setStretch(2, 1)
コード例 #9
0
class CueItemWidget(QWidget):
    def __init__(self, target, action, cue_dialog, **kwargs):
        super().__init__(**kwargs)

        self.target = target
        self.cue_dialog = cue_dialog

        self.setLayout(QHBoxLayout(self))
        self.layout().setContentsMargins(2, 1, 2, 1)

        self.selectButton = QPushButton(self)
        self.selectButton.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        self.selectButton.setText(target.name)
        self.selectButton.setToolTip(target.name)
        self.selectButton.clicked.connect(self.select_target)
        self.layout().addWidget(self.selectButton)

        self.targetActionsCombo = QComboBox(self)
        self.targetActionsCombo.addItems([a.name for a in CueAction])
        self.targetActionsCombo.setCurrentText(CueAction[action].name)
        self.layout().addWidget(self.targetActionsCombo)

        self.layout().setStretch(0, 3)
        self.layout().setStretch(1, 1)

    def get_target(self):
        return self.target.id, self.targetActionsCombo.currentText()

    def select_target(self):
        if self.cue_dialog.exec_() == QDialog.Accepted:
            self.target = self.cue_dialog.selected_cues()[0]
            self.selectButton.setText(self.target.name)
            self.selectButton.setToolTip(self.target.name)
コード例 #10
0
ファイル: settings.py プロジェクト: oleastre/frescobaldi
    def __init__(self, parent):
        super(LilyPondPreferences, self).__init__(parent)

        grid = QGridLayout()
        self.setLayout(grid)

        self.pitchLanguageLabel = QLabel()
        self.pitchLanguage = QComboBox()
        self.versionLabel = QLabel()
        self.version = QComboBox(editable=True)

        self.pitchLanguage.addItem('')
        self.pitchLanguage.addItems([lang.title() for lang in sorted(scoreproperties.keyNames)])
        self.version.addItem(lilypondinfo.preferred().versionString())
        for v in ("2.18.0", "2.16.0", "2.14.0", "2.12.0"):
            if v != lilypondinfo.preferred().versionString():
                self.version.addItem(v)

        grid.addWidget(self.pitchLanguageLabel, 0, 0)
        grid.addWidget(self.pitchLanguage, 0, 1)
        grid.addWidget(self.versionLabel, 1, 0)
        grid.addWidget(self.version, 1, 1)

        self.pitchLanguage.activated.connect(self.slotPitchLanguageChanged)
        app.translateUI(self)
        self.loadSettings()
        self.window().finished.connect(self.saveSettings)
コード例 #11
0
 def __addRangesLine(self):
     """
     Private slot to add a line of entry widgets for character ranges.
     """
     hbox = QWidget(self.rangesItemsBox)
     hboxLayout = QHBoxLayout(hbox)
     hboxLayout.setContentsMargins(0, 0, 0, 0)
     hboxLayout.setSpacing(6)
     hbox.setLayout(hboxLayout)
     cb1 = QComboBox(hbox)
     cb1.setEditable(False)
     cb1.addItems(self.comboItems)
     hboxLayout.addWidget(cb1)
     l1 = QLabel(self.tr("Between:"), hbox)
     hboxLayout.addWidget(l1)
     le1 = QLineEdit(hbox)
     le1.setValidator(self.charValidator)
     hboxLayout.addWidget(le1)
     l2 = QLabel(self.tr("And:"), hbox)
     hboxLayout.addWidget(l2)
     le2 = QLineEdit(hbox)
     le2.setValidator(self.charValidator)
     hboxLayout.addWidget(le2)
     self.rangesItemsBoxLayout.addWidget(hbox)
     
     cb1.activated[int].connect(self.__rangesCharTypeSelected)
     
     hbox.show()
     
     self.rangesItemsBox.adjustSize()
     
     self.rangesEntries.append([cb1, le1, le2])
コード例 #12
0
    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)
コード例 #13
0
    def __init__(self, parent=None):
        super().__init__(parent)

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

        dateLabel = QLabel(date)
        self.fromComboBox = QComboBox()
        self.fromComboBox.addItems(rates)
        self.fromSpinBox = QDoubleSpinBox()
        self.fromSpinBox.setRange(0.01, 10000000.00)
        self.fromSpinBox.setValue(1.00)
        self.toComboBox = QComboBox()
        self.toComboBox.addItems(rates)
        self.toLabel = QLabel("1.00")
        grid = QGridLayout()
        grid.addWidget(dateLabel, 0, 0)
        grid.addWidget(self.fromComboBox, 1, 0)
        grid.addWidget(self.fromSpinBox, 1, 1)
        grid.addWidget(self.toComboBox, 2, 0)
        grid.addWidget(self.toLabel, 2, 1)
        self.setLayout(grid)
        self.fromComboBox.currentIndexChanged.connect(self.updateUi)
        self.toComboBox.currentIndexChanged.connect(self.updateUi)
        self.fromSpinBox.valueChanged.connect(self.updateUi)
        self.setWindowTitle("Currency")
コード例 #14
0
ファイル: config_window.py プロジェクト: nimble0/plover
 def createEditor(self, parent, option, index):
     if index.column() == 1:
         combo = QComboBox(parent)
         combo.addItem('')
         combo.addItems(self._action_list)
         return combo
     return super().createEditor(parent, option, index)
コード例 #15
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
コード例 #16
0
    def __init__(self, size, parent=None):
        super().__init__(size, parent)

        # Startup layout
        self.layoutGroup = QGroupBox(self)
        self.layoutGroup.setTitle('Startup layout')
        self.layoutGroup.setLayout(QVBoxLayout())
        self.layoutGroup.setGeometry(0, 0, self.width(), 120)

        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.themeGroup.setGeometry(0, 125, self.width(), 80)

        self.themeCombo = QComboBox(self.themeGroup)
        self.themeCombo.addItems(styles.get_styles())
        self.themeGroup.layout().addWidget(self.themeCombo)
コード例 #17
0
ファイル: preferences.py プロジェクト: tallforasmurf/PPQT2
class ChooseFixedFont( ChoiceWidget ) :
    def __init__( self, explainer ) :
        super().__init__( _TR( 'Preference item title line',
                               'Choose a monospaced font for the Editor' ),
                          explainer )
        self.fcb = QComboBox()
        self.fcb.addItems( fonts.list_of_good_families() )
        self.fcb.activated[str].connect( self.choice_made )
        self.layout().addWidget(self.fcb)
        self.reset() # set the current font
        self.explanation = _TR( 'Preference item details',
'''Select the font to use in the Edit panel. Choose a monospaced font that shows a clear difference 1/l and 0/O, and that has a wide selection of Unicode characters. Good choices are Cousine and Liberation Mono.

When you select a font from the menu, that font is applied to this window. To apply it to the Edit panel, click Apply.''')
        self.reset()

    def choice_made(self, family) :
        self.choice = family
        qf = fonts.font_from_family( family )
        self.explainer.setFont(qf)

    def reset(self) :
        self.choice = fonts.get_fixed().family()
        self.fcb.setCurrentText( self.choice )

    def apply(self) :
        fonts.set_fixed( fonts.font_from_family( self.choice ) )
コード例 #18
0
    def setupUi(self):
        self.resize(1200, 900)
        gr = pg.PlotWidget(parent=self, background=[255, 255, 255])
        dtait = pg.PlotDataItem(pen=pg.mkPen('r', width=4))
        dtait2 = pg.PlotDataItem(pen=pg.mkPen('b', width=4))
        dtait.setVisible(True)
        gr.plotItem.addItem(dtait)
        gr.plotItem.addItem(dtait2)
        pl = gr.getPlotItem()
        vl = QVBoxLayout(self)
        vl.addWidget(gr)
        self.graph = gr
        self._plot_rms = dtait
        self._plot_ave = dtait2

        hl = QHBoxLayout()
        vl.addItem(hl)

        self.dirs = sorted([f for f in os.listdir() if os.path.isdir(f)])
        self.cb_dirs = QComboBox(self)
        self.cb_dirs.addItems(self.dirs)
        self.cb_dirs.currentTextChanged.connect(self._changedir)
        hl.addWidget(self.cb_dirs)

        self.cb_planes = QComboBox(self)
        self.cb_planes.addItems(self.planes + ('Wlkick', ))
        self.cb_planes.currentTextChanged.connect(self._changePlane)
        hl.addWidget(self.cb_planes)
コード例 #19
0
ファイル: filebrowser.py プロジェクト: bjones1/enki
    def __init__(self, fileBrowser):
        QComboBox.__init__(self, fileBrowser)

        self._fileBrowser = fileBrowser

        self.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.setAttribute(Qt.WA_MacSmallSize)
        self.setEditable(True)
        self.setMinimumContentsLength(1)
        self.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self.lineEdit().setReadOnly(False)
        self._completionModel = QDirModel(self.lineEdit())
        self._completionModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        self.lineEdit().setCompleter(QCompleter(self._completionModel,
                                                self.lineEdit()))
        # TODO QDirModel is deprecated but QCompleter does not yet handle
        # QFileSystemModel - please update when possible.
        self._count = 0

        # Show popup action
        self._showPopupAction = QAction(QIcon(':enkiicons/filtered.png'), "File browser history", self)
        self._showPopupAction.setShortcut('Ctrl+H')
        core.actionManager().addAction("mNavigation/mFileBrowser/aMenuShow", self._showPopupAction)
        self._showPopupAction.triggered.connect(self._onShowPopup)

        # reconnected in self.updateComboItems()
        self.currentIndexChanged[int].connect(self._onItemSelected)
コード例 #20
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)
コード例 #21
0
ファイル: ui_theme.py プロジェクト: PisiLinuxRepos/kaptan
    def createDesktopOption(self, layout):
        hlayout = QHBoxLayout()
        layout.addLayout(hlayout)

        vlayout1 = QVBoxLayout()
        vlayout2 = QVBoxLayout()
        hlayout.addLayout(vlayout1)
        hlayout.addLayout(vlayout2)

        label1 = QLabel()
        label1.setText(self.tr("Desktop Type"))
        vlayout1.addWidget(label1)
        label2 = QLabel()
        label2.setText(self.tr("Number of Desktops"))
        vlayout2.addWidget(label2)

        comboBox = QComboBox()
        comboBox.addItem(self.tr("Desktop View"))
        comboBox.addItem(self.tr("Folder View"))
        comboBox.currentIndexChanged.connect(self.desktopTypeCreate)
        vlayout1.addWidget(comboBox)
        spinBox = QSpinBox()
        spinBox.setMinimum(1)
        spinBox.setMaximum(20)
        spinBox.valueChanged.connect(self.desktopCreate)
        vlayout2.addWidget(spinBox)
コード例 #22
0
ファイル: GeneralTab.py プロジェクト: MaximeCheramy/simso-gui
    def __init__(self, parent, configuration):
        QTableWidget.__init__(self, 5, 1, parent)
        self._configuration = configuration
        self._manual_change = True
        self.setVerticalHeaderLabels(
            ["Duration (cycles)", "Duration (ms)", "Cycles / ms",
             'RAM access time', 'Execution Time Model'])
        self.horizontalHeader().setStretchLastSection(True)
        self.horizontalHeader().hide()
        self.setItem(0, 0, QTableWidgetItem(str(configuration.duration)))
        self.setItem(1, 0, QTableWidgetItem(str(
            float(configuration.duration) / configuration.cycles_per_ms)))
        self.setItem(2, 0, QTableWidgetItem(str(configuration.cycles_per_ms)))
        self.setItem(
            3, 0, QTableWidgetItem(str(configuration.memory_access_time)))

        item = QComboBox(self)
        selected = 0
        for i, (etm_name, etm_code) in \
                enumerate(execution_time_model_names.items()):
            item.addItem(etm_name)
            if etm_code == configuration.etm:
                selected = i
        item.setCurrentIndex(selected)
        self.setCellWidget(4, 0, item)

        def activation_handler(x):
            configuration.etm = execution_time_model_names[str(x)]
            configuration.conf_changed()
        item.activated['QString'].connect(activation_handler)

#        self._update_observe_window()

        self.cellChanged.connect(self._cell_changed)
コード例 #23
0
ファイル: midi.py プロジェクト: 19joho66/frescobaldi
    def __init__(self, page):
        super(MidiPorts, self).__init__(page)

        self._portsMessage = QLabel(wordWrap=True)
        self._playerLabel = QLabel()
        self._playerPort = QComboBox(editable=True,
            editTextChanged=self.changed, insertPolicy=QComboBox.NoInsert)
        self._inputLabel = QLabel()
        self._inputPort = QComboBox(editable=True,
            editTextChanged=self.changed, insertPolicy=QComboBox.NoInsert)

        self._reloadMidi = QPushButton(icon=icons.get('view-refresh'))
        self._reloadMidi.clicked.connect(self.refreshMidiPorts)

        grid = QGridLayout()
        self.setLayout(grid)
        grid.addWidget(self._portsMessage, 0, 0, 1, 3)
        grid.addWidget(self._playerLabel, 1, 0)
        grid.addWidget(self._playerPort, 1, 1, 1, 2)
        grid.addWidget(self._inputLabel, 2, 0)
        grid.addWidget(self._inputPort, 2, 1, 1, 2)
        grid.addWidget(self._reloadMidi, 3, 2)

        app.translateUI(self)
        self.loadMidiPorts()
コード例 #24
0
ファイル: qt.py プロジェクト: dasimon/weboob
 def __init__(self, value):
     QComboBox.__init__(self)
     self._value = value
     for k, l in value.choices.iteritems():
         self.addItem(l, QVariant(k))
         if value.default == k:
             self.setCurrentIndex(self.count()-1)
コード例 #25
0
 def __init__(self):
     super().__init__()
     vbox = QVBoxLayout(self)
     self.setTitle("Python Project")
     frame = QFrame()
     frame.setLineWidth(2)
     vbox.addStretch(1)
     frame.setFrameShape(QFrame.StyledPanel)
     vbox.addWidget(frame)
     box = QGridLayout(frame)
     box.addWidget(QLabel("Project Name:"), 0, 0)
     self._line_project_name = QLineEdit()
     self.registerField("name*", self._line_project_name)
     box.addWidget(self._line_project_name, 0, 1)
     box.addWidget(QLabel("Create in:"), 1, 0)
     self.line = QLineEdit()
     self.registerField("path", self.line)
     choose_dir_action = self.line.addAction(
         QIcon(self.style().standardPixmap(
             self.style().SP_DirIcon)), QLineEdit.TrailingPosition)
     box.addWidget(self.line, 1, 1)
     box.addWidget(QLabel("Interpreter:"), 2, 0)
     line_interpreter = QComboBox()
     line_interpreter.setEditable(True)
     line_interpreter.addItems(utils.get_python())
     box.addWidget(line_interpreter, 2, 1)
     # from ninja_ide.utils import utils
     choose_dir_action.triggered.connect(self._choose_dir)
     self.line.setText(utils.get_home_dir())
コード例 #26
0
class AddItemDialog(QDialog):
    def __init__(self):
        super(AddItemDialog, self).__init__()
        self.setupUi(self)

    def setupUi(self, AddItemDialog):
        self.item_type_picker = QComboBox()

        self.item_properties_switch = QStackedWidget()

        for form in FORMS:
            self.item_type_picker.addItem(form.__name__.split('_')[0],
                                          FORMS.index(form))
            self.item_properties_switch.addWidget(form())

        self.item_type_picker.currentIndexChanged.connect(
            self.item_properties_switch.setCurrentIndex)

        self.add_button = QPushButton("Add")

        mainLayout = QVBoxLayout(self)
        mainLayout.addWidget(self.item_type_picker)
        mainLayout.addWidget(self.item_properties_switch, 1)
        mainLayout.addWidget(self.add_button)

        self.add_button.clicked.connect(self.add_item)

        self.setWindowIcon(QIcon(QPixmap('hotel_icon.jpg')))
        self.layout().setSizeConstraint(QLayout.SetFixedSize)
        self.setWindowTitle("Add Items")

    def add_item(self):
        self.item_properties_switch.currentWidget().add_button_click()
コード例 #27
0
 def createKeySignatureWidget(self):
     self.keySignatureLabel = QLabel()
     self.keyNote = QComboBox()
     self.keyNote.setModel(listmodel.ListModel(keyNames['nederlands'], self.keyNote))
     self.keyMode = QComboBox()
     self.keyMode.setModel(listmodel.ListModel(modes, self.keyMode, display=listmodel.translate_index(1)))
     self.keySignatureLabel.setBuddy(self.keyNote)
コード例 #28
0
ファイル: crud_widget.py プロジェクト: aq1/Hospital-Helper-2
    def _get_combobox(self, column, relations, main_window):

        """
        Return combobox for foreign fields.
        """

        label = column.name
        if label.endswith('_id'):
            label = label[:-3]
        foreign_model = relations.get(label).mapper.class_
        items = list(db.SESSION.query(foreign_model).filter(foreign_model.deleted == False))
        self.foreigns[column.name] = items
        items_labels = [str(i) for i in items]
        widget = QWidget()
        widget.setStyleSheet('margin:0;')
        combo_box = QComboBox()
        combo_box.addItems(items_labels)
        combo_box.currentIndexChanged.connect(self._check_input)
        combo_box.setObjectName(column.name)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.setSpacing(0)
        hbox.addWidget(combo_box, stretch=95)
        for icon, new in zip(('pencil_g.png', 'plus.png'), (False, True)):
            b = QPushButton()
            b.setObjectName('icon')
            b.setIcon(QIcon(os.path.join(options.STATIC_DIR, 'icons', icon)))
            b.clicked.connect(functools.partial(
                self.open_crud, main_window, foreign_model, new, combo_box))
            hbox.addWidget(b, stretch=2)
        widget.setLayout(hbox)
        return label, widget
コード例 #29
0
ファイル: property_changer.py プロジェクト: mintoo/NetDim
class PropertyChanger(QWidget):
                                 
    @update_paths
    def __init__(self, objects, type, controller):
        super().__init__()
        
        # list of properties
        self.property_list = QComboBox()
        self.property_list.addItems(map(str, object_properties[type]))
                            
        self.value_edit = QLineEdit()

        confirmation_button = QPushButton()
        confirmation_button.setText('OK')
        confirmation_button.clicked.connect(lambda: self.confirm(objects))
                                       
        # position in the grid
        layout = QGridLayout()
        layout.addWidget(self.property_list, 0, 0)
        layout.addWidget(self.value_edit, 1, 0)
        layout.addWidget(confirmation_button, 2, 0)
        self.setLayout(layout)
        
    def confirm(self, objects):
        selected_property = pretty_name_to_class[self.property_list.currentText()]
        str_value = self.value_edit.text()
        value = self.network.objectizer(selected_property.name, str_value)
        for object in objects:
            setattr(object, selected_property.name, value)
        self.close()
コード例 #30
0
     def __init__(self, parent=None):
         super(Widget, self).__init__(parent)
         if route == 0:
             self.setWindowTitle("Raaplijst materialen uitgifte")
         else:
             self.setWindowTitle("Raaplijst printen") 
         self.setWindowIcon(QIcon('./images/logos/logo.jpg'))
 
         self.setFont(QFont('Arial', 10))
         
         if route < 2:
             self.Keuze = QLabel()
             k0Edit = QComboBox()
             k0Edit.setFixedWidth(240)
             k0Edit.setFont(QFont("Arial",10))
             k0Edit.setStyleSheet("color: black;  background-color: gainsboro")
             k0Edit.addItem('  Sorteersleutel voor zoeken')
             k0Edit.addItem('1. Alle afroepen')
             k0Edit.addItem('2. Interne werkorders')
             k0Edit.addItem('3. Externe werknummers')
             k0Edit.addItem('4. Per ordernummer')
             k0Edit.addItem('5. Per artikelnummer')           
             k0Edit.addItem('6. Op leverdatum')
             k0Edit.addItem('7. Op Poscode ivm Transport')
             k0Edit.addItem('8. Uitgeleverde afroepen')
             k0Edit.activated[str].connect(self.k0Changed)
         elif route == 2:
             self.Keuze = QLabel()
             k0Edit = QComboBox()
             k0Edit.setFixedWidth(240)
             k0Edit.setFont(QFont("Arial",10))
             k0Edit.setStyleSheet("color: black;  background-color: gainsboro")
             k0Edit.addItem('  Sorteersleutel voor zoeken')
             k0Edit.addItem('2. Interne werkorders')
             k0Edit.addItem('4. Per ordernummer')
             k0Edit.addItem('5. Per artikelnummer')           
             k0Edit.addItem('6. Op leverdatum')
             k0Edit.addItem('7. Op Poscode ivm Transport')
             k0Edit.addItem('8. Uitgeleverde afroepen')
             k0Edit.activated[str].connect(self.k0Changed)
         elif route == 3:
             self.Keuze = QLabel()
             k0Edit = QComboBox()
             k0Edit.setFixedWidth(240)
             k0Edit.setFont(QFont("Arial",10))
             k0Edit.setStyleSheet("color: black;  background-color: gainsboro")
             k0Edit.addItem('  Sorteersleutel voor zoeken')
             k0Edit.addItem('3. Externe werknummers')
             k0Edit.addItem('4. Per ordernummer')
             k0Edit.addItem('5. Per artikelnummer')           
             k0Edit.addItem('6. Op leverdatum')
             k0Edit.addItem('7. Op Poscode ivm Transport')
             k0Edit.addItem('8. Uitgeleverde afroepen')
             k0Edit.activated[str].connect(self.k0Changed)  
             
         self.Zoekterm = QLabel()
         zktermEdit = QLineEdit()
         zktermEdit.setFixedWidth(240)
         zktermEdit.setFont(QFont("Arial",10))
         zktermEdit.textChanged.connect(self.zktermChanged)
  
         grid = QGridLayout()
         grid.setSpacing(20)
                       
         lbl = QLabel()
         pixmap = QPixmap('./images/logos/verbinding.jpg')
         lbl.setPixmap(pixmap)
         grid.addWidget(lbl , 0, 0, 1, 2)
         
         if route == 0:
             grid.addWidget(QLabel('Keuzemenu voor het uitgeven van materialen'), 1, 0, 1, 3, Qt.AlignCenter)
         else:
             grid.addWidget(QLabel('Keuzemenu voor het printen van raaplijsten'), 1, 0, 1, 3, Qt.AlignCenter)
          
         logo = QLabel()
         pixmap = QPixmap('./images/logos/logo.jpg')
         logo.setPixmap(pixmap)
         grid.addWidget(logo , 0, 1, 1, 1, Qt.AlignRight)
                               
         grid.addWidget(k0Edit, 2, 1)
         lbl1 = QLabel('Zoekterm')  
         lbl1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
         grid.addWidget(lbl1, 3, 0)
         grid.addWidget(zktermEdit, 3, 1)
         
         self.setLayout(grid)
         self.setGeometry(500, 300, 150, 150)
         
         grid.addWidget(QLabel('\u00A9 2017 all rights reserved  [email protected]'), 5, 0, 1, 3, Qt.AlignCenter)
                   
         applyBtn = QPushButton('Zoeken')
         applyBtn.clicked.connect(self.accept)
                                    
         grid.addWidget(applyBtn, 4, 1, 1, 1, Qt.AlignRight)
         applyBtn.setFont(QFont("Arial",10))
         applyBtn.setFixedWidth(100)
         applyBtn.setStyleSheet("color: black;  background-color: gainsboro")
         
         cancelBtn = QPushButton('Sluiten')
         cancelBtn.clicked.connect(lambda: windowSluit(self, m_email))
 
         grid.addWidget(cancelBtn, 4, 1)
         cancelBtn.setFont(QFont("Arial",10))
         cancelBtn.setFixedWidth(100)
         cancelBtn.setStyleSheet("color: black;  background-color: gainsboro")
コード例 #31
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')
        self._tuShareProCheckBox.clicked.connect(self._tuShareProCheckBoxClicked)

        self._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(self._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)

        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

        self._tuShareProTokenLabel.setEnabled(enableTuSharePro and enableTushareProToken)
        self._tuShareProTokenLineEdit.setEnabled(enableTuSharePro and enableTushareProToken)

        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():
            self._windCheckBox.setChecked(True)

        self._enableTradeDaysComboBox()

    def _windCheckBoxClicked(self):
        self._checkBoxClicked()

    def _tuShareCheckBoxClicked(self):
        self._checkBoxClicked()

        enable = self._tuShareCheckBox.isChecked()
        self._tuShareProCheckBox.setEnabled(enable)

        enableToken = self._tuShareProCheckBox.isChecked()
        self._tuShareProTokenLabel.setEnabled(enable and enableToken)
        self._tuShareProTokenLineEdit.setEnabled(enable and enableToken)

    def _tuShareProCheckBoxClicked(self):
        enable = self._tuShareProCheckBox.isChecked()

        self._tuShareProTokenLabel.setEnabled(enable)
        self._tuShareProTokenLineEdit.setEnabled(enable)
コード例 #32
0
ファイル: scrape.py プロジェクト: cbonnell28/linkedin_scrape
    def __init__(self):
        QMainWindow.__init__(self)

        # Making window
        self.setMinimumSize(QSize(400, 150))
        self.setWindowTitle("Linkedin Scraper")

        # Making all labels
        self.searchLabel = QLabel(self)
        self.searchLabel.setText('Search:')
        self.daysLabel = QLabel(self)
        self.daysLabel.setText('Days since posted:')
        self.semesterLabel = QLabel(self)
        self.semesterLabel.setText('Semester:')
        self.coopLabel = QLabel(self)
        self.coopLabel.setText('Co-op')
        self.internshipLabel = QLabel(self)
        self.internshipLabel.setText('Internship')

        # Making all line edits
        self.searchLine = QLineEdit(self)
        self.dayLine = QLineEdit(self)

        # Making all combo boxes
        self.semesterBox = QComboBox(self)

        # Making all checkboxes
        self.coopBox = QCheckBox(self)
        self.internshipBox = QCheckBox(self)

        # Modifying search line
        self.searchLine.move(80, 20)
        self.searchLine.resize(306, 32)
        self.searchLabel.move(20, 20)

        # Modifying day line
        self.dayLine.move(160, 60)
        self.dayLine.resize(32, 32)
        self.daysLabel.move(20, 65)
        self.daysLabel.adjustSize()

        # Modifying semester line
        self.semesterBox.addItem("Summer")
        self.semesterBox.addItem("Fall")
        self.semesterBox.addItem("Spring")
        self.semesterBox.addItem("Winter")
        self.semesterBox.move(287, 60)
        self.semesterLabel.move(212, 60)

        # Modifying search button
        pybutton = QPushButton('Search', self)
        pybutton.clicked.connect(self.searchLinkedin)
        pybutton.resize(200, 32)
        pybutton.move(40, 102)

        # Modifying checkboxes
        self.coopBox.move(260, 95)
        self.coopLabel.move(280, 95)
        self.coopBox.stateChanged.connect(self.checkCoop)
        self.internshipBox.move(260, 110)
        self.internshipLabel.move(280, 110)
        self.internshipBox.stateChanged.connect(self.checkInternship)
コード例 #33
0
	def __init__(self):

		

		self.player_class = "No Class"
		self.player_name = "Zorg"
		self.character_name = "Character"

		self.barbarianString = "Barbarian"
		self.noClassString = "No Class"
		self.knightString = "Knight"
		self.nerdString = "Nerd"
		self.rogueString = "Rogue"


		super().__init__()


		######################################################################################################
		# Creating Layouts
		######################################################################################################

		# Sets as child to CentralWidget
		self.mainLayout = QVBoxLayout(self)

		self.interactionLayout = QVBoxLayout()

		self.attributeInventoryLayout = QHBoxLayout()

		self.imageInventoryLayout = QVBoxLayout()

		self.attributesLayout = QVBoxLayout()

		# Form layout for class and difficulty setters
		self.informationFormLayout = QFormLayout()
		self.informationFormLayout.setVerticalSpacing(25)


		######################################################################################################
		# Creating widgets to go in layouts
		######################################################################################################

		# Used to enter the player's name
		self.playerNameLineEdit = QLineEdit()
		self.playerNameLineEdit.setPlaceholderText("Enter player name here ")

		# Used to enter the character's name
		self.characterNameLineEdit = QLineEdit()
		self.characterNameLineEdit.setPlaceholderText("Enter character name here ")

		# Changes the below labels
		self.classSelectorComboBox = QComboBox()
		self.classSelectorComboBox.addItems([self.noClassString,self.barbarianString, self.knightString, self.nerdString, self.rogueString])

		# TBD add difficulty to game
		self.difficultyComboBox = QComboBox()
		self.difficultyComboBox.addItems(["Newb", "Decent", "Gud"])

		# Used to start the game
		self.finishPushButton = QPushButton("Finish")


		# Labels to display information to the user
		self.difficultyLabel = QLabel("A good difficulty for children and casuals")

		self.strengthLabel = QLabel("Strength: 10")

		self.dexterityLabel = QLabel("Dexterity: 10")

		self.constitutionLabel = QLabel("Constitution: 10")

		self.intellectLabel = QLabel("Intellect: 10")

		self.smallImageLabel = QLabel()

		self.inventoryLabel = QLabel("No class starts with a fist")



		######################################################################################################
		# Changing the looks of the widgets
		######################################################################################################

		self.imageResourceString = "resources/questionbox.jpg"
		self.smallImage = QImage(self.imageResourceString)
		self.smallerImage= self.smallImage.scaled(50,50)

		self.smallImagePixmap = QPixmap(self.smallerImage)

		self.smallImageLabel.setPixmap(self.smallImagePixmap)


		# Center imageInventory layout
		self.imageInventoryLayout.setAlignment(Qt.AlignCenter)

		## Center the image left to right in the layout
		self.smallImageLabel.setAlignment(Qt.AlignCenter)


		## Changing the colors of finishPushButton, difficultyComboBox, classSelectorComboBox
		newPalettePushButton = self.finishPushButton.palette()
		newPalettePushButton.setColor(newPalettePushButton.Button, QColor(255, 0, 0))
		self.finishPushButton.setAutoFillBackground( True )
		self.finishPushButton.setPalette(newPalettePushButton)

		newPaletteDifficultyComboBox = self.difficultyComboBox.palette()
		newPaletteDifficultyComboBox.setColor(self.difficultyComboBox.backgroundRole(), QColor(123, 123, 123))
		self.difficultyComboBox.setAutoFillBackground( True )
		self.difficultyComboBox.setPalette(newPaletteDifficultyComboBox)






		######################################################################################################
		# re-Parenting mainLayout
		######################################################################################################

		# The order widgets are added change the order they appear in the layout
		# Since main is QV order determines top to bottom
		self.mainLayout.addLayout(self.interactionLayout)

		self.mainLayout.addLayout(self.attributeInventoryLayout)

		self.mainLayout.addWidget(self.finishPushButton)


		######################################################################################################
		# re-Parenting interactionLayout
		######################################################################################################

		self.interactionLayout.addLayout(self.informationFormLayout)

		self.interactionLayout.addWidget(self.difficultyLabel)


		######################################################################################################
		# re-Parenting attributeInventoryLayout
		######################################################################################################

		self.attributeInventoryLayout.addLayout(self.attributesLayout)

		self.attributeInventoryLayout.addLayout(self.imageInventoryLayout)


		######################################################################################################
		# re-Parenting attributesLayout
		######################################################################################################

		self.attributesLayout.addWidget(self.strengthLabel)

		self.attributesLayout.addWidget(self.dexterityLabel)

		self.attributesLayout.addWidget(self.constitutionLabel)

		self.attributesLayout.addWidget(self.intellectLabel)

		######################################################################################################
		# re-Parenting imageInventoryLayout
		######################################################################################################

		self.imageInventoryLayout.addWidget(self.smallImageLabel)

		self.imageInventoryLayout.addWidget(self.inventoryLabel)


		######################################################################################################
		# Creating form layout for informationFormLayout
		######################################################################################################

		self.informationFormLayout.addRow("Player Name: ", self.playerNameLineEdit)

		self.informationFormLayout.addRow("Character Name: ", self.characterNameLineEdit)

		self.informationFormLayout.addRow("Class: ", self.classSelectorComboBox)

		self.informationFormLayout.addRow("Difficulty: ", self.difficultyComboBox)


		######################################################################################################
		# Connecting the widgets with methods
		######################################################################################################

		self.playerNameLineEdit.textChanged.connect(self.playerNameChange)

		self.classSelectorComboBox.activated[str].connect(self.classChange)

		self.classSelectorComboBox.activated[str].connect(self.classImageChange)

		self.difficultyComboBox.activated[str].connect(self.difficultyChange)

		self.finishPushButton.clicked.connect(self.finishChange)
コード例 #34
0
    def __init__(self, network: Network, config: 'SimpleConfig', wizard=False):
        self.network = network
        self.config = config
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(proxy_tab, _('Proxy'))

        fixed_width_hostname = 24 * char_width_in_lineedit()
        fixed_width_port = 6 * char_width_in_lineedit()

        # 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'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(fixed_width_hostname)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(fixed_width_port)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_password = PasswordLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))
        self.proxy_password.setFixedWidth(fixed_width_port)

        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: with Electrum-NMC servers, but also with 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)
        grid.addWidget(self.proxy_password, 5, 3)
        grid.setRowStretch(7, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg = ' '.join([
            _("Electrum-NMC 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.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)
        msg = ' '.join([
            _("If auto-connect is enabled, Electrum-NMC 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. Electrum-NMC will warn you if your server is lagging."
              )
        ])
        grid.addWidget(self.autoconnect_cb, 1, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.server_e = QLineEdit()
        self.server_e.setFixedWidth(fixed_width_hostname + fixed_width_port)
        self.server_e.editingFinished.connect(self.set_server)
        msg = _(
            "Electrum-NMC sends your wallet addresses to a single server, in order to receive your transaction history."
        )
        grid.addWidget(QLabel(_('Server') + ':'), 2, 0)
        grid.addWidget(self.server_e, 2, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 2, 4)

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

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

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

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        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()
コード例 #35
0
class CharacterCreateWidget(QWidget):
	"""
	Making a class from the QWidget class, is used in the game to receive information
	 from the user to be used for the character's information.

	Variables:
		mainLayout <QVBoxLayout>
		interactionLayout <QVBoxLayout>
		attributeInventoryLayout <QHBoxLayout>
		attributeLayout <QVBoxLayout>
		informationFormLayout<QFormLayout>

		characterNameLineEdit <QLineEdit>
		playerNameLineEdit <QLineEdit>
		classSelectorComboBox <QComboBox>
		difficultyComboBox <QComboBox>
		finishPushButton <QPushButton>

		difficultyLabel <QLabel>
		strengthLabel <QLabel>
		dexterifyLabel <QLabel>
		constitutionLabel <QLabel>
		intellectLabel <QLabel>
		smallImageLabel <QLabel>
		inventoryLabel <QLabel>

		

		player_class <str>
		player_name <str>
		character_name <str>
		barbarianString <str>
		noClassString <str>
		knightString <str>
		nerdString <str>
		rogueString <str>
		imageResourceString <str>

	Methods:
		classChange Changes text labels related to class
		classImageChange Changes image related to class
		difficultyChange Changes difficulty label
		finishChange Emits signals to centralwidget with the information provided by this screen
		playerNameChange Changes player_name variables 
		
	"""
	procGameStart = pyqtSignal(int, str, str, str)
	procCharLabel = pyqtSignal(str)

	def __init__(self):

		

		self.player_class = "No Class"
		self.player_name = "Zorg"
		self.character_name = "Character"

		self.barbarianString = "Barbarian"
		self.noClassString = "No Class"
		self.knightString = "Knight"
		self.nerdString = "Nerd"
		self.rogueString = "Rogue"


		super().__init__()


		######################################################################################################
		# Creating Layouts
		######################################################################################################

		# Sets as child to CentralWidget
		self.mainLayout = QVBoxLayout(self)

		self.interactionLayout = QVBoxLayout()

		self.attributeInventoryLayout = QHBoxLayout()

		self.imageInventoryLayout = QVBoxLayout()

		self.attributesLayout = QVBoxLayout()

		# Form layout for class and difficulty setters
		self.informationFormLayout = QFormLayout()
		self.informationFormLayout.setVerticalSpacing(25)


		######################################################################################################
		# Creating widgets to go in layouts
		######################################################################################################

		# Used to enter the player's name
		self.playerNameLineEdit = QLineEdit()
		self.playerNameLineEdit.setPlaceholderText("Enter player name here ")

		# Used to enter the character's name
		self.characterNameLineEdit = QLineEdit()
		self.characterNameLineEdit.setPlaceholderText("Enter character name here ")

		# Changes the below labels
		self.classSelectorComboBox = QComboBox()
		self.classSelectorComboBox.addItems([self.noClassString,self.barbarianString, self.knightString, self.nerdString, self.rogueString])

		# TBD add difficulty to game
		self.difficultyComboBox = QComboBox()
		self.difficultyComboBox.addItems(["Newb", "Decent", "Gud"])

		# Used to start the game
		self.finishPushButton = QPushButton("Finish")


		# Labels to display information to the user
		self.difficultyLabel = QLabel("A good difficulty for children and casuals")

		self.strengthLabel = QLabel("Strength: 10")

		self.dexterityLabel = QLabel("Dexterity: 10")

		self.constitutionLabel = QLabel("Constitution: 10")

		self.intellectLabel = QLabel("Intellect: 10")

		self.smallImageLabel = QLabel()

		self.inventoryLabel = QLabel("No class starts with a fist")



		######################################################################################################
		# Changing the looks of the widgets
		######################################################################################################

		self.imageResourceString = "resources/questionbox.jpg"
		self.smallImage = QImage(self.imageResourceString)
		self.smallerImage= self.smallImage.scaled(50,50)

		self.smallImagePixmap = QPixmap(self.smallerImage)

		self.smallImageLabel.setPixmap(self.smallImagePixmap)


		# Center imageInventory layout
		self.imageInventoryLayout.setAlignment(Qt.AlignCenter)

		## Center the image left to right in the layout
		self.smallImageLabel.setAlignment(Qt.AlignCenter)


		## Changing the colors of finishPushButton, difficultyComboBox, classSelectorComboBox
		newPalettePushButton = self.finishPushButton.palette()
		newPalettePushButton.setColor(newPalettePushButton.Button, QColor(255, 0, 0))
		self.finishPushButton.setAutoFillBackground( True )
		self.finishPushButton.setPalette(newPalettePushButton)

		newPaletteDifficultyComboBox = self.difficultyComboBox.palette()
		newPaletteDifficultyComboBox.setColor(self.difficultyComboBox.backgroundRole(), QColor(123, 123, 123))
		self.difficultyComboBox.setAutoFillBackground( True )
		self.difficultyComboBox.setPalette(newPaletteDifficultyComboBox)






		######################################################################################################
		# re-Parenting mainLayout
		######################################################################################################

		# The order widgets are added change the order they appear in the layout
		# Since main is QV order determines top to bottom
		self.mainLayout.addLayout(self.interactionLayout)

		self.mainLayout.addLayout(self.attributeInventoryLayout)

		self.mainLayout.addWidget(self.finishPushButton)


		######################################################################################################
		# re-Parenting interactionLayout
		######################################################################################################

		self.interactionLayout.addLayout(self.informationFormLayout)

		self.interactionLayout.addWidget(self.difficultyLabel)


		######################################################################################################
		# re-Parenting attributeInventoryLayout
		######################################################################################################

		self.attributeInventoryLayout.addLayout(self.attributesLayout)

		self.attributeInventoryLayout.addLayout(self.imageInventoryLayout)


		######################################################################################################
		# re-Parenting attributesLayout
		######################################################################################################

		self.attributesLayout.addWidget(self.strengthLabel)

		self.attributesLayout.addWidget(self.dexterityLabel)

		self.attributesLayout.addWidget(self.constitutionLabel)

		self.attributesLayout.addWidget(self.intellectLabel)

		######################################################################################################
		# re-Parenting imageInventoryLayout
		######################################################################################################

		self.imageInventoryLayout.addWidget(self.smallImageLabel)

		self.imageInventoryLayout.addWidget(self.inventoryLabel)


		######################################################################################################
		# Creating form layout for informationFormLayout
		######################################################################################################

		self.informationFormLayout.addRow("Player Name: ", self.playerNameLineEdit)

		self.informationFormLayout.addRow("Character Name: ", self.characterNameLineEdit)

		self.informationFormLayout.addRow("Class: ", self.classSelectorComboBox)

		self.informationFormLayout.addRow("Difficulty: ", self.difficultyComboBox)


		######################################################################################################
		# Connecting the widgets with methods
		######################################################################################################

		self.playerNameLineEdit.textChanged.connect(self.playerNameChange)

		self.classSelectorComboBox.activated[str].connect(self.classChange)

		self.classSelectorComboBox.activated[str].connect(self.classImageChange)

		self.difficultyComboBox.activated[str].connect(self.difficultyChange)

		self.finishPushButton.clicked.connect(self.finishChange)


	######################################################################################################
	# On Click Methods
	######################################################################################################



	def classChange(self, classNameText):
		"""
		Edits labels based on classNameText value
		## Create a stack layout and have each class have a VBoxLayout and when the signal is sent I change the image that is on top

		Input:
			classNameText <str>

		Output: 
			Change labels
		"""
		self.strengthString = "Strength: 10"
		self.dexterityString = "Dexterity: 10"
		self.constitutionString = "Constitution: 10"
		self.intellectString = "Intellect: 10"
		self.inventoryString = "No class starts with a fist"

		if (classNameText == self.barbarianString):

			self.strengthString ="Strength: 14"

			self.dexterityString = "Dexterity: 8"

			self.constitutionString = "Constitution: 12"

			self.intellectString = "Intellect: 6"

			self.inventoryString = "Barbarians start with an axe"



		elif (classNameText == self.knightString):

			self.strengthString = "Strength: 12"

			self.dexterityString = "Dexterity: 8"

			self.constitutionString = "Constitution: 12"

			self.intellectString = "Intellect: 8"

			self.inventoryString = "Knight = Sword, Duh"

		elif (classNameText == self.nerdString):

			self.strengthString = "Strength: 8"

			self.dexterityString = "Dexterity: 8"

			self.constitutionString = "Constitution: 8"

			self.intellectString = "Intellect: 16"

			self.inventoryString = "Nerds have no weapons"

		elif (classNameText == self.rogueString):

			self.strengthString = "Strength: 6"

			self.dexterityString = "Dexterity: 14"

			self.constitutionString = "Constitution: 8"

			self.intellectString = "Intellect: 12"

			self.inventoryString = "Rogues get a dagger"

		
		self.player_class = classNameText

		self.strengthLabel.setText(self.strengthString)

		self.dexterityLabel.setText(self.dexterityString)

		self.constitutionLabel.setText(self.constitutionString)

		self.intellectLabel.setText(self.intellectString)

		self.inventoryLabel.setText(self.inventoryString)




	def classImageChange(self, classNameText):
		"""
		Edits labels based on classNameText value

		Input:
			classNameText <str>

		Output: None
		"""
		

		if (classNameText == self.barbarianString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/barbarian.jpg"
			

		elif (classNameText == self.knightString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/knight.jpg"
			

		elif (classNameText == self.nerdString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/questionbox.jpg"
			

		elif (classNameText == self.rogueString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/rogue.png"
			

		elif (classNameText == self.noClassString):

			# ~/Documents/py/graphics_Basics/character_select/resources/
			self.imageResourceString = "resources/questionbox.jpg"
			

		self.smallImage = QImage(self.imageResourceString)
		self.smallerImage= self.smallImage.scaled(50,50)

		self.smallImagePixmap = QPixmap(self.smallerImage)

		self.smallImageLabel.setPixmap(self.smallImagePixmap)



	def difficultyChange(self, difficultyText):
		"""
		Edits labels based on difficultyText value

		Input:
			difficultyText <str>

		Output: None
		"""

		if (difficultyText == "Newb"):

			self.difficultyLabel.setText("A good difficulty for children and casuals")

		elif (difficultyText == "Decent"):

			self.difficultyLabel.setText("Fun and exciting adventure awaits")


		elif (difficultyText == "Gud"):

			self.difficultyLabel.setText("Good luck")



	def finishChange(self):
		"""
		TBD sends information decided on in the screen to game state
		Currently exits

		Input: None
			
		Output: None
		"""
		
		self.procGameStart.emit(1, self.player_class, self.character_name, self.player_name)
		self.procCharLabel.emit(self.imageResourceString)
		




	def playerNameChange(self, nameText):
		"""
		Changes player_name variable

		Input:
			nameText <str>

		Output: None
		"""
		self.player_name = nameText
コード例 #36
0
ファイル: dialogs.py プロジェクト: gbene/Rocpy
class import_dialog(QMainWindow,Ui_ImportOptionsWindow):
    '''[Gabriele]  New window class used to display import options and data preview.
    '''

    '''[Gabriele]  Different options that can be changed in the import menu:
        + in_path -> input file path
        + StartRowspinBox -> Start import from row number
        + EndRowspinBox -> End import on row number
        + Separator -> Type of separtor in the data set'''

    import_options_dict = {'in_path': '', 'StartRowspinBox': 0, 'EndRowspinBox': 100, 'SeparatorcomboBox': ' '}

    '''[Gabriele]  Different types of separators. By writing not using the symbol as a display we can avoid possible confusion between similar separators (e.g tab and space)-> now the separator is auto assigned with the auto_sep function'''

    sep_dict = {'<space>': ' ', '<comma>': ',', '<semi-col>': ';', '<tab>': '   '}

    def __init__(self,parent=None, *args, **kwargs):
        super(import_dialog, self).__init__(parent,*args, **kwargs)
        self.setupUi(self)
        self.parent = parent
        self.action = self.sender()  # [Gabriele] Name of the actionmenu from which the import function was called.

        self.args = []

        '''[Gabriele]  To generalize the import menu we can use the import_func_dict that has keys that correspond to the action name (eg actionImportPC) and items to the function (eg import_PC). If a new action needs to use this interface we can add to the dict the object name of the action and add a new function. This gives more flexibility in the importers output since it doesn't depend on a single function.

        To add a new import function (e.g. import_PC -> pc2vtk) add the function in this class and add it to the import_func_dict with this template:
            NameOfActionMenu: self.import_func()'''

        self.import_func_dict = {'actionImport_HB_data': self.import_HB}


        '''[Gabriele]  Different types of signals depending on the field in the import options'''
        self.PathtoolButton.clicked.connect(lambda: self.import_file())
        self.PathlineEdit.editingFinished.connect(lambda: self.import_file(path=self.PathlineEdit.text()))

        self.StartRowspinBox.valueChanged.connect(lambda: self.import_options(self.StartRowspinBox.objectName(), self.StartRowspinBox.value()))

        self.EndRowspinBox.valueChanged.connect(lambda: self.import_options(self.EndRowspinBox.objectName(), self.EndRowspinBox.value()))

        ''' [Gabriele] The text separator value is confronted with the dict values and then assigned the correct symbol. <comma> --> ","'''

        self.SeparatorcomboBox.currentTextChanged.connect(lambda: self.import_options(self.SeparatorcomboBox.objectName(), self.sep_dict[self.SeparatorcomboBox.currentText()]))

        self.PreviewButton.clicked.connect(lambda: self.preview_file(self.input_data_df))

        self.ConfirmBox.accepted.connect(self.import_func_dict[self.action.objectName()])
        self.ConfirmBox.rejected.connect(self.close)

        self.AssignTable.setColumnCount(2)
        self.AssignTable.setHorizontalHeaderLabels(['Column name', 'Property name'])
        self.AssignTable.setColumnWidth(1, 200)

        self.show_qt_canvas()

    def import_options(self, origin, value):
        '''[Gabriele]  Single function that manages all of the signals by adding to the import_options_dict a key,value pair corresponding to the origin object name and the set value.'''
        self.import_options_dict[origin] = value

    def show_qt_canvas(self):
        """Show the Qt Window"""
        self.show()

    def import_file(self, path=None):
        '''[Gabriele] Function used to read and preview a PC data file. The open_file_dialog function is used to obtain the file path. Once the file is chosen a different parser is used depending on the extension. Once the file is read the properties are autoassigned (where possible)'''
        if path == None:
            self.import_options_dict['in_path'] = open_file_dialog(parent=self, caption='Import point cloud data', filter="All supported (*.txt *.csv );; Text files (*.txt);; CSV files (*.csv)")
            self.PathlineEdit.setText(self.import_options_dict['in_path'])
        else:
            self.import_options_dict['in_path'] = path

        try:

            self.input_data_df = self.csv2df(self.import_options_dict['in_path'])

            self.default_attr_list = ['sci', 'mi', 'GSI', 'D', 'Ei', 'MR', 'application', 'gamma', 'H', 's3max', 'N.a.']

            '''[Gabriele]  Auto-assign values using the difflib library (internal). If there is no match then the column is not imported (N.a.). In this step the rename_dict dictionary is compiled where:
            - the keys correspond to the column index of the input df
            - the items correspond to the matched attribute (match score >0.8).
            If there is no match, the item will correspond to the original input column name.

            This dict is then used in the assign_data menu window to fill the corresponding values in each comboBox.
            '''

            col_names = list(self.input_data_df.columns)
            self.rename_dict = {}

            remove_char_dict = {"/": "", "\\": "", "?": "", "!": "", "-": "","_":""}  # [Gabriele] Forbidden characters that are removed from the names using the translate function

            for i, attr in enumerate(col_names):
                table = attr.maketrans(remove_char_dict)
                matches = [SequenceMatcher(None, attr.translate(table).lower(), string.lower()).ratio() for string in self.default_attr_list]
                match = max(matches)

                if match > 0.8:
                    index = matches.index(match)
                    self.rename_dict[i] = self.default_attr_list[index]
                else:
                    self.rename_dict[i] = 'N.a.'
            self.assign_data()  # [Gabriele] Open the assign data ui.
        except ValueError:
            print('Could not preview: invalid column, row or separator')
        except FileNotFoundError:
            print('Could not import: invalid file name')
            # [Gabriele] This clears the AssingTable and dataView table
            self.AssignTable.setRowCount(0)
            self.dataView.setModel(None)

    def preview_file(self, input_data_df):
        '''[Gabriele]  Function used to preview the data using the DataModel. The column and row ranges are obtained to properly slice the preview table.'''
        value_dict = {k: v for k, v in list(self.rename_dict.items()) if v != 'N.a.'}
        index_list = list(value_dict.keys())
        self.model = DataModel(self.input_data_df, index_list)
        self.dataView.setModel(self.model)

    def import_HB(self):

        clean_dict = {k: v for k, v in list(self.rename_dict.items()) if v != 'N.a.'}
        for key,name in clean_dict.items():
                dict_key = f'value_{name}'
                if dict_key == 'value_Ei':
                    print('ciao')
                    self.parent.calc_Ei.setChecked(True)
                elif dict_key == 'value_application':
                    value = self.input_data_df.iloc[0,key]
                    index = self.parent.value_application.findText(value)
                    self.parent.value_application.setCurrentIndex(index)

                else:
                    value = float(self.input_data_df.iloc[:,key])
                    if dict_key in self.parent.HB_in:
                        self.parent.HB_in[dict_key] = value
                    elif dict_key in self.parent.fail_in:
                        self.parent.fail_in[dict_key] = value
                    combo = getattr(self.parent,dict_key)
                    combo.setText(str(value))
                    combo.setFocus()
                    return_event = QKeyEvent(
                                        QEvent.KeyPress,
                                        Qt.Key_Return,
                                        Qt.NoModifier
                                    )
                    QCoreApplication.postEvent(combo,return_event)


    def csv2df(self, path):
        '''[Gabriele]  csv file parser.
        It reads the specified csv file using pd_read_csv. Wrapped in a function so that it can be profiled.
        --------------------------------------------------------
        Inputs:
        - csv file path

        Outputs:
        - Pandas df
        --------------------------------------------------------

        '''
        sep = ut.auto_sep(path)
        self.SeparatorcomboBox.setCurrentIndex(list(self.sep_dict.values()).index(sep))
        df = pd.read_csv(path, sep=sep, engine='c', index_col=False)
        return df


    def assign_data(self):

        df = self.input_data_df
        col_names = list(df.columns)
        LineList = []

        self.AssignTable.setRowCount(len(col_names))

        for i, col in enumerate(col_names):
            '''[Gabriele]  To create the assign menu we cicle through the column names and assign the comboBox text to the corresponding rename_dict item if the item is contained in the default_attr_list'''
            self.ColnameItem = QTableWidgetItem()
            self.ColnameItem.setText(str(col_names[i]))
            self.AttrcomboBox = QComboBox(self)
            self.AttrcomboBox.setObjectName(f'AttrcomboBox{i}')
            self.AttrcomboBox.setEditable(False)
            self.AttrcomboBox.addItems(self.default_attr_list)
            self.AttrcomboBox.activated.connect(lambda: ass_value())
            self.AssignTable.setItem(i, 0, self.ColnameItem)
            self.AssignTable.setCellWidget(i, 1, self.AttrcomboBox)

            self.AssignTable.cellWidget(i, 1).setCurrentText(self.rename_dict[i])

            self.AssignTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)

        # self.resize(750, 600) #[Gabriele] Set appropriate window size

        def ass_value():

            '''[Gabriele] Get column and row of clicked widget in table '''

            clicked = QApplication.focusWidget().pos()
            index = self.AssignTable.indexAt(clicked)
            col = index.column()
            row = index.row()
            sel_combo = self.AssignTable.cellWidget(row, col)  # [Gabriele] Combobox @ row and column

            '''[Gabriele] Use a dict to rename the columns. The keys are the column index of the original df while the values are the new names. '''


            items = list(self.rename_dict.values())
            if sel_combo.currentText() in items and sel_combo.currentText() != 'N.a.':
                print('Item already assigned')
            else:
                self.rename_dict[row] = sel_combo.currentText()
            self.preview_file(self.input_data_df)


    def close_ui(self):
        self.close()
        self.loop.quit()
コード例 #37
0
class App(QWidget):
    def __init__(self, data, showRows):
        super().__init__()
        self.data = data
        self.showRows = showRows
        self.initUI()

    def initUI(self):
        self.setWindowTitle('DataFrame Viewer')
        self.showMaximized()

        self.activePage = 0
        self.sortIndex = 0
        self.sortAscending = False

        #Buttons
        self.prevButton = QPushButton("< Prev", self)
        self.nextButton = QPushButton("Next >", self)
        self.lastButton = QPushButton("Last >>", self)
        self.firstButton = QPushButton("<< First", self)

        self.nextButton.clicked.connect(self.nextPage)
        self.prevButton.clicked.connect(self.prevPage)
        self.lastButton.clicked.connect(self.lastPage)
        self.firstButton.clicked.connect(self.firstPage)

        #Search
        self.searchBox = QLineEdit(self)
        self.searchBox.setPlaceholderText('Search in selected column...')
        self.searchBox.returnPressed.connect(self.loadDataFrame)
        self.searchComboBox = QComboBox()
        for col_name in list(self.data.columns):
            self.searchComboBox.addItem(col_name)
        self.searchComboBox.currentIndexChanged.connect(self.loadDataFrame)

        self.searchQueryCheckBox = QCheckBox("Search Query")
        self.searchQueryCheckBox.stateChanged.connect(self.loadDataFrame)

        #Table widget
        self.tableWidget = QTableWidget()
        self.tableWidget.horizontalHeader().sectionDoubleClicked.connect(
            self.changeSortCriteria)

        #Status bar
        self.statusBar = QStatusBar()

        #Layout
        self.Vlayout = QHBoxLayout()
        self.layout = QVBoxLayout()

        self.Vlayout.addWidget(self.searchBox)
        self.Vlayout.addWidget(self.searchComboBox)
        self.Vlayout.addWidget(self.searchQueryCheckBox)
        self.Vlayout.addWidget(self.prevButton)
        self.Vlayout.addWidget(self.nextButton)
        self.Vlayout.addWidget(self.firstButton)
        self.Vlayout.addWidget(self.lastButton)

        self.layout.addLayout(self.Vlayout)
        self.layout.addWidget(self.tableWidget)
        self.layout.addWidget(self.statusBar)
        self.setLayout(self.layout)
        self.loadDataFrame()
        self.show()

    @pyqtSlot()
    def nextPage(self):
        if self.activePage != self.maxPageNumber:
            self.activePage += 1
        self.loadDataFrame()

    def prevPage(self):
        if self.activePage != 0:
            self.activePage -= 1
        self.loadDataFrame()

    def lastPage(self):
        self.activePage = self.maxPageNumber
        self.loadDataFrame()

    def firstPage(self):
        self.activePage = 0
        self.loadDataFrame()

    def changeSortCriteria(self, i):
        if i == self.sortIndex:
            if self.sortAscending == True:
                self.sortAscending = False
            else:
                self.sortAscending = True

        self.sortIndex = i
        self.loadDataFrame()

    def loadDataFrame(self):
        try:
            df = self.data
            if len(self.searchBox.text()) >= 1:
                if self.searchQueryCheckBox.isChecked():
                    #Query mode
                    df = df.query(self.searchBox.text())
                    #We print query to log
                    print("Search Query: {}".format(self.searchBox.text()))
                else:
                    df = df[df[self.searchComboBox.currentText()].astype(
                        str).str.contains(self.searchBox.text())]

            self.rowsCount = df.shape[0]
            self.colsCount = df.shape[1]
            self.maxPageNumber = int(np.ceil(
                self.rowsCount / self.showRows)) - 1
            #to fix wrong page bug in search mode
            if self.activePage > self.maxPageNumber:
                self.activePage = 0
            self.statusBar.showMessage("Page {}/{}, Rows: {} - {}, Total Results : {}"\
                                       .format(self.activePage,\
                                           self.maxPageNumber,\
                                           (self.activePage*self.showRows),\
                                           (self.activePage*self.showRows+self.showRows),\
                                           self.rowsCount))

            df = df.reset_index()\
                .sort_values(self.data.columns[self.sortIndex], ascending=self.sortAscending)\
                .iloc[(self.activePage*self.showRows):(self.activePage*self.showRows+self.showRows)]

            self.tableWidget.setRowCount(0)
            self.tableWidget.setColumnCount(0)
            self.tableWidget.setColumnCount(self.colsCount)
            self.tableWidget.setHorizontalHeaderLabels(list(self.data.columns))
            self.tableWidget.setRowCount(df.shape[0])
            i = 0
            for index, row in df.iterrows():
                for col in range(self.colsCount):
                    w_item = QTableWidgetItem(str(row[col + 1]))
                    self.tableWidget.setItem(i, col, w_item)
                i += 1

        except Exception as e:
            print("An error occured. {}".format(e))
コード例 #38
0
 def createEditor(self, parent, option, idx):
     if idx.column() != 1:
         return None
     item = self.attrs_widget.model.itemFromIndex(idx)
     attr, dv = item.data(Qt.UserRole)
     text = item.text()
     if attr == ua.AttributeIds.NodeId:
         return None
     if dv.Value.VariantType == ua.VariantType.Boolean:
         combo = QComboBox(parent)
         combo.addItem("True")
         combo.addItem("False")
         combo.setCurrentText(text)
         return combo
     elif attr == ua.AttributeIds.NodeClass:
         combo = QComboBox(parent)
         for nclass in ua.NodeClass:
             combo.addItem(nclass.name)
         combo.setCurrentText(text)
         return combo
     elif attr == ua.AttributeIds.DataType:
         nodeid = getattr(ua.ObjectIds, text)
         node = Node(self.attrs_widget.current_node.server, nodeid)
         startnode = Node(self.attrs_widget.current_node.server, ua.ObjectIds.BaseDataType)
         button = GetNodeButton(parent, node, startnode)
         return button
     elif attr in (ua.AttributeIds.AccessLevel,
                   ua.AttributeIds.UserAccessLevel,
                   ua.AttributeIds.WriteMask,
                   ua.AttributeIds.UserWriteMask,
                   ua.AttributeIds.EventNotifier):
         #FIXME: make a ByteEditor we can choose and click bit ala QtCreator
         raise NotImplementedError
     else:
         return QStyledItemDelegate.createEditor(self, parent, option, idx)
コード例 #39
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')
        self._tuShareProCheckBox.clicked.connect(self._tuShareProCheckBoxClicked)

        self._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(self._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)

        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

        self._tuShareProTokenLabel.setEnabled(enableTuSharePro and enableTushareProToken)
        self._tuShareProTokenLineEdit.setEnabled(enableTuSharePro and enableTushareProToken)

        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)
コード例 #40
0
class GuiSettingsNiftiAnts(QWidget):
    """ Helper GUI, enabling setting changesconcerning different steps with the ANts Toolbox to analyse NIFTI data"""

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

        # Load configuration files and general settings
        self.cfg = Configuration.load_config(ROOTDIR)

        # General appearance of the GUI
        self.setFixedSize(800, 600)
        self.setWindowTitle('Settings for working with NIFTI files and ANTs Toolbox')
        self.show()

        # Create general layout
        self.layout_tot = QVBoxLayout(self)

        # ==============================    Create Content for Left Upper Box   ==============================
        self.optionboxBias = QGroupBox('N4BiasCorrection')
        self.settings_list1 = QVBoxLayout(self.optionboxBias)

        self.labelPrefix = QLabel('Output prefix?\t\t')
        self.labelPrefix.setToolTip(setToolTips.LabelPrefixBias())
        self.lineEditPrefix = QLineEdit()

        lay1 = QHBoxLayout()
        lay1.addWidget(self.labelPrefix)
        lay1.addWidget(self.lineEditPrefix)
        lay1.addStretch()

        self.labelDenoise = QLabel('Denoise images?\t\t')
        #        self.labelPrefix.setToolTip(setToolTips.LabelPrefixBias())
        self.btngroup_Denoise = QButtonGroup()
        self.rbtnDenoisey = QRadioButton('yes')
        self.rbtnDenoisen = QRadioButton('no')
        self.rbtnDenoisey.toggled.connect(self.onClickedRBTN_Denoise)
        self.rbtnDenoisen.toggled.connect(self.onClickedRBTN_Denoise)

        self.btngroup_Denoise.addButton(self.rbtnDenoisey)
        self.btngroup_Denoise.addButton(self.rbtnDenoisen)
        lay2 = QHBoxLayout()
        lay2.addWidget(self.labelDenoise)
        lay2.addWidget(self.rbtnDenoisey)
        lay2.addWidget(self.rbtnDenoisen)
        lay2.addStretch()

        self.labelShrink = QLabel('Shrink factor?\t\t')
        self.labelShrink.setToolTip(setToolTips.LabelShrink())
        self.lineEditShrink = QLineEdit()
        regex = QtCore.QRegExp('^[0-4]\d{0}$')
        validator1 = QtGui.QRegExpValidator(regex)
        self.lineEditShrink.setValidator(validator1)

        lay3 = QHBoxLayout()
        lay3.addWidget(self.labelShrink)
        lay3.addWidget(self.lineEditShrink)
        lay3.addStretch()

        # TODO double check the Label and the ToolTip to ensure accuracy
        self.labelBSplineDist = QLabel('Distance BSplines?\t')
        self.labelBSplineDist.setToolTip(setToolTips.BSplineDistance())
        self.lineEditBSplineDist = QLineEdit()
        regex = QtCore.QRegExp('^[0-9]\d{2}$')
        validator1 = QtGui.QRegExpValidator(regex)
        self.lineEditBSplineDist.setValidator(validator1)

        lay4 = QHBoxLayout()
        lay4.addWidget(self.labelBSplineDist)
        lay4.addWidget(self.lineEditBSplineDist)
        lay4.addStretch()

        width = 31.33
        self.labelConv = QLabel('Convergence?\t\t')
        self.labelConv.setToolTip(setToolTips.N4BiasConvergence())
        self.lineEditConv1 = QLineEdit()
        self.lineEditConv1.setFixedWidth(width)
        self.lineEditConv2 = QLineEdit()
        self.lineEditConv2.setFixedWidth(width)
        self.lineEditConv3 = QLineEdit()
        self.lineEditConv3.setFixedWidth(width)
        self.lineEditConv4 = QLineEdit()
        self.lineEditConv4.setFixedWidth(width)

        lay5 = QHBoxLayout()
        lay5.addWidget(self.labelConv)
        lay5.addWidget(self.lineEditConv1)
        lay5.addWidget(self.lineEditConv2)
        lay5.addWidget(self.lineEditConv3)
        lay5.addWidget(self.lineEditConv4)
        lay5.addStretch()

        self.labelTolerance = QLabel('Tolerance?\t\t')
        self.labelTolerance.setToolTip(setToolTips.N4BiasConvergence())
        self.lineEditTolerance = QLineEdit()

        lay6 = QHBoxLayout()
        lay6.addWidget(self.labelTolerance)
        lay6.addWidget(self.lineEditTolerance)
        lay6.addStretch()

        self.labelDiffPrefix = QLabel('Prefix for DTI data?\t')
        self.labelDiffPrefix.setToolTip(setToolTips.DiffPrefix())
        self.lineEditDiffPrefix = QLineEdit()

        lay7 = QHBoxLayout()
        lay7.addWidget(self.labelDiffPrefix)
        lay7.addWidget(self.lineEditDiffPrefix)
        lay7.addStretch()

        self.settings_list1.addLayout(lay1)
        self.settings_list1.addLayout(lay2)
        self.settings_list1.addLayout(lay3)
        self.settings_list1.addLayout(lay4)
        self.settings_list1.addLayout(lay5)
        self.settings_list1.addLayout(lay6)
        self.settings_list1.addLayout(lay7)
        self.settings_list1.addStretch()

        # ==============================    Create Content for Right Upper Box   ==============================
        self.optionboxRegistration = QGroupBox('ImageRegistration')
        self.settings_list2 = QVBoxLayout(self.optionboxRegistration)
        # self.settings_list2.addLayout(lay1)

        self.labelPrefixRegistration = QLabel('Registration prefix?\t')
        # self.labelPrefixRegistration.setToolTip(setToolTips.LabelPrefixBias())
        self.lineEditPrefixRegistration = QLineEdit()

        lay8 = QHBoxLayout()
        lay8.addWidget(self.labelPrefixRegistration)
        lay8.addWidget(self.lineEditPrefixRegistration)
        lay8.addStretch()

        self.labelResampleSpacing = QLabel('Resample Spacing?\t')
        self.labelResampleSpacing.setToolTip(setToolTips.LabelResampleImages())
        self.lineResampleSpacing = QLineEdit()

        lay10 = QHBoxLayout()
        lay10.addWidget(self.labelResampleSpacing)
        lay10.addWidget(self.lineResampleSpacing)
        lay10.addStretch()

        self.labelResampleMethod = QLabel('Resampling method?\t')
        self.labelResampleMethod.setToolTip(setToolTips.ResampleMethod())
        self.btngroup_ResampleMethod = QButtonGroup()
        self.rbtnResample0 = QRadioButton("0")  # 0 (lin.), 1 (near. neighb.), 2 (gauss.), 3 (window. sinc), 4 (bspline)
        self.rbtnResample1 = QRadioButton("1")
        self.rbtnResample2 = QRadioButton("2")
        self.rbtnResample3 = QRadioButton("3")
        self.rbtnResample4 = QRadioButton("4")
        self.rbtnResample0.toggled.connect(self.onClickedRBTN_ResampleMethod)
        self.rbtnResample1.toggled.connect(self.onClickedRBTN_ResampleMethod)
        self.rbtnResample2.toggled.connect(self.onClickedRBTN_ResampleMethod)
        self.rbtnResample3.toggled.connect(self.onClickedRBTN_ResampleMethod)
        self.rbtnResample4.toggled.connect(self.onClickedRBTN_ResampleMethod)

        self.btngroup_ResampleMethod.addButton(self.rbtnResample0)
        self.btngroup_ResampleMethod.addButton(self.rbtnResample1)
        self.btngroup_ResampleMethod.addButton(self.rbtnResample2)
        self.btngroup_ResampleMethod.addButton(self.rbtnResample3)
        self.btngroup_ResampleMethod.addButton(self.rbtnResample4)

        lay11 = QHBoxLayout()
        lay11.addWidget(self.labelResampleMethod)
        lay11.addWidget(self.rbtnResample0)
        lay11.addWidget(self.rbtnResample1)
        lay11.addWidget(self.rbtnResample2)
        lay11.addWidget(self.rbtnResample3)
        lay11.addWidget(self.rbtnResample4)

        self.labelDefaultSettings = QLabel('Default registration?\t')
        #        self.labelPrefix.setToolTip(setToolTips.LabelPrefixBias())
        self.btngroup_DefaultSettingsRegistration = QButtonGroup()
        self.rbtnDefaultRegistrationy = QRadioButton('yes')
        self.rbtnDefaultRegistrationn = QRadioButton('no')
        self.rbtnDefaultRegistrationy.toggled.connect(self.onClickedRBTN_DefaultRegistration)
        self.rbtnDefaultRegistrationn.toggled.connect(self.onClickedRBTN_DefaultRegistration)

        self.btngroup_DefaultSettingsRegistration.addButton(self.rbtnDefaultRegistrationy)
        self.btngroup_DefaultSettingsRegistration.addButton(self.rbtnDefaultRegistrationn)
        lay12 = QHBoxLayout()
        lay12.addWidget(self.labelDefaultSettings)
        lay12.addWidget(self.rbtnDefaultRegistrationy)
        lay12.addWidget(self.rbtnDefaultRegistrationn)
        lay12.addStretch()

        self.labelRegistrationMethod = QLabel('Registration method?\t')
        # self.labelRegistrationMethod.setToolTip(setToolTips.LabelResampleImages())
        self.lineRegistrationMethod = QComboBox()
        allowable_tx = [
            "SyNBold",
            "SyNBoldAff",
            "ElasticSyN",
            "SyN",
            "SyNRA",
            "SyNOnly",
            "SyNAggro",
            "SyNCC",
            "TRSAA",
            "SyNabp",
            "SyNLessAggro",
            "TVMSQ",
            "TVMSQC",
            "Rigid",
            "Similarity",
            "Translation",
            "Affine",
            "AffineFast",
            "BOLDAffine",
            "QuickRigid",
            "DenseRigid",
            "BOLDRigid",
        ]
        [self.lineRegistrationMethod.addItem(x) for x in allowable_tx]
        idx_method = self.lineRegistrationMethod.findText(self.cfg["preprocess"]["registration"]["registration_method"],
                                                          QtCore.Qt.MatchFixedString)
        if idx_method >= 0:
            self.lineRegistrationMethod.setCurrentIndex(idx_method)
        self.lineRegistrationMethod.currentTextChanged.connect(self.comboChangedRegDefault)
        self.lineRegistrationMethod.setDisabled(True)

        lay13 = QHBoxLayout()
        lay13.addWidget(self.labelRegistrationMethod)
        lay13.addWidget(self.lineRegistrationMethod)
        lay13.addStretch()

        self.labelCustomRegistration = QLabel('Edit registration settings?\t')
        self.PushButtonViewRegistration = QPushButton("Edit cmdline")
        self.PushButtonViewRegistration.setDisabled(True)
        self.PushButtonViewRegistration.clicked.connect(self.viewRegistrationCmdLine)

        lay14 = QHBoxLayout()
        lay14.addWidget(self.labelCustomRegistration)
        lay14.addWidget(self.PushButtonViewRegistration)
        lay14.addStretch()

        self.labelNormalisationTemplate = QLabel('Normalisation template?\t')
        # self.labelRegistrationMethod.setToolTip(setToolTips.LabelResampleImages())
        self.lineTemplatesAvailable = QComboBox()
        [self.lineTemplatesAvailable.addItem(os.path.split(x)[1]) for x in
         glob.glob(os.path.join(ROOTDIR, 'ext', 'templates' + '/*'))]
        idx_template = self.lineRegistrationMethod.findText(self.cfg["preprocess"]["normalisation"]["template_image"],
                                                            QtCore.Qt.MatchFixedString)

        if idx_template >= 0:
            self.lineRegistrationMethod.setCurrentIndex(idx_template)
        self.lineTemplatesAvailable.currentTextChanged.connect(self.comboChangedNormalisation)

        lay15 = QHBoxLayout()
        lay15.addWidget(self.labelNormalisationTemplate)
        lay15.addWidget(self.lineTemplatesAvailable)
        lay15.addStretch()

        self.labelNormalisationSequences = QLabel('Sequences to normalise?\t')
        # self.labelPrefixRegistration.setToolTip(setToolTips.LabelPrefixBias())
        self.lineEditNormalisationSequences = QLineEdit()

        lay16 = QHBoxLayout()
        lay16.addWidget(self.labelNormalisationSequences)
        lay16.addWidget(self.lineEditNormalisationSequences)
        lay16.addStretch()

        self.settings_list2.addLayout(lay8)
        self.settings_list2.addStretch(1)
        self.settings_list2.addLayout(lay10)
        self.settings_list2.addLayout(lay11)
        self.settings_list2.addStretch(1)
        self.settings_list2.addLayout(lay12)
        self.settings_list2.addLayout(lay13)
        self.settings_list2.addLayout(lay14)
        self.settings_list2.addStretch(1)
        self.settings_list2.addLayout(lay15)
        self.settings_list2.addLayout(lay16)
        self.settings_list2.addStretch(10)

        # Merge all upper boxes
        self.layout_upper = QHBoxLayout()
        self.layout_upper.addWidget(self.optionboxBias)
        self.layout_upper.addWidget(self.optionboxRegistration)

        # ====================    Create Content for Buttons at the Bottom      ====================
        layout_bottom = QHBoxLayout()
        self.buttonsave = QPushButton('Save settings \nand return')
        self.buttonsave.clicked.connect(self.close)
        self.buttondefault = QPushButton('Load Default \nsettings')
        self.buttondefault.clicked.connect(self.load_default_settings)

        layout_bottom.addStretch(1)
        layout_bottom.addWidget(self.buttonsave)
        layout_bottom.addWidget(self.buttondefault)

        # ====================    Set Content of box and buttoms to General Layout     =======================
        self.layout_tot.addLayout(self.layout_upper)
        self.layout_tot.addLayout(layout_bottom)
        self.get_settings_from_config()

    def get_settings_from_config(self):
        """function which enters the settings according to some cfg variable which is loaded"""

        if self.cfg == "":
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Warning)
            msgBox.setText("No default settings found, please double check the folder content. Continuing "
                           "with same settings.")
            msgBox.setWindowTitle("Warning")
            msgBox.setStandardButtons(QMessageBox.Close)
            msgBox.exec()
        else:
            # Left side, i.e. N4BiasCorrection
            self.lineEditPrefix.setText(self.cfg["preprocess"]["ANTsN4"]["prefix"])

            if self.cfg["preprocess"]["ANTsN4"]["denoise"] == 'yes':
                self.rbtnDenoisey.setChecked(True)
            else:
                self.rbtnDenoisen.setChecked(True)

            if self.cfg["preprocess"]["registration"]["resample_method"] == 1:
                self.rbtnResample1.setChecked(True)
            elif self.cfg["preprocess"]["registration"]["resample_method"] == 2:
                self.rbtnResample2.setChecked(True)
            elif self.cfg["preprocess"]["registration"]["resample_method"] == 3:
                self.rbtnResample3.setChecked(True)
            elif self.cfg["preprocess"]["registration"]["resample_method"] == 4:
                self.rbtnResample4.setChecked(True)
            else:
                self.rbtnResample0.setChecked(True)

            if self.cfg["preprocess"]["registration"]["default_registration"] == 'yes':
                self.rbtnDefaultRegistrationy.setChecked(True)

            self.lineEditShrink.setText(str(self.cfg["preprocess"]["ANTsN4"]["shrink-factor"]))
            self.lineEditBSplineDist.setText(str(self.cfg["preprocess"]["ANTsN4"]["bspline-fitting"]))
            self.lineEditConv1.setText(str(self.cfg["preprocess"]["ANTsN4"]["convergence"][0]))
            self.lineEditConv2.setText(str(self.cfg["preprocess"]["ANTsN4"]["convergence"][1]))
            self.lineEditConv3.setText(str(self.cfg["preprocess"]["ANTsN4"]["convergence"][2]))
            self.lineEditConv4.setText(str(self.cfg["preprocess"]["ANTsN4"]["convergence"][3]))
            self.lineEditTolerance.setText(str(self.cfg["preprocess"]["ANTsN4"]["threshold"]))
            self.lineEditDiffPrefix.setText(str(self.cfg["preprocess"]["ANTsN4"]["dti_prefix"]))

            # Right side, i.e. Registration
            self.lineEditPrefixRegistration.setText(self.cfg["preprocess"]["registration"]["prefix"])
            self.lineResampleSpacing.setText(str(self.cfg["preprocess"]["registration"]["resample_spacing"]))

            self.lineEditNormalisationSequences.setText(str(self.cfg["preprocess"]["normalisation"]["sequences"]))

    def closeEvent(self, event):
        """saves the settings found here as a yaml file which may be loaded the next time as the configuration used"""

        self.cfg["preprocess"]["ANTsN4"]["prefix"] = self.lineEditPrefix.text()
        self.cfg["preprocess"]["ANTsN4"]["shrink-factor"] = int(self.lineEditShrink.text())
        self.cfg["preprocess"]["ANTsN4"]["bspline-fitting"] = int(self.lineEditBSplineDist.text())
        self.cfg["preprocess"]["ANTsN4"]["convergence"][0] = int(self.lineEditConv1.text())
        self.cfg["preprocess"]["ANTsN4"]["convergence"][1] = int(self.lineEditConv2.text())
        self.cfg["preprocess"]["ANTsN4"]["convergence"][2] = int(self.lineEditConv3.text())
        self.cfg["preprocess"]["ANTsN4"]["convergence"][3] = int(self.lineEditConv4.text())
        self.cfg["preprocess"]["ANTsN4"]["threshold"] = float(self.lineEditTolerance.text())
        self.cfg["preprocess"]["ANTsN4"]["dti_prefix"] = self.lineEditDiffPrefix.text()

        self.cfg["preprocess"]["registration"]["prefix"] = self.lineEditPrefixRegistration.text()
        self.cfg["preprocess"]["registration"]["resample_spacing"] = self.lineResampleSpacing.text()

        self.cfg["preprocess"]["normalisation"]["sequences"] = self.lineEditNormalisationSequences.text()

        Configuration.save_config(ROOTDIR, self.cfg)
        event.accept()

    def load_default_settings(self):
        """loads the default settings as per the file in the private folder; for that a confirmation is necessary"""

        ret = QMessageBox.question(self, 'MessageBox', "Do you really want to restore default settings for ANTs?",
                                   QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        if ret == QMessageBox.Yes:
            with open(os.path.join(ROOTDIR, 'private/') + 'config_imagingTBdef.yaml', 'r') as cfg:
                cfg_temp = yaml.safe_load(cfg)
                self.cfg["preprocess"]["ANTsN4"] = cfg_temp["preprocess"]["ANTsN4"]
                self.cfg["preprocess"]["registration"] = cfg_temp["preprocess"]["registration"]
        self.get_settings_from_config()

        idx_method = self.lineRegistrationMethod.findText(self.cfg["preprocess"]["registration"]["registration_method"],
                                                          QtCore.Qt.MatchFixedString)
        if idx_method >= 0:
            self.lineRegistrationMethod.setCurrentIndex(idx_method)

        idx_template = self.lineRegistrationMethod.findText(self.cfg["preprocess"]["normalisation"]["template_image"],
                                                            QtCore.Qt.MatchFixedString)
        if idx_template >= 0:
            self.lineRegistrationMethod.setCurrentIndex(idx_template)
        self.lineTemplatesAvailable.currentTextChanged.connect(self.comboChangedNormalisation)

    # ====================    Actions when buttons are pressed      ====================
    @QtCore.pyqtSlot()
    def viewRegistrationCmdLine(self):
        """opens CmdLine to write custom registration settings. For correct arguments cf. to ANTs environment homepage
        (e.g.https://github.com/ANTsX/ANTs/wiki/Anatomy-of-an-antsRegistration-call). An example of how to implement
        something similar can be found in the [private] directory """
        from subprocess import Popen

        if sys.platform == 'linux':
            Popen(["gedit", os.path.join(ROOTDIR, 'utils', 'cmdline_ANTsRegistration.txt')],
                  stdin=open(os.devnull, 'r'))
        elif sys.platform == 'macos':
            print('Not yet implemented!!')

    @QtCore.pyqtSlot()
    def onClickedRBTN_shrink(self):
        radioBtn = self.sender()
        radioBtn.isChecked()
        self.cfg["preprocess"]["ANTsN4"]["shrink"] = self.sender().text()

    @QtCore.pyqtSlot()
    def onClickedRBTN_Denoise(self):
        radioBtn = self.sender()
        radioBtn.isChecked()
        self.cfg["preprocess"]["ANTsN4"]["denoise"] = self.sender().text()

    @QtCore.pyqtSlot()
    def onClickedRBTN_ResampleMethod(self):
        radioBtn = self.sender()
        radioBtn.isChecked()
        self.cfg["preprocess"]["registration"]["resample_method"] = self.sender().text()

    @QtCore.pyqtSlot()
    def onClickedRBTN_DefaultRegistration(self):
        radioBtn = self.sender()
        radioBtn.isChecked()
        self.cfg["preprocess"]["registration"]["default_registration"] = self.sender().text()

        if self.sender().text() == 'no':
            self.PushButtonViewRegistration.setEnabled(True)
            self.lineRegistrationMethod.setEnabled(False)
        else:
            self.PushButtonViewRegistration.setEnabled(False)
            self.lineRegistrationMethod.setEnabled(True)

    @QtCore.pyqtSlot()
    def comboChangedRegDefault(self):
        self.cfg["preprocess"]["registration"]["registration_method"] = self.lineRegistrationMethod.currentText()
        Configuration.save_config(ROOTDIR, self.cfg)

    @QtCore.pyqtSlot()
    def comboChangedNormalisation(self):
        self.cfg["preprocess"]["normalisation"]["template_image"] = self.lineTemplatesAvailable.currentText()
        Configuration.save_config(ROOTDIR, self.cfg)
コード例 #41
0
class SerialDialog(QDialog):
    def __init__(self):
        super(SerialDialog, self).__init__()
        #self.root = parent
        self.baudrate = 4800
        self.comport = "COM1"
        self.setup_dialog()
        self.setWindowTitle("Select Load Cell COM Port")
        self.setWindowModality(Qt.ApplicationModal)
        self.connected = False
        self.ser = None
        self.load_cell_settings_file = "load_cell_setting.txt"

    def setup_dialog(self):

        load_cell_port_label = QLabel("load_cell Communications Port")
        self.load_cell_port_combo_box = QComboBox()
        self.load_cell_port_combo_box.setInsertPolicy(QComboBox.NoInsert)
        for device in sorted(serial.tools.list_ports.comports(), reverse=True):
            self.load_cell_port_combo_box.addItem("{} - {}".format(
                device.device, device.description))
        self.load_cell_port_combo_box.setSizeAdjustPolicy(
            QComboBox.AdjustToContents)

        baud_list = [
            "{}".format(b) for b in [
                4800, 9600, 115200, 1200, 1800, 2400, 19200, 38400, 57600,
                115200, 230400, 460800, 500000, 576000, 921600, 1000000,
                1152000, 1500000, 2000000, 2500000, 3000000, 3500000, 4000000
            ]
        ]

        baud_label = QLabel("load_cell Baud Rate")
        self.baud_combo_box = QComboBox()
        self.baud_combo_box.setInsertPolicy(QComboBox.NoInsert)
        self.baud_combo_box.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.baud_combo_box.addItems(baud_list)

        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

        self.accepted.connect(self.set_load_cell)
        #self.rejected.connect(self.reject_load_cell)

        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(load_cell_port_label)
        self.v_layout.addWidget(self.load_cell_port_combo_box)
        self.v_layout.addWidget(baud_label)
        self.v_layout.addWidget(self.baud_combo_box)
        self.v_layout.addWidget(self.buttons)

        self.setLayout(self.v_layout)

    def run(self):
        self.load_cell_port_combo_box.clear()
        for device in sorted(serial.tools.list_ports.comports(), reverse=True):
            self.load_cell_port_combo_box.addItem("{} - {}".format(
                device.device, device.description))
        self.load_cell_port_combo_box.setSizeAdjustPolicy(
            QComboBox.AdjustToContents)
        self.exec_()

    def set_load_cell(self):
        self.comport = self.load_cell_port_combo_box.currentText().split(
            '-')[0].strip()
        self.baud = int(self.baud_combo_box.currentText())
        return self.connect_load_cell()

    def connect_load_cell(self):
        logger.debug("Trying to connect load_cell.")
        try:
            self.ser.close()
            del self.ser
        except AttributeError:
            pass

        try:
            self.ser = serial.Serial(self.comport,
                                     baudrate=self.baud,
                                     timeout=2)
        except serial.serialutil.SerialException:
            logger.debug(traceback.format_exc())
            if "PermissionError" in repr(traceback.format_exc()):
                QMessageBox.information(
                    self, "load_cell Status",
                    "The port {} is already in use. Please unplug and replug the load cell unit."
                    .format(self.comport))
            else:
                self.connected = False
                return False
        try:
            self.ser.write(
                "CT0\r".encode('ascii')
            )  # see http://www.loadstarsensors.com/assets/manuals/html/iload_commmand_set.html
            self.ser.readline()
            time.sleep(.1)
            self.ser.write(
                "SS1\r".encode('ascii')
            )  # see http://www.loadstarsensors.com/assets/manuals/html/iload_commmand_set.html
            test_sentence = self.ser.readline().decode('ascii',
                                                       'ignore').strip()
            logger.info("Connected to {}".format(test_sentence))

            if len(test_sentence) > 0:
                logger.info("Successful load cell connection on {}".format(
                    self.comport))
                with open(self.load_cell_settings_file, "w") as out_file:
                    out_file.write("{},{}\n".format(self.comport, self.baud))
                self.connected = True
                #self.ser.write("CPS 32\r".encode('ascii')) # see http://www.loadstarsensors.com/assets/manuals/html/iload_commmand_set.html
                #self.ser.readline()
                self.ser.write(
                    "CSS 5\r".encode('ascii')
                )  # see http://www.loadstarsensors.com/assets/manuals/html/iload_commmand_set.html
                self.ser.readline()
                self.ser.write(
                    "CLA 1\r".encode('ascii')
                )  # see http://www.loadstarsensors.com/assets/manuals/html/iload_commmand_set.html
                self.ser.readline()
                self.ser.write(
                    "O0W0\r".encode('ascii')
                )  # see http://www.loadstarsensors.com/assets/manuals/html/iload_commmand_set.html

                return True
            else:
                logger.debug(
                    "Could not find load cell connection on {}".format(
                        self.comport))
                QMessageBox.information(
                    self, "No Connection",
                    "Could not find load_cell connection on {}".format(
                        self.comport))
                self.connected = False
                return False
        except:
            logger.debug(traceback.format_exc())
            return False

    def try_loadcell(self):
        try:
            with open(self.load_cell_settings_file, "r") as in_file:
                lines = in_file.readlines()
            line_list = lines[0].split(",")
            self.comport = line_list[0]
            self.baud = line_list[1]
            self.connected = self.connect_load_cell()

        except FileNotFoundError:
            self.connected = False
        return self.connected
コード例 #42
0
class ChartLab(QWidget):
    def __init__(self, sas_if: sasIF):
        super(ChartLab, self).__init__()

        # ---------------- ext var ----------------

        self.__sas_if = sas_if
        self.__inited = False
        self.__plot_table = {}
        self.__paint_data = None

        # ------------- plot resource -------------

        self.__figure = plt.figure()
        self.__canvas = FigureCanvas(self.__figure)

        # -------------- ui resource --------------

        self.__data_frame_widget = None

        self.__combo_factor = QComboBox()
        self.__label_comments = QLabel('')

        # Parallel comparison
        self.__radio_parallel_comparison = QRadioButton('横向比较')
        self.__combo_year = QComboBox()
        self.__combo_quarter = QComboBox()
        self.__combo_industry = QComboBox()

        # Longitudinal comparison
        self.__radio_longitudinal_comparison = QRadioButton('纵向比较')
        self.__combo_stock = SecuritiesSelector(self.__sas_if)

        # Limitation
        self.__line_lower = QLineEdit('')
        self.__line_upper = QLineEdit('')

        self.__button_draw = QPushButton('绘图')
        self.__button_show = QPushButton('查看绘图数据')

        self.init_ui()

    # ---------------------------------------------------- UI Init -----------------------------------------------------

    def init_ui(self):
        self.__layout_control()
        self.__config_control()

    def __layout_control(self):
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)
        self.setMinimumSize(1280, 800)

        bottom_layout = QHBoxLayout()
        main_layout.addWidget(self.__canvas, 99)
        main_layout.addLayout(bottom_layout, 1)

        group_box, group_layout = create_v_group_box('因子')
        bottom_layout.addWidget(group_box, 2)

        group_layout.addWidget(self.__combo_factor)
        group_layout.addWidget(self.__label_comments)

        group_box, group_layout = create_v_group_box('比较方式')
        bottom_layout.addWidget(group_box, 2)

        line = QHBoxLayout()
        line.addWidget(self.__radio_parallel_comparison, 1)
        line.addWidget(self.__combo_industry, 5)
        line.addWidget(self.__combo_year, 5)
        line.addWidget(self.__combo_quarter, 5)
        group_layout.addLayout(line)

        line = QHBoxLayout()
        line.addWidget(self.__radio_longitudinal_comparison, 1)
        line.addWidget(self.__combo_stock, 10)
        group_layout.addLayout(line)

        group_box, group_layout = create_v_group_box('范围限制')
        bottom_layout.addWidget(group_box, 1)

        line = QHBoxLayout()
        line.addWidget(QLabel('下限'))
        line.addWidget(self.__line_lower)
        group_layout.addLayout(line)

        line = QHBoxLayout()
        line.addWidget(QLabel('上限'))
        line.addWidget(self.__line_upper)
        group_layout.addLayout(line)

        col = QVBoxLayout()
        col.addWidget(self.__button_draw)
        col.addWidget(self.__button_show)
        bottom_layout.addLayout(col, 1)

    def __config_control(self):
        for year in range(now().year, 1989, -1):
            self.__combo_year.addItem(str(year), str(year))
        self.__combo_year.setCurrentIndex(1)

        self.__combo_quarter.addItem('一季报', '03-31')
        self.__combo_quarter.addItem('中报', '06-30')
        self.__combo_quarter.addItem('三季报', '09-30')
        self.__combo_quarter.addItem('年报', '12-31')
        self.__combo_quarter.setCurrentIndex(3)

        self.__combo_industry.addItem('全部', '全部')
        identities = self.__sas_if.sas_get_all_industries()
        for identity in identities:
            self.__combo_industry.addItem(identity, identity)

        if self.__sas_if is not None:
            factors = self.__sas_if.sas_get_all_factors()
            for fct in factors:
                self.__combo_factor.addItem(fct, fct)
        self.on_factor_updated(0)

        self.__combo_stock.setEnabled(False)
        self.__radio_parallel_comparison.setChecked(True)

        self.__radio_parallel_comparison.setToolTip(TIP_PARALLEL_COMPARISON)
        self.__radio_longitudinal_comparison.setToolTip(
            TIP_LONGITUDINAL_COMPARISON)
        self.__line_lower.setToolTip(TIP_LIMIT_UPPER_LOWER)
        self.__line_upper.setToolTip(TIP_LIMIT_UPPER_LOWER)
        self.__button_show.setToolTip(TIP_BUTTON_SHOW)

        self.__button_draw.clicked.connect(self.on_button_draw)
        self.__button_show.clicked.connect(self.on_button_show)

        self.__combo_factor.currentIndexChanged.connect(self.on_factor_updated)
        self.__radio_parallel_comparison.clicked.connect(
            self.on_radio_comparison)
        self.__radio_longitudinal_comparison.clicked.connect(
            self.on_radio_comparison)

        mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']
        mpl.rcParams['axes.unicode_minus'] = False

    def on_factor_updated(self, value):
        self.__line_lower.setText('')
        self.__line_upper.setText('')
        factor = self.__combo_factor.itemData(value)
        comments = self.__sas_if.sas_get_factor_comments(factor)
        self.__label_comments.setText(comments)

    def on_button_draw(self):
        factor = self.__combo_factor.currentData()
        lower = str2float_safe(self.__line_lower.text(), None)
        upper = str2float_safe(self.__line_upper.text(), None)

        if self.__radio_parallel_comparison.isChecked():
            year = self.__combo_year.currentData()
            month_day = self.__combo_quarter.currentData()
            period = year + '-' + month_day
            industry = self.__combo_industry.currentData()
            self.plot_factor_parallel_comparison(factor, industry,
                                                 text_auto_time(period), lower,
                                                 upper)
        else:
            securities = self.__combo_stock.get_input_securities()
            self.plot_factor_longitudinal_comparison(factor, securities)

    def on_button_show(self):
        if self.__data_frame_widget is not None and \
                self.__data_frame_widget.isVisible():
            self.__data_frame_widget.close()
        if self.__paint_data is not None:
            self.__data_frame_widget = DataFrameWidget(self.__paint_data)
            self.__data_frame_widget.show()

    def on_radio_comparison(self):
        if self.__radio_parallel_comparison.isChecked():
            self.__combo_year.setEnabled(True)
            self.__combo_quarter.setEnabled(True)
            self.__line_lower.setEnabled(True)
            self.__line_upper.setEnabled(True)
            self.__combo_stock.setEnabled(False)
        else:
            self.__combo_year.setEnabled(False)
            self.__combo_quarter.setEnabled(False)
            self.__line_lower.setEnabled(False)
            self.__line_upper.setEnabled(False)
            self.__combo_stock.setEnabled(True)

    # ---------------------------------------------------------------------------------------

    def plot_factor_parallel_comparison(self, factor: str, industry: str,
                                        period: datetime.datetime,
                                        lower: float, upper: float):
        identities = ''
        if industry != '全部':
            identities = self.__sas_if.sas_get_industry_stocks(industry)
        df = self.__sas_if.sas_factor_query(identities, [factor],
                                            (period, period), {},
                                            readable=True)

        if df is None or df.empty:
            return

        s1 = df[factor]
        if lower is not None and upper is not None:
            s1 = s1.apply(lambda x: (x if x < upper else upper)
                          if x > lower else lower)
        elif lower is not None:
            s1 = s1.apply(lambda x: x if x > lower else lower)
        elif upper is not None:
            s1 = s1.apply(lambda x: x if x < upper else upper)

        plt.clf()
        plt.subplot(1, 1, 1)
        s1.hist(bins=100)
        plt.title(factor)

        self.__canvas.draw()
        self.__canvas.flush_events()

        self.__paint_data = df
        self.__paint_data.sort_values(factor, inplace=True)

    def plot_factor_longitudinal_comparison(self, factor: str,
                                            securities: str):
        df = self.__sas_if.sas_factor_query(securities, [factor],
                                            None, {},
                                            readable=True)
        # Only for annual report
        df = df[df['period'].dt.month == 12]
        df['报告期'] = df['period']
        df.set_index('报告期', inplace=True)

        s1 = df[factor]

        plt.clf()
        plt.subplot(1, 1, 1)
        s1.plot.line()
        plt.title(factor)

        self.__canvas.draw()
        self.__canvas.flush_events()

        self.__paint_data = df
        self.__paint_data.sort_values('period', ascending=False, inplace=True)

    # ---------------------------------------------------------------------------------------

    def plot(self):
        self.plot_histogram_statistics()

    def plot_histogram_statistics(self):
        # --------------------------- The Data and Period We Want to Check ---------------------------

        stock = ''
        period = (text_auto_time('2018-12-01'), text_auto_time('2018-12-31'))

        # --------------------------------------- Query Pattern --------------------------------------

        # fields_balance_sheet = ['货币资金', '资产总计', '负债合计',
        #                         '短期借款', '一年内到期的非流动负债', '其他流动负债',
        #                         '长期借款', '应付债券', '其他非流动负债', '流动负债合计',
        #                         '应收票据', '应收账款', '其他应收款', '预付款项',
        #                         '交易性金融资产', '可供出售金融资产',
        #                         '在建工程', '商誉', '固定资产']
        # fields_income_statement = ['营业收入', '营业总收入', '减:营业成本', '息税前利润']
        #
        # df, result = batch_query_readable_annual_report_pattern(
        #     self.__data_hub, stock, period, fields_balance_sheet, fields_income_statement)
        # if result is not None:
        #     return result

        # df_balance_sheet, result = query_readable_annual_report_pattern(
        #     self.__data_hub, 'Finance.BalanceSheet', stock, period, fields_balance_sheet)
        # if result is not None:
        #     print('Data Error')
        #
        # df_income_statement, result = query_readable_annual_report_pattern(
        #     self.__data_hub, 'Finance.IncomeStatement', stock, period, fields_income_statement)
        # if result is not None:
        #     print('Data Error')

        # -------------------------------- Merge and Pre-processing --------------------------------

        # df = pd.merge(df_balance_sheet,
        #               df_income_statement,
        #               how='left', on=['stock_identity', 'period'])

        # df = df.sort_values('period')
        # df = df.reset_index()
        # df = df.fillna(0)
        # df = df.replace(0, 1)

        # ------------------------------------- Calc and Plot -------------------------------------

        mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']
        mpl.rcParams['axes.unicode_minus'] = False

        # font = matplotlib.font_manager.FontProperties(fname='C:/Windows/Fonts/msyh.ttf')
        # mpl.rcParams['axes.unicode_minus'] = False

        # df['应收款'] = df['应收账款'] + df['应收票据']
        # df['净资产'] = df['资产总计'] - df['负债合计']
        # df['短期负债'] = df['短期借款'] + df['一年内到期的非流动负债'] + df['其他流动负债']
        # df['有息负债'] = df['短期负债'] + df['长期借款'] + df['应付债券'] + df['其他非流动负债']
        # df['金融资产'] = df['交易性金融资产'] + df['可供出售金融资产']
        #
        # df['财务费用正'] = df['减:财务费用'].apply(lambda x: x if x > 0 else 0)
        # df['三费'] = df['减:销售费用'] + df['减:管理费用'] + df['财务费用正']

        df = self.__sas_if.sas_auto_query(
            '', period,
            ['减:财务费用', '减:销售费用', '减:管理费用', '营业总收入', '营业收入', '减:营业成本'],
            ['stock_identity', 'period'])

        df['毛利润'] = df['营业收入'] - df['减:营业成本']
        df['财务费用正'] = df['减:财务费用'].apply(lambda x: x if x > 0 else 0)
        df['三费'] = df['减:销售费用'] + df['减:管理费用'] + df['财务费用正']

        s1 = df['三费'] / df['营业总收入']
        s1 = s1.apply(lambda x: (x if x < 1 else 1) if x > -0.1 else -0.1)
        plt.subplot(2, 1, 1)
        s1.hist(bins=100)
        plt.title('三费/营业总收入')

        s2 = df['三费'] / df['毛利润']
        s2 = s2.apply(lambda x: (x if x < 1 else 1) if x > -0.1 else -0.1)
        plt.subplot(2, 1, 2)
        s2.hist(bins=100)
        plt.title('三费/毛利润')

        # s1 = df['货币资金'] / df['有息负债']
        # s1 = s1.apply(lambda x: x if x < 10 else 10)
        # plt.subplot(2, 1, 1)
        # s1.hist(bins=100)
        # plt.title('货币资金/有息负债')
        #
        # s2 = df['有息负债'] / df['资产总计']
        # plt.subplot(2, 1, 2)
        # s2.hist(bins=100)
        # plt.title('有息负债/资产总计')

        # s1 = df['应收款'] / df['营业收入']
        # s1 = s1.apply(lambda x: x if x < 2 else 2)
        # plt.subplot(4, 1, 1)
        # s1.hist(bins=100)
        # plt.title('应收款/营业收入')
        #
        # s2 = df['其他应收款'] / df['营业收入']
        # s2 = s2.apply(lambda x: x if x < 1 else 1)
        # plt.subplot(4, 1, 2)
        # s2.hist(bins=100)
        # plt.title('其他应收款/营业收入')
        #
        # s3 = df['预付款项'] / df['营业收入']
        # s3 = s3.apply(lambda x: x if x < 1 else 1)
        # plt.subplot(4, 1, 3)
        # s3.hist(bins=100)
        # plt.title('预付款项/营业收入')
        #
        # s4 = df['预付款项'] / df['减:营业成本']
        # s4 = s4.apply(lambda x: x if x < 1 else 1)
        # plt.subplot(4, 1, 4)
        # s4.hist(bins=100)
        # plt.title('预付款项/营业成本')

        # s1 = df['商誉'] / df['净资产']
        # s1 = s1.apply(lambda x: (x if x < 1 else 1) if x > 0 else 0)
        # plt.subplot(3, 1, 1)
        # s1.hist(bins=100)
        # plt.title('商誉/净资产')
        #
        # s2 = df['在建工程'] / df['净资产']
        # s2 = s2.apply(lambda x: (x if x < 1 else 1) if x > 0 else 0)
        # plt.subplot(3, 1, 2)
        # s2.hist(bins=100)
        # plt.title('在建工程/净资产')
        #
        # s2 = df['在建工程'] / df['资产总计']
        # s2 = s2.apply(lambda x: (x if x < 1 else 1) if x > 0 else 0)
        # plt.subplot(3, 1, 3)
        # s2.hist(bins=100)
        # plt.title('在建工程/资产总计')

        # s1 = df['固定资产'] / df['资产总计']
        # s1 = s1.apply(lambda x: (x if x < 1 else 1) if x > 0 else 0)
        # plt.subplot(2, 1, 1)
        # s1.hist(bins=100)
        # plt.title('固定资产/资产总计')
        #
        # s2 = df['息税前利润'] / df['固定资产']
        # s2 = s2.apply(lambda x: (x if x < 10 else 10) if x > -10 else -10)
        # plt.subplot(2, 1, 2)
        # s2.hist(bins=100)
        # plt.title('息税前利润/固定资产')

        # self.plot_proportion([
        #     ChartLab.PlotItem('固定资产', '资产总计', 0, 1),
        #     ChartLab.PlotItem('息税前利润', '固定资产', -10, 10),
        # ], text_auto_time('2018-12-31'))

        self.repaint()

    class PlotItem:
        def __init__(self,
                     num: str,
                     den: str,
                     lower: float or None = None,
                     upper: float or None = None,
                     bins: int = 100):
            self.numerator = num
            self.denominator = den
            self.limit_lower = lower
            self.limit_upper = upper
            self.plot_bins = bins

    def plot_proportion(self, plot_set: [PlotItem], period: datetime.datetime):
        df = self.prepare_plot_data(plot_set, period)

        plot_count = len(plot_set)
        for plot_index in range(plot_count):
            plot_item = plot_set[plot_index]
            s = df[plot_item.numerator] / df[plot_item.denominator]
            if plot_item.limit_lower is not None:
                s = s.apply(lambda x: max(x, plot_item.limit_lower))
            if plot_item.limit_upper is not None:
                s = s.apply(lambda x: min(x, plot_item.limit_upper))
            plt.subplot(plot_count, 1, plot_index + 1)
            s.hist(bins=plot_item.plot_bins)
            plt.title(plot_item.numerator + '/' + plot_item.denominator)

    def prepare_plot_data(self, plot_set: [PlotItem],
                          period: datetime.datetime) -> pd.DataFrame:
        fields = []
        for plot_item in plot_set:
            fields.append(plot_item.numerator)
            fields.append(plot_item.denominator)
        fields = list(set(fields))
        return self.__sas_if.sas_auto_query(
            '', (period - datetime.timedelta(days=1), period), fields,
            ['stock_identity', 'period'])
コード例 #43
0
    def __init__(self, parent=None):
        super(GuiSettingsNiftiAnts, self).__init__(parent=None)

        # Load configuration files and general settings
        self.cfg = Configuration.load_config(ROOTDIR)

        # General appearance of the GUI
        self.setFixedSize(800, 600)
        self.setWindowTitle('Settings for working with NIFTI files and ANTs Toolbox')
        self.show()

        # Create general layout
        self.layout_tot = QVBoxLayout(self)

        # ==============================    Create Content for Left Upper Box   ==============================
        self.optionboxBias = QGroupBox('N4BiasCorrection')
        self.settings_list1 = QVBoxLayout(self.optionboxBias)

        self.labelPrefix = QLabel('Output prefix?\t\t')
        self.labelPrefix.setToolTip(setToolTips.LabelPrefixBias())
        self.lineEditPrefix = QLineEdit()

        lay1 = QHBoxLayout()
        lay1.addWidget(self.labelPrefix)
        lay1.addWidget(self.lineEditPrefix)
        lay1.addStretch()

        self.labelDenoise = QLabel('Denoise images?\t\t')
        #        self.labelPrefix.setToolTip(setToolTips.LabelPrefixBias())
        self.btngroup_Denoise = QButtonGroup()
        self.rbtnDenoisey = QRadioButton('yes')
        self.rbtnDenoisen = QRadioButton('no')
        self.rbtnDenoisey.toggled.connect(self.onClickedRBTN_Denoise)
        self.rbtnDenoisen.toggled.connect(self.onClickedRBTN_Denoise)

        self.btngroup_Denoise.addButton(self.rbtnDenoisey)
        self.btngroup_Denoise.addButton(self.rbtnDenoisen)
        lay2 = QHBoxLayout()
        lay2.addWidget(self.labelDenoise)
        lay2.addWidget(self.rbtnDenoisey)
        lay2.addWidget(self.rbtnDenoisen)
        lay2.addStretch()

        self.labelShrink = QLabel('Shrink factor?\t\t')
        self.labelShrink.setToolTip(setToolTips.LabelShrink())
        self.lineEditShrink = QLineEdit()
        regex = QtCore.QRegExp('^[0-4]\d{0}$')
        validator1 = QtGui.QRegExpValidator(regex)
        self.lineEditShrink.setValidator(validator1)

        lay3 = QHBoxLayout()
        lay3.addWidget(self.labelShrink)
        lay3.addWidget(self.lineEditShrink)
        lay3.addStretch()

        # TODO double check the Label and the ToolTip to ensure accuracy
        self.labelBSplineDist = QLabel('Distance BSplines?\t')
        self.labelBSplineDist.setToolTip(setToolTips.BSplineDistance())
        self.lineEditBSplineDist = QLineEdit()
        regex = QtCore.QRegExp('^[0-9]\d{2}$')
        validator1 = QtGui.QRegExpValidator(regex)
        self.lineEditBSplineDist.setValidator(validator1)

        lay4 = QHBoxLayout()
        lay4.addWidget(self.labelBSplineDist)
        lay4.addWidget(self.lineEditBSplineDist)
        lay4.addStretch()

        width = 31.33
        self.labelConv = QLabel('Convergence?\t\t')
        self.labelConv.setToolTip(setToolTips.N4BiasConvergence())
        self.lineEditConv1 = QLineEdit()
        self.lineEditConv1.setFixedWidth(width)
        self.lineEditConv2 = QLineEdit()
        self.lineEditConv2.setFixedWidth(width)
        self.lineEditConv3 = QLineEdit()
        self.lineEditConv3.setFixedWidth(width)
        self.lineEditConv4 = QLineEdit()
        self.lineEditConv4.setFixedWidth(width)

        lay5 = QHBoxLayout()
        lay5.addWidget(self.labelConv)
        lay5.addWidget(self.lineEditConv1)
        lay5.addWidget(self.lineEditConv2)
        lay5.addWidget(self.lineEditConv3)
        lay5.addWidget(self.lineEditConv4)
        lay5.addStretch()

        self.labelTolerance = QLabel('Tolerance?\t\t')
        self.labelTolerance.setToolTip(setToolTips.N4BiasConvergence())
        self.lineEditTolerance = QLineEdit()

        lay6 = QHBoxLayout()
        lay6.addWidget(self.labelTolerance)
        lay6.addWidget(self.lineEditTolerance)
        lay6.addStretch()

        self.labelDiffPrefix = QLabel('Prefix for DTI data?\t')
        self.labelDiffPrefix.setToolTip(setToolTips.DiffPrefix())
        self.lineEditDiffPrefix = QLineEdit()

        lay7 = QHBoxLayout()
        lay7.addWidget(self.labelDiffPrefix)
        lay7.addWidget(self.lineEditDiffPrefix)
        lay7.addStretch()

        self.settings_list1.addLayout(lay1)
        self.settings_list1.addLayout(lay2)
        self.settings_list1.addLayout(lay3)
        self.settings_list1.addLayout(lay4)
        self.settings_list1.addLayout(lay5)
        self.settings_list1.addLayout(lay6)
        self.settings_list1.addLayout(lay7)
        self.settings_list1.addStretch()

        # ==============================    Create Content for Right Upper Box   ==============================
        self.optionboxRegistration = QGroupBox('ImageRegistration')
        self.settings_list2 = QVBoxLayout(self.optionboxRegistration)
        # self.settings_list2.addLayout(lay1)

        self.labelPrefixRegistration = QLabel('Registration prefix?\t')
        # self.labelPrefixRegistration.setToolTip(setToolTips.LabelPrefixBias())
        self.lineEditPrefixRegistration = QLineEdit()

        lay8 = QHBoxLayout()
        lay8.addWidget(self.labelPrefixRegistration)
        lay8.addWidget(self.lineEditPrefixRegistration)
        lay8.addStretch()

        self.labelResampleSpacing = QLabel('Resample Spacing?\t')
        self.labelResampleSpacing.setToolTip(setToolTips.LabelResampleImages())
        self.lineResampleSpacing = QLineEdit()

        lay10 = QHBoxLayout()
        lay10.addWidget(self.labelResampleSpacing)
        lay10.addWidget(self.lineResampleSpacing)
        lay10.addStretch()

        self.labelResampleMethod = QLabel('Resampling method?\t')
        self.labelResampleMethod.setToolTip(setToolTips.ResampleMethod())
        self.btngroup_ResampleMethod = QButtonGroup()
        self.rbtnResample0 = QRadioButton("0")  # 0 (lin.), 1 (near. neighb.), 2 (gauss.), 3 (window. sinc), 4 (bspline)
        self.rbtnResample1 = QRadioButton("1")
        self.rbtnResample2 = QRadioButton("2")
        self.rbtnResample3 = QRadioButton("3")
        self.rbtnResample4 = QRadioButton("4")
        self.rbtnResample0.toggled.connect(self.onClickedRBTN_ResampleMethod)
        self.rbtnResample1.toggled.connect(self.onClickedRBTN_ResampleMethod)
        self.rbtnResample2.toggled.connect(self.onClickedRBTN_ResampleMethod)
        self.rbtnResample3.toggled.connect(self.onClickedRBTN_ResampleMethod)
        self.rbtnResample4.toggled.connect(self.onClickedRBTN_ResampleMethod)

        self.btngroup_ResampleMethod.addButton(self.rbtnResample0)
        self.btngroup_ResampleMethod.addButton(self.rbtnResample1)
        self.btngroup_ResampleMethod.addButton(self.rbtnResample2)
        self.btngroup_ResampleMethod.addButton(self.rbtnResample3)
        self.btngroup_ResampleMethod.addButton(self.rbtnResample4)

        lay11 = QHBoxLayout()
        lay11.addWidget(self.labelResampleMethod)
        lay11.addWidget(self.rbtnResample0)
        lay11.addWidget(self.rbtnResample1)
        lay11.addWidget(self.rbtnResample2)
        lay11.addWidget(self.rbtnResample3)
        lay11.addWidget(self.rbtnResample4)

        self.labelDefaultSettings = QLabel('Default registration?\t')
        #        self.labelPrefix.setToolTip(setToolTips.LabelPrefixBias())
        self.btngroup_DefaultSettingsRegistration = QButtonGroup()
        self.rbtnDefaultRegistrationy = QRadioButton('yes')
        self.rbtnDefaultRegistrationn = QRadioButton('no')
        self.rbtnDefaultRegistrationy.toggled.connect(self.onClickedRBTN_DefaultRegistration)
        self.rbtnDefaultRegistrationn.toggled.connect(self.onClickedRBTN_DefaultRegistration)

        self.btngroup_DefaultSettingsRegistration.addButton(self.rbtnDefaultRegistrationy)
        self.btngroup_DefaultSettingsRegistration.addButton(self.rbtnDefaultRegistrationn)
        lay12 = QHBoxLayout()
        lay12.addWidget(self.labelDefaultSettings)
        lay12.addWidget(self.rbtnDefaultRegistrationy)
        lay12.addWidget(self.rbtnDefaultRegistrationn)
        lay12.addStretch()

        self.labelRegistrationMethod = QLabel('Registration method?\t')
        # self.labelRegistrationMethod.setToolTip(setToolTips.LabelResampleImages())
        self.lineRegistrationMethod = QComboBox()
        allowable_tx = [
            "SyNBold",
            "SyNBoldAff",
            "ElasticSyN",
            "SyN",
            "SyNRA",
            "SyNOnly",
            "SyNAggro",
            "SyNCC",
            "TRSAA",
            "SyNabp",
            "SyNLessAggro",
            "TVMSQ",
            "TVMSQC",
            "Rigid",
            "Similarity",
            "Translation",
            "Affine",
            "AffineFast",
            "BOLDAffine",
            "QuickRigid",
            "DenseRigid",
            "BOLDRigid",
        ]
        [self.lineRegistrationMethod.addItem(x) for x in allowable_tx]
        idx_method = self.lineRegistrationMethod.findText(self.cfg["preprocess"]["registration"]["registration_method"],
                                                          QtCore.Qt.MatchFixedString)
        if idx_method >= 0:
            self.lineRegistrationMethod.setCurrentIndex(idx_method)
        self.lineRegistrationMethod.currentTextChanged.connect(self.comboChangedRegDefault)
        self.lineRegistrationMethod.setDisabled(True)

        lay13 = QHBoxLayout()
        lay13.addWidget(self.labelRegistrationMethod)
        lay13.addWidget(self.lineRegistrationMethod)
        lay13.addStretch()

        self.labelCustomRegistration = QLabel('Edit registration settings?\t')
        self.PushButtonViewRegistration = QPushButton("Edit cmdline")
        self.PushButtonViewRegistration.setDisabled(True)
        self.PushButtonViewRegistration.clicked.connect(self.viewRegistrationCmdLine)

        lay14 = QHBoxLayout()
        lay14.addWidget(self.labelCustomRegistration)
        lay14.addWidget(self.PushButtonViewRegistration)
        lay14.addStretch()

        self.labelNormalisationTemplate = QLabel('Normalisation template?\t')
        # self.labelRegistrationMethod.setToolTip(setToolTips.LabelResampleImages())
        self.lineTemplatesAvailable = QComboBox()
        [self.lineTemplatesAvailable.addItem(os.path.split(x)[1]) for x in
         glob.glob(os.path.join(ROOTDIR, 'ext', 'templates' + '/*'))]
        idx_template = self.lineRegistrationMethod.findText(self.cfg["preprocess"]["normalisation"]["template_image"],
                                                            QtCore.Qt.MatchFixedString)

        if idx_template >= 0:
            self.lineRegistrationMethod.setCurrentIndex(idx_template)
        self.lineTemplatesAvailable.currentTextChanged.connect(self.comboChangedNormalisation)

        lay15 = QHBoxLayout()
        lay15.addWidget(self.labelNormalisationTemplate)
        lay15.addWidget(self.lineTemplatesAvailable)
        lay15.addStretch()

        self.labelNormalisationSequences = QLabel('Sequences to normalise?\t')
        # self.labelPrefixRegistration.setToolTip(setToolTips.LabelPrefixBias())
        self.lineEditNormalisationSequences = QLineEdit()

        lay16 = QHBoxLayout()
        lay16.addWidget(self.labelNormalisationSequences)
        lay16.addWidget(self.lineEditNormalisationSequences)
        lay16.addStretch()

        self.settings_list2.addLayout(lay8)
        self.settings_list2.addStretch(1)
        self.settings_list2.addLayout(lay10)
        self.settings_list2.addLayout(lay11)
        self.settings_list2.addStretch(1)
        self.settings_list2.addLayout(lay12)
        self.settings_list2.addLayout(lay13)
        self.settings_list2.addLayout(lay14)
        self.settings_list2.addStretch(1)
        self.settings_list2.addLayout(lay15)
        self.settings_list2.addLayout(lay16)
        self.settings_list2.addStretch(10)

        # Merge all upper boxes
        self.layout_upper = QHBoxLayout()
        self.layout_upper.addWidget(self.optionboxBias)
        self.layout_upper.addWidget(self.optionboxRegistration)

        # ====================    Create Content for Buttons at the Bottom      ====================
        layout_bottom = QHBoxLayout()
        self.buttonsave = QPushButton('Save settings \nand return')
        self.buttonsave.clicked.connect(self.close)
        self.buttondefault = QPushButton('Load Default \nsettings')
        self.buttondefault.clicked.connect(self.load_default_settings)

        layout_bottom.addStretch(1)
        layout_bottom.addWidget(self.buttonsave)
        layout_bottom.addWidget(self.buttondefault)

        # ====================    Set Content of box and buttoms to General Layout     =======================
        self.layout_tot.addLayout(self.layout_upper)
        self.layout_tot.addLayout(layout_bottom)
        self.get_settings_from_config()
コード例 #44
0
class App(QWidget):

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

        self.title = 'stock market'
        self.left = 500
        self.top = 300
        self.width = 600
        self.height = 400
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setWindowIcon(QtGui.QIcon("stock2.jpg"))
        self.setGeometry(self.left, self.top, self.width, self.height)

        label = QLabel(self)
        pixmap = QPixmap('stock5.jpg')
        label.setPixmap(pixmap)

        self.dropdown = QComboBox(self)  ## we have to make drop down in order to select company
        self.dropdown.addItems(["TSLA", "MSFT", "NVDA", "CSCO", "NFLX"])
        self.dropdown.move(20, 50)
        self.dropdown.show()
        self.dropdown.setStyleSheet("background-color: blue;color: white")
        comapny = self.dropdown.currentText()

        button = QPushButton('Show text', self)
        button.move(0, 80)
        button.clicked.connect(self.sel_comp)
        button.setStyleSheet("background-color: red;color: white")



        button = QPushButton('weekly', self)
        button.setToolTip('Weekly Analysis')
        button.move(100, 50)
        button.resize(100, 40)
        button.clicked.connect(self.on_click)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('monthly', self)
        button.setToolTip('Monthly Analysis')
        button.move(100, 100)
        button.resize(100, 40)
        button.clicked.connect(self.on_click2)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('daily', self)
        button.setToolTip('Daily analysis')
        button.move(100, 150)
        button.resize(100, 40)
        button.clicked.connect(self.on_click3)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('bolingerband', self)
        button.setToolTip('Bolinger_Bads_ info')
        button.move(100, 200)
        button.resize(100, 40)
        button.clicked.connect(self.on_click4)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('$ to Rupee', self)
        button.setToolTip('Currency conversion')
        button.move(350, 150)
        button.resize(100, 40)
        button.clicked.connect(self.on_click5)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('bitcoin in US$', self)
        button.setToolTip('Cryptocurrency Info')
        button.move(350, 100)
        button.resize(100, 40)
        button.clicked.connect(self.on_click6)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('bitcoin in INR', self)
        button.setToolTip('Cryptocurrencies in INR')
        button.move(350, 50)
        button.resize(100, 40)
        button.clicked.connect(self.on_click7)
        button.setStyleSheet("background-color: brown;color: white")

        self.show()

    @pyqtSlot()
    def on_click(self):
        print(company)
        plot_weekly()


    def on_click2(self):
        plot_monthly()

    def on_click3(self):
        plot_daily()

    def on_click4(self):
        bolinger_bands()

    def on_click5(self):
        currency_xchange()

    def on_click6(self):
        bitcoin_value_US()

    def on_click7(self):
        bitcoin_value_IND()

    def sel_comp(self):
        global company
        company = self.dropdown.currentText()
        print(self.dropdown.currentText())

    print(company)
コード例 #45
0
class Dialogo(QDialog):
    def __init__(self, img=None, img_name=None):
        '''
  Esta pantalla hereda de QDialog y es la pantalla en donde se encontrarán los botones de dibujo
  además de recortar y limpiar
  '''
        QDialog.__init__(self)
        self.setFixedSize(638, 600)
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        self.img_name = img_name
        self.img = img
        self.paint = Paint(self.img, self.img_name)
        self.btn_recortar = QPushButton("Recortar")
        self.btn_limpiar = QPushButton("Limpiar")
        self.combo_object = QComboBox(
        )  #El QComboBox es donde se encontraran las opciones de dibujo
        '''
  Añadimos elementos al comboBox
  '''
        self.combo_object.addItem("Seleccionar")
        self.combo_object.addItem("Linea")
        self.combo_object.addItem("recortar")
        self.combo_object.addItem("Elípse")
        self.combo_object.addItem("Polígono")
        '''
  Agregamos todos los Widgets a el gridlayout para que puedan ser visibles
  '''
        self.layout.addWidget(self.combo_object)
        self.layout.addWidget(self.btn_limpiar)
        self.layout.addWidget(self.paint)
        self.layout.addWidget(self.btn_recortar)
        self.btnDefault = "background-color: grey; border: 0; padding: 10px"
        self.btnActive = "background-color: orange; border: 0; padding: 10px"

        self.combo_object.setStyleSheet(self.btnDefault)

        self.btn_recortar.clicked.connect(self.isRecortar)
        self.combo_object.currentIndexChanged.connect(self.isObject)
        self.combo_object.activated.connect(self.isObject)
        self.btn_limpiar.clicked.connect(self.isLimpiar)

    def resizeEvent(self, event):
        self.paint.setSceneRect(QRectF(self.paint.viewport().rect()))

    def isObject(self):
        '''
  Esta función nos permite saber que opción de dibujo fue seleccionada
  '''
        object = self.combo_object.currentIndex()
        self.paint.isObject = object
        '''
  Cada vez que seleccionemos una opción de dibujo debemos borrar los puntos del poligono
  esto debe hacerse para que cuando la opción del poligono se seleccione de nuevo, se cree
  un nuevo poligono y no siga agregando puntos al ya dibujado
  '''
        del self.paint.arrayPolygon[:]
        del self.paint.puntosX[:]
        del self.paint.puntosY[:]

    def isRecortar(self):
        '''
  Esta función nos permite recortar el area del rectangulo dibujado cuando se de clic en el boton
  de recortar, sin embargo es necesario preguntar si en todo el QGraphicsView hay algun item Rectangulo
  en caso de que lo haya recortará dicha área, sino no hace nada  
  '''
        for self.paint.item in self.paint.scene.items():
            x = isinstance(self.paint.item, QGraphicsRectItem)
            if x:
                self.paint.img_recortada.save("imgs/imagen_recortada.png"
                                              )  #Guardamos la imágen recortada
                '''
      Creamos un objeto QPixmap que abra la imagen recortada, y a su vez la añadimos a la escena
      así mismo borramos los puntos del poligono para que cuando se dibuje uno, sea nuevo
      '''
                self.paint.imagen_recortada = QPixmap(
                    "imgs/imagen_recortada.png").scaled(638, 478)
                self.paint.scene.addPixmap(self.paint.imagen_recortada)
                self.paint.setScene(self.paint.scene)
                del self.paint.arrayPolygon[:]
                del self.paint.puntosX[:]
                del self.paint.puntosY[:]
                break
            else:
                continue

    def isLimpiar(self):
        '''
  Ya que la imagen es una escena, si pedimos limpiar toda la escena nos va a borrar la imagen también
  por lo que es necesario recorrer la lista de escenas y pedirle que no haga nada cuando la
  escena es la imagen, de esta forma limpiara todo escepto la imágen
  '''
        for self.paint.item in self.paint.scene.items():
            x = isinstance(self.paint.item, QGraphicsPixmapItem)
            if x:
                continue
            else:
                self.paint.scene.removeItem(self.paint.item)
                del self.paint.arrayPolygon[:]
                del self.paint.puntosX[:]
                del self.paint.puntosY[:]
コード例 #46
0
class thermophysicalProperties_water_form_class(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.interface_lng_val = parent.interface_lng_val
        self.con = parent.con
        self.full_dir = parent.full_dir
        self.par = parent

        if self.con.open():

            self.table = QTableWidget(16, 2)
            self.table.setColumnWidth(0, 150)
            self.table.setColumnWidth(1, 230)
            self.table.setFixedSize(674, 480)
            if self.interface_lng_val == 'Russian':
                self.table.setHorizontalHeaderLabels(["Параметр", "Значение"])
            elif self.interface_lng_val == 'English':
                self.table.setHorizontalHeaderLabels(["Parameter", "Value"])

# thermoType
            thermoType_lbl = QLabel('thermoType')
            self.table.setCellWidget(0, 0, thermoType_lbl)

            # type
            type_lbl = QLabel('type')
            self.type = QComboBox()
            self.type.setFixedSize(160, 25)
            type_list = ["heRhoThermo"]
            self.type.addItems(type_list)
            self.table.setCellWidget(1, 0, type_lbl)
            self.table.setCellWidget(1, 1, self.type)

            # mixture
            mixture_lbl = QLabel('mixture')
            self.mixture = QComboBox()
            self.mixture.setFixedSize(160, 25)
            mixture_list = ["pureMixture"]
            self.mixture.addItems(mixture_list)
            self.table.setCellWidget(2, 0, mixture_lbl)
            self.table.setCellWidget(2, 1, self.mixture)

            # transport
            transport_lbl = QLabel('transport')
            self.transport = QComboBox()
            self.transport.setFixedSize(160, 25)
            transport_list = ["const"]
            self.transport.addItems(transport_list)
            self.table.setCellWidget(3, 0, transport_lbl)
            self.table.setCellWidget(3, 1, self.transport)

            # thermo
            thermo_lbl = QLabel('thermo')
            self.thermo = QComboBox()
            self.thermo.setFixedSize(160, 25)
            thermo_list = ["hConst"]
            self.thermo.addItems(thermo_list)
            self.table.setCellWidget(4, 0, thermo_lbl)
            self.table.setCellWidget(4, 1, self.thermo)

            # equationOfState
            equationOfState_lbl = QLabel('thermo')
            self.equationOfState = QComboBox()
            self.equationOfState.setFixedSize(160, 25)
            equationOfState_list = ["perfectFluid"]
            self.equationOfState.addItems(equationOfState_list)
            self.table.setCellWidget(5, 0, equationOfState_lbl)
            self.table.setCellWidget(5, 1, self.equationOfState)

            # specie
            specie_lbl = QLabel('specie')
            self.specie = QComboBox()
            self.specie.setFixedSize(160, 25)
            specie_list = ["specie"]
            self.specie.addItems(specie_list)
            self.table.setCellWidget(6, 0, specie_lbl)
            self.table.setCellWidget(6, 1, self.specie)

            # energy
            energy_lbl = QLabel('energy')
            self.energy = QComboBox()
            self.energy.setFixedSize(160, 25)
            energy_list = ["sensibleInternalEnergy"]
            self.energy.addItems(energy_list)
            self.table.setCellWidget(7, 0, energy_lbl)
            self.table.setCellWidget(7, 1, self.energy)

            # mixture
            mixture_lbl = QLabel('mixture')
            self.table.setCellWidget(8, 0, mixture_lbl)

            # specie.molWeight
            specie_molWeight_lbl = QLabel('specie.molWeight')
            self.specie_molWeight = QLineEdit()
            self.specie_molWeight.setFixedSize(160, 25)
            self.table.setCellWidget(9, 0, specie_molWeight_lbl)
            self.table.setCellWidget(9, 1, self.specie_molWeight)

            # equationOfState.R
            equationOfState_R_lbl = QLabel('equationOfState.R')
            self.equationOfState_R = QLineEdit()
            self.equationOfState_R.setFixedSize(160, 25)
            self.table.setCellWidget(10, 0, equationOfState_R_lbl)
            self.table.setCellWidget(10, 1, self.equationOfState_R)

            # equationOfState.rho0
            equationOfState_rho0_lbl = QLabel('equationOfState.rho0')
            self.equationOfState_rho0 = QLineEdit()
            self.equationOfState_rho0.setFixedSize(160, 25)
            self.table.setCellWidget(11, 0, equationOfState_rho0_lbl)
            self.table.setCellWidget(11, 1, self.equationOfState_rho0)

            # thermodynamics.Cp
            thermodynamics_Cp_lbl = QLabel('thermodynamics.Cp')
            self.thermodynamics_Cp = QLineEdit()
            self.thermodynamics_Cp.setFixedSize(160, 25)
            self.table.setCellWidget(12, 0, thermodynamics_Cp_lbl)
            self.table.setCellWidget(12, 1, self.thermodynamics_Cp)

            # thermodynamics.Hf
            thermodynamics_Hf_lbl = QLabel('thermodynamics.Hf')
            self.thermodynamics_Hf = QLineEdit()
            self.thermodynamics_Hf.setFixedSize(160, 25)
            self.table.setCellWidget(13, 0, thermodynamics_Hf_lbl)
            self.table.setCellWidget(13, 1, self.thermodynamics_Hf)

            # transport.mu
            transport_mu_lbl = QLabel('transport.mu')
            self.transport_mu = QLineEdit()
            self.transport_mu.setFixedSize(160, 25)
            self.table.setCellWidget(14, 0, transport_mu_lbl)
            self.table.setCellWidget(14, 1, self.transport_mu)

            # transport.Pr
            transport_Pr_lbl = QLabel('transport.Pr')
            self.transport_Pr = QLineEdit()
            self.transport_Pr.setFixedSize(160, 25)
            self.table.setCellWidget(15, 0, transport_Pr_lbl)
            self.table.setCellWidget(15, 1, self.transport_Pr)

            # вывод значений параметров
            if 'thermophysicalProperties_water' in self.con.tables():
                query = QtSql.QSqlQuery()
                query.exec("SELECT * FROM thermophysicalProperties_water")
                if query.isActive():
                    query.first()
                    value_list = []
                    while query.isValid():
                        value_res = query.value('value')
                        value_list.append(value_res)
                        query.next()
                    print(value_list)
                    # type
                    type_mas = self.type.count()
                    for i in range(type_mas):
                        if self.type.itemText(i) == value_list[0]:
                            self.type.setCurrentIndex(i)

# mixture
                    mixture_mas = self.mixture.count()
                    for i in range(mixture_mas):
                        if self.mixture.itemText(i) == value_list[1]:
                            self.mixture.setCurrentIndex(i)

# transport
                    transport_mas = self.transport.count()
                    for i in range(transport_mas):
                        if self.transport.itemText(i) == value_list[2]:
                            self.transport.setCurrentIndex(i)

# thermo
                    thermo_mas = self.thermo.count()
                    for i in range(thermo_mas):
                        if self.thermo.itemText(i) == value_list[3]:
                            self.thermo.setCurrentIndex(i)

# equationOfState
                    equationOfState_mas = self.equationOfState.count()
                    for i in range(equationOfState_mas):
                        if self.equationOfState.itemText(i) == value_list[4]:
                            self.equationOfState.setCurrentIndex(i)

# specie
                    specie_mas = self.specie.count()
                    for i in range(specie_mas):
                        if self.specie.itemText(i) == value_list[5]:
                            self.specie.setCurrentIndex(i)

# energy
                    energy_mas = self.energy.count()
                    for i in range(energy_mas):
                        if self.energy.itemText(i) == value_list[6]:
                            self.energy.setCurrentIndex(i)

# specie.molWeight
                    self.specie_molWeight.setText(value_list[7])

                    # equationOfState.R
                    self.equationOfState_R.setText(value_list[8])

                    # equationOfState_rho0
                    self.equationOfState_rho0.setText(value_list[9])

                    # thermodynamics.Cp
                    self.thermodynamics_Cp.setText(value_list[10])

                    # thermodynamics.Hf
                    self.thermodynamics_Hf.setText(value_list[11])

                    # transport.mu
                    self.transport_mu.setText(value_list[12])

                    # transport.Pr
                    self.transport_Pr.setText(value_list[13])

            btnSave = QPushButton()
            btnSave.setFixedSize(80, 25)
            btnSave.clicked.connect(self.on_btnSave_clicked)

            if self.interface_lng_val == 'Russian':
                btnSave.setText("Сохранить")
            elif self.interface_lng_val == 'English':
                btnSave.setText("Save")

            vbox = QVBoxLayout()
            vbox.addWidget(self.table)
            vbox.addWidget(btnSave)

            # ---------------------Размещение на форме всех компонентов-------------------------

            form = QFormLayout()
            form.addRow(vbox)
            self.setLayout(form)

    def on_btnSave_clicked(self):
        type_txt = self.type.currentText()
        mixture_txt = self.mixture.currentText()
        transport_txt = self.transport.currentText()
        thermo_txt = self.thermo.currentText()
        equationOfState_txt = self.equationOfState.currentText()
        specie_txt = self.specie.currentText()
        energy_txt = self.energy.currentText()

        specie_molWeight_txt = self.specie_molWeight.text()
        equationOfState_R_txt = self.equationOfState_R.text()
        equationOfState_rho0_txt = self.equationOfState_rho0.text()
        thermodynamics_Cp_txt = self.thermodynamics_Cp.text()
        thermodynamics_Hf_txt = self.thermodynamics_Hf.text()
        transport_mu_txt = self.transport_mu.text()
        transport_Pr_txt = self.transport_Pr.text()

        mixture_list = [
            self.specie_molWeight.text(),
            self.thermodynamics_Cp.text(),
            self.thermodynamics_Hf.text(),
            self.transport_mu.text(),
            self.transport_Pr.text()
        ]

        if '' not in mixture_list:

            if 'thermophysicalProperties_water' not in self.con.tables():
                query = QtSql.QSqlQuery()
                query.exec(
                    "CREATE TABLE thermophysicalProperties_water(param, value)"
                )

                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('type', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('mixture', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('transport', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('thermo', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('equationOfState', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('specie', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('energy', ''))

                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('specie.molWeight', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('equationOfState.R', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('equationOfState.rho0', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('thermodynamics.Cp', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('thermodynamics.Hf', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('transport.mu', ''))
                query.exec(
                    "INSERT INTO thermophysicalProperties_water(param, value) VALUES ('%s','%s')"
                    % ('transport.Pr', ''))

            if 'thermophysicalProperties_water' in self.con.tables():
                query = QtSql.QSqlQuery()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='type'"
                )
                query.bindValue(0, type_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='mixture'"
                )
                query.bindValue(0, mixture_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='transport'"
                )
                query.bindValue(0, transport_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='thermo'"
                )
                query.bindValue(0, thermo_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='equationOfState'"
                )
                query.bindValue(0, equationOfState_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='specie'"
                )
                query.bindValue(0, specie_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='energy'"
                )
                query.bindValue(0, energy_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='specie.molWeight'"
                )
                query.bindValue(0, specie_molWeight_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='equationOfState.R'"
                )
                query.bindValue(0, thermodynamics_Cp_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='equationOfState.rho0'"
                )
                query.bindValue(0, thermodynamics_Hf_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='thermodynamics.Cp'"
                )
                query.bindValue(0, thermodynamics_Cp_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='thermodynamics.Hf'"
                )
                query.bindValue(0, thermodynamics_Hf_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='transport.mu'"
                )
                query.bindValue(0, transport_mu_txt)
                query.exec_()

                query.prepare(
                    "UPDATE thermophysicalProperties_water SET value=? WHERE param='transport.Pr'"
                )
                query.bindValue(0, transport_Pr_txt)
                query.exec_()

            # записываем файл thermophysicalProperties
            if os.path.exists(self.full_dir +
                              '/constant/thermophysicalProperties.water'):
                os.remove(self.full_dir +
                          '/constant/thermophysicalProperties.water')

            shutil.copyfile(
                "./matches/Shablon/constant/thermophysicalProperties.water",
                self.full_dir + '/constant/thermophysicalProperties.water')

            tP = open(
                self.full_dir + '/constant/thermophysicalProperties.water',
                'a')

            ###thermoType_start###
            tT_bl_start = '\n' + 'thermoType' + '\n' + '{' + '\n'

            ###type###
            t_bl = '    ' + 'type            ' + type_txt + ';' + '\n'

            ###mixture###
            m_bl = '    ' + 'mixture         ' + mixture_txt + ';' + '\n'

            ###transport###
            tr_bl = '    ' + 'transport       ' + transport_txt + ';' + '\n'

            ###thermo###
            th_bl = '    ' + 'thermo          ' + thermo_txt + ';' + '\n'

            ###equationOfState###
            eOS_bl = '    ' + 'equationOfState ' + equationOfState_txt + ';' + '\n'

            ###specie###
            s_bl = '    ' + 'specie          ' + specie_txt + ';' + '\n'

            ###energy###
            e_bl = '    ' + 'energy          ' + energy_txt + ';' + '\n'

            ###thermoType_end###
            tT_bl_end = '}' + '\n\n'

            ###mixture_start###
            m_bl_start = 'mixture' + '\n' + '{' + '\n'

            ###specie###
            sp_bl = '    ' + 'specie' + '\n' + '    ' + '{' + '\n' + '        ' + 'molWeight' + '   ' + specie_molWeight_txt + ';' + '\n' + '    ' + '}' + '\n'

            ###equationOfState###
            eOSS_bl = '    ' + 'equationOfState' + '\n' + '    ' + '{' + '\n' + '        ' + 'R' + '   ' + equationOfState_R_txt + ';' + '\n' + '        ' + 'rho0' + '   ' + equationOfState_rho0_txt + ';' + '\n' + '    ' + '}' + '\n'

            ###thermodynamics###
            td_bl = '    ' + 'thermodynamics' + '\n' + '    ' + '{' + '\n' + '        ' + 'Cp' + '   ' + thermodynamics_Cp_txt + ';' + '\n' + '        ' + 'Hf' + '   ' + thermodynamics_Hf_txt + ';' + '\n' + '    ' + '}' + '\n'

            ###transport###
            tra_bl = '    ' + 'transport' + '\n' + '    ' + '{' + '\n' + '        ' + 'mu' + '   ' + transport_mu_txt + ';' + '\n' + '        ' + 'Pr' + '   ' + transport_Pr_txt + ';' + '\n' + '    ' + '}'

            ###mixture_end###
            m_bl_end = '\n' + '}' + '\n\n'

            tP.write(tT_bl_start + t_bl + m_bl + tr_bl + th_bl + eOS_bl +
                     s_bl + e_bl + tT_bl_end + m_bl_start + sp_bl + eOSS_bl +
                     td_bl + tra_bl + m_bl_end)
            close_str = '// ************************************************************************* //'
            tP.write(close_str)

            tP.close()

            self.par.cdw.setWidget(self.par.outf_scroll)
            outf = open(self.full_dir +
                        '/constant/thermophysicalProperties.water')

            if self.interface_lng_val == 'Russian':
                msg_lbl = QLabel(
                    '<span style="color:green">Файл thermophysicalProperties.water сохранен</span>'
                )
            elif self.interface_lng_val == 'English':
                msg_lbl = QLabel(
                    '<span style="color:green">The thermophysicalProperties.water file saved</span>'
                )

            data = outf.read()

            if self.interface_lng_val == 'Russian':
                self.par.outf_lbl.setText("Файл " + "<font color='peru'>" +
                                          'thermophysicalProperties.water' +
                                          "</font>")
            elif self.interface_lng_val == 'English':
                self.par.outf_lbl.setText("<font color='peru'>" +
                                          'thermophysicalProperties.water' +
                                          "</font>" + " file")
            self.par.outf_edit.setText(data)

            self.par.cdw.setTitleBarWidget(self.par.cdw_frame)
            outf.close()

        else:

            if self.interface_lng_val == 'Russian':
                msg_lbl = QLabel(
                    '<span style="color:red">Проверьте корректность заполнения всех параметров</span>'
                )
            elif self.interface_lng_val == 'English':
                msg_lbl = QLabel(
                    '<span style="color:red">Check the correctness of filling all the parameters</span>'
                )

        self.par.listWidget.clear()
        self.par.item = QListWidgetItem()
        self.par.listWidget.addItem(self.par.item)
        self.par.listWidget.setItemWidget(self.par.item, msg_lbl)
コード例 #47
0
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setWindowIcon(QtGui.QIcon("stock2.jpg"))
        self.setGeometry(self.left, self.top, self.width, self.height)

        label = QLabel(self)
        pixmap = QPixmap('stock5.jpg')
        label.setPixmap(pixmap)

        self.dropdown = QComboBox(self)  ## we have to make drop down in order to select company
        self.dropdown.addItems(["TSLA", "MSFT", "NVDA", "CSCO", "NFLX"])
        self.dropdown.move(20, 50)
        self.dropdown.show()
        self.dropdown.setStyleSheet("background-color: blue;color: white")
        comapny = self.dropdown.currentText()

        button = QPushButton('Show text', self)
        button.move(0, 80)
        button.clicked.connect(self.sel_comp)
        button.setStyleSheet("background-color: red;color: white")



        button = QPushButton('weekly', self)
        button.setToolTip('Weekly Analysis')
        button.move(100, 50)
        button.resize(100, 40)
        button.clicked.connect(self.on_click)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('monthly', self)
        button.setToolTip('Monthly Analysis')
        button.move(100, 100)
        button.resize(100, 40)
        button.clicked.connect(self.on_click2)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('daily', self)
        button.setToolTip('Daily analysis')
        button.move(100, 150)
        button.resize(100, 40)
        button.clicked.connect(self.on_click3)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('bolingerband', self)
        button.setToolTip('Bolinger_Bads_ info')
        button.move(100, 200)
        button.resize(100, 40)
        button.clicked.connect(self.on_click4)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('$ to Rupee', self)
        button.setToolTip('Currency conversion')
        button.move(350, 150)
        button.resize(100, 40)
        button.clicked.connect(self.on_click5)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('bitcoin in US$', self)
        button.setToolTip('Cryptocurrency Info')
        button.move(350, 100)
        button.resize(100, 40)
        button.clicked.connect(self.on_click6)
        button.setStyleSheet("background-color: brown;color: white")

        button = QPushButton('bitcoin in INR', self)
        button.setToolTip('Cryptocurrencies in INR')
        button.move(350, 50)
        button.resize(100, 40)
        button.clicked.connect(self.on_click7)
        button.setStyleSheet("background-color: brown;color: white")

        self.show()
コード例 #48
0
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.setWindowTitle("Opvragen Webverkooporder")
            self.setWindowIcon(QIcon('./images/logos/logo.jpg'))

            self.setFont(QFont('Arial', 10))

            self.Keuze = QLabel()
            k0Edit = QComboBox()
            k0Edit.setFixedWidth(220)
            k0Edit.setFont(QFont("Arial", 10))
            k0Edit.setStyleSheet("color: black;  background-color: gainsboro")
            k0Edit.addItem(' Sorteersleutel voor zoeken')
            k0Edit.addItem('1. Alle Orders')
            k0Edit.addItem('2. Gefilterd op postcode')
            k0Edit.addItem('3. Gefilterd op achternaam')
            k0Edit.addItem('4. Gefilterd op ordernummer')
            k0Edit.addItem('5. Gefilterd op besteldatum')
            k0Edit.activated[str].connect(self.k0Changed)

            self.Zoekterm = QLabel()
            zktrmEdit = QLineEdit()
            zktrmEdit.setFixedWidth(220)
            zktrmEdit.setFont(QFont("Arial", 10))
            zktrmEdit.textChanged.connect(self.zktrmChanged)
            reg_ex = QRegExp('.*$')
            input_validator = QRegExpValidator(reg_ex, zktrmEdit)
            zktrmEdit.setValidator(input_validator)

            grid = QGridLayout()
            grid.setSpacing(20)

            lbl = QLabel()
            pixmap = QPixmap('./images/logos/verbinding.jpg')
            lbl.setPixmap(pixmap)
            grid.addWidget(lbl, 1, 0, 1, 2)

            logo = QLabel()
            pixmap = QPixmap('./images/logos/logo.jpg')
            logo.setPixmap(pixmap)
            grid.addWidget(logo, 1, 1, 1, 2, Qt.AlignRight)

            lbl1 = QLabel('Zoekterm')
            grid.addWidget(lbl1, 3, 0, 1, 1, Qt.AlignRight)
            grid.addWidget(zktrmEdit, 3, 1, 1, 2)
            grid.addWidget(k0Edit, 2, 1, 1, 2, Qt.AlignRight)

            self.setLayout(grid)
            self.setGeometry(500, 300, 150, 150)

            grid.addWidget(
                QLabel('\u00A9 2017 all rights reserved [email protected]'),
                5, 0, 1, 3, Qt.AlignCenter)

            applyBtn = QPushButton('Zoeken')
            applyBtn.clicked.connect(self.accept)

            grid.addWidget(applyBtn, 4, 2, 1, 1, Qt.AlignRight)
            applyBtn.setFont(QFont("Arial", 10))
            applyBtn.setFixedWidth(100)
            applyBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")

            closeBtn = QPushButton('Sluiten')
            closeBtn.clicked.connect(lambda: windowSluit(self, m_email))

            grid.addWidget(closeBtn, 4, 1, 1, 1, Qt.AlignRight)
            closeBtn.setFont(QFont("Arial", 10))
            closeBtn.setFixedWidth(100)
            closeBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")
コード例 #49
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.interface_lng_val = parent.interface_lng_val
        self.con = parent.con
        self.full_dir = parent.full_dir
        self.par = parent

        if self.con.open():

            self.table = QTableWidget(16, 2)
            self.table.setColumnWidth(0, 150)
            self.table.setColumnWidth(1, 230)
            self.table.setFixedSize(674, 480)
            if self.interface_lng_val == 'Russian':
                self.table.setHorizontalHeaderLabels(["Параметр", "Значение"])
            elif self.interface_lng_val == 'English':
                self.table.setHorizontalHeaderLabels(["Parameter", "Value"])

# thermoType
            thermoType_lbl = QLabel('thermoType')
            self.table.setCellWidget(0, 0, thermoType_lbl)

            # type
            type_lbl = QLabel('type')
            self.type = QComboBox()
            self.type.setFixedSize(160, 25)
            type_list = ["heRhoThermo"]
            self.type.addItems(type_list)
            self.table.setCellWidget(1, 0, type_lbl)
            self.table.setCellWidget(1, 1, self.type)

            # mixture
            mixture_lbl = QLabel('mixture')
            self.mixture = QComboBox()
            self.mixture.setFixedSize(160, 25)
            mixture_list = ["pureMixture"]
            self.mixture.addItems(mixture_list)
            self.table.setCellWidget(2, 0, mixture_lbl)
            self.table.setCellWidget(2, 1, self.mixture)

            # transport
            transport_lbl = QLabel('transport')
            self.transport = QComboBox()
            self.transport.setFixedSize(160, 25)
            transport_list = ["const"]
            self.transport.addItems(transport_list)
            self.table.setCellWidget(3, 0, transport_lbl)
            self.table.setCellWidget(3, 1, self.transport)

            # thermo
            thermo_lbl = QLabel('thermo')
            self.thermo = QComboBox()
            self.thermo.setFixedSize(160, 25)
            thermo_list = ["hConst"]
            self.thermo.addItems(thermo_list)
            self.table.setCellWidget(4, 0, thermo_lbl)
            self.table.setCellWidget(4, 1, self.thermo)

            # equationOfState
            equationOfState_lbl = QLabel('thermo')
            self.equationOfState = QComboBox()
            self.equationOfState.setFixedSize(160, 25)
            equationOfState_list = ["perfectFluid"]
            self.equationOfState.addItems(equationOfState_list)
            self.table.setCellWidget(5, 0, equationOfState_lbl)
            self.table.setCellWidget(5, 1, self.equationOfState)

            # specie
            specie_lbl = QLabel('specie')
            self.specie = QComboBox()
            self.specie.setFixedSize(160, 25)
            specie_list = ["specie"]
            self.specie.addItems(specie_list)
            self.table.setCellWidget(6, 0, specie_lbl)
            self.table.setCellWidget(6, 1, self.specie)

            # energy
            energy_lbl = QLabel('energy')
            self.energy = QComboBox()
            self.energy.setFixedSize(160, 25)
            energy_list = ["sensibleInternalEnergy"]
            self.energy.addItems(energy_list)
            self.table.setCellWidget(7, 0, energy_lbl)
            self.table.setCellWidget(7, 1, self.energy)

            # mixture
            mixture_lbl = QLabel('mixture')
            self.table.setCellWidget(8, 0, mixture_lbl)

            # specie.molWeight
            specie_molWeight_lbl = QLabel('specie.molWeight')
            self.specie_molWeight = QLineEdit()
            self.specie_molWeight.setFixedSize(160, 25)
            self.table.setCellWidget(9, 0, specie_molWeight_lbl)
            self.table.setCellWidget(9, 1, self.specie_molWeight)

            # equationOfState.R
            equationOfState_R_lbl = QLabel('equationOfState.R')
            self.equationOfState_R = QLineEdit()
            self.equationOfState_R.setFixedSize(160, 25)
            self.table.setCellWidget(10, 0, equationOfState_R_lbl)
            self.table.setCellWidget(10, 1, self.equationOfState_R)

            # equationOfState.rho0
            equationOfState_rho0_lbl = QLabel('equationOfState.rho0')
            self.equationOfState_rho0 = QLineEdit()
            self.equationOfState_rho0.setFixedSize(160, 25)
            self.table.setCellWidget(11, 0, equationOfState_rho0_lbl)
            self.table.setCellWidget(11, 1, self.equationOfState_rho0)

            # thermodynamics.Cp
            thermodynamics_Cp_lbl = QLabel('thermodynamics.Cp')
            self.thermodynamics_Cp = QLineEdit()
            self.thermodynamics_Cp.setFixedSize(160, 25)
            self.table.setCellWidget(12, 0, thermodynamics_Cp_lbl)
            self.table.setCellWidget(12, 1, self.thermodynamics_Cp)

            # thermodynamics.Hf
            thermodynamics_Hf_lbl = QLabel('thermodynamics.Hf')
            self.thermodynamics_Hf = QLineEdit()
            self.thermodynamics_Hf.setFixedSize(160, 25)
            self.table.setCellWidget(13, 0, thermodynamics_Hf_lbl)
            self.table.setCellWidget(13, 1, self.thermodynamics_Hf)

            # transport.mu
            transport_mu_lbl = QLabel('transport.mu')
            self.transport_mu = QLineEdit()
            self.transport_mu.setFixedSize(160, 25)
            self.table.setCellWidget(14, 0, transport_mu_lbl)
            self.table.setCellWidget(14, 1, self.transport_mu)

            # transport.Pr
            transport_Pr_lbl = QLabel('transport.Pr')
            self.transport_Pr = QLineEdit()
            self.transport_Pr.setFixedSize(160, 25)
            self.table.setCellWidget(15, 0, transport_Pr_lbl)
            self.table.setCellWidget(15, 1, self.transport_Pr)

            # вывод значений параметров
            if 'thermophysicalProperties_water' in self.con.tables():
                query = QtSql.QSqlQuery()
                query.exec("SELECT * FROM thermophysicalProperties_water")
                if query.isActive():
                    query.first()
                    value_list = []
                    while query.isValid():
                        value_res = query.value('value')
                        value_list.append(value_res)
                        query.next()
                    print(value_list)
                    # type
                    type_mas = self.type.count()
                    for i in range(type_mas):
                        if self.type.itemText(i) == value_list[0]:
                            self.type.setCurrentIndex(i)

# mixture
                    mixture_mas = self.mixture.count()
                    for i in range(mixture_mas):
                        if self.mixture.itemText(i) == value_list[1]:
                            self.mixture.setCurrentIndex(i)

# transport
                    transport_mas = self.transport.count()
                    for i in range(transport_mas):
                        if self.transport.itemText(i) == value_list[2]:
                            self.transport.setCurrentIndex(i)

# thermo
                    thermo_mas = self.thermo.count()
                    for i in range(thermo_mas):
                        if self.thermo.itemText(i) == value_list[3]:
                            self.thermo.setCurrentIndex(i)

# equationOfState
                    equationOfState_mas = self.equationOfState.count()
                    for i in range(equationOfState_mas):
                        if self.equationOfState.itemText(i) == value_list[4]:
                            self.equationOfState.setCurrentIndex(i)

# specie
                    specie_mas = self.specie.count()
                    for i in range(specie_mas):
                        if self.specie.itemText(i) == value_list[5]:
                            self.specie.setCurrentIndex(i)

# energy
                    energy_mas = self.energy.count()
                    for i in range(energy_mas):
                        if self.energy.itemText(i) == value_list[6]:
                            self.energy.setCurrentIndex(i)

# specie.molWeight
                    self.specie_molWeight.setText(value_list[7])

                    # equationOfState.R
                    self.equationOfState_R.setText(value_list[8])

                    # equationOfState_rho0
                    self.equationOfState_rho0.setText(value_list[9])

                    # thermodynamics.Cp
                    self.thermodynamics_Cp.setText(value_list[10])

                    # thermodynamics.Hf
                    self.thermodynamics_Hf.setText(value_list[11])

                    # transport.mu
                    self.transport_mu.setText(value_list[12])

                    # transport.Pr
                    self.transport_Pr.setText(value_list[13])

            btnSave = QPushButton()
            btnSave.setFixedSize(80, 25)
            btnSave.clicked.connect(self.on_btnSave_clicked)

            if self.interface_lng_val == 'Russian':
                btnSave.setText("Сохранить")
            elif self.interface_lng_val == 'English':
                btnSave.setText("Save")

            vbox = QVBoxLayout()
            vbox.addWidget(self.table)
            vbox.addWidget(btnSave)

            # ---------------------Размещение на форме всех компонентов-------------------------

            form = QFormLayout()
            form.addRow(vbox)
            self.setLayout(form)
コード例 #50
0
ファイル: RedfieldWindow.py プロジェクト: kendall-s/HyPro2_py
class redfieldPlot(QMainPlotterTemplate):
    def __init__(self, database):
        super().__init__()
        self.database = database

        self.peak_numbers = []
        self.run_numbers = []

        self.apply_button.clicked.connect(self.draw_data)

        self.setWindowTitle('Redfield Ratio Plot')

        self.main_plot.set_title('Redfield Ratio', fontsize=18)
        self.main_plot.set_xlabel('[NOx] (uM)', fontsize=15)
        self.main_plot.set_ylabel('[Phosphate] (uM)', fontsize=15)

        self.main_plot.grid(alpha=0.1)
        survey_label = QLabel('Survey to use:', self)

        self.survey_selector = QComboBox()
        self.survey_selector.setFont(QFont('Segoe UI'))

        self.qvbox_layout.insertWidget(0, survey_label)
        self.qvbox_layout.insertWidget(1, self.survey_selector)

        self.populate_fields()
        self.show()

        self.canvas.mpl_connect('pick_event', self.on_pick)

    def populate_fields(self):

        conn = sqlite3.connect(self.database)
        c = conn.cursor()
        c.execute('SELECT DISTINCT runNumber FROM nitrateData')
        nitrate_runs = sorted(list(c.fetchall()))
        c.execute('SELECT DISTINCT runNumber FROM phosphateData')
        phosphate_runs = list(c.fetchall())

        runs = []
        for x in nitrate_runs:
            if x in phosphate_runs:
                runs.append(x[0])
                self.run_list.addItem(str(x[0]))
        query_placeholder = ', '.join('?' for unused in runs)
        c.execute(
            f'SELECT DISTINCT survey from nitrateData WHERE runNumber in ({query_placeholder})',
            (runs))
        distinct_surveys = list(c.fetchall())
        c.close()
        for x in distinct_surveys:
            self.survey_selector.addItem(x[0])

    def draw_data(self):

        del self.main_plot.collections[:]

        selected = self.run_list.selectedItems()
        selected_runs = [int(item.text()) for item in selected]

        if selected_runs:
            conn = sqlite3.connect(self.database)
            query_placeholder = ', '.join('?' for unused in selected_runs)
            nox_df = pd.read_sql_query(
                f"SELECT * FROM nitrateData WHERE runNumber IN ({query_placeholder})",
                conn,
                params=selected_runs)
            phos_df = pd.read_sql_query(
                f"SELECT * FROM phosphateData WHERE runNumber IN ({query_placeholder})",
                conn,
                params=selected_runs)

            nox_df = nox_df.loc[nox_df['cupType'] == 'SAMP']

            conn.close()
            nox_plottable = []
            phos_plottable = []
            self.runs = []
            self.peak_nums = []
            for nox_row in nox_df.itertuples():
                phos_point = phos_df.loc[(phos_df['runNumber'] == nox_row[1]) &
                                         (phos_df['peakNumber'] == nox_row[4])]
                self.runs.append(nox_row[1])
                self.peak_nums.append(nox_row[4])
                nox_plottable.append(nox_row[7])
                phos_plottable.append(float(phos_point['concentration']))

            self.main_plot.scatter(nox_plottable,
                                   phos_plottable,
                                   marker='o',
                                   facecolors='#FFB186',
                                   edgecolors='#EF8A68',
                                   alpha=0.75,
                                   picker=5)

            self.canvas.draw()

    def on_pick(self, event):
        self.base_on_pick(event, self.database, self.runs, self.peak_nums,
                          'nitrate')
コード例 #51
0
ファイル: address_list.py プロジェクト: mikakzm/electrum-ltc
class AddressList(MyTreeView):
    class Columns(IntEnum):
        TYPE = 0
        ADDRESS = 1
        LABEL = 2
        COIN_BALANCE = 3
        FIAT_BALANCE = 4
        NUM_TXS = 5

    filter_columns = [
        Columns.TYPE, Columns.ADDRESS, Columns.LABEL, Columns.COIN_BALANCE
    ]

    ROLE_SORT_ORDER = Qt.UserRole + 1000
    ROLE_ADDRESS_STR = Qt.UserRole + 1001

    def __init__(self, parent):
        super().__init__(parent,
                         self.create_menu,
                         stretch_column=self.Columns.LABEL,
                         editable_columns=[self.Columns.LABEL])
        self.wallet = self.parent.wallet
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.setSortingEnabled(True)
        self.show_change = AddressTypeFilter.ALL  # type: AddressTypeFilter
        self.show_used = AddressUsageStateFilter.ALL  # type: AddressUsageStateFilter
        self.change_button = QComboBox(self)
        self.change_button.currentIndexChanged.connect(self.toggle_change)
        for addr_type in AddressTypeFilter.__members__.values(
        ):  # type: AddressTypeFilter
            self.change_button.addItem(addr_type.ui_text())
        self.used_button = QComboBox(self)
        self.used_button.currentIndexChanged.connect(self.toggle_used)
        for addr_usage_state in AddressUsageStateFilter.__members__.values(
        ):  # type: AddressUsageStateFilter
            self.used_button.addItem(addr_usage_state.ui_text())
        self.std_model = QStandardItemModel(self)
        self.proxy = MySortModel(self, sort_role=self.ROLE_SORT_ORDER)
        self.proxy.setSourceModel(self.std_model)
        self.setModel(self.proxy)
        self.update()
        self.sortByColumn(self.Columns.TYPE, Qt.AscendingOrder)

    def get_toolbar_buttons(self):
        return QLabel(_("Filter:")), self.change_button, self.used_button

    def on_hide_toolbar(self):
        self.show_change = AddressTypeFilter.ALL  # type: AddressTypeFilter
        self.show_used = AddressUsageStateFilter.ALL  # type: AddressUsageStateFilter
        self.update()

    def save_toolbar_state(self, state, config):
        config.set_key('show_toolbar_addresses', state)

    def refresh_headers(self):
        fx = self.parent.fx
        if fx and fx.get_fiat_address_config():
            ccy = fx.get_currency()
        else:
            ccy = _('Fiat')
        headers = {
            self.Columns.TYPE: _('Type'),
            self.Columns.ADDRESS: _('Address'),
            self.Columns.LABEL: _('Label'),
            self.Columns.COIN_BALANCE: _('Balance'),
            self.Columns.FIAT_BALANCE: ccy + ' ' + _('Balance'),
            self.Columns.NUM_TXS: _('Tx'),
        }
        self.update_headers(headers)

    def toggle_change(self, state: int):
        if state == self.show_change:
            return
        self.show_change = AddressTypeFilter(state)
        self.update()

    def toggle_used(self, state: int):
        if state == self.show_used:
            return
        self.show_used = AddressUsageStateFilter(state)
        self.update()

    @profiler
    def update(self):
        if self.maybe_defer_update():
            return
        current_address = self.get_role_data_for_current_item(
            col=self.Columns.LABEL, role=self.ROLE_ADDRESS_STR)
        if self.show_change == AddressTypeFilter.RECEIVING:
            addr_list = self.wallet.get_receiving_addresses()
        elif self.show_change == AddressTypeFilter.CHANGE:
            addr_list = self.wallet.get_change_addresses()
        else:
            addr_list = self.wallet.get_addresses()
        self.proxy.setDynamicSortFilter(
            False)  # temp. disable re-sorting after every change
        self.std_model.clear()
        self.refresh_headers()
        fx = self.parent.fx
        set_address = None
        addresses_beyond_gap_limit = self.wallet.get_all_known_addresses_beyond_gap_limit(
        )
        for address in addr_list:
            num = self.wallet.get_address_history_len(address)
            label = self.wallet.get_label(address)
            c, u, x = self.wallet.get_addr_balance(address)
            balance = c + u + x
            is_used_and_empty = self.wallet.is_used(address) and balance == 0
            if self.show_used == AddressUsageStateFilter.UNUSED and (
                    balance or is_used_and_empty):
                continue
            if self.show_used == AddressUsageStateFilter.FUNDED and balance == 0:
                continue
            if self.show_used == AddressUsageStateFilter.USED_AND_EMPTY and not is_used_and_empty:
                continue
            balance_text = self.parent.format_amount(balance, whitespaces=True)
            # create item
            if fx and fx.get_fiat_address_config():
                rate = fx.exchange_rate()
                fiat_balance = fx.value_str(balance, rate)
            else:
                fiat_balance = ''
            labels = [
                '', address, label, balance_text, fiat_balance,
                "%d" % num
            ]
            address_item = [QStandardItem(e) for e in labels]
            # align text and set fonts
            for i, item in enumerate(address_item):
                item.setTextAlignment(Qt.AlignVCenter)
                if i not in (self.Columns.TYPE, self.Columns.LABEL):
                    item.setFont(QFont(MONOSPACE_FONT))
            self.set_editability(address_item)
            address_item[self.Columns.FIAT_BALANCE].setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            # setup column 0
            if self.wallet.is_change(address):
                address_item[self.Columns.TYPE].setText(_('change'))
                address_item[self.Columns.TYPE].setBackground(
                    ColorScheme.YELLOW.as_color(True))
            else:
                address_item[self.Columns.TYPE].setText(_('receiving'))
                address_item[self.Columns.TYPE].setBackground(
                    ColorScheme.GREEN.as_color(True))
            address_item[self.Columns.LABEL].setData(address,
                                                     self.ROLE_ADDRESS_STR)
            address_path = self.wallet.get_address_index(address)
            address_item[self.Columns.TYPE].setData(address_path,
                                                    self.ROLE_SORT_ORDER)
            address_path_str = self.wallet.get_address_path_str(address)
            if address_path_str is not None:
                address_item[self.Columns.TYPE].setToolTip(address_path_str)
            address_item[self.Columns.FIAT_BALANCE].setData(
                balance, self.ROLE_SORT_ORDER)
            # setup column 1
            if self.wallet.is_frozen_address(address):
                address_item[self.Columns.ADDRESS].setBackground(
                    ColorScheme.BLUE.as_color(True))
            if address in addresses_beyond_gap_limit:
                address_item[self.Columns.ADDRESS].setBackground(
                    ColorScheme.RED.as_color(True))
            # add item
            count = self.std_model.rowCount()
            self.std_model.insertRow(count, address_item)
            address_idx = self.std_model.index(count, self.Columns.LABEL)
            if address == current_address:
                set_address = QPersistentModelIndex(address_idx)
        self.set_current_idx(set_address)
        # show/hide columns
        if fx and fx.get_fiat_address_config():
            self.showColumn(self.Columns.FIAT_BALANCE)
        else:
            self.hideColumn(self.Columns.FIAT_BALANCE)
        self.filter()
        self.proxy.setDynamicSortFilter(True)

    def create_menu(self, position):
        from electrum_ltc.wallet import Multisig_Wallet
        is_multisig = isinstance(self.wallet, Multisig_Wallet)
        can_delete = self.wallet.can_delete_address()
        selected = self.selected_in_column(self.Columns.ADDRESS)
        if not selected:
            return
        multi_select = len(selected) > 1
        addrs = [self.item_from_index(item).text() for item in selected]
        menu = QMenu()
        if not multi_select:
            idx = self.indexAt(position)
            if not idx.isValid():
                return
            item = self.item_from_index(idx)
            if not item:
                return
            addr = addrs[0]
            addr_column_title = self.std_model.horizontalHeaderItem(
                self.Columns.LABEL).text()
            addr_idx = idx.sibling(idx.row(), self.Columns.LABEL)
            self.add_copy_menu(menu, idx)
            menu.addAction(_('Details'),
                           lambda: self.parent.show_address(addr))
            persistent = QPersistentModelIndex(addr_idx)
            menu.addAction(_("Edit {}").format(addr_column_title),
                           lambda p=persistent: self.edit(QModelIndex(p)))
            #menu.addAction(_("Request payment"), lambda: self.parent.receive_at(addr))
            if self.wallet.can_export():
                menu.addAction(_("Private key"),
                               lambda: self.parent.show_private_key(addr))
            if not is_multisig and not self.wallet.is_watching_only():
                menu.addAction(_("Sign/verify message"),
                               lambda: self.parent.sign_verify_message(addr))
                menu.addAction(_("Encrypt/decrypt message"),
                               lambda: self.parent.encrypt_message(addr))
            if can_delete:
                menu.addAction(_("Remove from wallet"),
                               lambda: self.parent.remove_address(addr))
            addr_URL = block_explorer_URL(self.config, 'addr', addr)
            if addr_URL:
                menu.addAction(_("View on block explorer"),
                               lambda: webopen(addr_URL))

            if not self.wallet.is_frozen_address(addr):
                menu.addAction(
                    _("Freeze"), lambda: self.parent.
                    set_frozen_state_of_addresses([addr], True))
            else:
                menu.addAction(
                    _("Unfreeze"), lambda: self.parent.
                    set_frozen_state_of_addresses([addr], False))

        coins = self.wallet.get_spendable_coins(addrs)
        if coins:
            menu.addAction(_("Spend from"),
                           lambda: self.parent.utxo_list.set_spend_list(coins))

        run_hook('receive_menu', menu, addrs, self.wallet)
        menu.exec_(self.viewport().mapToGlobal(position))

    def place_text_on_clipboard(self, text: str, *, title: str = None) -> None:
        if is_address(text):
            try:
                self.wallet.check_address_for_corruption(text)
            except InternalAddressCorruption as e:
                self.parent.show_error(str(e))
                raise
        super().place_text_on_clipboard(text, title=title)

    def get_edit_key_from_coordinate(self, row, col):
        if col != self.Columns.LABEL:
            return None
        return self.get_role_data_from_coordinate(row,
                                                  col,
                                                  role=self.ROLE_ADDRESS_STR)

    def on_edited(self, idx, edit_key, *, text):
        self.parent.wallet.set_label(edit_key, text)
        self.parent.history_model.refresh('address label edited')
        self.parent.utxo_list.update()
        self.parent.update_completions()
コード例 #52
0
ファイル: ChartThemes.py プロジェクト: xiliangjianke/PyQt
    def createLegendBox(self):
        legendComboBox = QComboBox()

        legendComboBox.addItem("No Legend ", 0)
        legendComboBox.addItem("Legend Top", Qt.AlignTop)
        legendComboBox.addItem("Legend Bottom", Qt.AlignBottom)
        legendComboBox.addItem("Legend Left", Qt.AlignLeft)
        legendComboBox.addItem("Legend Right", Qt.AlignRight)

        return legendComboBox
コード例 #53
0
    def initUI(self):
        self.lbl = QLabel("Ubuntu", self)

        combo = QComboBox(self)
        combo.addItem("Ubuntu")
        combo.addItem("Mandriva")
        combo.addItem("Fedora")
        combo.addItem("Arch")
        combo.addItem("Gentoo")

        combo.move(50, 50)
        self.lbl.move(50, 150)

        combo.activated[str].connect(self.onActivated)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QComboBox')
        self.show()
コード例 #54
0
class NetworkChoiceLayout(object):
    def __init__(self, network: Network, config: 'SimpleConfig', wizard=False):
        self.network = network
        self.config = config
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(proxy_tab, _('Proxy'))

        fixed_width_hostname = 24 * char_width_in_lineedit()
        fixed_width_port = 6 * char_width_in_lineedit()

        # 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'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(fixed_width_hostname)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(fixed_width_port)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_password = PasswordLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))
        self.proxy_password.setFixedWidth(fixed_width_port)

        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: with Electrum-NMC servers, but also with 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)
        grid.addWidget(self.proxy_password, 5, 3)
        grid.setRowStretch(7, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg = ' '.join([
            _("Electrum-NMC 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.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)
        msg = ' '.join([
            _("If auto-connect is enabled, Electrum-NMC 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. Electrum-NMC will warn you if your server is lagging."
              )
        ])
        grid.addWidget(self.autoconnect_cb, 1, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.server_e = QLineEdit()
        self.server_e.setFixedWidth(fixed_width_hostname + fixed_width_port)
        self.server_e.editingFinished.connect(self.set_server)
        msg = _(
            "Electrum-NMC sends your wallet addresses to a single server, in order to receive your transaction history."
        )
        grid.addWidget(QLabel(_('Server') + ':'), 2, 0)
        grid.addWidget(self.server_e, 2, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 2, 4)

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

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

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

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        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_e.setEnabled(enabled)
        else:
            for w in [
                    self.autoconnect_cb, self.server_e, self.nodes_list_widget
            ]:
                w.setEnabled(False)

    def update(self):
        net_params = self.network.get_parameters()
        server = net_params.server
        auto_connect = net_params.auto_connect
        if not self.server_e.hasFocus():
            self.server_e.setText(server.net_addr_str())
        self.autoconnect_cb.setChecked(auto_connect)

        height_str = "%d " % (self.network.get_local_height()) + _('blocks')
        self.height_label.setText(height_str)
        n = len(self.network.get_interfaces())
        status = _("Connected to {0} nodes.").format(n) if n > 1 else _(
            "Connected to {0} node.").format(n) if n == 1 else _(
                "Not connected")
        self.status_label.setText(status)
        chains = self.network.get_blockchains()
        if len(chains) > 1:
            chain = self.network.blockchain()
            forkpoint = chain.get_max_forkpoint()
            name = chain.get_name()
            msg = _('Chain split detected at block {0}').format(
                forkpoint) + '\n'
            msg += (_('You are following branch') if auto_connect else
                    _('Your server is on branch')) + ' ' + name
            msg += ' (%d %s)' % (chain.get_branch_size(), _('blocks'))
        else:
            msg = ''
        self.split_label.setText(msg)
        self.nodes_list_widget.update(network=self.network,
                                      servers=self.network.get_servers(),
                                      use_tor=self.tor_cb.isChecked())
        self.enable_set_server()

    def fill_in_proxy_settings(self):
        proxy_config = self.network.get_parameters().proxy
        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 follow_branch(self, chain_id):
        self.network.run_from_another_thread(
            self.network.follow_chain_given_id(chain_id))
        self.update()

    def follow_server(self, server: ServerAddr):
        self.network.run_from_another_thread(
            self.network.follow_chain_given_server(server))
        self.update()

    def accept(self):
        pass

    def set_server(self):
        net_params = self.network.get_parameters()
        try:
            server = ServerAddr.from_str_with_inference(
                str(self.server_e.text()))
            if not server: raise Exception("failed to parse")
        except Exception:
            return
        net_params = net_params._replace(
            server=server, auto_connect=self.autoconnect_cb.isChecked())
        self.network.run_from_another_thread(
            self.network.set_parameters(net_params))

    def set_proxy(self):
        net_params = 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)
        net_params = net_params._replace(proxy=proxy)
        self.network.run_from_another_thread(
            self.network.set_parameters(net_params))

    def suggest_proxy(self, found_proxy):
        if found_proxy is None:
            self.tor_cb.hide()
            return
        self.tor_proxy = found_proxy
        self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
        if (self.proxy_cb.isChecked() and 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.info("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)
コード例 #55
0
ファイル: New_Main.py プロジェクト: Anushka30/prj_ev
    def __init__(self, parent=None):
        super(WidgetGallery, self).__init__(parent)
        self.answer = ""
        self.originalPalette = QApplication.palette()

        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())

        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)

        self.useStylePaletteCheckBox = QCheckBox("&Use SP")
        self.useStylePaletteCheckBox.setChecked(True)

        disableWidgetsCheckBox = QCheckBox("&Disable widgets")

        #    self.createTopLeftGroupBox()
        self.createBottomRightGroupBox()
        self.createTopRightGroupBox()
        # self.createBottomLeftTabWidget()
        # self.createBottomRightGroupBox()
        # self.createProgressBar()

        styleComboBox.activated[str].connect(self.changeStyle)
        self.useStylePaletteCheckBox.toggled.connect(self.changePalette)
        #    disableWidgetsCheckBox.toggled.connect(self.topLeftGroupBox.setDisabled)
        disableWidgetsCheckBox.toggled.connect(
            self.topRightGroupBox.setDisabled)
        # disableWidgetsCheckBox.toggled.connect(self.bottomLeftTabWidget.setDisabled)
        disableWidgetsCheckBox.toggled.connect(
            self.bottomRightGroupBox.setDisabled)

        topLayout = QHBoxLayout()
        topLayout.addWidget(styleLabel)
        topLayout.addWidget(styleComboBox)
        topLayout.addStretch(1)
        topLayout.addWidget(self.useStylePaletteCheckBox)
        topLayout.addWidget(disableWidgetsCheckBox)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 2)
        mainLayout.addWidget(self.topRightGroupBox, 5, 0, 1, 0)
        mainLayout.addWidget(self.bottomRightGroupBox, 1, 0, 1, 0)
        # mainLayout.addWidget(self.topLeftGroupBox, 1, 1)
        mainLayout.setRowStretch(0, 0)
        mainLayout.setRowStretch(0, 0)
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(1, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle("EagleVoice")
        #    self.setMinimumSize(QSize(440, 240))
        #    self.windowIcon(QtGui.QIcon())
        self.changeStyle('Windows')

        with open('result.json', 'r') as fp:
            self.ques_dict = json.load(fp)
        # self.ques_dict = {"what is your name?": "My name is XY",
        #                   "good morning": "Good Morning",
        #                   "bye": "Good Bye",
        #                   "hi": "Hello",
        #                   "how are you?": "I am fine, How about you ?",
        #                   }

        self.ques_lst = []
        self.answer = []
コード例 #56
0
class HistoryList(MyTreeView, AcceptFileDragDrop):
    filter_columns = [
        HistoryColumns.STATUS, HistoryColumns.DIP2, HistoryColumns.DESCRIPTION,
        HistoryColumns.AMOUNT, HistoryColumns.TXID
    ]

    def __init__(self, parent, model: HistoryModel):
        super().__init__(parent,
                         self.create_menu,
                         stretch_column=HistoryColumns.DESCRIPTION)
        self.config = parent.config
        self.hm = model
        self.setModel(model)
        AcceptFileDragDrop.__init__(self, ".txn")
        self.setSortingEnabled(True)
        self.start_date = None
        self.end_date = None
        self.years = []
        self.create_toolbar_buttons()
        self.wallet = self.parent.wallet  # type: Abstract_Wallet
        self.sortByColumn(HistoryColumns.STATUS, Qt.AscendingOrder)
        self.editable_columns |= {HistoryColumns.FIAT_VALUE}

        self.header().setStretchLastSection(False)
        self.header().setMinimumSectionSize(32)
        for col in HistoryColumns:
            sm = QHeaderView.Stretch if col == self.stretch_column else QHeaderView.ResizeToContents
            self.header().setSectionResizeMode(col, sm)

    def format_date(self, d):
        return str(datetime.date(d.year, d.month, d.day)) if d else _('None')

    def on_combo(self, x):
        s = self.period_combo.itemText(x)
        x = s == _('Custom')
        self.start_button.setEnabled(x)
        self.end_button.setEnabled(x)
        if s == _('All'):
            self.start_date = None
            self.end_date = None
            self.start_button.setText("-")
            self.end_button.setText("-")
        else:
            try:
                year = int(s)
            except:
                return
            self.start_date = datetime.datetime(year, 1, 1)
            self.end_date = datetime.datetime(year + 1, 1, 1)
            self.start_button.setText(
                _('From') + ' ' + self.format_date(self.start_date))
            self.end_button.setText(
                _('To') + ' ' + self.format_date(self.end_date))
        self.hide_rows()

    def create_toolbar_buttons(self):
        self.period_combo = QComboBox()
        self.start_button = QPushButton('-')
        self.start_button.pressed.connect(self.select_start_date)
        self.start_button.setEnabled(False)
        self.end_button = QPushButton('-')
        self.end_button.pressed.connect(self.select_end_date)
        self.end_button.setEnabled(False)
        self.period_combo.addItems([_('All'), _('Custom')])
        self.period_combo.activated.connect(self.on_combo)

    def get_toolbar_buttons(self):
        return self.period_combo, self.start_button, self.end_button

    def on_hide_toolbar(self):
        self.start_date = None
        self.end_date = None
        self.hide_rows()

    def save_toolbar_state(self, state, config):
        config.set_key('show_toolbar_history', state)

    def select_start_date(self):
        self.start_date = self.select_date(self.start_button)
        self.hide_rows()

    def select_end_date(self):
        self.end_date = self.select_date(self.end_button)
        self.hide_rows()

    def select_date(self, button):
        d = WindowModalDialog(self, _("Select date"))
        d.setMinimumSize(600, 150)
        d.date = None
        vbox = QVBoxLayout()

        def on_date(date):
            d.date = date

        cal = QCalendarWidget()
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(on_date)
        vbox.addWidget(cal)
        vbox.addLayout(Buttons(OkButton(d), CancelButton(d)))
        d.setLayout(vbox)
        if d.exec_():
            if d.date is None:
                return None
            date = d.date.toPyDate()
            button.setText(self.format_date(date))
            return datetime.datetime(date.year, date.month, date.day)

    def show_summary(self):
        fx = self.parent.fx
        show_fiat = fx and fx.is_enabled() and fx.get_history_config()
        if not show_fiat:
            self.parent.show_message(
                _("Enable fiat exchange rate with history."))
            return
        h = self.parent.wallet.get_detailed_history(
            from_timestamp=time.mktime(self.start_date.timetuple())
            if self.start_date else None,
            to_timestamp=time.mktime(self.end_date.timetuple())
            if self.end_date else None,
            fx=fx)
        summary = h['summary']
        if not summary:
            self.parent.show_message(_("Nothing to summarize."))
            return
        start = summary['begin']
        end = summary['end']
        flow = summary['flow']
        start_date = start.get('date')
        end_date = end.get('date')
        format_amount = lambda x: self.parent.format_amount(
            x.value) + ' ' + self.parent.base_unit()
        format_fiat = lambda x: str(x) + ' ' + self.parent.fx.ccy

        d = WindowModalDialog(self, _("Summary"))
        d.setMinimumSize(600, 150)
        vbox = QVBoxLayout()
        msg = messages.to_rtf(messages.MSG_CAPITAL_GAINS)
        vbox.addWidget(WWLabel(msg))
        grid = QGridLayout()
        grid.addWidget(QLabel(_("Begin")), 0, 1)
        grid.addWidget(QLabel(_("End")), 0, 2)
        #
        grid.addWidget(QLabel(_("Date")), 1, 0)
        grid.addWidget(QLabel(self.format_date(start_date)), 1, 1)
        grid.addWidget(QLabel(self.format_date(end_date)), 1, 2)
        #
        grid.addWidget(QLabel(_("Dash balance")), 2, 0)
        grid.addWidget(QLabel(format_amount(start['BTC_balance'])), 2, 1)
        grid.addWidget(QLabel(format_amount(end['BTC_balance'])), 2, 2)
        #
        grid.addWidget(QLabel(_("Dash Fiat price")), 3, 0)
        grid.addWidget(QLabel(format_fiat(start.get('BTC_fiat_price'))), 3, 1)
        grid.addWidget(QLabel(format_fiat(end.get('BTC_fiat_price'))), 3, 2)
        #
        grid.addWidget(QLabel(_("Fiat balance")), 4, 0)
        grid.addWidget(QLabel(format_fiat(start.get('fiat_balance'))), 4, 1)
        grid.addWidget(QLabel(format_fiat(end.get('fiat_balance'))), 4, 2)
        #
        grid.addWidget(QLabel(_("Acquisition price")), 5, 0)
        grid.addWidget(QLabel(format_fiat(start.get('acquisition_price', ''))),
                       5, 1)
        grid.addWidget(QLabel(format_fiat(end.get('acquisition_price', ''))),
                       5, 2)
        #
        grid.addWidget(QLabel(_("Unrealized capital gains")), 6, 0)
        grid.addWidget(QLabel(format_fiat(start.get('unrealized_gains', ''))),
                       6, 1)
        grid.addWidget(QLabel(format_fiat(end.get('unrealized_gains', ''))), 6,
                       2)
        #
        grid2 = QGridLayout()
        grid2.addWidget(QLabel(_("Dash incoming")), 0, 0)
        grid2.addWidget(QLabel(format_amount(flow['BTC_incoming'])), 0, 1)
        grid2.addWidget(QLabel(_("Fiat incoming")), 1, 0)
        grid2.addWidget(QLabel(format_fiat(flow.get('fiat_incoming'))), 1, 1)
        grid2.addWidget(QLabel(_("Dash outgoing")), 2, 0)
        grid2.addWidget(QLabel(format_amount(flow['BTC_outgoing'])), 2, 1)
        grid2.addWidget(QLabel(_("Fiat outgoing")), 3, 0)
        grid2.addWidget(QLabel(format_fiat(flow.get('fiat_outgoing'))), 3, 1)
        #
        grid2.addWidget(QLabel(_("Realized capital gains")), 4, 0)
        grid2.addWidget(
            QLabel(format_fiat(flow.get('realized_capital_gains'))), 4, 1)
        vbox.addLayout(grid)
        vbox.addWidget(QLabel(_('Cash flow')))
        vbox.addLayout(grid2)
        vbox.addLayout(Buttons(CloseButton(d)))
        d.setLayout(vbox)
        d.exec_()

    def plot_history_dialog(self):
        if plot_history is None:
            self.parent.show_message(
                _("Can't plot history.") + '\n' +
                _("Perhaps some dependencies are missing...") +
                " (matplotlib?)")
            return
        try:
            res = []
            for tx_item, children in self.hm.tx_tree[::-1]:
                if children:
                    res.extend(children[::-1])
                res.append(tx_item)
            plt = plot_history(res)
            plt.show()
        except NothingToPlotException as e:
            self.parent.show_message(str(e))

    def on_edited(self, index, user_role, text):
        if not index.isValid():
            return

        column = index.column()
        tx_item = index.internalPointer()
        key = get_item_key(tx_item)
        if column == HistoryColumns.DESCRIPTION:
            if self.wallet.set_label(key, text):  #changed
                self.hm.update_label(index, tx_item)
                self.parent.update_completions()
        elif column == HistoryColumns.FIAT_VALUE:
            self.wallet.set_fiat_value(key, self.parent.fx.ccy, text,
                                       self.parent.fx, tx_item['value'].value)
            value = tx_item['value'].value
            if value is not None:
                self.hm.update_fiat(index, tx_item)
        else:
            assert False

    def mouseDoubleClickEvent(self, event: QMouseEvent):
        idx = self.indexAt(event.pos())
        if not idx.isValid():
            return
        tx_item = idx.internalPointer()
        if idx.column() == HistoryColumns.TX_GROUP:
            event.ignore()
            return
        is_parent = ('group_label' in tx_item)
        txid = tx_item['txid']
        if self.hm.flags(idx) & Qt.ItemIsEditable:
            if is_parent and txid not in self.hm.expanded_groups:
                self.show_transaction(txid)
            else:
                super().mouseDoubleClickEvent(event)
        else:
            self.show_transaction(txid)

    def mousePressEvent(self, event: QMouseEvent):
        if event.button() == Qt.LeftButton:
            idx = self.indexAt(event.pos())
            if idx.isValid() and idx.column() == HistoryColumns.TX_GROUP:
                tx_item = idx.internalPointer()
                txid = tx_item.get('txid')
                is_parent = ('group_label' in tx_item)
                if is_parent:
                    if txid not in self.hm.expanded_groups:
                        self.expand_tx_group(txid)
                    else:
                        self.collapse_tx_group(txid)
                    event.ignore()
                    return
                group_txid = tx_item.get('group_txid')
                if group_txid:
                    self.collapse_tx_group(group_txid)
                    event.ignore()
                    return
        super().mousePressEvent(event)

    def show_transaction(self, tx_hash):
        tx = self.wallet.db.get_transaction(tx_hash)
        if not tx:
            return
        label = self.wallet.get_label_for_txid(
            tx_hash
        ) or None  # prefer 'None' if not defined (force tx dialog to hide Description field if missing)
        self.parent.show_transaction(tx, tx_desc=label)

    def add_copy_menu(self, menu, idx):
        cc = menu.addMenu(_("Copy"))
        for column in HistoryColumns:
            if column == HistoryColumns.TX_GROUP:
                continue
            if self.isColumnHidden(column):
                continue
            column_title = self.hm.headerData(column, Qt.Horizontal,
                                              Qt.DisplayRole)
            idx2 = idx.sibling(idx.row(), column)
            tx_item = self.hm.data(idx2, Qt.DisplayRole)
            if not tx_item:
                continue
            column_data = (tx_item.value() or '').strip()
            cc.addAction(column_title,
                         lambda text=column_data, title=column_title: self.
                         place_text_on_clipboard(text, title=title))
        return cc

    def create_menu(self, position: QPoint):
        idx: QModelIndex = self.indexAt(position)
        if not idx.isValid():
            # can happen e.g. before list is populated for the first time
            return
        tx_item = idx.internalPointer()
        tx_hash = tx_item['txid']
        group_txid = tx_item.get('group_txid')
        is_parent = ('group_label' in tx_item)
        if is_parent and tx_hash in self.hm.expanded_groups:
            expanded = True
        else:
            expanded = False
        tx = self.wallet.db.get_transaction(tx_hash)
        if not tx:
            return
        tx_URL = block_explorer_URL(self.config, 'tx', tx_hash)
        tx_details = self.wallet.get_tx_info(tx)
        menu = QMenu()
        if group_txid:
            collapse_m = lambda: self.collapse_tx_group(group_txid)
            menu.addAction(_("Collapse Tx Group"), collapse_m)
        if is_parent:
            if expanded:
                collapse_m = lambda: self.collapse_tx_group(tx_hash)
                menu.addAction(_("Collapse Tx Group"), collapse_m)
            else:
                expand_m = lambda: self.expand_tx_group(tx_hash)
                menu.addAction(_("Expand Tx Group"), expand_m)
        if tx_details.can_remove and (not is_parent or expanded):
            menu.addAction(_("Remove"), lambda: self.remove_local_tx(tx_hash))
        cc = self.add_copy_menu(menu, idx)
        cc.addAction(
            _("Transaction ID"),
            lambda: self.place_text_on_clipboard(tx_hash, title="TXID"))
        for c in self.editable_columns:
            if is_parent and not expanded: continue
            if self.isColumnHidden(c): continue
            label = self.hm.headerData(c, Qt.Horizontal, Qt.DisplayRole)
            # TODO use siblingAtColumn when min Qt version is >=5.11
            persistent = QPersistentModelIndex(idx.sibling(idx.row(), c))
            menu.addAction(_("Edit {}").format(label),
                           lambda p=persistent: self.edit(QModelIndex(p)))
        menu.addAction(_("View Transaction"),
                       lambda: self.show_transaction(tx_hash))
        invoices = self.wallet.get_relevant_invoices_for_tx(tx)
        if len(invoices) == 1:
            menu.addAction(
                _("View invoice"),
                lambda inv=invoices[0]: self.parent.show_onchain_invoice(inv))
        elif len(invoices) > 1:
            menu_invs = menu.addMenu(_("Related invoices"))
            for inv in invoices:
                menu_invs.addAction(
                    _("View invoice"),
                    lambda inv=inv: self.parent.show_onchain_invoice(inv))
        if tx_URL:
            menu.addAction(_("View on block explorer"),
                           lambda: webopen(tx_URL))
        menu.exec_(self.viewport().mapToGlobal(position))

    def expand_tx_group(self, txid):
        if txid not in self.hm.expanded_groups:
            idx = self.hm.index_from_txid(txid)
            if idx.isValid():
                idx_last = idx.sibling(idx.row(), HistoryColumns.TXID)
                self.hm.expanded_groups.add(txid)
                self.expand(idx)
                self.hm.dataChanged.emit(idx, idx_last)

    def collapse_tx_group(self, txid):
        if txid in self.hm.expanded_groups:
            idx = self.hm.index_from_txid(txid)
            if idx.isValid():
                idx_last = idx.sibling(idx.row(), HistoryColumns.TXID)
                self.hm.expanded_groups.remove(txid)
                self.collapse(idx)
                self.hm.dataChanged.emit(idx, idx_last)

    def remove_local_tx(self, tx_hash):
        num_child_txs = len(self.wallet.get_depending_transactions(tx_hash))
        question = _("Are you sure you want to remove this transaction?")
        if num_child_txs > 0:
            question = (_(
                "Are you sure you want to remove this transaction and {} child transactions?"
            ).format(num_child_txs))
        if not self.parent.question(msg=question, title=_("Please confirm")):
            return
        self.wallet.remove_transaction(tx_hash)
        self.wallet.save_db()
        # need to update at least: history_list, utxo_list, address_list
        self.parent.need_update.set()

    def onFileAdded(self, fn):
        try:
            with open(fn) as f:
                tx = self.parent.tx_from_text(f.read())
        except IOError as e:
            self.parent.show_error(e)
            return
        if not tx:
            return
        self.parent.save_transaction_into_wallet(tx)

    def export_history_dialog(self):
        d = WindowModalDialog(self, _('Export History'))
        d.setMinimumSize(400, 200)
        vbox = QVBoxLayout(d)
        defaultname = os.path.expanduser('~/electrum-dash-history.csv')
        select_msg = _('Select file to export your wallet transactions to')
        hbox, filename_e, csv_button = filename_field(self, self.config,
                                                      defaultname, select_msg)
        vbox.addLayout(hbox)
        vbox.addStretch(1)
        hbox = Buttons(CancelButton(d), OkButton(d, _('Export')))
        vbox.addLayout(hbox)
        #run_hook('export_history_dialog', self, hbox)
        self.update()
        if not d.exec_():
            return
        filename = filename_e.text()
        if not filename:
            return
        try:
            self.do_export_history(filename, csv_button.isChecked())
        except (IOError, os.error) as reason:
            export_error_label = _(
                "Dash Electrum was unable to produce a transaction export.")
            self.parent.show_critical(export_error_label + "\n" + str(reason),
                                      title=_("Unable to export history"))
            return
        self.parent.show_message(
            _("Your wallet history has been successfully exported."))

    def do_export_history(self, file_name, is_csv):
        hist = self.wallet.get_detailed_history(fx=self.parent.fx)
        txns = hist['transactions']
        lines = []
        if is_csv:
            for item in txns:
                lines.append([
                    item['txid'],
                    item.get('label', ''), item['confirmations'],
                    item['bc_value'],
                    item.get('fiat_value', ''),
                    item.get('fee', ''),
                    item.get('fiat_fee', ''), item['date']
                ])
        with open(file_name, "w+", encoding='utf-8') as f:
            if is_csv:
                import csv
                transaction = csv.writer(f, lineterminator='\n')
                transaction.writerow([
                    "transaction_hash", "label", "confirmations", "value",
                    "fiat_value", "fee", "fiat_fee", "timestamp"
                ])
                for line in lines:
                    transaction.writerow(line)
            else:
                from electrum_dash.util import json_encode
                f.write(json_encode(txns))
        os.chmod(file_name, FILE_OWNER_MODE)

    def hide_rows(self):
        for i, (tx_item, children) in enumerate(self.hm.tx_tree):
            if children:
                left_children = len(children)
                parent_idx = self.hm.createIndex(i, 0, tx_item)
                for ch_tx_item in children:
                    if self.hide_tx_item(ch_tx_item, parent_idx):
                        left_children -= 1
                not_hide = (left_children > 0)
                self.hide_tx_item(tx_item, QModelIndex(), not_hide=not_hide)
            else:
                self.hide_tx_item(tx_item, QModelIndex())

    def hide_tx_item(self, tx_item, parent_idx, not_hide=False):
        idx = self.hm.index_from_txid(tx_item['txid'])
        if not idx.isValid():
            return True
        if not_hide:
            self.setRowHidden(idx.row(), parent_idx, False)
            return False
        should_hide = self.should_hide(tx_item)
        if not self.current_filter and should_hide is None:
            # no filters at all, neither date nor search
            self.setRowHidden(idx.row(), parent_idx, False)
            return False
        for column in self.filter_columns:
            txt_idx = idx.sibling(idx.row(), column)
            txt = self.hm.data(txt_idx, Qt.DisplayRole).value().lower()
            if self.current_filter in txt:
                # the filter matched, but the date filter might apply
                self.setRowHidden(idx.row(), parent_idx, bool(should_hide))
                return bool(should_hide)
        else:
            # we did not find the filter in any columns, hide the item
            self.setRowHidden(idx.row(), parent_idx, True)
            return True

    def should_hide(self, tx_item):
        if self.start_date and self.end_date:
            date = tx_item['date']
            if date:
                in_interval = self.start_date <= date <= self.end_date
                if not in_interval:
                    return True
            return False

    def get_text_and_userrole_from_coordinate(self, row, col, idx):
        if not idx.isValid():
            return None, None
        tx_item = idx.internalPointer()
        return self.hm.data(idx, Qt.DisplayRole).value(), get_item_key(tx_item)
コード例 #57
0
ファイル: ChartThemes.py プロジェクト: xiliangjianke/PyQt
    def createThemeBox(self):
        themeComboBox = QComboBox()

        themeComboBox.addItem("Light", QChart.ChartThemeLight)
        themeComboBox.addItem("Blue Cerulean", QChart.ChartThemeBlueCerulean)
        themeComboBox.addItem("Dark", QChart.ChartThemeDark)
        themeComboBox.addItem("Brown Sand", QChart.ChartThemeBrownSand)
        themeComboBox.addItem("Blue NCS", QChart.ChartThemeBlueNcs)
        themeComboBox.addItem("High Contrast", QChart.ChartThemeHighContrast)
        themeComboBox.addItem("Blue Icy", QChart.ChartThemeBlueIcy)

        return themeComboBox
コード例 #58
0
class wizard(QWidget):
	def __init__(self):
		super().__init__()
		self.dbg=True
		self.btnClose=False
		self.err={1:ERR_PASS_MATCH,2:ERR_PASS_LEN,3:ERR_USR_LEN,4:ERR_PASS_LONG,5:ERR_USR_LONG}
		(self.keymap,self.modmap)=self._load_keys()
		self._render_gui()
	#def init

	def _debug(self,msg):
		if self.dbg:
			print("wizard: %s"%msg)
		self.setWindowOpacity(.60)
	#def _debug

	def _load_keys(self):
		keymap={}
		self.closeKey=False
		for key,value in vars(Qt).items():
			if isinstance(value, Qt.Key):
				keymap[value]=key.partition('_')[2]
		modmap={
					Qt.ControlModifier: keymap[Qt.Key_Control],
					Qt.AltModifier: keymap[Qt.Key_Alt],
					Qt.ShiftModifier: keymap[Qt.Key_Shift],
					Qt.MetaModifier: keymap[Qt.Key_Meta],
					Qt.GroupSwitchModifier: keymap[Qt.Key_AltGr],
					Qt.KeypadModifier: keymap[Qt.Key_NumLock]
					}
		return(keymap,modmap)
	
	def closeEvent(self,event):
		if self.close==False: 
			event.ignore()
	#def closeEvent
	
	def keyPressEvent(self,event):
		key=self.keymap.get(event.key(),event.text())
		if key=="Alt":
			self.grab=True
			self.grabKeyboard()
		if key=="Super_L":
			event.accept()
		
	#def eventFilter
	
	def keyReleaseEvent(self,event):
		key=self.keymap.get(event.key(),event.text())
		if key=='Alt' or key=='Control':
			self.releaseKeyboard()
			self.grab=False
			if key=='Alt':
				if self.closeKey:
					self.closeKey=False
	#def keyReleaseEvent

	def _init_gui(self):
		self.setWindowFlags(Qt.FramelessWindowHint)
		self.setWindowFlags(Qt.X11BypassWindowManagerHint)
		self.setWindowState(Qt.WindowFullScreen)
		self.setWindowFlags(Qt.WindowStaysOnTopHint)
		self.setWindowModality(Qt.WindowModal)
		self.setStyleSheet(self._define_css())
		self.avatar="%s/user.svg"%RSRC
		self.bg="%s/background.svg"%RSRC
		self.showFullScreen()
		#self.show()
	#def _init_gui(self):

	def _render_gui(self):
		#Enable transparent window
		#self.setAttribute(Qt.WA_TranslucentBackground)

		####
		self._init_gui()
		self.frm_Init=QFrame()
		self.frm_End=QFrame()
		oImage = QtGui.QImage(self.bg)
		##sImage = oImage.scaled(QSize(300,200))                   # resize Image to widgets size
		palette = QtGui.QPalette()
		palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(oImage))                        
		self.setPalette(palette)

		self.box=QGridLayout()
		self.mbox=QGridLayout()
		pxm_logo=QtGui.QPixmap("%s/logo.svg"%RSRC)
		#wlc_msg=QLabel(WLC_MSG)
		wlc_msg=QLabel()
		wlc_msg.setPixmap(pxm_logo)
		wlc_msg.setObjectName("Message")
		self.box.addWidget(wlc_msg,0,0,1,2,Qt.AlignCenter|Qt.AlignBottom)
		usr_frame=QFrame()
		usr_layout=QGridLayout()
		usr_layout.addWidget(QLabel(USR_MSG),0,0,1,3,Qt.AlignCenter|Qt.AlignBottom)
		usr_frame.setLayout(usr_layout)

		self.usr_name=QLineEdit()
		self.usr_name.setPlaceholderText(LBL_USER)
		usr_layout.addWidget(self.usr_name,2,0,1,1,Qt.Alignment(0))
		self.usr_pass=QLineEdit()
		self.usr_pass.setEchoMode(QLineEdit.Password)
		self.usr_pass.setPlaceholderText(LBL_PASS)
		usr_layout.addWidget(self.usr_pass,3,0,1,1)
		self.usr_pass2=QLineEdit()
		self.usr_pass2.setEchoMode(QLineEdit.Password)
		self.usr_pass2.setPlaceholderText(LBL_PASS2)
		usr_layout.addWidget(self.usr_pass2,4,0,1,1)
		self.chk_login=QCheckBox(LBL_LOGIN)
		usr_layout.addWidget(self.chk_login,4,2,1,1,Qt.Alignment(1))
		self.box.addWidget(usr_frame,2,0,1,2,Qt.AlignCenter|Qt.AlignTop)

		self.usr_avatar=QPushButton()
		self.usr_avatar.setObjectName("QPushButton")
		icn=QtGui.QIcon(self.avatar)
		self.usr_avatar.setIcon(icn)
		self.usr_avatar.setIconSize(QSize(128,128))
		usr_layout.addWidget(self.usr_avatar,2,2,2,1,Qt.Alignment(1))
		
		lng_frame=QFrame()
		lng_frame.setObjectName("QFrame2")
		lng_layout=QGridLayout()
		lbl_lang=QLabel(LNG_MSG)
		lbl_lang.setStyleSheet("padding:0px;border:0px;margin:0px;margin-right:6px")
		lbl_lang.setObjectName("QLabel")
		lng_layout.addWidget(lbl_lang,5,0,1,1,Qt.AlignLeft)
		self.lng_locale=QComboBox()
		self.lng_locale.addItems([_("Valencian"),_("Spanish"),_("English")])
		self.lng_locale.addItems(locale.locale_alias)
		lng_layout.addWidget(self.lng_locale,5,1,1,1,Qt.Alignment(1))
		lng_frame.setLayout(lng_layout)
		usr_layout.addWidget(lng_frame,5,0,1,1,Qt.AlignLeft)
		
		self.hostname=QLineEdit()
		self.hostname.setPlaceholderText("%s (optional)"%HOST_MSG)
		usr_layout.addWidget(self.hostname,5,2,1,1)

		self.err_label=QLabel()
		self.box.addWidget(self.err_label,3,0,1,2,Qt.AlignCenter|Qt.AlignBottom)
		btn_Ko=QPushButton(_("Cancel"))
		btn_Ko.clicked.connect(self._on_close)
		self.box.addWidget(btn_Ko,4,0,1,1,Qt.AlignCenter)
		btn_Ok=QPushButton(_("Continue"))
		btn_Ok.clicked.connect(self._on_apply)
		self.box.addWidget(btn_Ok,4,1,1,1,Qt.AlignCenter)
		self.frm_Init.setLayout(self.box)
		self.frm_Init.setObjectName("QFrame")
		self.mbox.addWidget(self.frm_Init,0,0,1,1)
		self.setLayout(self.mbox)
	#def _render_gui

	def _on_exit(self,*args):
		self.btnClose=True
		self.close()

	def _on_apply(self):
		self.err_label.hide()
		self.usr_name.setStyleSheet("background:none")
		self.usr_pass.setStyleSheet("background:none")
		err=self._validate_fields()
		if err==0:
			self._confirm_user()
		else:
			self.err_label.setText(self.err.get(err,ERR_UNKNOWN))
			self.err_label.show()
			if err in [1,2,5]:
				self.usr_pass.setStyleSheet("background:red")
			if err in [3,4]:
				self.usr_name.setStyleSheet("background:red")

	def _validate_fields(self):
		err=0
		usr=self.usr_name.text()
		pwd=self.usr_pass.text()
		pwd2=self.usr_pass2.text()
		if pwd!=pwd2:
			err=1
		if len(pwd)<6:
			err=2
		if len(pwd)>30:
			err=5
		if len(usr)<2:
			err=3
		if len(usr)>20:
			err=4
		return err

	def _confirm_user(self):
		md=QDialog()
		md.accepted.connect(self._setConfig)
		md.setWindowTitle(MSG_CONFIRM_TITLE)
		hostname=self.hostname.text()
		if hostname=="":
			hostname="LliuWin"
		txt="%s\n"%LBL_NEW
		txt+="\n%s: %s"%(LBL_USER,self.usr_name.text())
		txt+="\n%s: %s"%(LBL_LOCALE,self.lng_locale.currentText())
		txt+="\n%s: %s"%(HOST_MSG,hostname)
		lay=QGridLayout()
		md.setLayout(lay)
		lay.addWidget(QLabel("%s"%txt),0,0,1,2)
		btn_Ok=QPushButton(ACCEPT)
		btn_Ok.clicked.connect(md.accept)
		lay.addWidget(btn_Ok,1,1,1,1)
		btn_Ko=QPushButton(CANCEL)
		btn_Ko.clicked.connect(md.reject)
		lay.addWidget(btn_Ko,1,0,1,1)
		md.setWindowModality(Qt.ApplicationModal)
		md.resize(600,300)
		md.exec_()
	#def _confirm_user

	def _setConfig(self):
		autologin=""
		if self.chk_login.isChecked()==True:
			autologin=self.usr_name.text()
		lang=self._get_user_locale()
		hostname=self.hostname.text()
		if hostname=="":
			hostname="LliuWin"
		cmd=['pkexec','%s/wizard_helper.sh'%SRC,self.usr_name.text(),self.usr_pass.text(),lang,hostname,autologin]
		try:
			subprocess.run(cmd)
		except Exception as e:
			print(str(e))
			return False
		self._on_finish()
	#def _setConfig

	def _get_user_locale(self):
		lang=self.lng_locale.currentText()
		if lang in [_("Valencian"),_("Spanish"),_("English")]:
			if lang==_("Valencian"):
				lang="ca_ES.utf8@valencia"
			elif lang==_("Spanish"):
				lang="es_ES.utf8"
			else:
				lang="en_US.utf8"
		return lang
	#def _get_user_locale

	def _on_finish(self):
		frm_End=QFrame()
		frm_End.setObjectName("QFrame")
		lay=QGridLayout()
		lbl=QLabel(LBL_END)
		lbl.setStyleSheet("font-size:24px;color:white")
		lay.addWidget(lbl,0,0,1,1,Qt.AlignCenter)
		btn=QPushButton(START)
		lay.addWidget(btn,1,0,1,1,Qt.AlignTop|Qt.AlignCenter)
		btn.clicked.connect(self._on_close)
		self.frm_Init.hide()
		frm_End.setLayout(lay)
		self.mbox.addWidget(frm_End,0,0,1,1)
	#def _on_finish

	def _on_close(self,*args):
		cmd=["loginctl","terminate-user","lliurex"]
		try:
			subprocess.run(cmd)
		except Exception as e:
			print(str(e))
			return False
		self.close()

	def showMessage(self,msg,status="error",height=252):
		return()
		self.statusBar.height_=height
		self.statusBar.setText(msg)
		if status:
			self.statusBar.show(state=status)
		else:
			self.statusBar.show(state=None)
	#def _show_message

	def _define_css(self):
		css="""
		#Message{
			padding:10px;
			margin:60px;
			border:40px;
		}
		#QPushButton{
			background-color:rgba(255,255,255,0);
			border-radius:25px;
		}
		QFrame{
			background-color:rgba(255,255,255,0.5);
			padding:10px;
			margin:10px;

		}
		#QFrame{
			background-color:rgba(255,255,255,0);
			padding:10px;
			margin:10px;

		}
		#QFrame2{
			background-color:rgba(255,255,255,0);
			padding:0px;
			margin:0px;

		}
		QLabel{
			font-weight:bold;
			background-color:transparent;
			font-size: 18px;	
		}
		#QLabel{
			font-weight:Normal;
			background-color:transparent;
			font-size: 14px;	
		}
		QLineEdit{
			padding:3px;
			margin:6px;
		}

		QCheckBox{
			margin:6px;
		}
		"""
		return(css)
コード例 #59
0
ファイル: scrape.py プロジェクト: cbonnell28/linkedin_scrape
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        # Making window
        self.setMinimumSize(QSize(400, 150))
        self.setWindowTitle("Linkedin Scraper")

        # Making all labels
        self.searchLabel = QLabel(self)
        self.searchLabel.setText('Search:')
        self.daysLabel = QLabel(self)
        self.daysLabel.setText('Days since posted:')
        self.semesterLabel = QLabel(self)
        self.semesterLabel.setText('Semester:')
        self.coopLabel = QLabel(self)
        self.coopLabel.setText('Co-op')
        self.internshipLabel = QLabel(self)
        self.internshipLabel.setText('Internship')

        # Making all line edits
        self.searchLine = QLineEdit(self)
        self.dayLine = QLineEdit(self)

        # Making all combo boxes
        self.semesterBox = QComboBox(self)

        # Making all checkboxes
        self.coopBox = QCheckBox(self)
        self.internshipBox = QCheckBox(self)

        # Modifying search line
        self.searchLine.move(80, 20)
        self.searchLine.resize(306, 32)
        self.searchLabel.move(20, 20)

        # Modifying day line
        self.dayLine.move(160, 60)
        self.dayLine.resize(32, 32)
        self.daysLabel.move(20, 65)
        self.daysLabel.adjustSize()

        # Modifying semester line
        self.semesterBox.addItem("Summer")
        self.semesterBox.addItem("Fall")
        self.semesterBox.addItem("Spring")
        self.semesterBox.addItem("Winter")
        self.semesterBox.move(287, 60)
        self.semesterLabel.move(212, 60)

        # Modifying search button
        pybutton = QPushButton('Search', self)
        pybutton.clicked.connect(self.searchLinkedin)
        pybutton.resize(200, 32)
        pybutton.move(40, 102)

        # Modifying checkboxes
        self.coopBox.move(260, 95)
        self.coopLabel.move(280, 95)
        self.coopBox.stateChanged.connect(self.checkCoop)
        self.internshipBox.move(260, 110)
        self.internshipLabel.move(280, 110)
        self.internshipBox.stateChanged.connect(self.checkInternship)

    def searchLinkedin(self):
        print('Your search: ' + self.searchLine.text())
        print('Days since posted: ' + self.dayLine.text())
        print('Semester: ' + self.semesterBox.currentText())
        print('Co-op: ' + str(self.coopBox.isChecked()))
        print('Internship: ' + str(self.internshipBox.isChecked()))

        # Populate search query dictionary
        search_query['search'] = self.searchLine.text()
        search_query['days_since_posting'] = self.dayLine.text()
        search_query['semester'] = self.semesterBox.currentText()
        query = search_query['search'] + ' ' + search_query[
            'semester'] + ' ' + search_query['coop'] + ' ' + search_query[
                'internship']
        print(query.split())

        url = self.format_url(query.split())
        self.scrape(url)

    def checkCoop(self, state):
        if state == QtCore.Qt.Checked:
            search_query['coop'] = 'coop'
        else:
            search_query['coop'] = ''

    def checkInternship(sefl, state):
        if state == QtCore.Qt.Checked:
            search_query['internship'] = 'internship'
        else:
            search_query['internship'] = ''

    def format_url(self, query):
        url_start = 'https://www.linkedin.com/jobs-guest/jobs/api/jobPostings/jobs?keywords='
        url_end = '&location=United%20States&trk=guest_job_search_jobs-search-bar_search-submit&redirect=false&position=1&pageNum=0&start=0'
        url_keywords = ''
        for word in query:
            url_keywords = url_keywords + word + '%20'
        url_keywords = url_keywords[0:len(url_keywords) - 3]
        linkedin_api_url = url_start + url_keywords + url_end
        return linkedin_api_url

    def scrape_soup(self, page_soup, file):
        # Grabs the list elements(li) from the web page with the job search results
        # Note: if the html classes ever change for Linkedin the
        # "result-card job-result-card result-card--with-hover-state"
        # may need to be updated to reflect this
        job_list = page_soup.findAll(
            "li", "result-card job-result-card result-card--with-hover-state")

        for job in job_list:

            print(job)

            job_company = job.find(
                "h4", "result-card__subtitle job-result-card__subtitle").text

            job_position = job.find(
                "h3", "result-card__title job-result-card__title").text

            job_link = job.find("a", "result-card__full-card-link")["href"]

            posted = job.find("time", "job-result-card__listdate")
            if posted == None:
                posted = job.find("time", "job-result-card__listdate--new")

            days_posted = posted["datetime"]
            print(days_posted)

            insertion_date = dateutil.parser.parse(days_posted)
            print("Insertion date: " + str(insertion_date))

            print("Days since posting: " + search_query['days_since_posting'])
            try:
                oldest_permitted_date = datetime.today() - timedelta(
                    days=int(search_query['days_since_posting']))
                print("Oldest permitted date: " + str(oldest_permitted_date))
            except ValueError:
                oldest_permitted_date = datetime.today() - timedelta(days=28)
                print("Oldest permitted date: " + str(oldest_permitted_date))

            if insertion_date > oldest_permitted_date:
                # print("job_company: " + job_company)
                # print("job_position: " + job_position)
                # print("job_link: " + job_link)
                print("added")

                file.write(
                    job_company.replace(",", "|") + "," +
                    job_position.replace(",", "|") + "," +
                    job_link.replace(",", "|") + "\n")

    def scrape(self, url):

        filename = search_query['file_name']
        file = open(filename, "w")

        header = "Company,Position,Link\n"

        file.write(header)

        page_start = '0'

        while True:
            # Opening and connecting to web client
            uClient = uReq(url)
            page_html = uClient.read()
            uClient.close()

            # Parse the html into a soup
            page_soup = soup(page_html, "html.parser")
            #print("THIS IS THE PAGE SOUP" + page_soup.text)
            if page_soup.text == '':
                print("break")
                break

            self.scrape_soup(page_soup, file)
            url = url[0:len(url) - len(page_start)]
            page_start = str(
                int(page_start) + 25
            )  # Changes the start page of the url to 25 further than before
            url = url + page_start
            print(url)

        file.close()
コード例 #60
-1
ファイル: fade.py プロジェクト: tornel/linux-show-player
    def __init__(self, size, Id, parent=None):
        super().__init__(size, parent)

        self.id = Id

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

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

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

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

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

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

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

        self.verticalLayout.addWidget(self.groupFadeIn)

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

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

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

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

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

        self.verticalLayout.addWidget(self.groupFadeOut)

        self.retranslateUi()