예제 #1
0
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setWindowTitle(self.tr('Insert table'))
        buttonBox = QDialogButtonBox(self)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok |
                                     QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.makeTable)
        buttonBox.rejected.connect(self.close)

        layout = QGridLayout(self)

        rowsLabel = QLabel(self.tr('Number of rows') + ':', self)
        columnsLabel = QLabel(self.tr('Number of columns') + ':', self)
        self.rowsSpinBox = QSpinBox(self)
        self.columnsSpinBox = QSpinBox(self)

        self.rowsSpinBox.setRange(1, 10)
        self.columnsSpinBox.setRange(1, 10)
        self.rowsSpinBox.setValue(3)
        self.columnsSpinBox.setValue(3)

        layout.addWidget(rowsLabel, 0, 0)
        layout.addWidget(self.rowsSpinBox, 0, 1, Qt.AlignRight)
        layout.addWidget(columnsLabel, 1, 0)
        layout.addWidget(self.columnsSpinBox, 1, 1, Qt.AlignRight)
        layout.addWidget(buttonBox, 2, 0, 1, 2)
예제 #2
0
    def __init__(self, page):
        super(Indenting, self).__init__(page)

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

        self.tabwidthBox = QSpinBox(minimum=1, maximum=99)
        self.tabwidthLabel = l = QLabel()
        l.setBuddy(self.tabwidthBox)

        self.nspacesBox = QSpinBox(minimum=0, maximum=99)
        self.nspacesLabel = l = QLabel()
        l.setBuddy(self.nspacesBox)

        self.dspacesBox = QSpinBox(minimum=0, maximum=99)
        self.dspacesLabel = l = QLabel()
        l.setBuddy(self.dspacesBox)

        layout.addWidget(self.tabwidthLabel, 0, 0)
        layout.addWidget(self.tabwidthBox, 0, 1)
        layout.addWidget(self.nspacesLabel, 1, 0)
        layout.addWidget(self.nspacesBox, 1, 1)
        layout.addWidget(self.dspacesLabel, 2, 0)
        layout.addWidget(self.dspacesBox, 2, 1)

        self.tabwidthBox.valueChanged.connect(page.changed)
        self.nspacesBox.valueChanged.connect(page.changed)
        self.dspacesBox.valueChanged.connect(page.changed)
        self.translateUI()
class IntegerParameterWidget(NumericParameterWidget):
    """Widget class for Integer parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A IntegerParameter object.
        :type parameter: IntegerParameter

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

        self._input = QSpinBox()
        self._input.setValue(self._parameter.value)
        self._input.setMinimum(self._parameter.minimum_allowed_value)
        self._input.setMaximum(self._parameter.maximum_allowed_value)
        tool_tip = 'Choose a number between %d and %d' % (
            self._parameter.minimum_allowed_value,
            self._parameter.maximum_allowed_value)
        self._input.setToolTip(tool_tip)

        self._input.setSizePolicy(self._spin_box_size_policy)

        self.inner_input_layout.addWidget(self._input)
        self.inner_input_layout.addWidget(self._unit_widget)
예제 #4
0
    def __init__(self, low, upp, parent=None):
        QWidget.__init__(self, parent)
        self.layout = QHBoxLayout(self)
        self._spin_start = QSpinBox(self)
        self._spin_end = QSpinBox(self)
        self.layout.addWidget(self._spin_start)

        self._slider = QxtSpanSlider(self)
        self._slider.setHandleMovementMode(QxtSpanSlider.NoOverlapping)

        self._slider.lowerPositionChanged.connect(lambda x: self._spin_start.setValue(x))
        self._slider.upperPositionChanged.connect(lambda x: self._spin_end.setValue(x))
        self._spin_start.valueChanged.connect(
            lambda x: self._slider.setLowerPosition(x)
            if x < self._slider.upperValue
            else self._spin_start.setValue(self._slider.upperValue - 1))
        self._spin_end.valueChanged.connect(
            lambda x: self._slider.setUpperPosition(x)
            if x > self._slider.lowerValue
            else self._spin_end.setValue(self._slider.lowerValue + 1))

        self.layout.addWidget(self._slider)
        self.layout.addWidget(self._spin_end)

        self.setRange(low, upp)
        self.setSpan(low, upp)
예제 #5
0
 def edit_label(self, label, type='lineedit'):
     def remove_label(self, label, dialog):
         label.remove()
         self.labels.remove([l for l in self.labels if l[1] == label][0])
         self.profile_plot.figure.canvas.draw()
         dialog.reject()
     dialog = QDialog()
     dialog.setWindowTitle("Edit Label")
     dialog.setLayout(QVBoxLayout())
     font_size = QSpinBox()
     font_size.setValue(label.get_fontsize())
     dialog.layout().addWidget(QLabel("Font Size"))
     dialog.layout().addWidget(font_size)
     text_edit = None
     if type == 'lineedit':
         text_edit = QLineEdit(label.get_text())
     else:
         text_edit = QTextEdit()
         text_edit.setPlainText(label.get_text())
         
     dialog.layout().addWidget(QLabel("Text"))
     dialog.layout().addWidget(text_edit)
     button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
     button_box.accepted.connect(dialog.accept)
     button_box.rejected.connect(dialog.reject)
     remove_button = QPushButton('Remove')
     remove_button.clicked.connect(lambda: remove_label(self, label, dialog))
     dialog.layout().addWidget(remove_button)
     dialog.layout().addWidget(button_box)
     if QDialog.Accepted != dialog.exec():
         return
     label.set_text(text_edit.text() if type=='lineedit' else text_edit.toPlainText())
     label.set_fontsize(font_size.value())
     label.axes.figure.canvas.draw()
예제 #6
0
    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)
예제 #7
0
class Organ(KeyboardPart):
    @staticmethod
    def title(_=_base.translate):
        return _("Organ")
    
    @staticmethod
    def short(_=_base.translate):
        return _("abbreviation for Organ", "Org.")
    
    midiInstrument = 'church organ'

    def createWidgets(self, layout):
        super(Organ, self).createWidgets(layout)
        grid = layout.itemAt(layout.count() - 1).layout()
        self.pedalVoices = QSpinBox(minimum=0, maximum=4, value=1)
        self.pedalVoicesLabel = QLabel()
        self.pedalVoicesLabel.setBuddy(self.pedalVoices)
        grid.addWidget(self.pedalVoicesLabel, 2, 0)
        grid.addWidget(self.pedalVoices)
        
    def translateWidgets(self):
        super(Organ, self).translateWidgets()
        self.pedalVoicesLabel.setText(_("Pedal:"))
        self.pedalVoices.setToolTip(_(
            "Set to 0 to disable the pedal altogether."))
    
    def build(self, data, builder):
        super(Organ, self).build(data, builder)
        if self.pedalVoices.value():
            data.nodes.append(self.buildStaff(data, builder,
                'pedal', -1, self.pedalVoices.value(), clef="bass"))
예제 #8
0
class NewValuesWidget(QGroupBox):
    def __init__(self, parent):
        super(NewValuesWidget, self).__init__(parent)

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

        self.ui()
        self.properties()

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

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

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

        self.new_rd.setChecked(True)

    def ui(self):
        self.grid.addWidget(self.new_rd, 0, 0, 1, 1, Qt.AlignTop)
        self.grid.addWidget(self.new_sb, 0, 1, 1, 9, Qt.AlignTop)
        self.grid.addWidget(self.system_missing, 1, 0, 1, 10, Qt.AlignTop)
        self.grid.addWidget(self.copy_old_values, 2, 0, 1, 10)
        self.grid.setSpacing(1)
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
예제 #9
0
    def createBottomRightGroupBox(self):
        self.bottomRightGroupBox = QGroupBox("Group 3")
        self.bottomRightGroupBox.setCheckable(True)
        self.bottomRightGroupBox.setChecked(True)

        lineEdit = QLineEdit('s3cRe7')
        lineEdit.setEchoMode(QLineEdit.Password)

        spinBox = QSpinBox(self.bottomRightGroupBox)
        spinBox.setValue(50)

        dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox)
        dateTimeEdit.setDateTime(QDateTime.currentDateTime())

        slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox)
        slider.setValue(40)

        scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox)
        scrollBar.setValue(60)

        dial = QDial(self.bottomRightGroupBox)
        dial.setValue(30)
        dial.setNotchesVisible(True)

        layout = QGridLayout()
        layout.addWidget(lineEdit, 0, 0, 1, 2)
        layout.addWidget(spinBox, 1, 0, 1, 2)
        layout.addWidget(dateTimeEdit, 2, 0, 1, 2)
        layout.addWidget(slider, 3, 0)
        layout.addWidget(scrollBar, 4, 0)
        layout.addWidget(dial, 3, 1, 2, 1)
        layout.setRowStretch(5, 1)
        self.bottomRightGroupBox.setLayout(layout)
예제 #10
0
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A IntegerParameter object.
        :type parameter: IntegerParameter

        """
        # Size policy
        self._spin_box_size_policy = QSizePolicy(
            QSizePolicy.Fixed, QSizePolicy.Fixed)

        super().__init__(parameter, parent)

        self._input_x = QSpinBox()
        self._input_x.setValue(self._parameter.value[0])
        tool_tip = 'X'
        self._input_x.setToolTip(tool_tip)
        self._input_x.setSizePolicy(self._spin_box_size_policy)

        self._input_y = QSpinBox()
        self._input_y.setValue(self._parameter.value[1])
        tool_tip = 'Y'
        self._input_y.setToolTip(tool_tip)
        self._input_y.setSizePolicy(self._spin_box_size_policy)

        self.inner_input_layout.addWidget(self._input_x)
        self.inner_input_layout.addWidget(self._input_y)
예제 #11
0
    def set_view(self):
        self.setWindowTitle("QOtpToken")

        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Secret: "))
        self.secret = QLineEdit()
        hbox.addWidget(self.secret)
        vbox.addLayout(hbox)

        hbox = QHBoxLayout()
        self.counter = QSpinBox()
        self.counter.setMinimum(0)
        self.length = QSpinBox()
        self.length.setValue(6)
        self.length.setMinimum(6)
        self.length.setMaximum(8)
        self.generate = QPushButton("Générer")
        hbox.addWidget(QLabel("Compteur: "))
        hbox.addWidget(self.counter)
        hbox.addWidget(QLabel("Taille: "))
        hbox.addWidget(self.length)
        hbox.addWidget(self.generate)
        vbox.addLayout(hbox)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Mot de passe jetable: "))
        self.display = QLineEdit("")
        self.display.setReadOnly(True)
        hbox.addWidget(self.display)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        pass
예제 #12
0
    def __init__(self, width, height, parent=None):
        super(ResizeDlg, self).__init__(parent)

        widthLabel = QLabel("&Width:")
        self.widthSpinBox = QSpinBox()
        widthLabel.setBuddy(self.widthSpinBox)
        self.widthSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
        self.widthSpinBox.setRange(4, width * 4)
        self.widthSpinBox.setValue(width)
        heightLabel = QLabel("&Height:")
        self.heightSpinBox = QSpinBox()
        heightLabel.setBuddy(self.heightSpinBox)
        self.heightSpinBox.setAlignment(Qt.AlignRight|
                                        Qt.AlignVCenter)
        self.heightSpinBox.setRange(4, height * 4)
        self.heightSpinBox.setValue(height)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                     QDialogButtonBox.Cancel)

        layout = QGridLayout()
        layout.addWidget(widthLabel, 0, 0)
        layout.addWidget(self.widthSpinBox, 0, 1)
        layout.addWidget(heightLabel, 1, 0)
        layout.addWidget(self.heightSpinBox, 1, 1)
        layout.addWidget(buttonBox, 2, 0, 1, 2)
        self.setLayout(layout)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
#        self.connect(buttonBox, SIGNAL("accepted()"), self.accept)
#        self.connect(buttonBox, SIGNAL("rejected()"), self.reject)

        self.setWindowTitle("Image Changer - Resize")
예제 #13
0
    def __init__(self, val, maxval, step, func):
        QSpinBox.__init__(self)

        self.setRange(0, maxval)
        self.setValue(val)
        self.setSingleStep(step)
        self.valueChanged.connect(func)
예제 #14
0
class Window(QWidget):

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

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

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

        self.btn = QPushButton("Print")

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

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

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

        vbox = QVBoxLayout()

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

        self.setLayout(vbox)

    def printText(self):
        print(self.spinbox.value())
예제 #15
0
class Console(QFrame):
    def __init__(self, parent=None):
        super(Console, self).__init__(parent)
        
        self.applyButton = QPushButton("Apply")
        self.playButton = QPushButton("Play")
        self.pauseButton = QPushButton("Pause")
        
        self.speedLabel = QLabel("Speed:")
        self.speedLabel.setAlignment(Qt.AlignCenter|Qt.AlignRight)
        self.speedSpin = QSpinBox()
        self.speedSpin.setValue(10)
        self.adjustButton = QPushButton("Adjust")
        
        layout = QGridLayout()
        for i in range (6):
            layout.setColumnStretch(i, 10)
        
        layout.addWidget(self.applyButton, 0, 0)
        layout.addWidget(self.playButton, 0, 1)
        layout.addWidget(self.pauseButton, 0, 2)
        
        layout.addWidget(self.speedLabel, 0, 3)
        layout.addWidget(self.speedSpin, 0, 4)
        layout.addWidget(self.adjustButton, 0, 5)
        
        self.setLayout(layout)
예제 #16
0
 def _addOptionToGrid(self, name, row):
     label = WidgetUtils.addLabel(None, None, name)
     spin = QSpinBox()
     spin.setMinimum(1)
     spin.setMaximum(20)
     self.top_layout.addWidget(label, row, 0)
     self.top_layout.addWidget(spin, row, 1)
     return label, spin
예제 #17
0
class PianoStaffPart(Part):
    """Base class for parts creating a piano staff."""
    def createWidgets(self, layout):
        self.label = QLabel(wordWrap=True)
        self.upperVoicesLabel = QLabel()
        self.lowerVoicesLabel = QLabel()
        self.upperVoices = QSpinBox(minimum=1, maximum=4, value=1)
        self.lowerVoices = QSpinBox(minimum=1, maximum=4, value=1)
        
        self.upperVoicesLabel.setBuddy(self.upperVoices)
        self.lowerVoicesLabel.setBuddy(self.lowerVoices)
        
        layout.addWidget(self.label)
        grid = QGridLayout()
        grid.addWidget(self.upperVoicesLabel, 0, 0)
        grid.addWidget(self.upperVoices, 0, 1)
        grid.addWidget(self.lowerVoicesLabel, 1, 0)
        grid.addWidget(self.lowerVoices, 1, 1)
        layout.addLayout(grid)
    
    def translateWidgets(self):
        self.label.setText('{0} <i>({1})</i>'.format(
            _("Adjust how many separate voices you want on each staff."),
            _("This is primarily useful when you write polyphonic music "
              "like a fuge.")))
        self.upperVoicesLabel.setText(_("Right hand:"))
        self.lowerVoicesLabel.setText(_("Left hand:"))
    
    def buildStaff(self, data, builder, name, octave, numVoices=1, node=None, clef=None):
        """Build a staff with the given number of voices and name."""
        staff = ly.dom.Staff(name, parent=node)
        builder.setMidiInstrument(staff, self.midiInstrument)
        c = ly.dom.Seqr(staff)
        if clef:
            ly.dom.Clef(clef, c)
        if numVoices == 1:
            a = data.assignMusic(name, octave)
            ly.dom.Identifier(a.name, c)
        else:
            c = ly.dom.Sim(c)
            for i in range(1, numVoices):
                a = data.assignMusic(name + ly.util.int2text(i), octave)
                ly.dom.Identifier(a.name, c)
                ly.dom.VoiceSeparator(c)
            a = data.assignMusic(name + ly.util.int2text(numVoices), octave)
            ly.dom.Identifier(a.name, c)
        return staff

    def build(self, data, builder):
        """ Setup structure for a 2-staff PianoStaff. """
        p = ly.dom.PianoStaff()
        builder.setInstrumentNamesFromPart(p, self, data)
        s = ly.dom.Sim(p)
        # add two staves, with a respective number of voices.
        self.buildStaff(data, builder, 'right', 1, self.upperVoices.value(), s)
        self.buildStaff(data, builder, 'left', 0, self.lowerVoices.value(), s, "bass")
        data.nodes.append(p)
예제 #18
0
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletIndustrialQuadRelayV2, *args)

        self.setupUi(self)

        self.iqr = self.device

        self.open_pixmap = load_masked_pixmap('plugin_system/plugins/industrial_quad_relay/relay_open.bmp')
        self.close_pixmap = load_masked_pixmap('plugin_system/plugins/industrial_quad_relay/relay_close.bmp')

        self.relay_buttons = [self.b0, self.b1, self.b2, self.b3]
        self.relay_button_icons = [self.b0_icon, self.b1_icon, self.b2_icon, self.b3_icon]
        self.relay_button_labels = [self.b0_label, self.b1_label, self.b2_label, self.b3_label]

        for icon in self.relay_button_icons:
            icon.setPixmap(self.open_pixmap)
            icon.show()

        for i in range(len(self.relay_buttons)):
            self.relay_buttons[i].clicked.connect(functools.partial(self.relay_button_clicked, i))

        self.monoflop_values = []
        self.monoflop_times = []

        for i in range(4):
            self.monoflop_channel.setItemData(i, i)

            monoflop_value = QComboBox()
            monoflop_value.addItem('On', True)
            monoflop_value.addItem('Off', False)

            self.monoflop_values.append(monoflop_value)
            self.monoflop_value_stack.addWidget(monoflop_value)

            monoflop_time = QSpinBox()
            monoflop_time.setRange(1, (1 << 31) - 1)
            monoflop_time.setValue(1000)

            self.monoflop_times.append(monoflop_time)
            self.monoflop_time_stack.addWidget(monoflop_time)

        self.monoflop = Monoflop(self.iqr,
                                 [0, 1, 2, 3],
                                 self.monoflop_values,
                                 self.cb_value_change_by_monoflop,
                                 self.monoflop_times,
                                 None,
                                 self)

        self.monoflop_channel.currentIndexChanged.connect(self.monoflop_channel_changed)
        self.monoflop_go.clicked.connect(self.monoflop_go_clicked)

        self.cbox_cs0_cfg.currentIndexChanged.connect(self.cbox_cs0_cfg_changed)
        self.cbox_cs1_cfg.currentIndexChanged.connect(self.cbox_cs1_cfg_changed)
        self.cbox_cs2_cfg.currentIndexChanged.connect(self.cbox_cs2_cfg_changed)
        self.cbox_cs3_cfg.currentIndexChanged.connect(self.cbox_cs3_cfg_changed)
예제 #19
0
class InsertTableDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setWindowTitle(self.tr('Insert table'))
        buttonBox = QDialogButtonBox(self)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok |
                                     QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.makeTable)
        buttonBox.rejected.connect(self.close)

        layout = QGridLayout(self)

        rowsLabel = QLabel(self.tr('Number of rows') + ':', self)
        columnsLabel = QLabel(self.tr('Number of columns') + ':', self)
        self.rowsSpinBox = QSpinBox(self)
        self.columnsSpinBox = QSpinBox(self)

        self.rowsSpinBox.setRange(1, 10)
        self.columnsSpinBox.setRange(1, 10)
        self.rowsSpinBox.setValue(3)
        self.columnsSpinBox.setValue(3)

        layout.addWidget(rowsLabel, 0, 0)
        layout.addWidget(self.rowsSpinBox, 0, 1, Qt.AlignRight)
        layout.addWidget(columnsLabel, 1, 0)
        layout.addWidget(self.columnsSpinBox, 1, 1, Qt.AlignRight)
        layout.addWidget(buttonBox, 2, 0, 1, 2)

    def makeTable(self):
        rowsCount = self.rowsSpinBox.value()
        columnsCount = self.columnsSpinBox.value() + 1

        tab = self.parent.currentTab
        cursor = tab.editBox.textCursor()

        tableCode = '' if cursor.atBlockStart() else '\n\n'
        if tab.activeMarkupClass == ReStructuredTextMarkup:
            # Insert reStructuredText grid table
            tableCode += '-----'.join('+' * columnsCount) + '\n'
            tableCode += '     '.join('|' * columnsCount) + '\n'
            tableCode += '====='.join('+' * columnsCount) + '\n'
            tableCode += ('     '.join('|' * columnsCount) + '\n' +
                          '-----'.join('+' * columnsCount) + '\n') * rowsCount
        else:
            # Insert Markdown table
            tableCode += '     '.join('|' * columnsCount) + '\n'
            tableCode += '-----'.join('|' * columnsCount) + '\n'
            tableCode += ('     '.join('|' * columnsCount) + '\n') * rowsCount

        cursor.insertText(tableCode)
        self.close()

        # Activate the Table editing mode
        self.parent.actionTableMode.setChecked(True)
        tab.editBox.tableModeEnabled = True
    def createEditor(self, parent, option, index):
        editor = QSpinBox(parent=parent)

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

        editor.setRange(0, 3)

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

        self._COMBOBOX_ITEM_LIST = (QtCore.QT_TRANSLATE_NOOP("PlotControlWidget", "Area chart"),
                                    QtCore.QT_TRANSLATE_NOOP("PlotControlWidget", "Line chart"))

        # create labels and input fields
        self.viewLabel = QLabel()
        self.viewInput = QComboBox(self)

        self.lengthCheckBox = QCheckBox()
        self.lengthCheckBox.setCheckState(Qt.Checked)
        self.lengthCheckBox.setDisabled(True)
        self.lengthInput = QSpinBox(self, maximum=99999)
        self.lengthInput.setSuffix(" Lfm.")
        self.lengthInput.setDisabled(True)

        self.countCheckBox = QCheckBox()
        self.countCheckBox.setCheckState(Qt.Checked)
        self.countCheckBox.setDisabled(True)
        self.countInput = QSpinBox(self, maximum=99999)
        self.countInput.setSuffix(" St.")
        self.countInput.setDisabled(True)
        self.countCalculator = QPushButton()
        self.countCalculator.setDisabled(True)

        lineFrame = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.VLine)

        # create layout
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.viewLabel)
        layout.addWidget(self.viewInput)
        layout.addStretch()
        layout.addWidget(self.lengthCheckBox)
        layout.addWidget(self.lengthInput)
        layout.addWidget(lineFrame)
        layout.addWidget(self.countCheckBox)
        layout.addWidget(self.countInput)
        layout.addWidget(self.countCalculator)

        # connect signals
        self.viewInput.currentIndexChanged.connect(self.chartViewChanged)
        self.lengthCheckBox.stateChanged.connect(self.enableLengthInput)
        self.countCheckBox.stateChanged.connect(self.enableCountInput)
        self.lengthInput.valueChanged.connect(self.lengthChanged)
        self.lengthInput.editingFinished.connect(self.lengthFinished)
        self.countInput.valueChanged.connect(self.countChanged)

        self.countCalculator.clicked.connect(self.countCalculation)

        # translate the graphical user interface
        self.retranslateUi()
예제 #22
0
    def __init__(self, **kwds):
        super(InputSettings, self).__init__(**kwds)

        self.top_layout = WidgetUtils.addLayout(grid=True)
        self.setLayout(self.top_layout)
        label = WidgetUtils.addLabel(None, None, "Max recently used")
        spin = QSpinBox()
        spin.setMinimum(1)
        spin.setMaximum(20)
        self.top_layout.addWidget(label, 0, 0)
        self.top_layout.addWidget(spin, 0, 1)
        self.max_recent_spinbox = spin
        self.setup()
예제 #23
0
class YearSelector(QFrame):
    def __init__(self, text='Year:', min_year=1950, max_year=2100, **kwargs):
        QFrame.__init__(self)
        self.main_layout = QHBoxLayout(self)
        self.label = QLabel(text)
        self.year_selector = QSpinBox()
        self.year_selector.setRange(min_year, max_year)
        self.main_layout.addWidget(self.label)
        self.main_layout.addWidget(self.year_selector)

    def get_selected_year(self):
        return self.year_selector.value()

    def set_year(self, year):
        self.year_selector.setValue(int(year))
예제 #24
0
    def __init__(self, parent):
        super(PercentSlider, self).__init__(parent)

        self._slider = QSlider(Qt.Vertical, self)
        self._slider.setMinimum(-100)
        self._slider.setMaximum(100)
        self._slider.setValue(0)
        self._slider.setTickInterval(100)
        self._slider.setTickPosition(QSlider.TicksBothSides)
        self._slider.valueChanged.connect(lambda: self._spinbox.setValue(self._slider.value()))

        self._spinbox = QSpinBox(self)
        self._spinbox.setMinimum(-100)
        self._spinbox.setMaximum(100)
        self._spinbox.setValue(0)
        self._spinbox.valueChanged.connect(lambda: self._slider.setValue(self._spinbox.value()))

        self._zero_button = make_icon_button("hand-stop-o", "Zero setpoint", self, on_clicked=self.zero)

        layout = QVBoxLayout(self)
        sub_layout = QHBoxLayout(self)
        sub_layout.addStretch()
        sub_layout.addWidget(self._slider)
        sub_layout.addStretch()
        layout.addLayout(sub_layout)
        layout.addWidget(self._spinbox)
        layout.addWidget(self._zero_button)
        self.setLayout(layout)

        self.setMinimumHeight(400)
예제 #25
0
    def createControl(self):
        self.Buttons = QGridLayout()

        self.btn_solve_five_graph = QPushButton("Randomize, Solve 5, Graph")
        self.btn_Reset = QPushButton("Reset")
        self.btn_RotateCL = QPushButton("Rotate Left Side Clockwise")
        self.btn_RotateCCL = QPushButton("Rotate Left Side Counter-Clockwise")

        self.btn_RotateCR = QPushButton("Rotate Right Side Clockwise")
        self.btn_RotateCCR = QPushButton("Rotate Right Side Counter-Clockwise")
        self.btn_Solve = QPushButton("Solve")

        self.btn_Randomize = QPushButton("Randomize the Puzzle")
        self.RanomizeCounter = QSpinBox()
        self.RanomizeCounter.setRange(1, 100)
        self.RanomizeCounter.setSingleStep(1)

       # self.Buttons.addWidget(self.self.btn_solve_five_graph, 6, 0)
        self.Buttons.addWidget(self.btn_RotateCL, 1, 0)
        self.Buttons.addWidget(self.btn_RotateCCL, 1, 1)
        self.Buttons.addWidget(self.btn_RotateCR, 2, 0)
        self.Buttons.addWidget(self.btn_RotateCCR, 2, 1)
        self.Buttons.addWidget(self.btn_Randomize, 4, 0)
        self.Buttons.addWidget(self.RanomizeCounter, 4, 1)
        self.Buttons.addWidget(self.btn_Reset,5,1)
        self.Buttons.addWidget(self.btn_Solve,5,0)
        self.Buttons.addWidget(self.btn_solve_five_graph,6,0)
예제 #26
0
    def __init__(self, capture_context, parent):
        """Initializes the dialog.

        `capture_context` is the detection.ExamCaptureContext object
        to be used.

        """
        super().__init__(parent)
        self.capture_context = capture_context
        self.setWindowTitle(_('Select a camera'))
        layout = QVBoxLayout(self)
        self.setLayout(layout)
        self.camview = widgets.CamView((320, 240), self, border=True)
        self.label = QLabel(self)
        self.button = QPushButton(_('Try this camera'))
        self.camera_selector = QSpinBox(self)
        container = widgets.LineContainer(self, self.camera_selector,
                                          self.button)
        self.button.clicked.connect(self._select_camera)
        buttons = QDialogButtonBox(QDialogButtonBox.Ok)
        buttons.accepted.connect(self.accept)
        layout.addWidget(self.camview)
        layout.addWidget(self.label)
        layout.addWidget(container)
        layout.addWidget(buttons)
        self.camera_error.connect(self._show_camera_error,
                                  type=Qt.QueuedConnection)
        self.timer = None
예제 #27
0
 def __init__(self, page):
     super(Browser, self).__init__(page)
     
     layout = QGridLayout()
     self.setLayout(layout)
     
     self.languagesLabel = QLabel()
     self.languages = QComboBox(currentIndexChanged=self.changed)
     layout.addWidget(self.languagesLabel, 0, 0)
     layout.addWidget(self.languages, 0, 1)
     
     items = ['', '']
     items.extend(language_names.languageName(l, l) for l in lilydoc.translations)
     self.languages.addItems(items)
     
     self.fontLabel = QLabel()
     self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
     self.fontSize = QSpinBox(valueChanged=self.changed)
     self.fontSize.setRange(6, 32)
     self.fontSize.setSingleStep(1)
     
     layout.addWidget(self.fontLabel, 1, 0)
     layout.addWidget(self.fontChooser, 1, 1)
     layout.addWidget(self.fontSize, 1, 2)
     
     app.translateUI(self)
예제 #28
0
    def __init__(self, *args):
        super().__init__(BrickletAnalogIn, *args)

        self.ai = self.device

        # the firmware version of a EEPROM Bricklet can (under common circumstances)
        # not change during the lifetime of an EEPROM Bricklet plugin. therefore,
        # it's okay to make final decisions based on it here
        self.has_range = self.firmware_version >= (2, 0, 1)
        self.has_averaging = self.firmware_version >= (2, 0, 3)

        self.cbe_voltage = CallbackEmulator(self.ai.get_voltage,
                                            None,
                                            self.cb_voltage,
                                            self.increase_error_count)

        self.current_voltage = CurveValueWrapper() # float, V

        plots = [('Voltage', Qt.red, self.current_voltage, format_voltage)]
        self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)

        if self.has_range:
            self.combo_range = QComboBox()
            self.combo_range.addItem('Automatic', BrickletAnalogIn.RANGE_AUTOMATIC)

            if self.has_averaging:
                self.combo_range.addItem('0 - 3.30 V', BrickletAnalogIn.RANGE_UP_TO_3V)

            self.combo_range.addItem('0 - 6.05 V', BrickletAnalogIn.RANGE_UP_TO_6V)
            self.combo_range.addItem('0 - 10.32 V', BrickletAnalogIn.RANGE_UP_TO_10V)
            self.combo_range.addItem('0 - 36.30 V', BrickletAnalogIn.RANGE_UP_TO_36V)
            self.combo_range.addItem('0 - 45.00 V', BrickletAnalogIn.RANGE_UP_TO_45V)
            self.combo_range.currentIndexChanged.connect(self.range_changed)

            hlayout = QHBoxLayout()
            hlayout.addWidget(QLabel('Range:'))
            hlayout.addWidget(self.combo_range)
            hlayout.addStretch()

            if self.has_averaging:
                self.spin_average = QSpinBox()
                self.spin_average.setMinimum(0)
                self.spin_average.setMaximum(255)
                self.spin_average.setSingleStep(1)
                self.spin_average.setValue(50)
                self.spin_average.editingFinished.connect(self.spin_average_finished)

                hlayout.addWidget(QLabel('Average Length:'))
                hlayout.addWidget(self.spin_average)

            line = QFrame()
            line.setObjectName("line")
            line.setFrameShape(QFrame.HLine)
            line.setFrameShadow(QFrame.Sunken)

            layout.addWidget(line)
            layout.addLayout(hlayout)
    def __init__(self, format, parent=None):
        super(NumberFormatDlg, self).__init__(parent)

        thousandsLabel = QLabel("&Thousands separator")
        self.thousandsEdit = QLineEdit(format["thousandsseparator"])
        thousandsLabel.setBuddy(self.thousandsEdit)
        decimalMarkerLabel = QLabel("Decimal &marker")
        self.decimalMarkerEdit = QLineEdit(format["decimalmarker"])
        decimalMarkerLabel.setBuddy(self.decimalMarkerEdit)
        decimalPlacesLabel = QLabel("&Decimal places")
        self.decimalPlacesSpinBox = QSpinBox()
        decimalPlacesLabel.setBuddy(self.decimalPlacesSpinBox)
        self.decimalPlacesSpinBox.setRange(0, 6)
        self.decimalPlacesSpinBox.setValue(format["decimalplaces"])
        self.redNegativesCheckBox = QCheckBox("&Red negative numbers")
        self.redNegativesCheckBox.setChecked(format["rednegatives"])

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.format = format.copy()

        grid = QGridLayout()
        grid.addWidget(thousandsLabel, 0, 0)
        grid.addWidget(self.thousandsEdit, 0, 1)
        grid.addWidget(decimalMarkerLabel, 1, 0)
        grid.addWidget(self.decimalMarkerEdit, 1, 1)
        grid.addWidget(decimalPlacesLabel, 2, 0)
        grid.addWidget(self.decimalPlacesSpinBox, 2, 1)
        grid.addWidget(self.redNegativesCheckBox, 3, 0, 1, 2)
        grid.addWidget(buttonBox, 4, 0, 1, 2)
        self.setLayout(grid)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        self.setWindowTitle("Set Number Format (Modal)")
예제 #30
0
	def __init__(self, name, conf, min, max, parent=None):
		super(SpinBox, self).__init__(parent)
		self.conf = conf
		layout = QVBoxLayout()
		self.l = QLabel(name)
		self.l.setAlignment(Qt.AlignCenter)
		layout.addWidget(self.l)
		self.sp = QSpinBox()
		if self.l.text() == "Filter":
			if len(self.conf.columnToFilter):
				self.sp.setValue(self.conf.columnToFilter[0])
		if self.l.text() == "Click":
			self.sp.setValue(self.conf.nbClickValidMax)
		if self.l.text() == "Row min":
			self.sp.setValue(self.conf.startIdx)
		if self.l.text() == "Row max":
			self.sp.setValue(self.conf.endIdx)
		if self.l.text() == "Nb Q":
			self.sp.setValue(self.conf.nbQuestions)
		if min is None:
			self.sp.setMaximum(max)
		elif max is None:
			self.sp.setMinimum(min)
		else:
			self.sp.setRange(min, max)
		layout.addWidget(self.sp)
		self.sp.valueChanged.connect(self.valuechange)
		self.setLayout(layout)
예제 #31
0
    def __init__(self, parent, maxMark, lst, questnum, curtestname, com=None):
        super(QDialog, self).__init__()
        self.parent = parent
        self.questnum = questnum
        self.setWindowTitle("Edit comment")
        self.CB = QComboBox()
        self.TE = QTextEdit()
        self.SB = QSpinBox()
        self.DE = QCheckBox("Delta-mark enabled")
        self.DE.setCheckState(Qt.Checked)
        self.DE.stateChanged.connect(self.toggleSB)
        self.TEtag = QTextEdit()
        self.TEmeta = QTextEdit()
        self.TEtestname = QLineEdit()
        # TODO: how to make it smaller vertically than the TE?
        # self.TEtag.setMinimumHeight(self.TE.minimumHeight() // 2)
        # self.TEtag.setMaximumHeight(self.TE.maximumHeight() // 2)
        self.QSpecific = QCheckBox(
            "Available only in question {}".format(questnum))
        self.QSpecific.stateChanged.connect(self.toggleQSpecific)

        flay = QFormLayout()
        flay.addRow("Enter text", self.TE)
        flay.addRow("Choose text", self.CB)
        flay.addRow("Set delta", self.SB)
        flay.addRow("", self.DE)
        flay.addRow("", self.QSpecific)
        flay.addRow("Tags", self.TEtag)
        # TODO: support multiple tests, change label to "test(s)" here
        flay.addRow("Specific to test", self.TEtestname)
        flay.addRow("", QLabel("(leave blank to share between tests)"))
        flay.addRow("Meta", self.TEmeta)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok
                                   | QDialogButtonBox.Cancel)

        vlay = QVBoxLayout()
        vlay.addLayout(flay)
        vlay.addWidget(buttons)
        self.setLayout(vlay)

        # set up widgets
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        self.SB.setRange(-maxMark, maxMark)
        self.CB.addItem("")
        self.CB.addItems(lst)
        # Set up TE and CB so that when CB changed, text is updated
        self.CB.currentTextChanged.connect(self.changedCB)
        # If supplied with current text/delta then set them
        if com:
            if com["text"]:
                self.TE.clear()
                self.TE.insertPlainText(com["text"])
            if com["tags"]:
                self.TEtag.clear()
                self.TEtag.insertPlainText(com["tags"])
            if com["meta"]:
                self.TEmeta.clear()
                self.TEmeta.insertPlainText(com["meta"])
            if com["delta"]:
                if com["delta"] == ".":
                    self.SB.setValue(0)
                    self.DE.setCheckState(Qt.Unchecked)
                else:
                    self.SB.setValue(int(com["delta"]))
            if com["testname"]:
                self.TEtestname.setText(com["testname"])
            # TODO: ideally we would do this on TE change signal
            # TODO: textEdited() signal (not textChanged())
            if commentHasMultipleQTags(com):
                self.QSpecific.setEnabled(False)
            elif commentTaggedQn(com, self.questnum):
                self.QSpecific.setCheckState(Qt.Checked)
            else:
                self.QSpecific.setCheckState(Qt.Unchecked)
        else:
            self.TEtestname.setText(curtestname)
            self.QSpecific.setCheckState(Qt.Checked)
            self.TE.setPlaceholderText(
                'Prepend with "tex:" to use math.\n\n'
                'You can "Choose text" to harvest comments from an existing annotation.\n\n'
                'Change "delta" below to set a point-change associated with this comment.'
            )
            self.TEmeta.setPlaceholderText(
                "notes to self, hints on when to use this comment, etc.\n\n"
                "Not shown to student!")
예제 #32
0
    def setupUi(self, Widget):

        # widget rysujący ksztalty, instancja klasy Ksztalt
        self.ksztalt1 = Ksztalt(self, Ksztalty.Polygon)
        self.ksztalt2 = Ksztalt(self, Ksztalty.Ellipse)
        self.ksztaltAktywny = self.ksztalt1

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

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

        # Slider i LCDNumber
        self.suwak = QSlider(Qt.Horizontal)
        self.suwak.setMinimum(0)
        self.suwak.setMaximum(255)
        self.lcd = QLCDNumber()
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        # układ poziomy (splitter) dla slajdera i lcd
        ukladH2 = QSplitter(Qt.Horizontal, self)
        ukladH2.addWidget(self.suwak)
        ukladH2.addWidget(self.lcd)
        ukladH2.setSizes((125, 75))

        # przyciski RadioButton
        self.ukladR = QHBoxLayout()
        for v in ('R', 'G', 'B'):
            self.radio = QRadioButton(v)
            self.ukladR.addWidget(self.radio)
        self.ukladR.itemAt(0).widget().setChecked(True)
        # grupujemy przyciski
        self.grupaRBtn = QGroupBox('Opcje RGB')
        self.grupaRBtn.setLayout(self.ukladR)
        self.grupaRBtn.setObjectName('Radio')
        self.grupaRBtn.setCheckable(True)
        # układ poziomy dla grupy Radio
        ukladH3 = QHBoxLayout()
        ukladH3.addWidget(self.grupaRBtn)

        # Lista ComboBox i SpinBox ###
        self.listaRGB = QComboBox(self)
        for v in ('R', 'G', 'B'):
            self.listaRGB.addItem(v)
        self.listaRGB.setEnabled(False)
        # SpinBox
        self.spinRGB = QSpinBox()
        self.spinRGB.setMinimum(0)
        self.spinRGB.setMaximum(255)
        self.spinRGB.setEnabled(False)
        # układ pionowy dla ComboBox i SpinBox
        uklad = QVBoxLayout()
        uklad.addWidget(self.listaRGB)
        uklad.addWidget(self.spinRGB)
        # do układu poziomego grupy Radio dodajemy układ ComboBox i SpinBox
        ukladH3.insertSpacing(1, 25)
        ukladH3.addLayout(uklad)
        # koniec ComboBox i SpinBox ###

        # przyciski PushButton ###
        self.ukladP = QHBoxLayout()
        self.grupaP = QButtonGroup()
        self.grupaP.setExclusive(False)
        for v in ('R', 'G', 'B'):
            self.btn = QPushButton(v)
            self.btn.setCheckable(True)
            self.grupaP.addButton(self.btn)
            self.ukladP.addWidget(self.btn)
        # grupujemy przyciski
        self.grupaPBtn = QGroupBox('Przyciski RGB')
        self.grupaPBtn.setLayout(self.ukladP)
        self.grupaPBtn.setObjectName('Push')
        self.grupaPBtn.setCheckable(True)
        self.grupaPBtn.setChecked(False)
        # koniec PushButton ###

        # etykiety QLabel i pola QLineEdit ###
        ukladH4 = QHBoxLayout()
        self.labelR = QLabel('R')
        self.labelG = QLabel('G')
        self.labelB = QLabel('B')
        self.kolorR = QLineEdit('0')
        self.kolorG = QLineEdit('0')
        self.kolorB = QLineEdit('0')
        for v in ('R', 'G', 'B'):
            label = getattr(self, 'label' + v)
            kolor = getattr(self, 'kolor' + v)
            if v == 'R':
                label.setStyleSheet("QWidget { font-weight: bold }")
                kolor.setEnabled(True)
            else:
                label.setStyleSheet("QWidget { font-weight: normal }")
                kolor.setEnabled(False)
            ukladH4.addWidget(label)
            ukladH4.addWidget(kolor)
            kolor.setMaxLength(3)
        # koniec QLabel i QLineEdit ###

        # główny układ okna, pionowy
        ukladOkna = QVBoxLayout()
        ukladOkna.addLayout(ukladH1)
        ukladOkna.addWidget(ukladH2)
        ukladOkna.addLayout(ukladH3)
        ukladOkna.addWidget(self.grupaPBtn)
        ukladOkna.addLayout(ukladH4)

        self.setLayout(ukladOkna)
        self.setWindowTitle('Widżety')
예제 #33
0
b = QToolButton(widget)
b.setIcon(QIcon.fromTheme("media-seek-backward"))
layout.addWidget(b)
buttons.append(b)

b = QToolButton(widget)
b.setIcon(QIcon.fromTheme("media-playback-start"))
layout.addWidget(b)
buttons.append(b)

b = QToolButton(widget)
b.setIcon(QIcon.fromTheme("media-playback-stop"))
layout.addWidget(b)
buttons.append(b)

sb = QSpinBox(widget)
sb.setMinimum(PINS.min.get())
sb.setValue(PINS.value.get())
layout.addWidget(sb)

b = QToolButton(widget)
b.setIcon(QIcon.fromTheme("media-seek-forward"))
layout.addWidget(b)
buttons.append(b)

b = QToolButton(widget)
b.setIcon(QIcon.fromTheme("media-skip-forward"))
layout.addWidget(b)
buttons.append(b)

label = QLabel(widget)
예제 #34
0
    def setupUi(self, widget):
        now = datetime.now()
        widget.resize(2000, 1200)
        widget.setWindowIcon(QIcon("icons/bookkeeping.ico"))
        widget.setToolTipDuration(-1)
        widget.setStyleSheet("QPushButton:hover{\n"
                             "background-color: silver;\n"
                             "}")
        # SHOW CHART BUTTON
        self.chartBtn = QPushButton(widget)
        self.chartBtn.setGeometry(1620, 20, 250, 110)
        self.chartBtn.setStyleSheet("background: lightgreen;\n"
                                    "color: white;\n"
                                    "font-size: 40px;")
        self.chartBtn.setText("Диаграмма")
        # SELECT TYPES CHARTS
        self.TypesCharts = QComboBox(widget)
        self.TypesCharts.setGeometry(1650, 150, 200, 40)
        self.TypesCharts.setStyleSheet("font-size: 30px;")
        self.TypesCharts.addItem("общая")
        self.TypesCharts.addItem("по времени")
        self.TypesCharts.addItem("по типам")
        self.TypesCharts.addItem("по продуктам")
        # TAB WIDGET EXPENSES AND INCOME
        self.MainTab = QTabWidget(widget)
        self.MainTab.setGeometry(1, 10, 1480, 1110)
        # TEBLE EXPENSES
        self.tableExpenses = QTableWidget(widget)
        self.tableExpenses.setGeometry(5, 5, 1480, 1110)
        self.tableExpenses.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.tableExpenses.setAutoScroll(True)
        self.tableExpenses.setRowCount(1000)
        self.tableExpenses.setColumnCount(5)
        self.tableExpenses.horizontalHeader().setDefaultSectionSize(270)
        self.tableExpenses.verticalHeader().setDefaultSectionSize(50)
        self.tableExpenses.setStyleSheet(u"font-size: 30px;")
        self.tableExpenses.setHorizontalHeaderLabels(
            ('Сумма', 'Продукт', 'Дата', 'Тип', 'Источник'))
        # TEBLE INCOME
        self.tableIncome = QTableWidget(widget)
        self.tableIncome.setGeometry(5, 5, 1480, 1110)
        self.tableIncome.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.tableIncome.setAutoScroll(True)
        self.tableIncome.setRowCount(1000)
        self.tableIncome.setColumnCount(5)
        self.tableIncome.horizontalHeader().setDefaultSectionSize(270)
        self.tableIncome.verticalHeader().setDefaultSectionSize(50)
        self.tableIncome.setStyleSheet(u"font-size: 30px;")
        self.tableIncome.setHorizontalHeaderLabels(
            ('Сумма', 'Продукт', 'Дата', 'Тип', 'Источник'))

        self.tableGave = QTableWidget(widget)
        self.tableGave.setGeometry(5, 5, 1480, 1110)
        self.tableGave.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.tableGave.setAutoScroll(True)
        self.tableGave.setRowCount(1000)
        self.tableGave.setColumnCount(4)
        self.tableGave.horizontalHeader().setDefaultSectionSize(338)
        self.tableGave.verticalHeader().setDefaultSectionSize(50)
        self.tableGave.setStyleSheet(u"font-size: 30px;")
        self.tableGave.setHorizontalHeaderLabels(
            ('Сумма', 'Кому', 'Когда', 'Вернули'))

        self.tableTook = QTableWidget(widget)
        self.tableTook.setGeometry(5, 5, 1480, 1110)
        self.tableTook.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.tableTook.setAutoScroll(True)
        self.tableTook.setRowCount(1000)
        self.tableTook.setColumnCount(4)
        self.tableTook.horizontalHeader().setDefaultSectionSize(338)
        self.tableTook.verticalHeader().setDefaultSectionSize(50)
        self.tableTook.setStyleSheet(u"font-size: 30px;")
        self.tableTook.setHorizontalHeaderLabels(
            ('Сумма', 'У кого', 'Когда', 'Использовал'))
        # ADD TAB TO TabWidget FOR EXPENSES AND INCOME
        self.MainTab.addTab(self.tableExpenses, "Расходы")
        self.MainTab.addTab(self.tableIncome, "Доходы")
        self.MainTab.addTab(self.tableTook, "Взял")
        self.MainTab.addTab(self.tableGave, "Дал")
        # TOTAL EXPENSES AND INCOME LABEL
        self.TotalLabel = QLabel(widget)
        self.TotalLabel.setGeometry(10, 1130, 1000, 60)
        self.TotalLabel.setStyleSheet("font-size: 39px;")
        self.TotalLabel.setText("Итоговй расход: ")
        # TOTAL LABEL
        self.TotalLabel_2 = QLabel(widget)
        self.TotalLabel_2.setGeometry(550, 1130, 1000, 60)
        self.TotalLabel_2.setStyleSheet("font-size: 39px;")
        self.TotalLabel_2.setText("Итог:  ")

        self.percentTotalLabel = QLabel(widget)
        self.percentTotalLabel.setGeometry(850, 1130, 1000, 60)
        self.percentTotalLabel.setStyleSheet("font-size: 39px;\n"
                                             "color: green;")
        # GROUP BOX (DELET EXPENSES AND INCOME)
        self.groupBoxType = QGroupBox(widget)
        self.groupBoxType.setGeometry(1500, 200, 480, 300)
        self.groupBoxType.setStyleSheet("font-size: 30px;")
        # ROW DELET
        self.RowDelet = QSpinBox(self.groupBoxType)
        self.RowDelet.setGeometry(250, 80, 200, 50)
        self.RowDelet.setMaximum(1000000)
        self.RowDelet.setMinimum(1)
        # BUTTON FOR DELETE EXPENSES OR INCOME
        self.DeletBtn = QPushButton(self.groupBoxType)
        self.DeletBtn.setGeometry(140, 210, 220, 70)
        self.DeletBtn.setStyleSheet("background: lightgreen;\n"
                                    "color: white;\n"
                                    "font-size: 40px;")
        self.DeletBtn.setText("Удалить")
        # ROW LABEL
        self.RowLabel = QLabel(self.groupBoxType)
        self.RowLabel.setGeometry(30, 80, 200, 50)
        self.RowLabel.setStyleSheet("font-size: 30px;")
        # GROUP BOX (ADD EXPENSES)
        self.groupBox = QGroupBox(widget)
        self.groupBox.setGeometry(1500, 560, 480, 600)
        self.groupBox.setStyleSheet("font-size: 30px;")
        self.groupBox.setTitle("Удалить Расход")
        # ADD BUTTON
        self.Add = QPushButton(self.groupBox)
        self.Add.setGeometry(110, 480, 230, 110)
        self.Add.setStyleSheet("background-color: lightgreen;\n"
                               "color: white;\n"
                               "font-size: 50px;")
        self.Add.setText("Добавить")
        # PRICE LABEL
        self.PriceLabel = QLabel(self.groupBox)
        self.PriceLabel.setGeometry(20, 50, 130, 31)
        self.PriceLabel.setStyleSheet("font-size: 30px;")
        # PRICE ENTERY
        self.PriceEntery = QLineEdit(self.groupBox)
        self.PriceEntery.setGeometry(200, 40, 200, 50)
        self.PriceEntery.setTabletTracking(False)
        self.PriceEntery.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.PriceEntery.setAutoFillBackground(False)
        self.PriceEntery.setFrame(True)
        self.PriceEntery.setEchoMode(QLineEdit.Normal)
        self.PriceEntery.setCursorPosition(0)
        self.PriceEntery.setDragEnabled(False)
        self.PriceEntery.setCursorMoveStyle(Qt.LogicalMoveStyle)
        self.PriceEntery.setClearButtonEnabled(False)
        # PRODUCT LABEL
        self.ProductLabel = QLabel(self.groupBox)
        self.ProductLabel.setGeometry(20, 135, 130, 31)
        self.ProductLabel.setStyleSheet("font-size: 30px;")
        # PRODUCT ENTERY
        self.ProductEntery = QLineEdit(self.groupBox)
        self.ProductEntery.setGeometry(200, 125, 200, 50)
        self.ProductEntery.setTabletTracking(False)
        self.ProductEntery.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.ProductEntery.setAutoFillBackground(False)
        self.ProductEntery.setFrame(True)
        self.ProductEntery.setEchoMode(QLineEdit.Normal)
        self.ProductEntery.setCursorPosition(0)
        self.ProductEntery.setDragEnabled(False)
        self.ProductEntery.setCursorMoveStyle(Qt.LogicalMoveStyle)
        self.ProductEntery.setClearButtonEnabled(False)
        # TYPE LABEL
        self.TypeLabel = QLabel(self.groupBox)
        self.TypeLabel.setGeometry(20, 200, 130, 40)
        self.TypeLabel.setStyleSheet("font-size: 30px;")
        # TYPE ENTERY
        self.TypeEntery = QComboBox(self.groupBox)
        self.TypeEntery.setGeometry(200, 200, 200, 40)
        self.TypeEntery.addItem("продукты")
        self.TypeEntery.addItem("транспорт")
        self.TypeEntery.addItem("развлечения")
        self.TypeEntery.addItem("техника")
        self.TypeEntery.addItem("одежда")
        self.TypeEntery.addItem("учёба")
        self.TypeEntery.addItem("книги")
        self.TypeEntery.addItem("другое")
        # DATE LABEL
        self.DateLabel = QLabel(self.groupBox)
        self.DateLabel.setGeometry(20, 270, 130, 31)
        self.DateLabel.setStyleSheet("font-size: 30px;")
        # DATE ENTERY
        self.DateEntery = QDateEdit(self.groupBox)
        self.DateEntery.setGeometry(200, 270, 200, 40)
        self.DateEntery.setDate(QDate(now.year, now.month, now.day))

        self.sourceLabel = QLabel(self.groupBox)
        self.sourceLabel.setGeometry(20, 350, 130, 31)
        self.sourceLabel.setText("Источник")

        self.sourceEntery = QComboBox(self.groupBox)
        self.sourceEntery.setGeometry(200, 350, 200, 40)
        self.sourceEntery.addItem("мои деньги")

        self.retranslateUi(widget)

        QMetaObject.connectSlotsByName(widget)
예제 #35
0
class ToolsConfig(QtWidgets.QWidget):
    def __init__(self, parent):
        super().__init__()
        self.parent = parent

        __current_screen = QtWidgets.QApplication.desktop().cursor().pos()
        __screen = QtWidgets.QDesktopWidget().screenNumber(__current_screen)
        __screen_geo = QtWidgets.QApplication.desktop().screenGeometry(
            __screen)

        self.screen = __screen
        self.height, self.width, self.left, self.top = (__screen_geo.height(),
                                                        __screen_geo.width(),
                                                        __screen_geo.left(),
                                                        __screen_geo.top())
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint
                            | QtCore.Qt.FramelessWindowHint
                            | QtCore.Qt.X11BypassWindowManagerHint)

        self.widget_width, self.widget_height = 600, 260
        self.setFixedSize(self.widget_width, self.widget_height)
        self.setGeometry((self.width // 2) - (self.widget_width // 2),
                         self.parent.pos().y() + 36, self.widget_width,
                         self.widget_height)

        self.color_picker = None
        self.init_ui()

    def init_ui(self):
        hbox = QHBoxLayout()
        vbox = QVBoxLayout()

        hbox_left = QHBoxLayout()
        hbox_right = QHBoxLayout()

        right_frame = QFrame()
        right_frame.setFrameStyle(QFrame().StyledPanel | QFrame().Sunken)
        inner_wrap = QVBoxLayout()

        vb_0 = QVBoxLayout()
        vb_1 = QHBoxLayout()
        vb_2 = QHBoxLayout()
        vb_3 = QHBoxLayout()

        pen_size = QLabel("Pen size")
        pen_hbox = QHBoxLayout()

        self.qsl_pen = QSlider(Qt.Horizontal)
        self.qsl_pen.setTickInterval(1)
        self.qsl_pen.setTickPosition(QSlider.TicksAbove)
        self.qsl_pen.setRange(0, 20)
        self.qsl_pen.valueChanged.connect(
            lambda x: self.update_pen_value(self.qsl_pen.value()))

        self.qsp = QSpinBox()
        self.qsp.setFixedWidth(46)
        self.qsp.setRange(0, 20)
        self.qsp.valueChanged.connect(
            lambda x: self.update_pen_value(self.qsp.value()))

        self.qsl_pen.setValue(self.parent.pen_size)

        pen_hbox.addWidget(self.qsl_pen)
        pen_hbox.addWidget(self.qsp)

        vb_0.addWidget(pen_size)
        vb_0.addItem(pen_hbox)

        line_cap = QLabel("Line cap")
        self.line_qcomb = QComboBox()
        self.line_qcomb.addItem("Square")
        self.line_qcomb.addItem("Round")
        self.line_qcomb.currentIndexChanged.connect(self.update_pen_cap)

        ind = 0
        if self.parent.cap == Qt.RoundCap:
            ind = 1
        self.line_qcomb.setCurrentIndex(ind)

        vb_1.addWidget(line_cap)
        vb_1.addWidget(self.line_qcomb)

        line_joint = QLabel("Line joint style")
        self.line_joint_qcomb = QComboBox()
        self.line_joint_qcomb.addItem("Round")
        self.line_joint_qcomb.addItem("Bevel")
        self.line_joint_qcomb.addItem("Acute")
        self.line_joint_qcomb.currentIndexChanged.connect(
            self.update_pen_joint)

        ind = 0
        if self.parent.joint == Qt.BevelJoin:
            ind = 1
        elif self.parent.joint == Qt.MiterJoin:
            ind = 2
        self.line_joint_qcomb.setCurrentIndex(ind)

        vb_2.addWidget(line_joint)
        vb_2.addWidget(self.line_joint_qcomb)

        pen_style = QLabel("Line style")
        self.style_qcomb = QComboBox()
        self.style_qcomb.addItem("Solid")
        self.style_qcomb.addItem("Dashed")
        self.style_qcomb.addItem("Dotted")
        self.style_qcomb.addItem("Dash-Dot")
        self.style_qcomb.currentIndexChanged.connect(self.update_pen_style)

        ind = 0
        if self.parent.pen_style == Qt.DashLine:
            ind = 1
        elif self.parent.pen_style == Qt.DotLine:
            ind = 2
        elif self.parent.pen_style == Qt.DashDotLine:
            ind = 3
        self.style_qcomb.setCurrentIndex(ind)

        vb_3.addWidget(pen_style)
        vb_3.addWidget(self.style_qcomb)

        vb_4 = QHBoxLayout()
        out_lab = QLabel("Outline")
        self.outline = QComboBox()
        self.outline.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLength)
        self.outline.addItem("Disabled")
        self.outline.addItem("Black")
        self.outline.addItem("Background")
        curr_out = self.parent.config.parse['config']['canvas']['outline']
        if curr_out == 'black':
            self.outline.setCurrentIndex(1)
        elif curr_out == 'background':
            self.outline.setCurrentIndex(2)
        self.outline.currentIndexChanged.connect(self.update_outline)
        vb_4.addWidget(out_lab)
        vb_4.addWidget(self.outline)

        inner_wrap.addItem(vb_0)
        inner_wrap.addItem(vb_1)
        inner_wrap.addItem(vb_2)
        inner_wrap.addItem(vb_3)
        inner_wrap.addItem(vb_4)
        inner_wrap.addStretch(1)

        right_frame.setLayout(inner_wrap)
        right_wrap = QVBoxLayout()
        right_wrap.addWidget(right_frame)
        hbox_right.addItem(right_wrap)

        vbox.addStretch(1)
        vbox_vert = QVBoxLayout()

        left_frame = QFrame()
        left_frame.setFrameStyle(QFrame().StyledPanel | QFrame().Sunken)
        left_inner_wrap = QVBoxLayout()

        self.color_picker = ColorPicker(self.parent.config)
        left_inner_wrap.addWidget(self.color_picker)
        left_frame.setLayout(left_inner_wrap)
        left_wrap = QVBoxLayout()
        left_wrap.addWidget(left_frame)
        hbox_left.addItem(left_wrap)

        hbox_lq = QWidget()
        hbox_lq.setLayout(hbox_left)
        hbox_lq.setFixedWidth(300)
        hbox_lq.setFixedHeight(260)

        hbox_q = QWidget()
        hbox_q.setLayout(hbox_right)
        hbox_q.setFixedWidth(300)
        hbox_q.setFixedHeight(260)

        hbox.addWidget(hbox_lq)
        hbox.addWidget(hbox_q)

        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.setSpacing(0)
        hbox.setAlignment(Qt.AlignLeft)
        vbox_vert.addItem(hbox)
        vbox_vert.setContentsMargins(0, 0, 0, 0)
        vbox_vert.setSpacing(0)
        self.setLayout(vbox_vert)

    def update_pen_style(self):
        ind = self.style_qcomb.currentIndex()
        styles = [["solid", Qt.SolidLine], ["dash", Qt.DashLine],
                  ["dot", Qt.DotLine], ["dashdot", Qt.DashDotLine]]
        for i in range(4):
            if ind == i:
                self.parent.pen_style = styles[i][1]

        self.parent.config.change_config("canvas", "last_style",
                                         styles[ind][0])

    def update_pen_value(self, value):
        if type(value) is int:
            self.qsl_pen.setValue(value)
            self.qsp.setValue(value)
            self.parent.pen_size = value

            self.parent.config.change_config("canvas", "last_size", value)

    def update_pen_cap(self):
        ind = self.line_qcomb.currentIndex()
        caps = ["square", "round"]
        if ind == 0:
            self.parent.cap = Qt.SquareCap
        else:
            self.parent.cap = Qt.RoundCap

        self.parent.config.change_config("canvas", "last_cap", caps[ind])

    def update_outline(self):
        self.parent.config.change_config('canvas', 'outline',
                                         self.outline.currentText().lower())

    def update_pen_joint(self):
        ind = self.line_joint_qcomb.currentIndex()
        joints = ["round", "bevel", "miter"]
        if ind == 0:
            self.parent.joint = Qt.RoundJoin
        elif ind == 1:
            self.parent.joint = Qt.BevelJoin
        else:
            self.parent.joint = Qt.MiterJoin

        self.parent.config.change_config("canvas", "last_joint", joints[ind])

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QtGui.QPainter(self)
        painter.setPen(QtGui.QPen(QtGui.QColor('#8EB3E4'), 3))
        painter.drawRect(0, 0, self.widget_width - 1, self.widget_height - 1)
        painter.end()
예제 #36
0
    def initUI(self):
        # Image Label Source
        self.imageLabelSrc = QLabel()
        self.imageLabelSrc.setAlignment(QtCore.Qt.AlignCenter)
        # Image Label Result
        self.imageLabelRes = QLabel()
        self.imageLabelRes.setAlignment(QtCore.Qt.AlignCenter)

        # Area Threshold Slider
        self.areaThresholdSlider = QSlider(QtCore.Qt.Horizontal)
        self.areaThresholdSlider.setRange(0, 1)
        self.areaThresholdSlider.valueChanged.connect(
            self.areaThresholdSliderChanged)
        # Area Threshold Spinbox
        self.areaThresholdSpinbox = QSpinBox()
        self.areaThresholdSpinbox.setRange(0, 1)
        self.areaThresholdSpinbox.valueChanged.connect(
            self.areaThresholdSpinboxChanged)

        # Layout
        self.imageLabelLayout = QHBoxLayout()
        self.thresholdLayout = QHBoxLayout()

        self.imageLabelLayout.addWidget(self.imageLabelSrc)
        self.imageLabelLayout.addWidget(self.imageLabelRes)
        self.imageLabelLayoutWidget = QWidget()
        self.imageLabelLayoutWidget.setLayout(self.imageLabelLayout)

        self.thresholdLayout.addWidget(self.areaThresholdSlider)
        self.thresholdLayout.addWidget(self.areaThresholdSpinbox)
        self.thresholdLayoutWidget = QWidget()
        self.thresholdLayoutWidget.setLayout(self.thresholdLayout)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.imageLabelLayoutWidget)
        self.mainLayout.addWidget(self.thresholdLayoutWidget)

        # Main Widget
        self.window = QWidget()
        self.window.setLayout(self.mainLayout)

        # Set Central Widget
        self.setCentralWidget(self.window)

        # Actions
        # Open File
        openFile = QAction('Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.triggered.connect(self.openImageDialog)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)

        # Center Window
        xbase = (app.desktop().screenGeometry().width() - self.xsize) / 2
        ybase = (app.desktop().screenGeometry().height() - self.ysize) / 2

        # Window Property
        self.setGeometry(xbase, ybase, self.xsize, self.ysize)
        self.setWindowTitle('MaMPy Max-Tree demo')
        self.show()
예제 #37
0
class MirandasWindow(QWidget):
    def __init__(self, *args, **kwargs):

        super().__init__()

        self.p = profile.Profile()
        self.p.enable()

        self.estilo = int(sys.argv[1])

        #Aqui basicamente se instancia e inicia todas as partes da interface
        self.iniciaComponentes()

        self.jogo = Jogo()

        self.playerAtual = self.jogo.turno

        self.alteraContexto()
        self.alteraContexto()

        self.ia1 = IA(self.jogo)
        self.ia2 = IA(self.jogo)

        #print(self.jogo.packletters[self.playerAtual])
        #self.labelLetras.setText(letrasIniciais)

    #Função que iniciará todos os componentes da tela
    def iniciaComponentes(self):

        self.setWindowTitle('Screble')

        #Configuração do botão que adiciona as palavras
        self.botaoAddWord = QPushButton('Add Word')
        self.botaoAddWord.setToolTip('Botão para adicionar uma palavra')
        self.botaoAddWord.clicked.connect(self.clickbotao_addWord)

        #Configuração dos labels do player 1
        self.label1 = QLabel('Player1:')
        self.label1Pts = QLabel('0')

        #Configuração dos labels do player 2
        self.label2 = QLabel('Player2:')
        self.label2Pts = QLabel('0')

        #Configuração do identificador textual da coluna para adicionamento da palavra
        self.editRow = QSpinBox()
        self.editRow.setMinimum(1)
        self.editRow.setMaximum(15)
        self.labelRow = QLabel('Linha:')

        #Configuração do identificador textual da coluna para adicionamento da palavra
        self.editCol = QSpinBox()
        self.editCol.setMinimum(1)
        self.editCol.setMaximum(15)
        self.labelCol = QLabel('Coluna:')

        #Configuração dos edits que conterão a palavra a ser adicionada e a direção da mesma
        self.comboDir = QComboBox()
        self.comboDir.addItem("V")
        self.comboDir.addItem("H")
        self.labelDir = QLabel('Direção:')
        self.editWord = QLineEdit('Palavra')
        self.labelWord = QLabel('Palavra:')

        #Configuração da matriz que contem as letras e bonus das palavras colocadas
        self.tabela_matriz = QTableWidget()
        self.tabela_matriz.setColumnCount(15)
        self.tabela_matriz.setRowCount(15)
        self.tabela_matriz.setShowGrid(True)
        self.tabela_matriz.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.setaLetrasIniciais()
        self.tabela_matriz.resizeColumnsToContents()
        self.tabela_matriz.resizeRowsToContents()

        #Configuração do label das letras disponíveis
        self.labelDisponiveis = QLabel('Letras disponíveis:')
        self.labelLetras = QLabel('')

        #Configuração do edit que conterá as letras a serem trocadas
        self.editTroca = QLineEdit('')

        #Configuração do botão que troca as letras
        self.botaoTrocaLetras = QPushButton('Troca letras')
        self.botaoTrocaLetras.setToolTip('Botão para trocar suas letras')
        self.botaoTrocaLetras.clicked.connect(self.clickbotao_trocaLetra)

        #Configuração do botão de passar a vez
        self.botaoPassaVez = QPushButton('Passar vez')
        self.botaoPassaVez.setToolTip('Botão para passar sua rodada')
        #self.botaoPassaVez.clicked.connect(self.clickbotao_passaVez)

        #Configuração dos layouts
        main_layout = QVBoxLayout()

        # Header
        layout = QHBoxLayout()
        layout.addWidget(self.label1)
        layout.addWidget(self.label1Pts)
        layout.addStretch()
        layout.addWidget(self.label2)
        layout.addWidget(self.label2Pts)

        main_layout.addLayout(layout)

        # Main Vision
        layout = QHBoxLayout()
        layout.addWidget(self.tabela_matriz)
        l = QVBoxLayout()
        l.addWidget(self.labelDisponiveis)
        l.addWidget(self.labelLetras)

        l1 = QHBoxLayout()
        l1.addWidget(self.editTroca)
        l1.addWidget(self.botaoTrocaLetras)
        l1.addWidget(self.botaoPassaVez)
        l.addLayout(l1)
        layout.addLayout(l)

        main_layout.addLayout(layout)

        # Footer
        layout = QVBoxLayout()
        l = QHBoxLayout()
        l.addWidget(self.labelRow)
        l.addWidget(self.editRow)
        l.addWidget(self.labelCol)
        l.addWidget(self.editCol)
        l.addWidget(self.labelDir)
        l.addWidget(self.comboDir)
        l.addWidget(self.labelWord)
        l.addWidget(self.editWord)
        layout.addLayout(l)
        layout.addWidget(self.botaoAddWord)

        main_layout.addLayout(layout)

        #Input do layout completo
        self.setLayout(main_layout)
        self.setGeometry(50, 50, 1220, 450)

    #Ação do botão que adicionará uma palavra na matriz
    @pyqtSlot()
    def clickbotao_addWord(self):

        if (self.jogo.finalJogo):
            self.p.disable()
            pstats.Stats(self.p).sort_stats('cumulative').print_stats(30)

            string = "VITORIA "

            print(str(self.jogo.points1))
            print(str(self.jogo.points2))

            if self.jogo.points1 > self.jogo.points2:
                if self.estilo == 2:
                    string += "DA CPU UM !"
                else:
                    string += "DO JOGADOR UM !"
            elif self.jogo.points1 < self.jogo.points2:
                if self.estilo == 0:
                    string += "DO JOGADOR UM !"
                else:
                    string += "DA CPU DOIS !"
            else:
                string = "EMPATE DOS JOGADORES !!"

            QMessageBox.about(self, "FIM DE JOGO", string)
            return

        row, col, word, direcao = 0, 0, '', ''
        #Caso do jogador

        #Caso de ser PVP
        if (self.estilo == 0):
            row = self.editRow.value()
            col = self.editCol.value()
            word = self.editWord.text().lower()
            direcao = self.comboDir.currentText()

        #Caso de ser PvsIA
        elif (self.estilo == 1):
            #Jogada do player
            if self.playerAtual == 0:
                #Pega todos os dados digitados
                row = self.editRow.value()
                col = self.editCol.value()
                word = self.editWord.text().lower()
                direcao = self.comboDir.currentText()
            #Jogada da IA
            else:
                row, col, word, direcao = self.ia1.permutation(
                    self.jogo.packletters[1])
                print('saindo ' + str(row) + ' ' + str(col) + ' ' + word +
                      ' ' + direcao)
                #Chamar troca de letra

        #Caso de ser IAvsIA
        else:
            #Jogada da IA1
            if self.playerAtual == 0:
                row, col, word, direcao = self.ia1.permutation(
                    self.jogo.packletters[0])
                print('saindo ' + str(row) + ' ' + str(col) + ' ' + word +
                      ' ' + direcao)
                #Chamar troca de letra
            #Jogada da IA2
            else:
                row, col, word, direcao = self.ia2.permutation(
                    self.jogo.packletters[1])
                print('saindo ' + str(row) + ' ' + str(col) + ' ' + word +
                      ' ' + direcao)
                #Chamar troca de letra

        #Caso a IA queira passar a vez ele mandará uma string vazia que também serve para o jogador
        self.jogo.checkFinalJogo(word)
        if word == '':
            if (self.estilo == 2):
                self.clickbotao_trocaLetra(
                    self.jogo.packletters[self.jogo.playerAtual])

            elif (self.estilo == 1 and self.playerAtual == 1):
                self.clickbotao_trocaLetra(self.jogo.packletters[1])

            else:
                self.passaVez()

            return 1

        #Faz a checagem de erros
        if self.estilo != 2 or (self.estilo == 1 and self.playerAtual == 0):
            res = self.jogo.checkWord(row, col, word, direcao)

            if (res != 1):
                self.printError(res)
                self.passaVez()
                return -1

        #Chama a função para calcular os pontos e a palavra final que pode ser modificada caso use-se um coringa
        pontos, palavra = self.jogo.inputWord(row, col, word, direcao)
        #Chama a função para colocar a palavra na matriz
        self.inputWord(row, col, palavra, direcao)

        self.jogo.inicio = False
        #Chama a função de adicionar a pontuação
        self.addPonts(pontos)
        #Chamará a troca de contexto na interface e no backend
        self.passaVez()

    #Ação doo botão que trocara as letras do determinado player
    @pyqtSlot()
    def clickbotao_trocaLetra(self, letrasAntigas=[]):

        if ((self.estilo == 0)
                or (self.playerAtual == 0 and self.estilo == 1)):
            #Pega as letras do edit, da um split para que se transforme em uma lista
            letrasAntigas = self.editTroca.text().split(',')

        #Chama a função de trocar letras
        listaNovasLetras = self.jogo.exchangeLetters(letrasAntigas)

        #Casos de erros
        if (type(listaNovasLetras) == int):
            self.printError(listaNovasLetras)
            return -1

        novasLetras = self.listToStr(listaNovasLetras)

        self.labelLetras.setText(novasLetras)
        self.passaVez()

    #Ação do botão que adicionará uma palavra na matriz
    @pyqtSlot()
    def clickbotao_passaVez(self):

        #Chamará a troca de contexto na interface e no backend
        self.passaVez()

    #Chamará a troca de contexto na interface e também no backend do jogo
    def passaVez(self):
        self.alteraContexto()
        self.jogo.passaVez()

    #Função que fará a transição de jogadas entre o jogador 1 e 2
    def alteraContexto(self):

        if (self.playerAtual == 0):
            self.label1.setStyleSheet(
                "QLabel { background-color : lightgray; color : black; }")
            self.label2.setStyleSheet(
                "QLabel { background-color : lightgreen; color : black; }")
            self.playerAtual = 1
        else:
            self.label2.setStyleSheet(
                "QLabel { background-color : lightgray; color : black; }")
            self.label1.setStyleSheet(
                "QLabel { background-color : lightgreen; color : black; }")
            self.playerAtual = 0
        self.labelLetras.setText(
            self.listToStr(self.jogo.packletters[self.playerAtual]))

    #Função que adiciona uma palavra na matriz
    def inputWord(self, row, col, word, direcao):

        for i in range(0, len(word)):
            if (direcao == 'V'):
                self.tabela_matriz.setItem(row + i - 1, col - 1,
                                           QTableWidgetItem(word[i]))
            else:
                self.tabela_matriz.setItem(row - 1, col + i - 1,
                                           QTableWidgetItem(word[i]))

    #Função que adiciona pontos na pontuação de determinado jogador
    def addPonts(self, pontos):
        if (self.playerAtual == 0):
            self.jogo.points1 += pontos
            self.label1Pts.setNum(self.jogo.points1)
        else:
            self.jogo.points2 += pontos
            self.label2Pts.setNum(self.jogo.points2)

    #Função que seta as letras iniciais para que o tabuleiro fique igual ao do scrabble
    def setaLetrasIniciais(self):

        self.tabela_matriz.setItem(7, 7, QTableWidgetItem('*'))

        for i in range(0, 15, 7):
            for j in range(0, 15, 7):
                if (not (i == 7 == j)):
                    self.tabela_matriz.setItem(i, j, QTableWidgetItem('TP'))

        for i in range(1, 5):
            self.tabela_matriz.setItem(i, i, QTableWidgetItem('DP'))
            self.tabela_matriz.setItem(14 - i, 14 - i, QTableWidgetItem('DP'))
            self.tabela_matriz.setItem(i, 14 - i, QTableWidgetItem('DP'))
            self.tabela_matriz.setItem(14 - i, i, QTableWidgetItem('DP'))

        for i in range(0, 15, 14):
            self.tabela_matriz.setItem(3, i, QTableWidgetItem('DL'))
            self.tabela_matriz.setItem(i, 3, QTableWidgetItem('DL'))
            self.tabela_matriz.setItem(11, i, QTableWidgetItem('DL'))
            self.tabela_matriz.setItem(i, 11, QTableWidgetItem('DL'))

        for i in range(1, 15, 12):
            self.tabela_matriz.setItem(5, i, QTableWidgetItem('TL'))
            self.tabela_matriz.setItem(i, 5, QTableWidgetItem('TL'))
            self.tabela_matriz.setItem(9, i, QTableWidgetItem('TL'))
            self.tabela_matriz.setItem(i, 9, QTableWidgetItem('TL'))

        for i in range(2, 15, 10):
            self.tabela_matriz.setItem(6, i, QTableWidgetItem('DL'))
            self.tabela_matriz.setItem(i, 6, QTableWidgetItem('DL'))
            self.tabela_matriz.setItem(8, i, QTableWidgetItem('DL'))
            self.tabela_matriz.setItem(i, 8, QTableWidgetItem('DL'))

        for i in range(3, 15, 8):
            self.tabela_matriz.setItem(7, i, QTableWidgetItem('DL'))
            self.tabela_matriz.setItem(i, 7, QTableWidgetItem('DL'))

        for i in range(5, 11, 4):
            self.tabela_matriz.setItem(5, i, QTableWidgetItem('TL'))
            self.tabela_matriz.setItem(9, i, QTableWidgetItem('TL'))

        for i in range(6, 10, 2):
            self.tabela_matriz.setItem(6, i, QTableWidgetItem('DL'))
            self.tabela_matriz.setItem(8, i, QTableWidgetItem('DL'))

    #Função que printa o erro correspondente
    def printError(self, erro):

        string = ''
        if (erro == enumError.er_exchBigger7):
            string = 'ERRO: Impossível trocar mais que 7 letras.'
        elif (erro == enumError.er_exchBiggerPack):
            string = 'ERRO: Impossível trocar esta quantidade pois não há esta mesma quantidade de letras disponíveis.'
        elif (erro == enumError.er_exchLetterNotFound):
            string = 'ERRO: Impossível trocar pois há letras a serem trocadas que você não possui.'
        elif (erro == enumError.er_inWordLine):
            string = 'ERRO: A palavra a ser adicionada ultrapassa o mapa horizontalmente.'
        elif (erro == enumError.er_inWordCol):
            string = 'ERRO: A palavra a ser adicionada ultrapassa o mapa verticalmente.'
        elif (erro == enumError.er_inWordInexist):
            string = 'ERRO: A palavra a ser adicionada não existe no dicionário.'
        elif (erro == enumError.er_inWordInitFail):
            string = 'ERRO: A palavra a ser adicionada não atravessou o centro do mapa.'
        elif (erro == enumError.er_inWordNotTableUsed):
            string = 'ERRO: A palavra a ser adicionada não utilizou nenhuma outra letra do mapa.'
        elif (erro == enumError.er_inWordNotPossibleIn):
            string = 'ERRO: A palavra a ser adicionada não pode ser montada no mapa com suas letras.'
        elif (erro == enumError.er_inWordConflict):
            string = 'ERRO: A palavra a ser adicionada conflitou com outras palavras já presentes no mapa'

        QMessageBox.about(self, "ERROR", string)

    #Função facilitadora pois é muito utilizada no módulo
    def listToStr(self, lista):

        string = ''
        for el in lista:
            string += el + ','

        return string[0:-1]
예제 #38
0
    def __init__(self,
                 parent: 'ElectrumWindow',
                 config: 'SimpleConfig',
                 go_tab=None):
        WindowModalDialog.__init__(self, parent, _('Preferences'))
        self.config = config
        self.window = parent
        self.need_restart = False
        self.fx = self.window.fx
        self.wallet = self.window.wallet

        vbox = QVBoxLayout()
        tabs = QTabWidget()
        tabs.setObjectName("settings_tab")
        gui_widgets = []
        tx_widgets = []
        oa_widgets = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        show_dip2_cb = QCheckBox(_('Show transaction type in wallet history'))
        def_dip2 = not self.window.wallet.psman.unsupported
        show_dip2_cb.setChecked(self.config.get('show_dip2_tx_type', def_dip2))

        def on_dip2_state_changed(x):
            show_dip2 = (x == Qt.Checked)
            self.config.set_key('show_dip2_tx_type', show_dip2, True)
            self.window.history_model.refresh('on_dip2')

        show_dip2_cb.stateChanged.connect(on_dip2_state_changed)
        gui_widgets.append((show_dip2_cb, None))

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

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

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

        watchonly_w_cb = QCheckBox(_('Show warning for watching only wallets'))
        watchonly_w_cb.setChecked(self.config.get('watch_only_warn', True))

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

        watchonly_w_cb.stateChanged.connect(on_set_watch_only_warn)
        gui_widgets.append((watchonly_w_cb, None))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        vbox.addWidget(tabs)
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CloseButton(self)))
        self.setLayout(vbox)

        if go_tab is not None:
            go_tab_w = tabs.findChild(QWidget, go_tab)
            if go_tab_w:
                tabs.setCurrentWidget(go_tab_w)
예제 #39
0
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        # Create titles
        self.title_tagline = QLabel('Welcome to')
        self.title_tagline.setSizePolicy(QSizePolicy.Preferred,
                                         QSizePolicy.Expanding)
        self.title_tagline.setStyleSheet('font: 12px;'
                                         ' color:#000000;'
                                         )

        self.title_text = QLabel('tumbly.')
        self.title_text.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Expanding)
        self.title_text.setStyleSheet('font: 24px;'
                                      ' color:#000000;'
                                      )

        # Create Labels
        self.number_label = QLabel('Number of images to scrape:')
        self.offset_label = QLabel('Post offest (start point):')

        # Create output box
        self.status_out = QTextEdit()
        self.status_out.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Expanding)

        # Create input boxes
        self.username_box = QLineEdit(self)
        self.username_box.setText('Enter username to scrape')
        self.username_box.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Expanding)
        self.username_box.textChanged[str].connect(self.text_changed)

        # Create number boxes
        self.number_of_images = QSpinBox()
        self.number_of_images.setMinimum(1)
        self.number_of_images.setSizePolicy(QSizePolicy.Preferred,
                                            QSizePolicy.Expanding)
        self.number_of_images.valueChanged[int].connect(self.number_changed)

        self.post_offset = QSpinBox()
        self.post_offset.setMinimum(20)
        self.post_offset.setSizePolicy(QSizePolicy.Preferred,
                                       QSizePolicy.Expanding)
        self.post_offset.valueChanged[int].connect(self.offset_changed)

        # Create get images button
        self.get_button = QPushButton('Get images')
        self.get_button.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Expanding)
        self.get_button.setStyleSheet('font: 12px;'
                                      ' color:#000000;'
                                      ' border: 1px solid #000000')

        # Create get images button
        self.get_settings = QPushButton('Set Auth')
        self.get_settings.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Expanding)
        self.get_settings.setStyleSheet('font: 12px;'
                                        ' color:#000000;'
                                        ' border: 1px solid #000000')

        # Create layout, add widgets
        self.grid = QGridLayout()
        self.grid.addWidget(self.title_tagline, 1, 0, 1, 2)
        self.grid.addWidget(self.title_text, 2, 0, 2, 2)
        self.grid.addWidget(self.username_box, 5, 0, 3, 1)
        self.grid.addWidget(self.get_button, 8, 0, 4, 2)
        self.grid.addWidget(self.number_label, 12, 0)
        self.grid.addWidget(self.offset_label, 12, 1)
        self.grid.addWidget(self.number_of_images, 13, 0, 2, 1)
        self.grid.addWidget(self.post_offset, 13, 1, 2, 1)
        self.grid.addWidget(self.status_out, 15, 0, 2, 2)
        self.grid.addWidget(self.get_settings, 17, 0, 4, 2)

        # Set layout
        self.setLayout(self.grid)

        # Get values
        self.number = self.number_of_images.value()
        self.offset = self.post_offset.value()

        # Connect get images button to get_images function
        self.get_button.clicked.connect(self.start_thread)
        # Connect get settings button to add_auth function
        self.get_settings.clicked.connect(self.add_auth)

        # Set window
        self.setFixedSize(500, 250)
        self.setWindowTitle('tumbly')
        self.setWindowIcon(QIcon(''))
        self.setStyleSheet('background: #FFFFFF')
예제 #40
0
class Tumbly(QWidget):

    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        # Create titles
        self.title_tagline = QLabel('Welcome to')
        self.title_tagline.setSizePolicy(QSizePolicy.Preferred,
                                         QSizePolicy.Expanding)
        self.title_tagline.setStyleSheet('font: 12px;'
                                         ' color:#000000;'
                                         )

        self.title_text = QLabel('tumbly.')
        self.title_text.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Expanding)
        self.title_text.setStyleSheet('font: 24px;'
                                      ' color:#000000;'
                                      )

        # Create Labels
        self.number_label = QLabel('Number of images to scrape:')
        self.offset_label = QLabel('Post offest (start point):')

        # Create output box
        self.status_out = QTextEdit()
        self.status_out.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Expanding)

        # Create input boxes
        self.username_box = QLineEdit(self)
        self.username_box.setText('Enter username to scrape')
        self.username_box.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Expanding)
        self.username_box.textChanged[str].connect(self.text_changed)

        # Create number boxes
        self.number_of_images = QSpinBox()
        self.number_of_images.setMinimum(1)
        self.number_of_images.setSizePolicy(QSizePolicy.Preferred,
                                            QSizePolicy.Expanding)
        self.number_of_images.valueChanged[int].connect(self.number_changed)

        self.post_offset = QSpinBox()
        self.post_offset.setMinimum(20)
        self.post_offset.setSizePolicy(QSizePolicy.Preferred,
                                       QSizePolicy.Expanding)
        self.post_offset.valueChanged[int].connect(self.offset_changed)

        # Create get images button
        self.get_button = QPushButton('Get images')
        self.get_button.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Expanding)
        self.get_button.setStyleSheet('font: 12px;'
                                      ' color:#000000;'
                                      ' border: 1px solid #000000')

        # Create get images button
        self.get_settings = QPushButton('Set Auth')
        self.get_settings.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Expanding)
        self.get_settings.setStyleSheet('font: 12px;'
                                        ' color:#000000;'
                                        ' border: 1px solid #000000')

        # Create layout, add widgets
        self.grid = QGridLayout()
        self.grid.addWidget(self.title_tagline, 1, 0, 1, 2)
        self.grid.addWidget(self.title_text, 2, 0, 2, 2)
        self.grid.addWidget(self.username_box, 5, 0, 3, 1)
        self.grid.addWidget(self.get_button, 8, 0, 4, 2)
        self.grid.addWidget(self.number_label, 12, 0)
        self.grid.addWidget(self.offset_label, 12, 1)
        self.grid.addWidget(self.number_of_images, 13, 0, 2, 1)
        self.grid.addWidget(self.post_offset, 13, 1, 2, 1)
        self.grid.addWidget(self.status_out, 15, 0, 2, 2)
        self.grid.addWidget(self.get_settings, 17, 0, 4, 2)

        # Set layout
        self.setLayout(self.grid)

        # Get values
        self.number = self.number_of_images.value()
        self.offset = self.post_offset.value()

        # Connect get images button to get_images function
        self.get_button.clicked.connect(self.start_thread)
        # Connect get settings button to add_auth function
        self.get_settings.clicked.connect(self.add_auth)

        # Set window
        self.setFixedSize(500, 250)
        self.setWindowTitle('tumbly')
        self.setWindowIcon(QIcon(''))
        self.setStyleSheet('background: #FFFFFF')

    def text_changed(self, text):
        # Get text changes
        self.username = str(text)
        global user_username
        user_username = self.username

    def number_changed(self, number):
        self.number = int(number)
        global user_number
        user_number = self.number

    def offset_changed(self, number):
        self.offset = int(number)
        global user_offset
        user_offset = self.offset

    def add_auth(self):

        key, ok = QInputDialog.getText(self, 'No config file',
                                             'Enter your app key:')

        if ok:
            app_key = key

        else:
            app_key = ''

        secret, ok = QInputDialog.getText(self, 'No config file',
                                                'Enter your app secret:')
        if ok:
            app_secret = secret

        else:
            app_secret = ''

        if app_key == '' or app_secret == '':
            input_check = QMessageBox.question(self,
                                               'Error',
                                               'You must enter an app key'
                                               ' and an app secret to use'
                                               ' tumbly.',
                                               QMessageBox.Retry | QMessageBox.Cancel)

            if input_check == QMessageBox.Retry:
                self.add_auth()

        put_config('config/tumblyconfig.ini',
                   app_key, app_secret)

    @pyqtSlot(str)
    def append_text(self, text):
        self.status_out.moveCursor(QTextCursor.End)
        self.status_out.insertPlainText(text)

    @pyqtSlot()
    def start_thread(self):
        # Check config file exists, make one if not
        if not os.path.isfile('config/tumblyconfig.ini'):
            self.add_auth()
        else:
            self.thread = QThread()
            self.main_thread = RunMain()
            self.main_thread.moveToThread(self.thread)
            self.thread.started.connect(self.main_thread.run)
            self.thread.start()
예제 #41
0
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QGridLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        j = QSpinBox()
        j.setMinimum(0)
        j.setMaximum(31)
        j.setToolTip("Jour")
        m = QSpinBox()
        m.setMinimum(0)
        m.setMaximum(12)
        m.setToolTip("Mois")
        a = QSpinBox()
        a.setMinimum(0)
        a.setMaximum(2500)
        a.setToolTip("Année")
        j.setAlignment(Qt.AlignCenter)
        m.setAlignment(Qt.AlignCenter)
        a.setAlignment(Qt.AlignCenter)
        j.setSpecialValueText("-")
        m.setSpecialValueText("-")
        a.setSpecialValueText("-")
        layout.addWidget(j, 0, 0)
        layout.addWidget(m, 0, 1)
        layout.addWidget(a, 0, 2, 1, 2)

        j.valueChanged.connect(
            lambda v: self.data_changed.emit(self.get_data()))
        m.valueChanged.connect(
            lambda v: self.data_changed.emit(self.get_data()))
        a.valueChanged.connect(
            lambda v: self.data_changed.emit(self.get_data()))
        a.editingFinished.connect(self.on_editing)
        self.ws = (a, m, j)
예제 #42
0
파일: vocal.py 프로젝트: stweil/frescobaldi
class VocalPart(_base.Part):
    """Base class for vocal parts."""
    midiInstrument = 'choir aahs'

    def createWidgets(self, layout):
        self.createStanzaWidget(layout)
        self.createAmbitusWidget(layout)
        
    def translateWidgets(self):
        self.translateStanzaWidget()
        self.translateAmbitusWidget()
        
    def createStanzaWidget(self, layout):
        self.stanzas = QSpinBox(minimum=1, maximum=99, value=1)
        self.stanzasLabel = QLabel()
        self.stanzasLabel.setBuddy(self.stanzas)
        box = QHBoxLayout(spacing=0)
        box.addWidget(self.stanzasLabel)
        box.addWidget(self.stanzas)
        layout.addLayout(box)
        
    def translateStanzaWidget(self):
        self.stanzasLabel.setText(_("Stanzas:"))
        self.stanzas.setToolTip(_("The number of stanzas."))
    
    def createAmbitusWidget(self, layout):
        self.ambitus = QCheckBox()
        layout.addWidget(self.ambitus)
        
    def translateAmbitusWidget(self):
        self.ambitus.setText(_("Ambitus"))
        self.ambitus.setToolTip(_(
            "Show the pitch range of the voice at the beginning of the staff."))
    
    def assignLyrics(self, data, name, verse=0):
        """Creates an empty assignment for lyrics.
        
        Returns the assignment.
        
        """
        l = ly.dom.LyricMode()
        if verse:
            name = name + ly.util.int2text(verse)
            ly.dom.Line('\\set stanza = "{0}."'.format(verse), l)
        a = data.assign(name)
        a.append(l)
        ly.dom.LineComment(_("Lyrics follow here."), l)
        ly.dom.BlankLine(l)
        return a
    
    def addStanzas(self, data, node):
        """Add stanzas to the given (Voice) node.
        
        The stanzas (as configured in self.stanzas.value()) are added
        using \\addlyrics.
        
        """
        if self.stanzas.value() == 1:
            ly.dom.Identifier(self.assignLyrics(data, 'verse').name, ly.dom.AddLyrics(node))
        else:
            for i in range(self.stanzas.value()):
                ly.dom.Identifier(self.assignLyrics(data, 'verse', i + 1).name, ly.dom.AddLyrics(node))
    def flags(self, index):
        return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled


app = QApplication(sys.argv)

window = QWidget()

data = MyData()

table_view = QTableView()
my_model = MyModel(data)
table_view.setModel(my_model)

spin_box = QSpinBox()
spin_box.setMinimum(-10000)
spin_box.setMaximum(10000)
line_edit = QLineEdit()

vbox = QVBoxLayout()

vbox.addWidget(table_view)
vbox.addWidget(spin_box)
vbox.addWidget(line_edit)

window.setLayout(vbox)

###

mapper = QDataWidgetMapper()  # <--
예제 #44
0
    def iniciaComponentes(self):

        self.setWindowTitle('Screble')

        #Configuração do botão que adiciona as palavras
        self.botaoAddWord = QPushButton('Add Word')
        self.botaoAddWord.setToolTip('Botão para adicionar uma palavra')
        self.botaoAddWord.clicked.connect(self.clickbotao_addWord)

        #Configuração dos labels do player 1
        self.label1 = QLabel('Player1:')
        self.label1Pts = QLabel('0')

        #Configuração dos labels do player 2
        self.label2 = QLabel('Player2:')
        self.label2Pts = QLabel('0')

        #Configuração do identificador textual da coluna para adicionamento da palavra
        self.editRow = QSpinBox()
        self.editRow.setMinimum(1)
        self.editRow.setMaximum(15)
        self.labelRow = QLabel('Linha:')

        #Configuração do identificador textual da coluna para adicionamento da palavra
        self.editCol = QSpinBox()
        self.editCol.setMinimum(1)
        self.editCol.setMaximum(15)
        self.labelCol = QLabel('Coluna:')

        #Configuração dos edits que conterão a palavra a ser adicionada e a direção da mesma
        self.comboDir = QComboBox()
        self.comboDir.addItem("V")
        self.comboDir.addItem("H")
        self.labelDir = QLabel('Direção:')
        self.editWord = QLineEdit('Palavra')
        self.labelWord = QLabel('Palavra:')

        #Configuração da matriz que contem as letras e bonus das palavras colocadas
        self.tabela_matriz = QTableWidget()
        self.tabela_matriz.setColumnCount(15)
        self.tabela_matriz.setRowCount(15)
        self.tabela_matriz.setShowGrid(True)
        self.tabela_matriz.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.setaLetrasIniciais()
        self.tabela_matriz.resizeColumnsToContents()
        self.tabela_matriz.resizeRowsToContents()

        #Configuração do label das letras disponíveis
        self.labelDisponiveis = QLabel('Letras disponíveis:')
        self.labelLetras = QLabel('')

        #Configuração do edit que conterá as letras a serem trocadas
        self.editTroca = QLineEdit('')

        #Configuração do botão que troca as letras
        self.botaoTrocaLetras = QPushButton('Troca letras')
        self.botaoTrocaLetras.setToolTip('Botão para trocar suas letras')
        self.botaoTrocaLetras.clicked.connect(self.clickbotao_trocaLetra)

        #Configuração do botão de passar a vez
        self.botaoPassaVez = QPushButton('Passar vez')
        self.botaoPassaVez.setToolTip('Botão para passar sua rodada')
        #self.botaoPassaVez.clicked.connect(self.clickbotao_passaVez)

        #Configuração dos layouts
        main_layout = QVBoxLayout()

        # Header
        layout = QHBoxLayout()
        layout.addWidget(self.label1)
        layout.addWidget(self.label1Pts)
        layout.addStretch()
        layout.addWidget(self.label2)
        layout.addWidget(self.label2Pts)

        main_layout.addLayout(layout)

        # Main Vision
        layout = QHBoxLayout()
        layout.addWidget(self.tabela_matriz)
        l = QVBoxLayout()
        l.addWidget(self.labelDisponiveis)
        l.addWidget(self.labelLetras)

        l1 = QHBoxLayout()
        l1.addWidget(self.editTroca)
        l1.addWidget(self.botaoTrocaLetras)
        l1.addWidget(self.botaoPassaVez)
        l.addLayout(l1)
        layout.addLayout(l)

        main_layout.addLayout(layout)

        # Footer
        layout = QVBoxLayout()
        l = QHBoxLayout()
        l.addWidget(self.labelRow)
        l.addWidget(self.editRow)
        l.addWidget(self.labelCol)
        l.addWidget(self.editCol)
        l.addWidget(self.labelDir)
        l.addWidget(self.comboDir)
        l.addWidget(self.labelWord)
        l.addWidget(self.editWord)
        layout.addLayout(l)
        layout.addWidget(self.botaoAddWord)

        main_layout.addLayout(layout)

        #Input do layout completo
        self.setLayout(main_layout)
        self.setGeometry(50, 50, 1220, 450)
예제 #45
0
    def __init__(self, theParent, theProject):
        QWidget.__init__(self, theParent)

        self.mainConf = nw.CONFIG
        self.theParent = theParent
        self.theProject = theProject
        self.theTheme = theParent.theTheme
        self.theIndex = theParent.theIndex
        self.optState = theProject.optState

        # Internal
        self._theToC = []

        iPx = self.theTheme.baseIconSize
        hPx = self.mainConf.pxInt(12)
        vPx = self.mainConf.pxInt(4)

        # Contents Tree
        # =============

        self.tocTree = QTreeWidget()
        self.tocTree.setIconSize(QSize(iPx, iPx))
        self.tocTree.setIndentation(0)
        self.tocTree.setColumnCount(6)
        self.tocTree.setSelectionMode(QAbstractItemView.NoSelection)
        self.tocTree.setHeaderLabels(
            ["Title", "Words", "Pages", "Page", "Progress", ""])

        treeHeadItem = self.tocTree.headerItem()
        treeHeadItem.setTextAlignment(self.C_WORDS, Qt.AlignRight)
        treeHeadItem.setTextAlignment(self.C_PAGES, Qt.AlignRight)
        treeHeadItem.setTextAlignment(self.C_PAGE, Qt.AlignRight)
        treeHeadItem.setTextAlignment(self.C_PROG, Qt.AlignRight)

        treeHeader = self.tocTree.header()
        treeHeader.setStretchLastSection(True)
        treeHeader.setMinimumSectionSize(hPx)

        wCol0 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol0", 200))
        wCol1 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol1", 60))
        wCol2 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol2", 60))
        wCol3 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol3", 60))
        wCol4 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol4", 90))

        self.tocTree.setColumnWidth(0, wCol0)
        self.tocTree.setColumnWidth(1, wCol1)
        self.tocTree.setColumnWidth(2, wCol2)
        self.tocTree.setColumnWidth(3, wCol3)
        self.tocTree.setColumnWidth(4, wCol4)
        self.tocTree.setColumnWidth(5, hPx)

        # Options
        # =======

        wordsPerPage = self.optState.getInt("GuiProjectDetails",
                                            "wordsPerPage", 350)
        countFrom = self.optState.getInt("GuiProjectDetails", "countFrom", 1)
        clearDouble = self.optState.getInt("GuiProjectDetails", "clearDouble",
                                           True)

        wordsHelp = (
            "Typical word count for a 5 by 8 inch book page with 11 pt font is 350."
        )
        offsetHelp = ("Start counting page numbers from this page.")
        dblHelp = (
            "Assume a new chapter or partition always start on an odd numbered page."
        )

        self.wpLabel = QLabel("Words per page")
        self.wpLabel.setToolTip(wordsHelp)

        self.wpValue = QSpinBox()
        self.wpValue.setMinimum(10)
        self.wpValue.setMaximum(1000)
        self.wpValue.setSingleStep(10)
        self.wpValue.setValue(wordsPerPage)
        self.wpValue.setToolTip(wordsHelp)
        self.wpValue.valueChanged.connect(self._populateTree)

        self.poLabel = QLabel("Count pages from")
        self.poLabel.setToolTip(offsetHelp)

        self.poValue = QSpinBox()
        self.poValue.setMinimum(1)
        self.poValue.setMaximum(9999)
        self.poValue.setSingleStep(1)
        self.poValue.setValue(countFrom)
        self.poValue.setToolTip(offsetHelp)
        self.poValue.valueChanged.connect(self._populateTree)

        self.dblLabel = QLabel("Clear double pages")
        self.dblLabel.setToolTip(dblHelp)

        self.dblValue = QSwitch(self, 2 * iPx, iPx)
        self.dblValue.setChecked(clearDouble)
        self.dblValue.setToolTip(dblHelp)
        self.dblValue.clicked.connect(self._populateTree)

        self.optionsBox = QGridLayout()
        self.optionsBox.addWidget(self.wpLabel, 0, 0)
        self.optionsBox.addWidget(self.wpValue, 0, 1)
        self.optionsBox.addWidget(self.dblLabel, 0, 3)
        self.optionsBox.addWidget(self.dblValue, 0, 4)
        self.optionsBox.addWidget(self.poLabel, 1, 0)
        self.optionsBox.addWidget(self.poValue, 1, 1)
        self.optionsBox.setHorizontalSpacing(hPx)
        self.optionsBox.setVerticalSpacing(vPx)
        self.optionsBox.setColumnStretch(2, 1)

        # Assemble
        # ========

        self.outerBox = QVBoxLayout()
        self.outerBox.addWidget(QLabel("<b>Table of Contents</b>"))
        self.outerBox.addWidget(self.tocTree)
        self.outerBox.addLayout(self.optionsBox)

        self.setLayout(self.outerBox)

        self._prepareData()
        self._populateTree()

        return
예제 #46
0
class GUIApplicationGt(BaseApplicationGt, QApplicationWindow):
    """[summary]

    [description]
    """
    def __init__(self, name="Gt", parent=None):
        """
        **Constructor**

        Keyword Arguments:
            - name {[type]} -- [description] (default: {"Gt"})
            - parent {[type]} -- [description] (default: {None})
        """
        super().__init__(name, parent)

        self.add_oversampling_widget()
        self.set_oversampling_widget_visible(False)

        self.add_xrange_widget_view()
        self.set_xrange_widgets_view_visible(False)

    def add_oversampling_widget(self):
        """Add spinbox for the oversampling ratio"""
        self.sb_oversampling = QSpinBox()
        self.sb_oversampling.setRange(self.MIN_OVER, self.MAX_OVER)
        self.sb_oversampling.setValue(self.OVER)
        self.sb_oversampling.valueChanged.connect(self.change_oversampling)

        self.viewLayout.insertWidget(2, self.sb_oversampling)

    def add_xrange_widget_view(self):
        """Add widgets below the view combobox to select the
        x-range applied to view transformation"""
        hlayout = QHBoxLayout()

        hlayout.addStretch()
        #xmin
        self.xmin_view = QLineEdit("-inf")
        self.xmin_view.textChanged.connect(self.change_xmin)
        self.xmin_view.setValidator(QDoubleValidator())
        self.xmin_view.setMaximumWidth(35)
        self.xmin_view.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.xmin_label = QLabel("<b>log(t<sub>min</sub>)</b>")
        hlayout.addWidget(self.xmin_label)
        hlayout.addWidget(self.xmin_view)
        #space
        hlayout.addSpacing(5)
        #xmax
        self.xmax_view = QLineEdit("inf")
        self.xmax_view.textChanged.connect(self.change_xmax)
        self.xmax_view.setValidator(QDoubleValidator())
        self.xmax_view.setMaximumWidth(35)
        self.xmax_view.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.xmax_label = QLabel(" <b>log(t<sub>max</sub>)</b>")
        hlayout.addWidget(self.xmax_label)
        hlayout.addWidget(self.xmax_view)
        #push button to refresh view
        self.pb = QPushButton("GO")
        self.pb.setMaximumWidth(25)
        self.pb.clicked.connect(self.update_all_ds_plots)
        hlayout.addWidget(self.pb)
        self.hlayout_view = hlayout
        self.ViewDataTheoryLayout.insertLayout(1, self.hlayout_view)

    def change_xmin(self, text):
        """Update the value of t_min"""
        if text in "-np.inf -inf":
            self.tmin_view = -np.inf
        else:
            try:
                self.tmin_view = 10**float(text)
            except:
                pass

    def change_xmax(self, text):
        """Update the value of t_max"""
        if text in "np.inf inf":
            self.tmax_view = np.inf
        else:
            try:
                self.tmax_view = 10**float(text)
            except:
                pass

    def change_oversampling(self, val):
        """Change the value of the oversampling ratio.
        Called when the spinbox value is changed"""
        self.OVER = val

    def set_oversampling_widget_visible(self, state):
        """Show/Hide the extra widget "sampling ratio" """
        self.sb_oversampling.setVisible(state)

    def set_xrange_widgets_view_visible(self, state):
        """Show/Hide the extra widgets for xrange selection"""
        self.pb.setVisible(state)
        self.xmin_label.setVisible(state)
        self.xmax_label.setVisible(state)
        self.xmin_view.setVisible(state)
        self.xmax_view.setVisible(state)

    def set_view_tools(self, view_name):
        """Show/Hide extra view widgets depending on the current view"""
        if view_name in ["i-Rheo G',G''", "Schwarzl G',G''"]:
            self.set_xrange_widgets_view_visible(True)
            self.set_oversampling_widget_visible(False)
        elif view_name == "i-Rheo-Over G',G''":
            self.set_xrange_widgets_view_visible(True)
            self.set_oversampling_widget_visible(True)
        else:
            try:
                self.set_xrange_widgets_view_visible(False)
                self.set_oversampling_widget_visible(False)
            except AttributeError:
                pass
예제 #47
0
    def commonUI(self):
        if not self._multiple_galleries:
            f_web = QGroupBox("Metadata from the Web")
            f_web.setCheckable(False)
            self.main_layout.addWidget(f_web)
            web_main_layout = QVBoxLayout()
            web_info = misc.ClickedLabel(
                "Which gallery URLs are supported? (hover)", parent=self)
            web_info.setToolTip(app_constants.SUPPORTED_METADATA_URLS)
            web_info.setToolTipDuration(999999999)
            web_main_layout.addWidget(web_info)
            web_layout = QHBoxLayout()
            web_main_layout.addLayout(web_layout)
            f_web.setLayout(web_main_layout)

            def basic_web(name):
                return QLabel(name), QLineEdit(), QPushButton(
                    "Get metadata"), QProgressBar()

            url_lbl, self.url_edit, url_btn, url_prog = basic_web("URL:")
            url_btn.clicked.connect(lambda: self.web_metadata(
                self.url_edit.text(), url_btn, url_prog))
            url_prog.setTextVisible(False)
            url_prog.setMinimum(0)
            url_prog.setMaximum(0)
            web_layout.addWidget(url_lbl, 0, Qt.AlignLeft)
            web_layout.addWidget(self.url_edit, 0)
            web_layout.addWidget(url_btn, 0, Qt.AlignRight)
            web_layout.addWidget(url_prog, 0, Qt.AlignRight)
            self.url_edit.setPlaceholderText(
                "Insert supported gallery URLs or just press the button!")
            url_prog.hide()

        f_gallery = QGroupBox("Gallery Info")
        f_gallery.setCheckable(False)
        self.main_layout.addWidget(f_gallery)
        gallery_layout = QFormLayout()
        f_gallery.setLayout(gallery_layout)

        def checkbox_layout(widget):
            if self._multiple_galleries:
                l = QHBoxLayout()
                l.addWidget(widget.g_check)
                widget.setSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Preferred)
                l.addWidget(widget)
                return l
            else:
                widget.g_check.setChecked(True)
                widget.g_check.hide()
                return widget

        def add_check(widget):
            widget.g_check = QCheckBox(self)
            return widget

        self.title_edit = add_check(QLineEdit())
        self.author_edit = add_check(QLineEdit())
        author_completer = misc.GCompleter(self, False, True, False)
        author_completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.author_edit.setCompleter(author_completer)
        self.descr_edit = add_check(QTextEdit())
        self.descr_edit.setAcceptRichText(True)
        self.lang_box = add_check(QComboBox())
        self.lang_box.addItems(app_constants.G_LANGUAGES)
        self.lang_box.addItems(app_constants.G_CUSTOM_LANGUAGES)
        self.rating_box = add_check(QSpinBox())
        self.rating_box.setMaximum(5)
        self.rating_box.setMinimum(0)
        self._find_combobox_match(self.lang_box, app_constants.G_DEF_LANGUAGE,
                                  0)
        tags_l = QVBoxLayout()
        tag_info = misc.ClickedLabel(
            "How do i write namespace & tags? (hover)", parent=self)
        tag_info.setToolTip(
            "Ways to write tags:\n\nNormal tags:\ntag1, tag2, tag3\n\n" +
            "Namespaced tags:\nns1:tag1, ns1:tag2\n\nNamespaced tags with one or more"
            +
            " tags under same namespace:\nns1:[tag1, tag2, tag3], ns2:[tag1, tag2]\n\n"
            +
            "Those three ways of writing namespace & tags can be combined freely.\n"
            +
            "Tags are seperated by a comma, NOT whitespace.\nNamespaces will be capitalized while tags"
            + " will be lowercased.")
        tag_info.setToolTipDuration(99999999)
        tags_l.addWidget(tag_info)
        self.tags_edit = add_check(misc.CompleterTextEdit())
        self.tags_edit.setCompleter(misc.GCompleter(self, False, False))
        if self._multiple_galleries:
            tags_l.addLayout(checkbox_layout(self.tags_edit), 3)
        else:
            tags_l.addWidget(checkbox_layout(self.tags_edit), 3)
        self.tags_edit.setPlaceholderText(
            "Press Tab to autocomplete (Ctrl + E to show popup)")
        self.type_box = add_check(QComboBox())
        self.type_box.addItems(app_constants.G_TYPES)
        self._find_combobox_match(self.type_box, app_constants.G_DEF_TYPE, 0)
        #self.type_box.currentIndexChanged[int].connect(self.doujin_show)
        #self.doujin_parent = QLineEdit()
        #self.doujin_parent.setVisible(False)
        self.status_box = add_check(QComboBox())
        self.status_box.addItems(app_constants.G_STATUS)
        self._find_combobox_match(self.status_box, app_constants.G_DEF_STATUS,
                                  0)
        self.pub_edit = add_check(QDateEdit())
        self.pub_edit.setCalendarPopup(True)
        self.pub_edit.setDate(QDate.currentDate())
        self.path_lbl = misc.ClickedLabel("")
        self.path_lbl.setWordWrap(True)
        self.path_lbl.clicked.connect(lambda a: utils.open_path(a, a)
                                      if a else None)

        link_layout = QHBoxLayout()
        self.link_lbl = add_check(QLabel(""))
        self.link_lbl.setWordWrap(True)
        self.link_edit = QLineEdit()
        link_layout.addWidget(self.link_edit)
        if self._multiple_galleries:
            link_layout.addLayout(checkbox_layout(self.link_lbl))
        else:
            link_layout.addWidget(checkbox_layout(self.link_lbl))
        self.link_edit.hide()
        self.link_btn = QPushButton("Modify")
        self.link_btn.setFixedWidth(50)
        self.link_btn2 = QPushButton("Set")
        self.link_btn2.setFixedWidth(40)
        self.link_btn.clicked.connect(self.link_modify)
        self.link_btn2.clicked.connect(self.link_set)
        link_layout.addWidget(self.link_btn)
        link_layout.addWidget(self.link_btn2)
        self.link_btn2.hide()

        rating_ = checkbox_layout(self.rating_box)
        lang_ = checkbox_layout(self.lang_box)
        if self._multiple_galleries:
            rating_.insertWidget(0, QLabel("Rating:"))
            lang_.addLayout(rating_)
            lang_l = lang_
        else:
            lang_l = QHBoxLayout()
            lang_l.addWidget(lang_)
            lang_l.addWidget(QLabel("Rating:"), 0, Qt.AlignRight)
            lang_l.addWidget(rating_)

        gallery_layout.addRow("Title:", checkbox_layout(self.title_edit))
        gallery_layout.addRow("Author:", checkbox_layout(self.author_edit))
        gallery_layout.addRow("Description:", checkbox_layout(self.descr_edit))
        gallery_layout.addRow("Language:", lang_l)
        gallery_layout.addRow("Tags:", tags_l)
        gallery_layout.addRow("Type:", checkbox_layout(self.type_box))
        gallery_layout.addRow("Status:", checkbox_layout(self.status_box))
        gallery_layout.addRow("Publication Date:",
                              checkbox_layout(self.pub_edit))
        gallery_layout.addRow("Path:", self.path_lbl)
        gallery_layout.addRow("Link:", link_layout)

        self.title_edit.setFocus()
예제 #48
0
class Dialog(QWidget):
    #codeFound = pyqtSignal()
    words = ''
    lastwords = ''
    canSend = False
    requestToSend = ''
    m_waitTimeout = 100
    m_attemp = 0
    stockf021 = b''

    def __init__(self):
        super().__init__()
        self.m_transaction = 0
        self.stop = True
        self.m_serialt = st.SerialTransaction()
        self.initUI()
        #self.longdelay = 0.8
        self.shortdelay = 0.05

    def initUI(self):

        self.m_serialPortLabel = QLabel("Serial port:")
        self.m_serialPortComboBox = QComboBox()
        self.m_serialBaudsLabel = QLabel("Bauds:")
        self.m_serialBaudsComboBox = QComboBox()
        self.m_waitResponseLabel = QLabel("Wait response, msec:")
        self.m_waitResponseSpinBox = QSpinBox()
        self.m_longDelayLabel = QLabel("transaction delay, msec:")
        self.m_longDelaySpinBox = QSpinBox()

        self.m_runButton = QPushButton("Send request")
        self.m_requestLabel = QLabel("Request (hex without 0x):")
        self.m_requestLineEdit = QLineEdit("09")
        self.m_trafficLabel = QLabel("No traffic.")
        self.m_statusLabel = QLabel("Status: Not running.")

        available_ports = QSerialPortInfo.availablePorts()
        for port in available_ports:
            self.m_serialPortComboBox.addItem(port.portName())

        available_bauds = QSerialPortInfo.standardBaudRates()
        for bauds in available_bauds:
            self.m_serialBaudsComboBox.addItem(str(bauds))
        self.m_serialBaudsComboBox.itemText(9)

        self.m_waitResponseSpinBox.setRange(0, 10000)
        self.m_waitResponseSpinBox.setValue(1500)

        self.m_longDelaySpinBox.setRange(0, 10000)
        self.m_longDelaySpinBox.setValue(100)
        self.longdelay = 0.1

        mainLayout = QGridLayout()

        mainLayout.addWidget(self.m_serialPortLabel, 0, 0)
        mainLayout.addWidget(self.m_serialPortComboBox, 0, 1)
        mainLayout.addWidget(self.m_serialBaudsLabel, 0, 2)
        mainLayout.addWidget(self.m_serialBaudsComboBox, 0, 3)

        mainLayout.addWidget(self.m_waitResponseLabel, 1, 0)
        mainLayout.addWidget(self.m_waitResponseSpinBox, 1, 1)

        mainLayout.addWidget(self.m_longDelayLabel, 2, 0)
        mainLayout.addWidget(self.m_longDelaySpinBox, 2, 1)

        #mainLayout.addWidget(self.m_stopButton,1,2,2,1)
        mainLayout.addWidget(self.m_requestLabel, 3, 0)
        mainLayout.addWidget(self.m_requestLineEdit, 3, 1)

        mainLayout.addWidget(self.m_runButton, 4, 1)

        mainLayout.addWidget(self.m_trafficLabel, 5, 0, 1, 4)

        mainLayout.addWidget(self.m_statusLabel, 6, 0, 1, 5)

        self.setLayout(mainLayout)

        self.setWindowTitle("TDC7201 Terminal")
        self.setWindowIcon(QIcon('pinion-icon.png'))
        self.m_serialPortComboBox.setFocus()

        #connection
        self.m_runButton.clicked.connect(self.transactionUI)
        self.m_serialt.responseSignal.connect(self.showResponse)
        self.m_serialt.errorSignal.connect(self.processError)
        self.m_serialt.timeoutSignal.connect(self.processTimeout)
        self.m_longDelaySpinBox.valueChanged.connect(self.updLongDelay)
        self.m_waitResponseSpinBox.valueChanged.connect(self.updwaitTimeout)

        self.center()

        self.show()

    def transaction(self):
        #self.setControlsEnabled(False)
        self.m_statusLabel.setText(
            "Status: Running, connected to port {}.".format(
                self.m_serialPortComboBox.currentText()))
        response=self.m_serialt.transaction(self.m_serialPortComboBox.currentText(),\
                                  self.m_waitTimeout,\
                                  self.requestToSend)

        #wait_until(self.readyToSend,self.longdelay,self.shortdelay)
        return response

    def transactionUI(self):
        #self.setControlsEnabled(False)
        self.m_statusLabel.setText(
            "Status: Running, connected to port {} with bauds {}.".format(
                self.m_serialPortComboBox.currentText(),
                self.m_serialBaudsComboBox.currentText()))
        #wait_until(self.readyToSend,self.longdelay,self.shortdelay)
        response = self.m_serialt.transaction(self.m_serialPortComboBox.currentText(),\
                                  int(self.m_serialBaudsComboBox.currentText()),\
                                  self.m_waitTimeout,\
                                  self.m_requestLineEdit.text())
        #wait_until(self.readyToSend,self.longdelay,self.shortdelay)
        self.m_waitTimeout = self.m_waitResponseSpinBox.value()
        return response

    def showResponse(self, ba):
        print("receive at {}".format(QTime.currentTime().toString()))
        #self.setControlsEnabled(True)
        self.m_transaction += 1
        self.m_trafficLabel.setText("response ({} bytes):{}".format(
            ba.size(), ba))
        #ok = False
        #print(ba.toInt(ok))
        #print(ba)
        #self.canSend=True
        return

    def readyToSend(self):
        return self.canSend

    def processError(self, s):
        self.setControlsEnabled(True)
        self.m_statusLabel.setText("Status: Not running, {}.".format(s))
        self.m_trafficLabel.setText("No traffic.")
        return

    def processTimeout(self, s):
        self.setControlsEnabled(True)
        self.m_statusLabel.setText("Status: Running, {}.".format(s))
        self.m_trafficLabel.setText("No traffic.")
        return

    def updLongDelay(self, val):
        #self.longdelay = self.m_longDelaySpinBox.value()/1000
        self.londelay = val / 1000
        print("Long delay = {} s".format(self.londelay))
        return

    def updwaitTimeout(self, val):
        #self.longdelay = self.m_longDelaySpinBox.value()/1000
        self.m_waitTimeout = val
        print("Long delay = {} s".format(self.m_waitTimeout))
        return

    def setControlsEnabled(self, enable):
        self.m_runButton.setEnabled(enable)
        self.m_serialPortComboBox.setEnabled(enable)
        self.m_waitResponseSpinBox.setEnabled(enable)
        self.m_requestLineEdit.setEnabled(enable)
        return

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

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message', "Are you sure to quit?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
예제 #49
0
class MaMPyGUIDemoMaxTree(QMainWindow):
    # default size of GUI
    xsize = 800
    ysize = 600

    # Images Attributes
    imageSrc = None
    imageSrcFlat = None
    maxtree_p = None
    maxtree_s = None
    maxtree_a = None

    # Initialisation of the class
    def __init__(self):
        super().__init__()
        self.initUI()

    # Initialisation of the user interface.
    def initUI(self):
        # Image Label Source
        self.imageLabelSrc = QLabel()
        self.imageLabelSrc.setAlignment(QtCore.Qt.AlignCenter)
        # Image Label Result
        self.imageLabelRes = QLabel()
        self.imageLabelRes.setAlignment(QtCore.Qt.AlignCenter)

        # Area Threshold Slider
        self.areaThresholdSlider = QSlider(QtCore.Qt.Horizontal)
        self.areaThresholdSlider.setRange(0, 1)
        self.areaThresholdSlider.valueChanged.connect(
            self.areaThresholdSliderChanged)
        # Area Threshold Spinbox
        self.areaThresholdSpinbox = QSpinBox()
        self.areaThresholdSpinbox.setRange(0, 1)
        self.areaThresholdSpinbox.valueChanged.connect(
            self.areaThresholdSpinboxChanged)

        # Layout
        self.imageLabelLayout = QHBoxLayout()
        self.thresholdLayout = QHBoxLayout()

        self.imageLabelLayout.addWidget(self.imageLabelSrc)
        self.imageLabelLayout.addWidget(self.imageLabelRes)
        self.imageLabelLayoutWidget = QWidget()
        self.imageLabelLayoutWidget.setLayout(self.imageLabelLayout)

        self.thresholdLayout.addWidget(self.areaThresholdSlider)
        self.thresholdLayout.addWidget(self.areaThresholdSpinbox)
        self.thresholdLayoutWidget = QWidget()
        self.thresholdLayoutWidget.setLayout(self.thresholdLayout)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.imageLabelLayoutWidget)
        self.mainLayout.addWidget(self.thresholdLayoutWidget)

        # Main Widget
        self.window = QWidget()
        self.window.setLayout(self.mainLayout)

        # Set Central Widget
        self.setCentralWidget(self.window)

        # Actions
        # Open File
        openFile = QAction('Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.triggered.connect(self.openImageDialog)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)

        # Center Window
        xbase = (app.desktop().screenGeometry().width() - self.xsize) / 2
        ybase = (app.desktop().screenGeometry().height() - self.ysize) / 2

        # Window Property
        self.setGeometry(xbase, ybase, self.xsize, self.ysize)
        self.setWindowTitle('MaMPy Max-Tree demo')
        self.show()

    def resizeEvent(self, event):
        self.xsize = event.size().width()
        self.ysize = event.size().height()

        self.updateImages()

        QMainWindow.resizeEvent(self, event)

    def areaThresholdSliderChanged(self, event):
        self.areaThresholdSpinbox.setValue(self.areaThresholdSlider.value())
        self.updateImages()

    def areaThresholdSpinboxChanged(self, event):
        self.areaThresholdSlider.setValue(self.areaThresholdSpinbox.value())
        self.updateImages()

    def openImageDialog(self):
        filename = QFileDialog.getOpenFileName(
            self, "Open file", None, 'Image Files (*.png *.jpg *.bmp)')

        if filename[0]:
            # Read the image
            self.imageSrc = image_read(filename[0])

            # Compute the Max-Tree
            (self.maxtree_p,
             self.maxtree_s) = maxtree_union_find_level_compression(
                 self.imageSrc, connection8=True)

            self.imageSrcFlat = self.imageSrc.flatten()
            self.maxtree_a = compute_attribute_area(self.maxtree_s,
                                                    self.maxtree_p,
                                                    self.imageSrcFlat)

            # Update slider and spinbox in the image resolution range
            self.areaThresholdSlider.setRange(
                0, (self.imageSrc.shape[0] * self.imageSrc.shape[1]))
            self.areaThresholdSpinbox.setRange(
                0, (self.imageSrc.shape[0] * self.imageSrc.shape[1]))

            # Update the image label
            self.updateImages()

    def updateImages(self):
        # Check if an image is loaded
        if self.imageSrc is None:
            return

        # Image Source
        pixmapSrc = QPixmap(qimage2ndarray.array2qimage(self.imageSrc))
        pixmapSrc = pixmapSrc.scaled((self.xsize / 2) - 50, self.ysize - 50,
                                     QtCore.Qt.KeepAspectRatio)

        self.imageLabelSrc.setPixmap(pixmapSrc)

        # Image Result
        self.imageRes = direct_filter(self.maxtree_s, self.maxtree_p,
                                      self.imageSrcFlat, self.maxtree_a,
                                      self.areaThresholdSpinbox.value())
        self.imageRes = self.imageRes.reshape(self.imageSrc.shape)

        pixmapRes = QPixmap(qimage2ndarray.array2qimage(self.imageRes))
        pixmapRes = pixmapRes.scaled((self.xsize / 2) - 50, self.ysize - 50,
                                     QtCore.Qt.KeepAspectRatio)

        self.imageLabelRes.setPixmap(pixmapRes)
예제 #50
0
def createSpinBox(value, minimum, maximum, step):
    spinBox = QSpinBox()
    spinBox.setRange(minimum, maximum)
    spinBox.setSingleStep(step)
    spinBox.setValue(value)
    return spinBox
예제 #51
0
    def initUI(self):

        self.m_serialPortLabel = QLabel("Serial port:")
        self.m_serialPortComboBox = QComboBox()
        self.m_serialBaudsLabel = QLabel("Bauds:")
        self.m_serialBaudsComboBox = QComboBox()
        self.m_waitResponseLabel = QLabel("Wait response, msec:")
        self.m_waitResponseSpinBox = QSpinBox()
        self.m_longDelayLabel = QLabel("transaction delay, msec:")
        self.m_longDelaySpinBox = QSpinBox()

        self.m_runButton = QPushButton("Send request")
        self.m_requestLabel = QLabel("Request (hex without 0x):")
        self.m_requestLineEdit = QLineEdit("09")
        self.m_trafficLabel = QLabel("No traffic.")
        self.m_statusLabel = QLabel("Status: Not running.")

        available_ports = QSerialPortInfo.availablePorts()
        for port in available_ports:
            self.m_serialPortComboBox.addItem(port.portName())

        available_bauds = QSerialPortInfo.standardBaudRates()
        for bauds in available_bauds:
            self.m_serialBaudsComboBox.addItem(str(bauds))
        self.m_serialBaudsComboBox.itemText(9)

        self.m_waitResponseSpinBox.setRange(0, 10000)
        self.m_waitResponseSpinBox.setValue(1500)

        self.m_longDelaySpinBox.setRange(0, 10000)
        self.m_longDelaySpinBox.setValue(100)
        self.longdelay = 0.1

        mainLayout = QGridLayout()

        mainLayout.addWidget(self.m_serialPortLabel, 0, 0)
        mainLayout.addWidget(self.m_serialPortComboBox, 0, 1)
        mainLayout.addWidget(self.m_serialBaudsLabel, 0, 2)
        mainLayout.addWidget(self.m_serialBaudsComboBox, 0, 3)

        mainLayout.addWidget(self.m_waitResponseLabel, 1, 0)
        mainLayout.addWidget(self.m_waitResponseSpinBox, 1, 1)

        mainLayout.addWidget(self.m_longDelayLabel, 2, 0)
        mainLayout.addWidget(self.m_longDelaySpinBox, 2, 1)

        #mainLayout.addWidget(self.m_stopButton,1,2,2,1)
        mainLayout.addWidget(self.m_requestLabel, 3, 0)
        mainLayout.addWidget(self.m_requestLineEdit, 3, 1)

        mainLayout.addWidget(self.m_runButton, 4, 1)

        mainLayout.addWidget(self.m_trafficLabel, 5, 0, 1, 4)

        mainLayout.addWidget(self.m_statusLabel, 6, 0, 1, 5)

        self.setLayout(mainLayout)

        self.setWindowTitle("TDC7201 Terminal")
        self.setWindowIcon(QIcon('pinion-icon.png'))
        self.m_serialPortComboBox.setFocus()

        #connection
        self.m_runButton.clicked.connect(self.transactionUI)
        self.m_serialt.responseSignal.connect(self.showResponse)
        self.m_serialt.errorSignal.connect(self.processError)
        self.m_serialt.timeoutSignal.connect(self.processTimeout)
        self.m_longDelaySpinBox.valueChanged.connect(self.updLongDelay)
        self.m_waitResponseSpinBox.valueChanged.connect(self.updwaitTimeout)

        self.center()

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

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

        if ui_direction == 'rtl':
            self.setLayoutDirection(Qt.RightToLeft)
        
        elif ui_direction in 'ltr':
            self.setLayoutDirection(Qt.LeftToRight)


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

        self.setMinimumSize(QtCore.QSize(520, 425))
        self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg')))

        # main layout
        window_verticalLayout = QVBoxLayout()

        # add link tab widget
        self.add_link_tabWidget = QTabWidget(self)
        window_verticalLayout.addWidget(self.add_link_tabWidget)

        # link tab
        self.link_tab = QWidget()

        link_tab_verticalLayout = QVBoxLayout(self.link_tab)
        link_tab_verticalLayout.setContentsMargins(21, 21, 21, 81)

        self.link_frame = QFrame(self.link_tab)
        self.link_frame.setFrameShape(QFrame.StyledPanel)
        self.link_frame.setFrameShadow(QFrame.Raised)

        horizontalLayout_2 = QHBoxLayout(self.link_frame)

        self.link_verticalLayout = QVBoxLayout()

        # link ->
        self.link_horizontalLayout = QHBoxLayout()
        self.link_label = QLabel(self.link_frame)
        self.link_horizontalLayout.addWidget(self.link_label)

        self.link_lineEdit = QLineEdit(self.link_frame)
        self.link_horizontalLayout.addWidget(self.link_lineEdit)

        self.link_verticalLayout.addLayout(self.link_horizontalLayout)

        horizontalLayout_2.addLayout(self.link_verticalLayout)
        link_tab_verticalLayout.addWidget(self.link_frame)

        # add change_name field ->
        change_name_horizontalLayout = QHBoxLayout()
        self.change_name_checkBox = QCheckBox(self.link_frame)
        change_name_horizontalLayout.addWidget(self.change_name_checkBox)

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

        self.link_verticalLayout.addLayout(change_name_horizontalLayout)

        # add_category ->
        queue_horizontalLayout = QHBoxLayout()

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

        add_queue_horizontalLayout = QHBoxLayout(self.queue_frame)

        self.add_queue_label = QLabel(self.queue_frame)
        add_queue_horizontalLayout.addWidget(self.add_queue_label)

        self.add_queue_comboBox = QComboBox(self.queue_frame)
        add_queue_horizontalLayout.addWidget(self.add_queue_comboBox)

        queue_horizontalLayout.addWidget(self.queue_frame)
        queue_horizontalLayout.addStretch(1)

        self.size_label = QLabel(self)
        queue_horizontalLayout.addWidget(self.size_label)

        link_tab_verticalLayout.addLayout(queue_horizontalLayout)

        link_tab_verticalLayout.addStretch(1)

        self.add_link_tabWidget.addTab(self.link_tab, '')


        # proxy tab
        self.proxy_tab = QWidget(self)

        proxy_verticalLayout = QVBoxLayout(self.proxy_tab)
        proxy_verticalLayout.setContentsMargins(21, 21, 21, 171)

        proxy_horizontalLayout = QHBoxLayout()

        self.proxy_checkBox = QCheckBox(self.proxy_tab)
        self.detect_proxy_pushButton = QPushButton(self.proxy_tab)
        self.detect_proxy_label = QLabel(self.proxy_tab)

        proxy_horizontalLayout.addWidget(self.proxy_checkBox)
        proxy_horizontalLayout.addWidget(self.detect_proxy_label)
        proxy_horizontalLayout.addWidget(self.detect_proxy_pushButton)

        proxy_verticalLayout.addLayout(proxy_horizontalLayout)

        self.proxy_frame = QFrame(self.proxy_tab)
        self.proxy_frame.setFrameShape(QFrame.StyledPanel)
        self.proxy_frame.setFrameShadow(QFrame.Raised)

        gridLayout = QGridLayout(self.proxy_frame)

        self.ip_label = QLabel(self.proxy_frame)
        gridLayout.addWidget(self.ip_label, 0, 0, 1, 1)


        self.ip_lineEdit = QLineEdit(self.proxy_frame)
        self.ip_lineEdit.setInputMethodHints(QtCore.Qt.ImhNone)
        gridLayout.addWidget(self.ip_lineEdit, 0, 1, 1, 1)

        self.port_label = QLabel(self.proxy_frame)
        gridLayout.addWidget(self.port_label, 0, 2, 1, 1)

        self.port_spinBox = QSpinBox(self.proxy_frame)
        self.port_spinBox.setMaximum(65535)
        self.port_spinBox.setSingleStep(1)
        gridLayout.addWidget(self.port_spinBox, 0, 3, 1, 1)
 
        self.proxy_user_label = QLabel(self.proxy_frame)
        gridLayout.addWidget(self.proxy_user_label, 2, 0, 1, 1)

        self.proxy_user_lineEdit = QLineEdit(self.proxy_frame)
        gridLayout.addWidget(self.proxy_user_lineEdit, 2, 1, 1, 1)

 
        self.proxy_pass_label = QLabel(self.proxy_frame)
        gridLayout.addWidget(self.proxy_pass_label, 2, 2, 1, 1)

        self.proxy_pass_lineEdit = QLineEdit(self.proxy_frame)
        self.proxy_pass_lineEdit.setEchoMode(QLineEdit.Password)
        gridLayout.addWidget(self.proxy_pass_lineEdit, 2, 3, 1, 1)

        proxy_verticalLayout.addWidget(self.proxy_frame)

        proxy_verticalLayout.addStretch(1)

        self.add_link_tabWidget.addTab(self.proxy_tab, '')

        # more options tab
        self.more_options_tab = QWidget(self)
        
        more_options_tab_verticalLayout = QVBoxLayout(self.more_options_tab)

        # download UserName & Password ->
        download_horizontalLayout = QHBoxLayout()
        download_horizontalLayout.setContentsMargins(-1, 10, -1, -1)

        download_verticalLayout = QVBoxLayout()
        self.download_checkBox = QCheckBox(self.more_options_tab)
        download_verticalLayout.addWidget(self.download_checkBox)

        self.download_frame = QFrame(self.more_options_tab)
        self.download_frame.setFrameShape(QFrame.StyledPanel)
        self.download_frame.setFrameShadow(QFrame.Raised)

        gridLayout_2 = QGridLayout(self.download_frame)

        self.download_user_lineEdit = QLineEdit(self.download_frame)
        gridLayout_2.addWidget(self.download_user_lineEdit, 0, 1, 1, 1)

        self.download_user_label = QLabel(self.download_frame)
        gridLayout_2.addWidget(self.download_user_label, 0, 0, 1, 1)

        self.download_pass_label = QLabel(self.download_frame)
        gridLayout_2.addWidget(self.download_pass_label, 1, 0, 1, 1)

        self.download_pass_lineEdit = QLineEdit(self.download_frame)
        self.download_pass_lineEdit.setEchoMode(QLineEdit.Password)
        gridLayout_2.addWidget(self.download_pass_lineEdit, 1, 1, 1, 1)
        download_verticalLayout.addWidget(self.download_frame)
        download_horizontalLayout.addLayout(download_verticalLayout)

        # select folder ->
        self.folder_frame = QFrame(self.more_options_tab)
        self.folder_frame.setFrameShape(QFrame.StyledPanel)
        self.folder_frame.setFrameShadow(QFrame.Raised)

        gridLayout_3 = QGridLayout(self.folder_frame)

        self.download_folder_lineEdit = QLineEdit(self.folder_frame)
        gridLayout_3.addWidget(self.download_folder_lineEdit, 2, 0, 1, 1)

        self.folder_pushButton = QPushButton(self.folder_frame)
        gridLayout_3.addWidget(self.folder_pushButton, 3, 0, 1, 1)
        self.folder_pushButton.setIcon(QIcon(icons + 'folder'))

        self.folder_label = QLabel(self.folder_frame)
        self.folder_label.setAlignment(QtCore.Qt.AlignCenter)
        gridLayout_3.addWidget(self.folder_label, 1, 0, 1, 1)
        download_horizontalLayout.addWidget(self.folder_frame)
        more_options_tab_verticalLayout.addLayout(download_horizontalLayout)

        # start time ->
        time_limit_horizontalLayout = QHBoxLayout()
        time_limit_horizontalLayout.setContentsMargins(-1, 10, -1, -1)

        start_verticalLayout = QVBoxLayout()
        self.start_checkBox = QCheckBox(self.more_options_tab)
        start_verticalLayout.addWidget(self.start_checkBox)

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

        horizontalLayout_5 = QHBoxLayout(self.start_frame)

        self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame)
        self.start_time_qDataTimeEdit.setDisplayFormat('H:mm')
        horizontalLayout_5.addWidget(self.start_time_qDataTimeEdit)
        
        start_verticalLayout.addWidget(self.start_frame)
        time_limit_horizontalLayout.addLayout(start_verticalLayout)

        # end time ->
        end_verticalLayout = QVBoxLayout()

        self.end_checkBox = QCheckBox(self.more_options_tab)
        end_verticalLayout.addWidget(self.end_checkBox)

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

        horizontalLayout_6 = QHBoxLayout(self.end_frame)

        self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame)
        self.end_time_qDateTimeEdit.setDisplayFormat('H:mm')
        horizontalLayout_6.addWidget(self.end_time_qDateTimeEdit)
 
        end_verticalLayout.addWidget(self.end_frame)
        time_limit_horizontalLayout.addLayout(end_verticalLayout)

        # limit Speed ->
        limit_verticalLayout = QVBoxLayout()

        self.limit_checkBox = QCheckBox(self.more_options_tab)
        limit_verticalLayout.addWidget(self.limit_checkBox)

        self.limit_frame = QFrame(self.more_options_tab)
        self.limit_frame.setFrameShape(QFrame.StyledPanel)
        self.limit_frame.setFrameShadow(QFrame.Raised)

        horizontalLayout_4 = QHBoxLayout(self.limit_frame)

        self.limit_spinBox = QDoubleSpinBox(self.limit_frame)
        self.limit_spinBox.setMinimum(1)
        self.limit_spinBox.setMaximum(1023)
        horizontalLayout_4.addWidget(self.limit_spinBox)

        self.limit_comboBox = QComboBox(self.limit_frame)
        self.limit_comboBox.addItem("")
        self.limit_comboBox.addItem("")
        horizontalLayout_4.addWidget(self.limit_comboBox)
        limit_verticalLayout.addWidget(self.limit_frame)
        time_limit_horizontalLayout.addLayout(limit_verticalLayout)
        more_options_tab_verticalLayout.addLayout(time_limit_horizontalLayout)

        # number of connections ->
        connections_horizontalLayout = QHBoxLayout()
        connections_horizontalLayout.setContentsMargins(-1, 10, -1, -1)

        self.connections_frame = QFrame(self.more_options_tab)
        self.connections_frame.setFrameShape(QFrame.StyledPanel)
        self.connections_frame.setFrameShadow(QFrame.Raised)

        horizontalLayout_3 = QHBoxLayout(self.connections_frame)
        self.connections_label = QLabel(self.connections_frame)
        horizontalLayout_3.addWidget(self.connections_label)

        self.connections_spinBox = QSpinBox(self.connections_frame)
        self.connections_spinBox.setMinimum(1)
        self.connections_spinBox.setMaximum(16)
        self.connections_spinBox.setProperty("value", 16)
        horizontalLayout_3.addWidget(self.connections_spinBox)
        connections_horizontalLayout.addWidget(self.connections_frame)
        connections_horizontalLayout.addStretch(1)

        more_options_tab_verticalLayout.addLayout(connections_horizontalLayout)

        more_options_tab_verticalLayout.addStretch(1)

        self.add_link_tabWidget.addTab(self.more_options_tab, '') 

        # advance options
        self.advance_options_tab = QWidget(self)

        advance_options_tab_verticalLayout = QVBoxLayout(self.advance_options_tab)

        # referer
        referer_horizontalLayout = QHBoxLayout()

        self.referer_label = QLabel(self.advance_options_tab)
        referer_horizontalLayout.addWidget(self.referer_label)

        self.referer_lineEdit = QLineEdit(self.advance_options_tab)
        referer_horizontalLayout.addWidget(self.referer_lineEdit)

        advance_options_tab_verticalLayout.addLayout(referer_horizontalLayout)

        # header
        header_horizontalLayout = QHBoxLayout()

        self.header_label = QLabel(self.advance_options_tab)
        header_horizontalLayout.addWidget(self.header_label)

        self.header_lineEdit = QLineEdit(self.advance_options_tab)
        header_horizontalLayout.addWidget(self.header_lineEdit)

        advance_options_tab_verticalLayout.addLayout(header_horizontalLayout)

        # user_agent
        user_agent_horizontalLayout = QHBoxLayout()

        self.user_agent_label = QLabel(self.advance_options_tab)
        user_agent_horizontalLayout.addWidget(self.user_agent_label)

        self.user_agent_lineEdit = QLineEdit(self.advance_options_tab)
        user_agent_horizontalLayout.addWidget(self.user_agent_lineEdit)

        advance_options_tab_verticalLayout.addLayout(user_agent_horizontalLayout)

        # load_cookies
        load_cookies_horizontalLayout = QHBoxLayout()

        self.load_cookies_label = QLabel(self.advance_options_tab)
        load_cookies_horizontalLayout.addWidget(self.load_cookies_label)

        self.load_cookies_lineEdit = QLineEdit(self.advance_options_tab)
        load_cookies_horizontalLayout.addWidget(self.load_cookies_lineEdit)

        advance_options_tab_verticalLayout.addLayout(load_cookies_horizontalLayout)

        advance_options_tab_verticalLayout.addStretch(1)

        self.add_link_tabWidget.addTab(self.advance_options_tab, '') 

        # ok cancel download_later buttons ->
        buttons_horizontalLayout = QHBoxLayout()
        buttons_horizontalLayout.addStretch(1)

        self.download_later_pushButton = QPushButton(self)
        self.download_later_pushButton.setIcon(QIcon(icons + 'stop'))

        self.cancel_pushButton = QPushButton(self)
        self.cancel_pushButton.setIcon(QIcon(icons + 'remove'))

        self.ok_pushButton = QPushButton(self)
        self.ok_pushButton.setIcon(QIcon(icons + 'ok'))

        buttons_horizontalLayout.addWidget(self.download_later_pushButton)
        buttons_horizontalLayout.addWidget(self.cancel_pushButton)
        buttons_horizontalLayout.addWidget(self.ok_pushButton)

        window_verticalLayout.addLayout(buttons_horizontalLayout)
        
        self.setLayout(window_verticalLayout)

        # labels ->
        self.setWindowTitle(QCoreApplication.translate("addlink_ui_tr", "Enter Your Link"))

        self.link_label.setText(QCoreApplication.translate("addlink_ui_tr", "Download Link: "))

        self.add_queue_label.setText(QCoreApplication.translate("addlink_ui_tr", "Add to category: "))

        self.change_name_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Change File Name: "))

        self.detect_proxy_pushButton.setText(QCoreApplication.translate("addlink_ui_tr", "Detect system proxy setting"))
        self.proxy_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Proxy"))
        self.proxy_pass_label.setText(QCoreApplication.translate("addlink_ui_tr", "Proxy PassWord: "******"addlink_ui_tr", "IP: "))
        self.proxy_user_label.setText(QCoreApplication.translate("addlink_ui_tr", "Proxy UserName: "******"addlink_ui_tr", "Port:"))

        self.download_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Download UserName and PassWord"))
        self.download_user_label.setText(QCoreApplication.translate("addlink_ui_tr", "Download UserName: "******"addlink_ui_tr", "Download PassWord: "******"addlink_ui_tr", "Change Download Folder"))
        self.folder_label.setText(QCoreApplication.translate("addlink_ui_tr", "Download Folder: "))

        self.start_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "Start Time"))
        self.end_checkBox.setText(QCoreApplication.translate("addlink_ui_tr", "End Time"))

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

        self.connections_label.setText(QCoreApplication.translate("addlink_ui_tr", "Number Of Connections:"))

        self.cancel_pushButton.setText(QCoreApplication.translate("addlink_ui_tr", "Cancel"))
        self.ok_pushButton.setText(QCoreApplication.translate("addlink_ui_tr", "OK"))

        self.download_later_pushButton.setText(QCoreApplication.translate("addlink_ui_tr", "Download later"))

        self.add_link_tabWidget.setTabText(self.add_link_tabWidget.indexOf(
            self.link_tab), QCoreApplication.translate("addlink_ui_tr","Link"))

        self.add_link_tabWidget.setTabText(self.add_link_tabWidget.indexOf(
            self.proxy_tab), QCoreApplication.translate("addlink_ui_tr", "Proxy"))

        self.add_link_tabWidget.setTabText(self.add_link_tabWidget.indexOf(
            self.more_options_tab), QCoreApplication.translate("addlink_ui_tr", "More Options"))

        self.add_link_tabWidget.setTabText(self.add_link_tabWidget.indexOf(
            self.advance_options_tab), QCoreApplication.translate("addlink_ui_tr", "Advanced Options"))

        self.referer_label.setText(QCoreApplication.translate("addlink_ui_tr", 'Referrer: '))

        self.header_label.setText(QCoreApplication.translate("addlink_ui_tr", 'Header: '))

        self.load_cookies_label.setText(QCoreApplication.translate("addlink_ui_tr", 'Load cookies: '))

        self.user_agent_label.setText(QCoreApplication.translate("addlink_ui_tr", 'User agent: '))
예제 #53
0
class GuiProjectDetailsContents(QWidget):

    C_TITLE = 0
    C_WORDS = 1
    C_PAGES = 2
    C_PAGE = 3
    C_PROG = 4

    def __init__(self, theParent, theProject):
        QWidget.__init__(self, theParent)

        self.mainConf = nw.CONFIG
        self.theParent = theParent
        self.theProject = theProject
        self.theTheme = theParent.theTheme
        self.theIndex = theParent.theIndex
        self.optState = theProject.optState

        # Internal
        self._theToC = []

        iPx = self.theTheme.baseIconSize
        hPx = self.mainConf.pxInt(12)
        vPx = self.mainConf.pxInt(4)

        # Contents Tree
        # =============

        self.tocTree = QTreeWidget()
        self.tocTree.setIconSize(QSize(iPx, iPx))
        self.tocTree.setIndentation(0)
        self.tocTree.setColumnCount(6)
        self.tocTree.setSelectionMode(QAbstractItemView.NoSelection)
        self.tocTree.setHeaderLabels(
            ["Title", "Words", "Pages", "Page", "Progress", ""])

        treeHeadItem = self.tocTree.headerItem()
        treeHeadItem.setTextAlignment(self.C_WORDS, Qt.AlignRight)
        treeHeadItem.setTextAlignment(self.C_PAGES, Qt.AlignRight)
        treeHeadItem.setTextAlignment(self.C_PAGE, Qt.AlignRight)
        treeHeadItem.setTextAlignment(self.C_PROG, Qt.AlignRight)

        treeHeader = self.tocTree.header()
        treeHeader.setStretchLastSection(True)
        treeHeader.setMinimumSectionSize(hPx)

        wCol0 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol0", 200))
        wCol1 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol1", 60))
        wCol2 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol2", 60))
        wCol3 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol3", 60))
        wCol4 = self.mainConf.pxInt(
            self.optState.getInt("GuiProjectDetails", "widthCol4", 90))

        self.tocTree.setColumnWidth(0, wCol0)
        self.tocTree.setColumnWidth(1, wCol1)
        self.tocTree.setColumnWidth(2, wCol2)
        self.tocTree.setColumnWidth(3, wCol3)
        self.tocTree.setColumnWidth(4, wCol4)
        self.tocTree.setColumnWidth(5, hPx)

        # Options
        # =======

        wordsPerPage = self.optState.getInt("GuiProjectDetails",
                                            "wordsPerPage", 350)
        countFrom = self.optState.getInt("GuiProjectDetails", "countFrom", 1)
        clearDouble = self.optState.getInt("GuiProjectDetails", "clearDouble",
                                           True)

        wordsHelp = (
            "Typical word count for a 5 by 8 inch book page with 11 pt font is 350."
        )
        offsetHelp = ("Start counting page numbers from this page.")
        dblHelp = (
            "Assume a new chapter or partition always start on an odd numbered page."
        )

        self.wpLabel = QLabel("Words per page")
        self.wpLabel.setToolTip(wordsHelp)

        self.wpValue = QSpinBox()
        self.wpValue.setMinimum(10)
        self.wpValue.setMaximum(1000)
        self.wpValue.setSingleStep(10)
        self.wpValue.setValue(wordsPerPage)
        self.wpValue.setToolTip(wordsHelp)
        self.wpValue.valueChanged.connect(self._populateTree)

        self.poLabel = QLabel("Count pages from")
        self.poLabel.setToolTip(offsetHelp)

        self.poValue = QSpinBox()
        self.poValue.setMinimum(1)
        self.poValue.setMaximum(9999)
        self.poValue.setSingleStep(1)
        self.poValue.setValue(countFrom)
        self.poValue.setToolTip(offsetHelp)
        self.poValue.valueChanged.connect(self._populateTree)

        self.dblLabel = QLabel("Clear double pages")
        self.dblLabel.setToolTip(dblHelp)

        self.dblValue = QSwitch(self, 2 * iPx, iPx)
        self.dblValue.setChecked(clearDouble)
        self.dblValue.setToolTip(dblHelp)
        self.dblValue.clicked.connect(self._populateTree)

        self.optionsBox = QGridLayout()
        self.optionsBox.addWidget(self.wpLabel, 0, 0)
        self.optionsBox.addWidget(self.wpValue, 0, 1)
        self.optionsBox.addWidget(self.dblLabel, 0, 3)
        self.optionsBox.addWidget(self.dblValue, 0, 4)
        self.optionsBox.addWidget(self.poLabel, 1, 0)
        self.optionsBox.addWidget(self.poValue, 1, 1)
        self.optionsBox.setHorizontalSpacing(hPx)
        self.optionsBox.setVerticalSpacing(vPx)
        self.optionsBox.setColumnStretch(2, 1)

        # Assemble
        # ========

        self.outerBox = QVBoxLayout()
        self.outerBox.addWidget(QLabel("<b>Table of Contents</b>"))
        self.outerBox.addWidget(self.tocTree)
        self.outerBox.addLayout(self.optionsBox)

        self.setLayout(self.outerBox)

        self._prepareData()
        self._populateTree()

        return

    def getColumnSizes(self):
        """Return the column widths for the tree columns.
        """
        retVals = [
            self.tocTree.columnWidth(0),
            self.tocTree.columnWidth(1),
            self.tocTree.columnWidth(2),
            self.tocTree.columnWidth(3),
            self.tocTree.columnWidth(4),
        ]
        return retVals

    ##
    #  Internal Functions
    ##

    def _prepareData(self):
        """Extract the data for the tree.
        """
        self._theToC = []
        self._theToC = self.theIndex.getTableOfContents(2)
        self._theToC.append(("", 0, "END", 0))
        return

    ##
    #  Slots
    ##

    def _populateTree(self):
        """Set the content of the chapter/page tree.
        """
        dblPages = self.dblValue.isChecked()
        wpPage = self.wpValue.value()
        fstPage = self.poValue.value() - 1

        pTotal = 0
        tPages = 1

        theList = []
        for _, tLevel, tTitle, wCount in self._theToC:
            pCount = math.ceil(wCount / wpPage)
            if dblPages:
                pCount += pCount % 2

            pTotal += pCount
            theList.append((tLevel, tTitle, wCount, pCount))

        pMax = pTotal - fstPage

        self.tocTree.clear()
        for tLevel, tTitle, wCount, pCount in theList:
            newItem = QTreeWidgetItem()

            if tPages <= fstPage:
                progPage = numberToRoman(tPages, True)
                progText = ""
            else:
                cPage = tPages - fstPage
                pgProg = 100.0 * (cPage - 1) / pMax if pMax > 0 else 0.0
                progPage = f"{cPage:n}"
                progText = f"{pgProg:.1f}{nwUnicode.U_THSP}%"

            newItem.setIcon(self.C_TITLE,
                            self.theTheme.getIcon("doc_h%d" % tLevel))
            newItem.setText(self.C_TITLE, tTitle)
            newItem.setText(self.C_WORDS, f"{wCount:n}")
            newItem.setText(self.C_PAGES, f"{pCount:n}")
            newItem.setText(self.C_PAGE, progPage)
            newItem.setText(self.C_PROG, progText)

            newItem.setTextAlignment(self.C_WORDS, Qt.AlignRight)
            newItem.setTextAlignment(self.C_PAGES, Qt.AlignRight)
            newItem.setTextAlignment(self.C_PAGE, Qt.AlignRight)
            newItem.setTextAlignment(self.C_PROG, Qt.AlignRight)

            # Make pages and titles/partitions stand out
            if tLevel < 2:
                bFont = newItem.font(self.C_TITLE)
                if tLevel == 0:
                    bFont.setItalic(True)
                else:
                    bFont.setBold(True)
                    bFont.setUnderline(True)
                newItem.setFont(self.C_TITLE, bFont)

            tPages += pCount

            self.tocTree.addTopLevelItem(newItem)

        return
예제 #54
0
    def __init__(self, parent: 'ElectrumWindow', config: 'SimpleConfig'):
        WindowModalDialog.__init__(self, parent, _('Preferences'))
        self.config = config
        self.window = parent
        self.need_restart = False
        self.fx = self.window.fx
        self.wallet = self.window.wallet

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # lightning
        lightning_widgets = []
        help_persist = _(
            """If this option is checked, Electrum will persist as a daemon after
you close all your wallet windows. Your local watchtower will keep
running, and it will protect your channels even if your wallet is not
open. For this to work, your computer needs to be online regularly.""")
        persist_cb = QCheckBox(_("Run as daemon after the GUI is closed"))
        persist_cb.setToolTip(help_persist)
        persist_cb.setChecked(bool(self.config.get('persist_daemon', False)))

        def on_persist_checked(x):
            self.config.set_key('persist_daemon', bool(x))

        persist_cb.stateChanged.connect(on_persist_checked)
        lightning_widgets.append((persist_cb, None))

        help_remote_wt = _(
            """To use a remote watchtower, enter the corresponding URL here""")
        remote_wt_cb = QCheckBox(_("Use a remote watchtower"))
        remote_wt_cb.setToolTip(help_remote_wt)
        remote_wt_cb.setChecked(bool(self.config.get('use_watchtower', False)))

        def on_remote_wt_checked(x):
            self.config.set_key('use_watchtower', bool(x))
            self.watchtower_url_e.setEnabled(bool(x))

        remote_wt_cb.stateChanged.connect(on_remote_wt_checked)
        watchtower_url = self.config.get('watchtower_url')
        self.watchtower_url_e = QLineEdit(watchtower_url)
        self.watchtower_url_e.setEnabled(
            self.config.get('use_watchtower', False))

        def on_wt_url():
            url = self.watchtower_url_e.text() or None
            watchtower_url = self.config.set_key('watchtower_url', url)

        self.watchtower_url_e.editingFinished.connect(on_wt_url)
        lightning_widgets.append((remote_wt_cb, self.watchtower_url_e))

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

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

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

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

        self.check_ssl_config()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        vbox.addWidget(tabs)
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CloseButton(self)))
        self.setLayout(vbox)
예제 #55
0
class MyWinMap(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.initWidget()  # 初始化组件
        self.initLayout()  # 初始化布局
        self.initWindow(800, 700)  # 初始化窗口
        self.initMap()  # 初始化地图
        self.initSerial(STR_COM)  # 初始化串口
        self.show()

    '''----------------------------------------------'''

    def initWidget(self):
        '''地图显示控件'''
        self.gscene_map = QGraphicsScene()
        self.gview_map = QGraphicsView(self.gscene_map)
        '''设定节点及阈值区'''
        self.chb_mark = QCheckBox('进入标记模式')
        self.chb_mark.toggle()
        self.sp_thre = QSpinBox()
        self.sp_thre.setRange(0, 10)  # 设置上界和下界
        '''数据显示区'''

    def initLayout(self):
        '''箱组声明'''
        self.gpbx_map = QGroupBox('地图', self)
        self.gpbx_mark_and_thre = QGroupBox('设定节点及阈值', self)
        self.gpbx_data = QGroupBox('数据', self)
        '''箱组布局类型'''
        self.lot_v_map = QVBoxLayout()
        self.lot_g_mark_and_thre = QGridLayout()
        self.lot_g_data = QGridLayout()
        self.lot_v_all = QVBoxLayout()
        '''箱组map布局设置'''
        self.lot_v_map.addWidget(self.gview_map, alignment=Qt.AlignHCenter)
        self.gpbx_map.setLayout(self.lot_v_map)
        '''箱组mark and thre布局设置'''
        #  _ __ __ _ _
        # |_|__|__|_|_|
        self.lot_g_mark_and_thre.addWidget(self.chb_mark, 0, 1, 1, 1,
                                           Qt.AlignCenter)
        self.lot_g_mark_and_thre.addWidget(self.sp_thre, 0, 3, 1, 1,
                                           Qt.AlignCenter)
        self.lot_g_mark_and_thre.setColumnStretch(0, 1)
        self.lot_g_mark_and_thre.setColumnStretch(1, 2)
        self.lot_g_mark_and_thre.setColumnStretch(2, 2)
        self.lot_g_mark_and_thre.setColumnStretch(3, 1)
        self.lot_g_mark_and_thre.setColumnStretch(4, 1)
        self.gpbx_mark_and_thre.setLayout(self.lot_g_mark_and_thre)
        '''箱组data布局设置'''
        for i in range(NODE_NUM):
            # 数据框
            le_temp = QLineEdit('*')
            le_temp.setReadOnly(True)
            le_temp.setAlignment(Qt.AlignHCenter)
            self.lot_g_data.addWidget(le_temp, 0, i)
        for i in range(NODE_NUM):
            # 节点号框
            lb_temp = QLabel('<div style="color:#d648ac;"><b>' + str(i + 1) +
                             '</b></div>')
            lb_temp.setAlignment(Qt.AlignCenter)
            self.lot_g_data.addWidget(lb_temp, 1, i)
        self.gpbx_data.setLayout(self.lot_g_data)
        '''总布局设置'''
        self.lot_v_all.addWidget(self.gpbx_map)
        self.lot_v_all.addWidget(self.gpbx_mark_and_thre)
        self.lot_v_all.addWidget(self.gpbx_data)
        self.setLayout(self.lot_v_all)

    def initWindow(self, w, h):
        '''获取屏幕居中点信息'''
        center_point = QDesktopWidget().availableGeometry().center()
        self.center_point_x = center_point.x()
        self.center_point_y = center_point.y()
        '''窗口初始化'''
        self.setGeometry(0, 0, w, h)
        self.max_w = (self.center_point_x - 10) * 2  # 窗口允许的最大宽
        self.max_h = (self.center_point_y - 20) * 2  # 窗口允许的最大高
        self.setMaximumSize(self.max_w, self.max_h)  # 防止窗口尺寸过大
        self.moveToCenter(w, h)
        self.win_name = GUI_NAME  # 窗口标题
        self.setWindowTitle(self.win_name)

    def moveToCenter(self, w, h):
        '''窗口过大则先进行调整'''
        if (w > self.max_w) or (h > self.max_h):
            self.adjustSize()
        '''窗口居中'''
        topleft_point_x = (int)(self.center_point_x - w / 2)
        topleft_point_y = (int)(self.center_point_y - h / 2)
        self.move(topleft_point_x, topleft_point_y)

    def initMap(self):
        try:
            # 地图加载部分
            self.pixmap_map = QPixmap('平面图_走廊_房间.png')
            if self.pixmap_map.isNull():  # 空图处理
                self.initMapErrorHandle()
                return
            self.pixmap_map = self.pixmap_map.scaled(700, 600,
                                                     Qt.KeepAspectRatio,
                                                     Qt.SmoothTransformation)
            self.gscene_map.addPixmap(self.pixmap_map)
            # 固定边界以禁用滑动条
            self.f_pixmap_map_x = float(self.pixmap_map.rect().x())
            self.f_pixmap_map_y = float(self.pixmap_map.rect().y())
            self.f_pixmap_map_w = float(self.pixmap_map.rect().width())
            self.f_pixmap_map_h = float(self.pixmap_map.rect().height())
            self.gview_map.setSceneRect(self.f_pixmap_map_x,
                                        self.f_pixmap_map_y,
                                        self.f_pixmap_map_w,
                                        self.f_pixmap_map_h)
            # 地图加载成功的标志位
            self.b_map_loaded = True
            # 复选框信号连接
            self.chb_mark.stateChanged.connect(self.updateMap)
            # view视图鼠标响应
            self.gview_map.mousePressEvent = self.markMap
            w = self.width()
            h = self.height()
            self.moveToCenter(w, h)
            # 节点相关部分
            self.node_list = []  # 存储节点的坐标及邻域信息
        except Exception as e:
            print(e)
            self.initMapErrorHandle()

    def initMapErrorHandle(self):
        self.b_map_loaded = False
        self.text_warning = '<div style="font:20px;\
                            color:red;\
                            text-align:center;">\
                            <b>⚠ WARNING ⚠</b><br /><br />\
                            地图加载出错啦<br /><br />\
                            ::>﹏<::\
                            </div>'

        self.gtext_warning = QGraphicsTextItem()
        self.gtext_warning.setHtml(self.text_warning)
        self.gscene_map.addItem(self.gtext_warning)

    def markMap(self, event):
        if self.b_map_loaded:
            if self.chb_mark.isChecked():
                self.node_pos = self.gview_map.mapToScene(event.pos())
                # 左键创建标记
                if event.button() == Qt.LeftButton:
                    if len(self.node_list) < NODE_NUM:
                        _is_near_init = False  # 标记模式下,初始化无近邻rssi
                        _append_iter = [self.node_pos,
                                        _is_near_init]  # 用list存储复合信息
                        self.node_list.append(_append_iter)
                        # 绘图部分
                        self.drawNode(len(self.node_list), _append_iter[0],
                                      _append_iter[1])
                # 右键回退标记
                if event.button() == Qt.RightButton:
                    if len(self.node_list) > 0:
                        self.node_list.pop()
                        self.gscene_map.clear()  # 清空scene
                        self.gscene_map.addPixmap(self.pixmap_map)  # 重新加载地图
                        for i in range(len(self.node_list)):
                            self.drawNode(i + 1, self.node_list[i][0],
                                          self.node_list[i][1])

    def updateMap(self):
        if self.b_map_loaded:
            if not self.chb_mark.isChecked():
                self.timer_map_refresh = QTimer(self)  # 设定地图刷新定时器
                self.timer_map_refresh.timeout.connect(self.redrawMap)
                self.timer_map_refresh.start(REFRESH_TIME_MS)  # 设置刷新时间为100毫秒

    def redrawMap(self):
        self.gscene_map.clear()  # 清空scene
        self.gscene_map.addPixmap(self.pixmap_map)  # 重新加载地图
        for i in range(len(self.node_list)):
            self.drawNode(i + 1, self.node_list[i][0], self.node_list[i][1])

    '''----------------------------------------------'''

    def drawNode(self, index, node_pos, is_near):
        # 样式设置
        node_draw_r = 15
        node_draw_x = node_pos.x() - node_draw_r
        node_draw_y = node_pos.y() - node_draw_r
        # node_draw_pos = QPointF(node_draw_x, node_draw_y)
        node_draw_pen = QPen(QColor(204, 47, 105), 3, Qt.SolidLine)
        node_draw_brush = QBrush(QColor(255, 110, 151), Qt.SolidPattern)
        # 正式画圆
        self.gellipse_node = self.gscene_map.addEllipse(
            node_draw_x, node_draw_y, 2 * node_draw_r, 2 * node_draw_r,
            node_draw_pen, node_draw_brush)
        # 索引号
        self.text_index = '<div style=\"font:26px;color:black;font-weight:900;\">' + \
            str(index) + '</div>'
        self.gtext_index = QGraphicsTextItem()
        self.gtext_index.setHtml(self.text_index)
        self.gtext_index.setParentItem(self.gellipse_node)
        self.gtext_index.setPos(node_draw_x + 4, node_draw_y - 2)
        if is_near:  # 若附近rssi判断有效
            node_draw_r = 20
            node_draw_x = node_pos.x() - node_draw_r
            node_draw_y = node_pos.y() - node_draw_r
            node_draw_pen = QPen(QColor(245, 229, 143), 10, Qt.DashLine)
            self.gscene_map.addEllipse(node_draw_x, node_draw_y,
                                       2 * node_draw_r, 2 * node_draw_r,
                                       node_draw_pen)

    '''----------------------------------------------'''

    def initSerial(self, str_com):
        self.data_zigbee_list = []
        # 初始化串口
        self.ser_data = QSerialPort(STR_COM,
                                    baudRate=QSerialPort.Baud115200,
                                    readyRead=self.receive)
        self.ser_data.open(QIODevice.ReadWrite)
        if self.ser_data.isOpen():
            print('串口开启成功!')
        else:
            print('串口打开失败……')

    @pyqtSlot()
    def receive(self):
        _data = self.ser_data.readLine().data()  # 读取数据
        if _data != b'':
            self.data_zigbee_list = []  # 清空数据
            self.data = _data[0:2 * NODE_NUM].decode("gbk")
            # 存储数据
            for i in range(len(self.data) // 2):
                # 每两位存储,用tuple存储,只读
                data_iter = (self.data[2 * i:2 * i + 1],
                             self.data[2 * i + 1:2 * i + 2])
                self.data_zigbee_list.append(data_iter)
            # print('data_zigbee_list:', self.data_zigbee_list)
            self.updateSerial()
        else:
            print('串口接收内容为空!')

    def updateSerial(self):
        if not self.chb_mark.isChecked():
            for i in range(NODE_NUM):
                if i < len(self.node_list):
                    value_update = self.data_zigbee_list[i][1]
                    # 更新节点列表
                    self.node_list[i][1] = (True
                                            if value_update == '1' else False)
                else:
                    value_update = '*'
                self.lot_g_data.itemAt(i).widget().setText(value_update)
예제 #56
0
class WeatherStationDownloader(QMainWindow):
    """
    Widget that allows the user to browse and select ECCC climate stations.
    """
    sig_download_process_ended = QSignal()
    ConsoleSignal = QSignal(str)
    staListSignal = QSignal(list)

    PROV_NAME = [x[0].title() for x in PROV_NAME_ABB]
    PROV_ABB = [x[1] for x in PROV_NAME_ABB]

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

        self.stn_finder_worker = WeatherStationFinder()
        self.stn_finder_worker.sig_load_database_finished.connect(
            self.receive_load_database)
        self.stn_finder_thread = QThread()
        self.stn_finder_worker.moveToThread(self.stn_finder_thread)
        self._database_isloading = False

        self.station_table = WeatherSationView()
        self.waitspinnerbar = WaitSpinnerBar()
        self.stn_finder_worker.sig_progress_msg.connect(
            self.waitspinnerbar.set_label)

        self.__initUI__()
        self._restore_window_geometry()

        # Setup the raw data downloader.
        self._dwnld_inprogress = False
        self._dwnld_stations_list = []
        self.dwnld_thread = QThread()
        self.dwnld_worker = RawDataDownloader()
        self.dwnld_worker.moveToThread(self.dwnld_thread)

        self.dwnld_worker.sig_download_finished.connect(
            self.process_station_data)
        self.dwnld_worker.sig_update_pbar.connect(self.progressbar.setValue)

        self.start_load_database()

    def __initUI__(self):
        self.setWindowTitle('Download Weather Data')
        self.setWindowIcon(get_icon('master'))
        self.setWindowFlags(Qt.Window)

        now = datetime.now()

        # Setup the proximity filter group.
        self.lat_spinBox = QDoubleSpinBox()
        self.lat_spinBox.setAlignment(Qt.AlignCenter)
        self.lat_spinBox.setSingleStep(0.1)
        self.lat_spinBox.setDecimals(3)
        self.lat_spinBox.setValue(CONF.get('download_data', 'latitude', 0))
        self.lat_spinBox.setMinimum(0)
        self.lat_spinBox.setMaximum(180)
        self.lat_spinBox.setSuffix(u' °')
        self.lat_spinBox.valueChanged.connect(self.proximity_grpbox_toggled)

        self.lon_spinBox = QDoubleSpinBox()
        self.lon_spinBox.setAlignment(Qt.AlignCenter)
        self.lon_spinBox.setSingleStep(0.1)
        self.lon_spinBox.setDecimals(3)
        self.lon_spinBox.setValue(CONF.get('download_data', 'longitude', 0))
        self.lon_spinBox.setMinimum(0)
        self.lon_spinBox.setMaximum(180)
        self.lon_spinBox.setSuffix(u' °')
        self.lon_spinBox.valueChanged.connect(self.proximity_grpbox_toggled)

        self.radius_SpinBox = QComboBox()
        self.radius_SpinBox.addItems(['25 km', '50 km', '100 km', '200 km'])
        self.radius_SpinBox.setCurrentIndex(
            CONF.get('download_data', 'radius_index', 0))
        self.radius_SpinBox.currentIndexChanged.connect(
            self.search_filters_changed)

        self.prox_grpbox = QGroupBox("Proximity Filter")
        self.prox_grpbox.setCheckable(True)
        self.prox_grpbox.setChecked(
            CONF.get('download_data', 'proximity_filter', False))
        self.prox_grpbox.toggled.connect(self.proximity_grpbox_toggled)

        prox_search_grid = QGridLayout(self.prox_grpbox)
        prox_search_grid.addWidget(QLabel('Latitude:'), 0, 0)
        prox_search_grid.addWidget(self.lat_spinBox, 0, 1)
        prox_search_grid.addWidget(QLabel('North'), 0, 2)
        prox_search_grid.addWidget(QLabel('Longitude:'), 1, 0)
        prox_search_grid.addWidget(self.lon_spinBox, 1, 1)
        prox_search_grid.addWidget(QLabel('West'), 1, 2)
        prox_search_grid.addWidget(QLabel('Search Radius:'), 2, 0)
        prox_search_grid.addWidget(self.radius_SpinBox, 2, 1)
        prox_search_grid.setColumnStretch(0, 100)
        prox_search_grid.setRowStretch(3, 100)

        # ---- Province filter
        self.prov_widg = QComboBox()
        self.prov_widg.addItems(['All'] + self.PROV_NAME)
        self.prov_widg.setCurrentIndex(
            CONF.get('download_data', 'province_index', 0))
        self.prov_widg.currentIndexChanged.connect(self.search_filters_changed)

        prov_grpbox = QGroupBox()
        prov_layout = QGridLayout(prov_grpbox)
        prov_layout.addWidget(QLabel('Province:'), 0, 0)
        prov_layout.addWidget(self.prov_widg, 0, 1)
        prov_layout.setColumnStretch(0, 1)
        prov_layout.setRowStretch(1, 1)

        # ---- Data availability filter

        # Number of years with data
        self.nbrYear = QSpinBox()
        self.nbrYear.setAlignment(Qt.AlignCenter)
        self.nbrYear.setSingleStep(1)
        self.nbrYear.setMinimum(0)
        self.nbrYear.setValue(CONF.get('download_data', 'min_nbr_of_years', 3))
        self.nbrYear.valueChanged.connect(self.search_filters_changed)

        subgrid1 = QGridLayout()
        subgrid1.setContentsMargins(0, 0, 0, 0)
        subgrid1.addWidget(QLabel('for at least'), 0, 0)
        subgrid1.addWidget(self.nbrYear, 0, 1)
        subgrid1.addWidget(QLabel('year(s)'), 0, 2)
        subgrid1.setColumnStretch(3, 100)
        subgrid1.setHorizontalSpacing(5)

        # Year range
        self.minYear = QSpinBox()
        self.minYear.setAlignment(Qt.AlignCenter)
        self.minYear.setSingleStep(1)
        self.minYear.setMinimum(1840)
        self.minYear.setMaximum(now.year)
        self.minYear.setValue(
            CONF.get('download_data', 'year_range_left_bound', 1840))
        self.minYear.valueChanged.connect(self.minYear_changed)

        label_and = QLabel('and')
        label_and.setAlignment(Qt.AlignCenter)

        self.maxYear = QSpinBox()
        self.maxYear.setAlignment(Qt.AlignCenter)
        self.maxYear.setSingleStep(1)
        self.maxYear.setMinimum(1840)
        self.maxYear.setMaximum(now.year)
        self.maxYear.setValue(
            CONF.get('download_data', 'year_range_right_bound', now.year))

        self.maxYear.valueChanged.connect(self.maxYear_changed)

        subgrid2 = QGridLayout()
        subgrid2.addWidget(QLabel('between'), 0, 0)
        subgrid2.addWidget(self.minYear, 0, 1)
        subgrid2.addWidget(label_and, 0, 2)
        subgrid2.addWidget(self.maxYear, 0, 3)
        subgrid2.setContentsMargins(0, 0, 0, 0)
        subgrid2.setColumnStretch(4, 100)
        subgrid2.setHorizontalSpacing(5)

        # Subgridgrid assembly
        self.year_widg = QGroupBox("Data Availability filter")
        self.year_widg.setCheckable(True)
        self.year_widg.setChecked(
            CONF.get('download_data', 'data_availability_filter', False))
        self.year_widg.toggled.connect(self.search_filters_changed)

        grid = QGridLayout(self.year_widg)
        grid.setRowMinimumHeight(0, 10)
        grid.addWidget(QLabel('Search for stations with data available'), 1, 0)
        grid.addLayout(subgrid1, 2, 0)
        grid.addLayout(subgrid2, 3, 0)
        grid.setRowStretch(4, 100)
        grid.setVerticalSpacing(8)

        # Setup the toolbar.
        self.btn_addSta = QPushButton('Add')
        self.btn_addSta.setIcon(get_icon('add2list'))
        self.btn_addSta.setIconSize(get_iconsize('small'))
        self.btn_addSta.setToolTip(
            'Add selected stations to the current list of weather stations.')
        self.btn_addSta.clicked.connect(self.btn_addSta_isClicked)
        self.btn_addSta.hide()

        btn_save = QPushButton('Save')
        btn_save.setToolTip('Save the list of selected stations to a file.')
        btn_save.clicked.connect(self.btn_save_isClicked)
        btn_save.hide()

        self.btn_download = QPushButton('Download')
        self.btn_download.clicked.connect(self.start_download_process)

        btn_close = QPushButton('Close')
        btn_close.clicked.connect(self.close)

        self.btn_fetch = btn_fetch = QPushButton('Refresh')
        btn_fetch.setToolTip(
            "Update the list of climate stations by fetching it from "
            "the ECCC remote location.")
        btn_fetch.clicked.connect(self.btn_fetch_isClicked)

        toolbar_widg = QWidget()
        toolbar_grid = QGridLayout(toolbar_widg)
        toolbar_grid.addWidget(self.btn_addSta, 1, 1)
        toolbar_grid.addWidget(btn_save, 1, 2)
        toolbar_grid.addWidget(btn_fetch, 1, 3)
        toolbar_grid.addWidget(self.btn_download, 1, 4)
        toolbar_grid.addWidget(btn_close, 1, 5)
        toolbar_grid.setColumnStretch(0, 100)
        toolbar_grid.setContentsMargins(0, 10, 0, 0)

        # Setup the left panel.
        self.left_panel = QFrame()
        left_panel_grid = QGridLayout(self.left_panel)
        left_panel_grid.setContentsMargins(0, 0, 0, 0)
        left_panel_grid.addWidget(QLabel('Search Criteria'), 0, 0)
        left_panel_grid.addWidget(prov_grpbox, 1, 0)
        left_panel_grid.addWidget(self.prox_grpbox, 2, 0)
        left_panel_grid.addWidget(self.year_widg, 3, 0)
        left_panel_grid.setRowStretch(3, 100)

        # Setup the progress bar.
        self.progressbar = QProgressBar()
        self.progressbar.setValue(0)
        self.progressbar.hide()

        # Setup the central widget.
        main_widget = QWidget()
        main_layout = QGridLayout(main_widget)
        main_layout.addWidget(self.left_panel, 0, 0)
        main_layout.addWidget(self.station_table, 0, 1)
        main_layout.addWidget(self.waitspinnerbar, 0, 1)
        main_layout.addWidget(toolbar_widg, 1, 0, 1, 2)
        main_layout.addWidget(self.progressbar, 2, 0, 1, 2)
        main_layout.setColumnStretch(1, 100)

        self.setCentralWidget(main_widget)

    @property
    def stationlist(self):
        return self.station_table.get_stationlist()

    @property
    def search_by(self):
        return ['proximity', 'province'][self.tab_widg.currentIndex()]

    @property
    def prov(self):
        if self.prov_widg.currentIndex() == 0:
            return self.PROV_NAME
        else:
            return [self.PROV_NAME[self.prov_widg.currentIndex() - 1]]

    @property
    def lat(self):
        return self.lat_spinBox.value()

    def set_lat(self, x, silent=True):
        if silent:
            self.lat_spinBox.blockSignals(True)
        self.lat_spinBox.setValue(x)
        self.lat_spinBox.blockSignals(False)
        self.proximity_grpbox_toggled()

    @property
    def lon(self):
        return self.lon_spinBox.value()

    def set_lon(self, x, silent=True):
        if silent:
            self.lon_spinBox.blockSignals(True)
        self.lon_spinBox.setValue(x)
        self.lon_spinBox.blockSignals(False)
        self.proximity_grpbox_toggled()

    @property
    def rad(self):
        return int(self.radius_SpinBox.currentText()[:-3])

    @property
    def prox(self):
        if self.prox_grpbox.isChecked():
            return (self.lat, -self.lon, self.rad)
        else:
            return None

    @property
    def year_min(self):
        return int(self.minYear.value())

    def set_yearmin(self, x, silent=True):
        if silent:
            self.minYear.blockSignals(True)
        self.minYear.setValue(x)
        self.minYear.blockSignals(False)

    @property
    def year_max(self):
        return int(self.maxYear.value())

    def set_yearmax(self, x, silent=True):
        if silent:
            self.maxYear.blockSignals(True)
        self.maxYear.setValue(x)
        self.maxYear.blockSignals(False)

    @property
    def nbr_of_years(self):
        return int(self.nbrYear.value())

    def set_yearnbr(self, x, silent=True):
        if silent:
            self.nbrYear.blockSignals(True)
        self.nbrYear.setValue(x)
        self.nbrYear.blockSignals(False)

    # ---- Load Station Database
    def start_load_database(self, force_fetch=False):
        """Start the process of loading the climate station database."""
        if self._database_isloading is False:
            self._database_isloading = True

            self.station_table.clear()
            self.waitspinnerbar.show()

            # Start the downloading process.
            if force_fetch:
                self.stn_finder_thread.started.connect(
                    self.stn_finder_worker.fetch_database)
            else:
                self.stn_finder_thread.started.connect(
                    self.stn_finder_worker.load_database)
            self.stn_finder_thread.start()

    @QSlot()
    def receive_load_database(self):
        """Handles when loading the database is finished."""
        # Disconnect the thread.
        self.stn_finder_thread.started.disconnect()

        # Quit the thread.
        self.stn_finder_thread.quit()
        waittime = 0
        while self.stn_finder_thread.isRunning():
            sleep(0.1)
            waittime += 0.1
            if waittime > 15:
                print("Unable to quit the thread.")
                break
        # Force an update of the GUI.
        self.proximity_grpbox_toggled()
        if self.stn_finder_worker.data is None:
            self.waitspinnerbar.show_warning_icon()
        else:
            self.waitspinnerbar.hide()
        self._database_isloading = False

    # ---- GUI handlers
    def minYear_changed(self):
        min_yr = min_yr = max(self.minYear.value(), 1840)

        now = datetime.now()
        max_yr = now.year

        self.maxYear.setRange(min_yr, max_yr)
        self.search_filters_changed()

    def maxYear_changed(self):
        min_yr = 1840

        now = datetime.now()
        max_yr = min(self.maxYear.value(), now.year)

        self.minYear.setRange(min_yr, max_yr)
        self.search_filters_changed()

    # ---- Toolbar Buttons Handlers
    def btn_save_isClicked(self):
        ddir = os.path.join(os.getcwd(), 'weather_station_list.csv')
        filename, ftype = QFileDialog().getSaveFileName(
            self, 'Save normals', ddir, '*.csv;;*.xlsx;;*.xls')
        self.station_table.save_stationlist(filename)

    def btn_addSta_isClicked(self):
        rows = self.station_table.get_checked_rows()
        if len(rows) > 0:
            staList = self.station_table.get_content4rows(rows)
            self.staListSignal.emit(staList)
            print('Selected stations sent to list')
        else:
            print('No station currently selected')

    def btn_fetch_isClicked(self):
        """Handles when the button fetch is clicked."""
        self.start_load_database(force_fetch=True)

    # ---- Search Filters Handlers
    def proximity_grpbox_toggled(self):
        """
        Set the values for the reference geo coordinates that are used in the
        WeatherSationView to calculate the proximity values and forces a
        refresh of the content of the table.
        """
        if self.prox_grpbox.isChecked():
            self.station_table.set_geocoord((self.lat, -self.lon))
        else:
            self.station_table.set_geocoord(None)
        self.search_filters_changed()

    def search_filters_changed(self):
        """
        Search for weather stations with the current filter values and forces
        an update of the station table content.
        """
        if self.stn_finder_worker.data is not None:
            stnlist = self.stn_finder_worker.get_stationlist(
                prov=self.prov,
                prox=self.prox,
                yrange=((self.year_min, self.year_max, self.nbr_of_years)
                        if self.year_widg.isChecked() else None))
            self.station_table.populate_table(stnlist)

    # ---- Download weather data
    def start_download_process(self):
        """Start the downloading process of raw weather data files."""
        if self._dwnld_inprogress is True:
            self.stop_download_process()
            return

        # Grab the info of the weather stations that are selected.
        rows = self.station_table.get_checked_rows()
        self._dwnld_stations_list = self.station_table.get_content4rows(rows)
        if len(self._dwnld_stations_list) == 0:
            QMessageBox.warning(self, 'Warning',
                                "No weather station currently selected.",
                                QMessageBox.Ok)
            return

        # Update the UI.
        self.progressbar.show()
        self.btn_download.setText("Cancel")
        self.left_panel.setEnabled(False)
        self.station_table.setEnabled(False)
        self.btn_fetch.setEnabled(False)

        # Set thread working directory.
        self.dwnld_worker.dirname = self.workdir

        # Start downloading data.
        self._dwnld_inprogress = True
        self.download_next_station()

    def stop_download_process(self):
        """Stop the downloading process."""
        print('Stopping the download process...')
        self.dwnld_worker.stop_download()
        self._dwnld_stations_list = []
        self.btn_download.setEnabled(False)

        self.wait_for_thread_to_quit()
        self.btn_download.setEnabled(True)
        self.btn_download.setText("Download")
        self.left_panel.setEnabled(True)
        self.station_table.setEnabled(True)
        self.btn_fetch.setEnabled(True)

        self._dwnld_inprogress = False
        self.sig_download_process_ended.emit()
        print('Download process stopped.')

    def download_next_station(self):
        self.wait_for_thread_to_quit()
        try:
            dwnld_station = self._dwnld_stations_list.pop(0)
        except IndexError:
            # There is no more data to download.
            print('Raw weather data downloaded for all selected stations.')
            self.btn_download.setText("Download")
            self.progressbar.hide()
            self.left_panel.setEnabled(True)
            self.station_table.setEnabled(True)
            self.btn_fetch.setEnabled(True)
            self._dwnld_inprogress = False
            self.sig_download_process_ended.emit()
            return

        # Set worker attributes.
        self.dwnld_worker.StaName = dwnld_station[0]
        self.dwnld_worker.stationID = dwnld_station[1]
        self.dwnld_worker.yr_start = dwnld_station[2]
        self.dwnld_worker.yr_end = dwnld_station[3]
        self.dwnld_worker.climateID = dwnld_station[5]

        # Highlight the row of the next station to download data from.
        self.station_table.selectRow(
            self.station_table.get_row_from_climateid(dwnld_station[5]))

        # Start the downloading process.
        try:
            self.dwnld_thread.started.disconnect(
                self.dwnld_worker.download_data)
        except TypeError:
            # The method self.dwnld_worker.download_data is not connected.
            pass
        finally:
            self.dwnld_thread.started.connect(self.dwnld_worker.download_data)
            self.dwnld_thread.start()

    def wait_for_thread_to_quit(self):
        self.dwnld_thread.quit()
        waittime = 0
        while self.dwnld_thread.isRunning():
            print('Waiting for the downloading thread to close')
            sleep(0.1)
            waittime += 0.1
            if waittime > 15:
                print("Unable to close the weather data dowloader thread.")
                return

    def process_station_data(self, climateid, file_list=None):
        """
        Read, concatenate, and save to csv the raw weather data that were
        just downloaded for the station corresponding to the specified
        climate ID.
        """
        if file_list:
            station_metadata = self.station_table.get_content4rows(
                [self.station_table.get_row_from_climateid(climateid)])[0]
            station_data = read_raw_datafiles(file_list)
            print(
                'Formating and concatenating raw data for station {}.'.format(
                    station_metadata[0]))

            # Define the concatenated filename.
            station_name = (station_metadata[0].replace('\\',
                                                        '_').replace('/', '_'))
            min_year = min(station_data.index).year
            max_year = max(station_data.index).year
            filename = osp.join("%s (%s)_%s-%s.csv" %
                                (station_name, climateid, min_year, max_year))

            # Save the concatenated data to csv.
            data_headers = [
                'Year', 'Month', 'Day', 'Max Temp (°C)', 'Min Temp (°C)',
                'Mean Temp (°C)', 'Total Precip (mm)'
            ]
            fcontent = [['Station Name', station_metadata[0]],
                        ['Province', station_metadata[4]],
                        ['Latitude (dd)', station_metadata[6]],
                        ['Longitude (dd)', station_metadata[7]],
                        ['Elevation (m)', station_metadata[8]],
                        ['Climate Identifier', station_metadata[5]], [],
                        data_headers]
            fcontent = fcontent + station_data[data_headers].values.tolist()

            # Save the data to csv.
            filepath = osp.join(self.dwnld_worker.dirname, filename)
            with open(filepath, 'w', encoding='utf-8') as f:
                writer = csv.writer(f, delimiter=',', lineterminator='\n')
                writer.writerows(fcontent)
        self.download_next_station()

    # ---- Main window settings
    def _restore_window_geometry(self):
        """
        Restore the geometry of this mainwindow from the value saved
        in the config.
        """
        hexstate = CONF.get('download_data', 'window/geometry', None)
        if hexstate:
            hexstate = hexstate_to_qbytearray(hexstate)
            self.restoreGeometry(hexstate)
        else:
            self.resize(1000, 450)

    def _save_window_geometry(self):
        """
        Save the geometry of this mainwindow to the config.
        """
        hexstate = qbytearray_to_hexstate(self.saveGeometry())
        CONF.set('download_data', 'window/geometry', hexstate)

    # ---- Qt overrides
    def closeEvent(self, event):
        self._save_window_geometry()

        # Proximity Filter Options.
        CONF.set('download_data', 'proximity_filter',
                 self.prox_grpbox.isChecked())
        CONF.set('download_data', 'latitude', self.lat)
        CONF.set('download_data', 'longitude', self.lon)
        CONF.set('download_data', 'radius_index',
                 self.radius_SpinBox.currentIndex())
        CONF.set('download_data', 'province_index',
                 self.prov_widg.currentIndex())

        # Data Availability Filter Options.
        CONF.set('download_data', 'data_availability_filter',
                 self.year_widg.isChecked())
        CONF.set('download_data', 'min_nbr_of_years', self.nbrYear.value())
        CONF.set('download_data', 'year_range_left_bound',
                 self.minYear.value())
        CONF.set('download_data', 'year_range_right_bound',
                 self.maxYear.value())
        event.accept()
예제 #57
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.horizontalSliders = SlidersGroup(Qt.Horizontal, "Horizontal")
        self.verticalSliders = SlidersGroup(Qt.Vertical, "Vertical")

        self.stackedWidget = QStackedWidget()
        self.stackedWidget.addWidget(self.horizontalSliders)
        self.stackedWidget.addWidget(self.verticalSliders)

        self.createControls("Controls")

        self.horizontalSliders.valueChanged.connect(self.verticalSliders.setValue)
        self.verticalSliders.valueChanged.connect(self.valueSpinBox.setValue)
        self.valueSpinBox.valueChanged.connect(self.horizontalSliders.setValue)

        layout = QHBoxLayout()
        layout.addWidget(self.controlsGroup)
        layout.addWidget(self.stackedWidget)
        self.setLayout(layout)

        self.minimumSpinBox.setValue(0)
        self.maximumSpinBox.setValue(20)
        self.valueSpinBox.setValue(5)

        self.setWindowTitle("Sliders")

    def createControls(self, title):
        self.controlsGroup = QGroupBox(title)

        minimumLabel = QLabel("Minimum value:")
        maximumLabel = QLabel("Maximum value:")
        valueLabel = QLabel("Current value:")

        invertedAppearance = QCheckBox("Inverted appearance")
        invertedKeyBindings = QCheckBox("Inverted key bindings")

        self.minimumSpinBox = QSpinBox()
        self.minimumSpinBox.setRange(-100, 100)
        self.minimumSpinBox.setSingleStep(1)

        self.maximumSpinBox = QSpinBox()
        self.maximumSpinBox.setRange(-100, 100)
        self.maximumSpinBox.setSingleStep(1)

        self.valueSpinBox = QSpinBox()
        self.valueSpinBox.setRange(-100, 100)
        self.valueSpinBox.setSingleStep(1)

        orientationCombo = QComboBox()
        orientationCombo.addItem("Horizontal slider-like widgets")
        orientationCombo.addItem("Vertical slider-like widgets")

        orientationCombo.activated.connect(self.stackedWidget.setCurrentIndex)
        self.minimumSpinBox.valueChanged.connect(self.horizontalSliders.setMinimum)
        self.minimumSpinBox.valueChanged.connect(self.verticalSliders.setMinimum)
        self.maximumSpinBox.valueChanged.connect(self.horizontalSliders.setMaximum)
        self.maximumSpinBox.valueChanged.connect(self.verticalSliders.setMaximum)
        invertedAppearance.toggled.connect(self.horizontalSliders.invertAppearance)
        invertedAppearance.toggled.connect(self.verticalSliders.invertAppearance)
        invertedKeyBindings.toggled.connect(self.horizontalSliders.invertKeyBindings)
        invertedKeyBindings.toggled.connect(self.verticalSliders.invertKeyBindings)

        controlsLayout = QGridLayout()
        controlsLayout.addWidget(minimumLabel, 0, 0)
        controlsLayout.addWidget(maximumLabel, 1, 0)
        controlsLayout.addWidget(valueLabel, 2, 0)
        controlsLayout.addWidget(self.minimumSpinBox, 0, 1)
        controlsLayout.addWidget(self.maximumSpinBox, 1, 1)
        controlsLayout.addWidget(self.valueSpinBox, 2, 1)
        controlsLayout.addWidget(invertedAppearance, 0, 2)
        controlsLayout.addWidget(invertedKeyBindings, 1, 2)
        controlsLayout.addWidget(orientationCombo, 3, 0, 1, 3)
        self.controlsGroup.setLayout(controlsLayout)
예제 #58
0
    def __initUI__(self):
        self.setWindowTitle('Download Weather Data')
        self.setWindowIcon(get_icon('master'))
        self.setWindowFlags(Qt.Window)

        now = datetime.now()

        # Setup the proximity filter group.
        self.lat_spinBox = QDoubleSpinBox()
        self.lat_spinBox.setAlignment(Qt.AlignCenter)
        self.lat_spinBox.setSingleStep(0.1)
        self.lat_spinBox.setDecimals(3)
        self.lat_spinBox.setValue(CONF.get('download_data', 'latitude', 0))
        self.lat_spinBox.setMinimum(0)
        self.lat_spinBox.setMaximum(180)
        self.lat_spinBox.setSuffix(u' °')
        self.lat_spinBox.valueChanged.connect(self.proximity_grpbox_toggled)

        self.lon_spinBox = QDoubleSpinBox()
        self.lon_spinBox.setAlignment(Qt.AlignCenter)
        self.lon_spinBox.setSingleStep(0.1)
        self.lon_spinBox.setDecimals(3)
        self.lon_spinBox.setValue(CONF.get('download_data', 'longitude', 0))
        self.lon_spinBox.setMinimum(0)
        self.lon_spinBox.setMaximum(180)
        self.lon_spinBox.setSuffix(u' °')
        self.lon_spinBox.valueChanged.connect(self.proximity_grpbox_toggled)

        self.radius_SpinBox = QComboBox()
        self.radius_SpinBox.addItems(['25 km', '50 km', '100 km', '200 km'])
        self.radius_SpinBox.setCurrentIndex(
            CONF.get('download_data', 'radius_index', 0))
        self.radius_SpinBox.currentIndexChanged.connect(
            self.search_filters_changed)

        self.prox_grpbox = QGroupBox("Proximity Filter")
        self.prox_grpbox.setCheckable(True)
        self.prox_grpbox.setChecked(
            CONF.get('download_data', 'proximity_filter', False))
        self.prox_grpbox.toggled.connect(self.proximity_grpbox_toggled)

        prox_search_grid = QGridLayout(self.prox_grpbox)
        prox_search_grid.addWidget(QLabel('Latitude:'), 0, 0)
        prox_search_grid.addWidget(self.lat_spinBox, 0, 1)
        prox_search_grid.addWidget(QLabel('North'), 0, 2)
        prox_search_grid.addWidget(QLabel('Longitude:'), 1, 0)
        prox_search_grid.addWidget(self.lon_spinBox, 1, 1)
        prox_search_grid.addWidget(QLabel('West'), 1, 2)
        prox_search_grid.addWidget(QLabel('Search Radius:'), 2, 0)
        prox_search_grid.addWidget(self.radius_SpinBox, 2, 1)
        prox_search_grid.setColumnStretch(0, 100)
        prox_search_grid.setRowStretch(3, 100)

        # ---- Province filter
        self.prov_widg = QComboBox()
        self.prov_widg.addItems(['All'] + self.PROV_NAME)
        self.prov_widg.setCurrentIndex(
            CONF.get('download_data', 'province_index', 0))
        self.prov_widg.currentIndexChanged.connect(self.search_filters_changed)

        prov_grpbox = QGroupBox()
        prov_layout = QGridLayout(prov_grpbox)
        prov_layout.addWidget(QLabel('Province:'), 0, 0)
        prov_layout.addWidget(self.prov_widg, 0, 1)
        prov_layout.setColumnStretch(0, 1)
        prov_layout.setRowStretch(1, 1)

        # ---- Data availability filter

        # Number of years with data
        self.nbrYear = QSpinBox()
        self.nbrYear.setAlignment(Qt.AlignCenter)
        self.nbrYear.setSingleStep(1)
        self.nbrYear.setMinimum(0)
        self.nbrYear.setValue(CONF.get('download_data', 'min_nbr_of_years', 3))
        self.nbrYear.valueChanged.connect(self.search_filters_changed)

        subgrid1 = QGridLayout()
        subgrid1.setContentsMargins(0, 0, 0, 0)
        subgrid1.addWidget(QLabel('for at least'), 0, 0)
        subgrid1.addWidget(self.nbrYear, 0, 1)
        subgrid1.addWidget(QLabel('year(s)'), 0, 2)
        subgrid1.setColumnStretch(3, 100)
        subgrid1.setHorizontalSpacing(5)

        # Year range
        self.minYear = QSpinBox()
        self.minYear.setAlignment(Qt.AlignCenter)
        self.minYear.setSingleStep(1)
        self.minYear.setMinimum(1840)
        self.minYear.setMaximum(now.year)
        self.minYear.setValue(
            CONF.get('download_data', 'year_range_left_bound', 1840))
        self.minYear.valueChanged.connect(self.minYear_changed)

        label_and = QLabel('and')
        label_and.setAlignment(Qt.AlignCenter)

        self.maxYear = QSpinBox()
        self.maxYear.setAlignment(Qt.AlignCenter)
        self.maxYear.setSingleStep(1)
        self.maxYear.setMinimum(1840)
        self.maxYear.setMaximum(now.year)
        self.maxYear.setValue(
            CONF.get('download_data', 'year_range_right_bound', now.year))

        self.maxYear.valueChanged.connect(self.maxYear_changed)

        subgrid2 = QGridLayout()
        subgrid2.addWidget(QLabel('between'), 0, 0)
        subgrid2.addWidget(self.minYear, 0, 1)
        subgrid2.addWidget(label_and, 0, 2)
        subgrid2.addWidget(self.maxYear, 0, 3)
        subgrid2.setContentsMargins(0, 0, 0, 0)
        subgrid2.setColumnStretch(4, 100)
        subgrid2.setHorizontalSpacing(5)

        # Subgridgrid assembly
        self.year_widg = QGroupBox("Data Availability filter")
        self.year_widg.setCheckable(True)
        self.year_widg.setChecked(
            CONF.get('download_data', 'data_availability_filter', False))
        self.year_widg.toggled.connect(self.search_filters_changed)

        grid = QGridLayout(self.year_widg)
        grid.setRowMinimumHeight(0, 10)
        grid.addWidget(QLabel('Search for stations with data available'), 1, 0)
        grid.addLayout(subgrid1, 2, 0)
        grid.addLayout(subgrid2, 3, 0)
        grid.setRowStretch(4, 100)
        grid.setVerticalSpacing(8)

        # Setup the toolbar.
        self.btn_addSta = QPushButton('Add')
        self.btn_addSta.setIcon(get_icon('add2list'))
        self.btn_addSta.setIconSize(get_iconsize('small'))
        self.btn_addSta.setToolTip(
            'Add selected stations to the current list of weather stations.')
        self.btn_addSta.clicked.connect(self.btn_addSta_isClicked)
        self.btn_addSta.hide()

        btn_save = QPushButton('Save')
        btn_save.setToolTip('Save the list of selected stations to a file.')
        btn_save.clicked.connect(self.btn_save_isClicked)
        btn_save.hide()

        self.btn_download = QPushButton('Download')
        self.btn_download.clicked.connect(self.start_download_process)

        btn_close = QPushButton('Close')
        btn_close.clicked.connect(self.close)

        self.btn_fetch = btn_fetch = QPushButton('Refresh')
        btn_fetch.setToolTip(
            "Update the list of climate stations by fetching it from "
            "the ECCC remote location.")
        btn_fetch.clicked.connect(self.btn_fetch_isClicked)

        toolbar_widg = QWidget()
        toolbar_grid = QGridLayout(toolbar_widg)
        toolbar_grid.addWidget(self.btn_addSta, 1, 1)
        toolbar_grid.addWidget(btn_save, 1, 2)
        toolbar_grid.addWidget(btn_fetch, 1, 3)
        toolbar_grid.addWidget(self.btn_download, 1, 4)
        toolbar_grid.addWidget(btn_close, 1, 5)
        toolbar_grid.setColumnStretch(0, 100)
        toolbar_grid.setContentsMargins(0, 10, 0, 0)

        # Setup the left panel.
        self.left_panel = QFrame()
        left_panel_grid = QGridLayout(self.left_panel)
        left_panel_grid.setContentsMargins(0, 0, 0, 0)
        left_panel_grid.addWidget(QLabel('Search Criteria'), 0, 0)
        left_panel_grid.addWidget(prov_grpbox, 1, 0)
        left_panel_grid.addWidget(self.prox_grpbox, 2, 0)
        left_panel_grid.addWidget(self.year_widg, 3, 0)
        left_panel_grid.setRowStretch(3, 100)

        # Setup the progress bar.
        self.progressbar = QProgressBar()
        self.progressbar.setValue(0)
        self.progressbar.hide()

        # Setup the central widget.
        main_widget = QWidget()
        main_layout = QGridLayout(main_widget)
        main_layout.addWidget(self.left_panel, 0, 0)
        main_layout.addWidget(self.station_table, 0, 1)
        main_layout.addWidget(self.waitspinnerbar, 0, 1)
        main_layout.addWidget(toolbar_widg, 1, 0, 1, 2)
        main_layout.addWidget(self.progressbar, 2, 0, 1, 2)
        main_layout.setColumnStretch(1, 100)

        self.setCentralWidget(main_widget)
    def __init__(self, prefs: Preferences, photoRenameWidget: RenameWidget,
                 videoRenameWidget: RenameWidget, parent) -> None:
        super().__init__(parent)

        self.prefs = prefs
        self.photoRenameWidget = photoRenameWidget
        self.videoRenameWidget = videoRenameWidget

        self.setBackgroundRole(QPalette.Base)
        self.setAutoFillBackground(True)

        compatibilityLayout = QVBoxLayout()
        layout = QVBoxLayout()
        self.setLayout(layout)

        # QSpinBox cannot display values greater than this value
        self.c_maxint = platform_c_maxint()

        tip = _('A counter for how many downloads occur on each day')
        self.downloadsTodayLabel = QLabel(_('Downloads today:'))
        self.downloadsToday = QSpinBox()
        self.downloadsToday.setMinimum(0)
        # QSpinBox defaults to a maximum of 99
        self.downloadsToday.setMaximum(self.c_maxint)
        self.downloadsToday.setToolTip(tip)

        # This instance of the downloads today tracker is secondary to the
        # instance in the rename files process. That process automatically
        # updates the value and then once a download is complete, the
        # downloads today value here is overwritten.
        self.downloads_today_tracker = DownloadsTodayTracker(
            day_start=self.prefs.day_start,
            downloads_today=self.prefs.downloads_today)

        downloads_today = self.downloads_today_tracker.get_or_reset_downloads_today(
        )
        if self.prefs.downloads_today != self.downloads_today_tracker.downloads_today:
            self.prefs.downloads_today = self.downloads_today_tracker.downloads_today

        self.downloadsToday.setValue(downloads_today)
        self.downloadsToday.valueChanged.connect(self.downloadsTodayChanged)

        tip = _('A counter that is remembered each time the program is run ')
        self.storedNumberLabel = QLabel(_('Stored number:'))
        self.storedNumberLabel.setToolTip(tip)
        self.storedNumber = QSpinBox()
        self.storedNumberLabel.setBuddy(self.storedNumber)
        self.storedNumber.setMinimum(0)
        self.storedNumber.setMaximum(self.c_maxint)
        self.storedNumber.setToolTip(tip)

        self.storedNumber.setValue(self.stored_sequence_no)
        self.storedNumber.valueChanged.connect(self.storedNumberChanged)

        tip = _(
            'The time at which the <i>Downloads today</i> sequence number should be reset'
        )
        self.dayStartLabel = QLabel(_('Day start:'))
        self.dayStartLabel.setToolTip(tip)

        self.dayStart = QTimeEdit()
        self.dayStart.setToolTip(tip)
        self.dayStart.setTime(self.prefs.get_day_start_qtime())
        self.dayStart.timeChanged.connect(self.timeChanged)
        # 24 hour format, if wanted in a future release:
        # self.dayStart.setDisplayFormat('HH:mm:ss')

        self.sync = QCheckBox(_('Synchronize RAW + JPEG'))
        self.sync.setChecked(self.prefs.synchronize_raw_jpg)
        self.sync.stateChanged.connect(self.syncChanged)
        tip = _(
            'Synchronize sequence numbers for matching RAW and JPEG pairs.\n\n'
            'See the online documentation for more details.')
        self.sync.setToolTip(tip)

        self.sequences = QGroupBox(_('Sequence Numbers'))

        sequencesLayout = QFormLayout()

        sequencesLayout.addRow(self.storedNumberLabel, self.storedNumber)
        sequencesLayout.addRow(self.downloadsTodayLabel, self.downloadsToday)
        sequencesLayout.addRow(self.dayStartLabel, self.dayStart)
        sequencesLayout.addRow(self.sync)

        self.sequences.setLayout(sequencesLayout)

        self.stripCharacters = QCheckBox(_('Strip incompatible characters'))
        self.stripCharacters.setChecked(self.prefs.strip_characters)
        self.stripCharacters.stateChanged.connect(self.stripCharactersChanged)
        self.stripCharacters.setToolTip(
            _('Whether photo, video and folder names should have any characters removed that '
              'are not allowed by other operating systems'))
        self.compatibility = QGroupBox(_('Compatibility'))
        self.compatibility.setLayout(compatibilityLayout)
        compatibilityLayout.addWidget(self.stripCharacters)

        layout.addWidget(self.sequences)
        layout.addWidget(self.compatibility)
        layout.addStretch()
        layout.setSpacing(18)

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        # Inicializacion de elementos de la ventana
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()
        self.tabs.resize(700, 500)
        self.lcd = QLCDNumber()
        self.sld = QSlider(Qt.Horizontal)
        self.sld.setMinimum(1)

        # Anadir pestanas a la ventana
        self.tabs.addTab(self.tab1, "División de noticias para entrenamiento")
        self.tabs.addTab(self.tab2, "Entrenar el modelo")
        self.tabs.addTab(self.tab3, "Categorizar noticias de prueba")
        self.tabs.addTab(self.tab4, "Categorizar una noticia")

        # Primera pestana
        self.tab1.layout = QVBoxLayout(self)
        self.pushButton1 = QPushButton("Dividir noticias!", self)
        self.pushButton1.setToolTip(
            "Pulsa para dividir las noticias en dos conjuntos, uno de entrenamiento y otro de prueba"
        )
        self.tab1.layout.addWidget(self.pushButton1)
        self.tab1.setLayout(self.tab1.layout)
        self.pushButton1.clicked.connect(
            lambda: parent.buttonClicked1(self.sld.value() / 100))
        self.tab1.layout.addWidget(self.lcd)
        self.tab1.layout.addWidget(self.sld)
        self.tab1.setLayout(self.tab1.layout)
        self.sld.valueChanged.connect(self.lcd.display)
        self.tab1.setGeometry(300, 300, 250, 150)
        self.show()

        # Segunda pestana
        self.tab2.layout = QVBoxLayout(self)
        self.pushButton2 = QPushButton("Entrenar modelo!")
        self.pushButton2.setToolTip(
            "Pulsa para crear un modelo estadístico a partir de las palabras clave y las categorías de las noticias de entrenamiento"
        )
        self.tab2.layout.addWidget(self.pushButton2)
        self.tab2.setLayout(self.tab2.layout)
        self.pushButton2.clicked.connect(parent.buttonClicked2)

        # Tercera pestana
        self.tab3.layout = QVBoxLayout(self)

        self.numberInput1 = QSpinBox(self)
        self.numberInput1.setToolTip(
            "Introduce el número de vecinos con los que se podrá comparar cada noticia para establecer su categoría"
        )
        self.numberInput1.setRange(1, 100)
        self.numberInput1.setAlignment(Qt.AlignBottom)
        self.tab3.layout.addWidget(self.numberInput1)

        self.pushButton3 = QPushButton("Categorizar múltiples noticias!")
        self.pushButton3.setToolTip(
            "Usa el modelo de entrenamiento para pronosticar las categorías de las noticias de prueba"
        )
        self.tab3.layout.addWidget(self.pushButton3)
        self.tab3.setLayout(self.tab3.layout)
        self.pushButton3.clicked.connect(
            lambda: parent.buttonClicked3(self.numberInput1.value()))

        # Cuarta pestana
        self.tab4.layout = QVBoxLayout(self)
        self.numberInput2 = QSpinBox(self)
        self.numberInput2.setToolTip(
            "Introduce el número de vecinos con los que se podrá comparar cada noticia para establecer su categoría"
        )
        self.numberInput2.setRange(1, 100)
        self.tab4.layout.addWidget(self.numberInput2)

        self.pushButton4 = QPushButton("Categorizar noticia de cultura!")
        self.pushButton4.setToolTip(
            "Pronostica la categoría de un documento de cultura")
        self.tab4.layout.addWidget(self.pushButton4)
        self.pushButton4.clicked.connect(lambda: parent.buttonClickedCategory(
            self.numberInput2.value(), 'archivos/test_cultura.csv'))

        self.pushButton5 = QPushButton("Categorizar noticia de sociedad!")
        self.pushButton5.setToolTip(
            "Pronostica la categoría de un documento de sociedad")
        self.tab4.layout.addWidget(self.pushButton5)
        self.pushButton5.clicked.connect(lambda: parent.buttonClickedCategory(
            self.numberInput2.value(), 'archivos/test_sociedad.csv'))

        self.pushButton6 = QPushButton("Categorizar noticia de deporte!")
        self.pushButton6.setToolTip(
            "Pronostica la categoría de un documento de deporte")
        self.tab4.layout.addWidget(self.pushButton6)
        self.pushButton6.clicked.connect(lambda: parent.buttonClickedCategory(
            self.numberInput2.value(), 'archivos/test_deporte.csv'))

        self.pushButton7 = QPushButton("Categorizar noticia de tecnología!")
        self.pushButton7.setToolTip(
            "Pronostica la categoría de un documento de tecnología")
        self.tab4.layout.addWidget(self.pushButton7)
        self.pushButton7.clicked.connect(lambda: parent.buttonClickedCategory(
            self.numberInput2.value(), 'archivos/test_tecnologia.csv'))

        self.pushButton8 = QPushButton("Categorizar noticia de economía!")
        self.pushButton8.setToolTip(
            "Pronostica la categoría de un documento de economía")
        self.tab4.layout.addWidget(self.pushButton8)
        self.pushButton8.clicked.connect(lambda: parent.buttonClickedCategory(
            self.numberInput2.value(), 'archivos/test_economia.csv'))

        self.pushButton9 = QPushButton("Categorizar noticia de ciencia!")
        self.pushButton9.setToolTip(
            "Pronostica la categoría de un documento de ciencia")
        self.tab4.layout.addWidget(self.pushButton9)
        self.tab4.setLayout(self.tab4.layout)
        self.pushButton9.clicked.connect(lambda: parent.buttonClickedCategory(
            self.numberInput2.value(), 'archivos/test_ciencia.csv'))

        self.pushButton10 = QPushButton(
            "Categorizar noticia de categoría desconocida!")
        self.pushButton10.setToolTip(
            "Pronostica la categoría de un documento del que no se sabe la categoría"
        )
        self.tab4.layout.addWidget(self.pushButton10)
        self.tab4.setLayout(self.tab4.layout)
        self.pushButton10.clicked.connect(lambda: parent.buttonClickedCategory(
            self.numberInput2.value(), 'archivos/test_usuario.csv'))

        # Anadir pestanas al widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)