Esempio n. 1
0
    def __init__(self,parent=None):
        super().__init__(parent)
        label = QLabel(self.tr("Find &what:"))
        self.lineEdit = QLineEdit()
        label.setBuddy(self.lineEdit)

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

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

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

        self.setWindowTitle(self.tr("Find"))
        self.setFixedHeight(self.sizeHint().height())
Esempio n. 2
0
def add_to_layout(layout, *items):
    """Add items to QVBox and QHBox layouts easily.

    Keyword arguments:
    layout -- a layout oject (QVBoxLayout or QHBoxLayout) or a string
              if "v" or "h" create a QVBox or QHBox respectively
    *items -- list with items to be added
    """
    if isinstance(layout, str):
        if layout == "v":
            layout = QVBoxLayout()
        elif layout == "h":
            layout = QHBoxLayout()
        else:
            raise TypeError("Invalid layout!")

    for item in items:
        if isinstance(item, QWidget):
            layout.addWidget(item)
        elif isinstance(item, QLayout):
            layout.addLayout(item)
        elif isinstance(item, QSpacerItem):
            layout.addItem(item)
        elif item is None:
            layout.addStretch()
        else:
            raise TypeError("Argument of wrong type!")
    return layout
Esempio n. 3
0
class LeftPanel(FFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.library_panel = LP_LibraryPanel(self._app)
        self.playlists_panel = LP_PlaylistsPanel(self._app)

        self._layout = QVBoxLayout(self)
        self.setLayout(self._layout)
        self.setObjectName('c_left_panel')
        self.set_theme_style()
        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: transparent;
            }}
        '''.format(self.objectName(),
                   theme.color5.name())
        self.setStyleSheet(style_str)

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)

        self._layout.addWidget(self.library_panel)
        self._layout.addWidget(self.playlists_panel)
        self._layout.addStretch(1)
Esempio n. 4
0
    def __init__(self, fileInfo, parent=None):
        super().__init__(parent)

        fileNameLabel = QLabel(_("File Name")+':')
        fileNameEdit  = QLineEdit(fileInfo.fileName())

        pathLabel      = QLabel(_("Path")+':')
        pathValueLabel = QLabel(fileInfo.absoluteFilePath())
        pathValueLabel.setFrameStyle(LABEL_STYLE)

        sizeLabel = QLabel(_("Size")+':')
        size = fileInfo.size() // 1024
        sizeValueLabel = QLabel("%d Ko" % size)
        sizeValueLabel.setFrameStyle(LABEL_STYLE)

        lastModLabel = QLabel(_("Last Modified")+':')
        lastModValueLabel = QLabel(fileInfo.lastModified().toString())
        lastModValueLabel.setFrameStyle(LABEL_STYLE)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(fileNameLabel)
        mainLayout.addWidget(fileNameEdit)
        mainLayout.addWidget(pathLabel)
        mainLayout.addWidget(pathValueLabel)
        mainLayout.addWidget(sizeLabel)
        mainLayout.addWidget(sizeValueLabel)
        mainLayout.addWidget(lastModLabel)
        mainLayout.addWidget(lastModValueLabel)
        mainLayout.addStretch(1)
        self.setLayout(mainLayout)
Esempio n. 5
0
 def export_history_dialog(self):
     d = WindowModalDialog(self, _('Export History'))
     d.setMinimumSize(400, 200)
     vbox = QVBoxLayout(d)
     defaultname = os.path.expanduser('~/vialectrum-history.csv')
     select_msg = _('Select file to export your wallet transactions to')
     hbox, filename_e, csv_button = filename_field(self, self.config, defaultname, select_msg)
     vbox.addLayout(hbox)
     vbox.addStretch(1)
     hbox = Buttons(CancelButton(d), OkButton(d, _('Export')))
     vbox.addLayout(hbox)
     #run_hook('export_history_dialog', self, hbox)
     self.update()
     if not d.exec_():
         return
     filename = filename_e.text()
     if not filename:
         return
     try:
         self.do_export_history(filename, csv_button.isChecked())
     except (IOError, os.error) as reason:
         export_error_label = _("Electrum was unable to produce a transaction export.")
         self.parent.show_critical(export_error_label + "\n" + str(reason), title=_("Unable to export history"))
         return
     self.parent.show_message(_("Your wallet history has been successfully exported."))
Esempio n. 6
0
    def __init__(self, win):
        QWidget.__init__(self)
        self.win = win
        self.setWindowTitle('Electrum - '+_('Payment Request'))
        self.setMinimumSize(800, 250)
        self.address = ''
        self.label = ''
        self.amount = 0
        self.setFocusPolicy(QtCore.Qt.NoFocus)

        main_box = QHBoxLayout()

        self.qrw = QRCodeWidget()
        main_box.addWidget(self.qrw, 1)

        vbox = QVBoxLayout()
        main_box.addLayout(vbox)

        self.address_label = QLabel("")
        #self.address_label.setFont(QFont(MONOSPACE_FONT))
        vbox.addWidget(self.address_label)

        self.label_label = QLabel("")
        vbox.addWidget(self.label_label)

        self.amount_label = QLabel("")
        vbox.addWidget(self.amount_label)

        vbox.addStretch(1)
        self.setLayout(main_box)
Esempio n. 7
0
    def __init__(self, url, color):
        QWidget.__init__(self)
        self.setStyleSheet("background-color: black")

        self.file_name_font = QFont()
        self.file_name_font.setPointSize(24)

        self.file_name_label = QLabel(self)
        self.file_name_label.setText(url)
        self.file_name_label.setFont(self.file_name_font)
        self.file_name_label.setAlignment(Qt.AlignCenter)
        self.file_name_label.setStyleSheet("color: #eee")

        self.qrcode_label = QLabel(self)

        self.notify_font = QFont()
        self.notify_font.setPointSize(12)
        self.notify_label = QLabel(self)
        self.notify_label.setText("Scan above QR to copy information")
        self.notify_label.setFont(self.notify_font)
        self.notify_label.setAlignment(Qt.AlignCenter)
        self.notify_label.setStyleSheet("color: #eee")

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addStretch()
        layout.addWidget(self.qrcode_label, 0, Qt.AlignCenter)
        layout.addSpacing(20)
        layout.addWidget(self.file_name_label, 0, Qt.AlignCenter)
        layout.addSpacing(40)
        layout.addWidget(self.notify_label, 0, Qt.AlignCenter)
        layout.addStretch()

        self.qrcode_label.setPixmap(qrcode.make(url, image_factory=Image).pixmap())
Esempio n. 8
0
    def initialize(self):
        tab_widget = QTabWidget()
        tab1 = QWidget()
        tab2 = QWidget()

        juggle_button = QPushButton("Juggle")
        juggle_button.clicked.connect(self.start_simulation)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(juggle_button)

        vbox = QVBoxLayout(tab1)
        vbox.addStretch(1)
        vbox.addLayout(hbox)

        hbox2 = QHBoxLayout(tab2)

        tab_widget.addTab(tab1, "Main")
        tab_widget.addTab(tab2, "Other")

        self.setCentralWidget(tab_widget)

        menubar = self.menuBar()
        file_menu = menubar.addMenu('&File')
        help_menu = menubar.addMenu('&Help')
        about = help_menu.addMenu('&About')
        exit_action = QAction(QIcon('exit.png'), '&Exit', self)
        exit_action.triggered.connect(qApp.quit)
        file_menu.addAction(exit_action)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Juggling Simulator')
        self.show()
Esempio n. 9
0
 def randomWidget(self):
     group = QGroupBox("Randomize")
     layout = QGridLayout()
     self.randomCount = QSpinBox()
     layout.addWidget(QLabel(self.tr("Count")), 0, 0)
     layout.addWidget(self.randomCount, 0, 1)
     self.minBrushSize = BrushSizeWidget(15)
     self.maxBrushSize = BrushSizeWidget(50)
     layout.addWidget(QLabel(self.tr("Min")), 1, 0)
     layout.addWidget(self.minBrushSize, 1, 1)
     layout.addWidget(QLabel(self.tr("Max")), 2, 0)
     layout.addWidget(self.maxBrushSize, 2, 1)
     self.xAngle = QSpinBox()
     self.yAngle = QSpinBox()
     self.zAngle = QSpinBox()
     layout.addWidget(QLabel(self.tr("Angle X")), 3, 0)
     layout.addWidget(self.xAngle, 3, 1)
     layout.addWidget(QLabel(self.tr("Angle Y")), 4, 0)
     layout.addWidget(self.yAngle, 4, 1)
     layout.addWidget(QLabel(self.tr("Angle Z")), 5, 0)
     layout.addWidget(self.zAngle, 5, 1)
     container = QVBoxLayout()
     container.addLayout(layout)
     container.addStretch(1)
     group.setLayout(container)
     group.setFixedWidth(150)
     return group
Esempio n. 10
0
    def __init__(self, parent=None):
        super(ConfigurationPage, self).__init__(parent)

        configGroup = QGroupBox("Server configuration")

        serverLabel = QLabel("Server:")
        serverCombo = QComboBox()
        serverCombo.addItem("Trolltech (Australia)")
        serverCombo.addItem("Trolltech (Germany)")
        serverCombo.addItem("Trolltech (Norway)")
        serverCombo.addItem("Trolltech (People's Republic of China)")
        serverCombo.addItem("Trolltech (USA)")

        serverLayout = QHBoxLayout()
        serverLayout.addWidget(serverLabel)
        serverLayout.addWidget(serverCombo)

        configLayout = QVBoxLayout()
        configLayout.addLayout(serverLayout)
        configGroup.setLayout(configLayout)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(configGroup)
        mainLayout.addStretch(1)

        self.setLayout(mainLayout)
Esempio n. 11
0
 def __init__(self ):  
     super().__init__()
     
     #1        
     label1 = QLabel(self)
     label1.setToolTip('这是一个文本标签')
     label1.setStyleSheet("QLabel{border-image: url(./images/python.jpg);}")
     label1.setFixedWidth(476)
     label1.setFixedHeight(259)
     
     #2
     btn1 = QPushButton(self )  
     btn1.setObjectName('btn1')
     btn1.setMaximumSize(48, 48)
     btn1.setMinimumSize(48, 48)
     style = '''
                 #btn1{
                     border-radius: 4px;
                     background-image: url('./images/add.png');
                     }
                 #btn1:Pressed{
                     background-image: url('./images/addhover.png');
                     }
             '''
     btn1.setStyleSheet(style)
     
     #3
     vbox=QVBoxLayout()
     vbox.addWidget(label1)
     vbox.addStretch()
     vbox.addWidget(btn1)
   
     self.setLayout(vbox)
     self.setWindowTitle("按钮和Label添加背景图片例子")
Esempio n. 12
0
 def initial_download_tab(self):
     self.downloadTab = QWidget()
     self.pathSelectPanel = PathSelectPanel()
     self.download_tab_revert_parameters()
     downloadTabLayout = QVBoxLayout(self.downloadTab)
     downloadTabLayout.addWidget(self.pathSelectPanel)
     downloadTabLayout.addStretch()
Esempio n. 13
0
class GSideToolbar(QWidget):
    selectionChanged = pyqtSignal(str)

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

        self.selectedId = None

        self.mainLayout = QVBoxLayout(self)
        self.buttonGroup = QButtonGroup()
        self.buttons = {}

        for button in buttons:
            b = QPushButton(button.name)
            self.buttonGroup.addButton(b)
            self.buttonGroup.setId(b, button.id)
            self.buttons[button.id] = b
            self.mainLayout.addWidget(b)

        self.buttonGroup.buttonClicked.connect(self.buttonClicked)

        self.mainLayout.addStretch()

    def buttonState(self, state):
        pass

    def buttonClicked(self, button : QPushButton):
        buttonId = self.buttonGroup.id(button)
        buttonName = self.buttons[buttonId].text()
        self.selectionChanged.emit(buttonName)

    @staticmethod
    def createButton(text, icon):
        pass
Esempio n. 14
0
    def __init__(self, main_window, items):
        super().__init__()

        vbox = QVBoxLayout()
        vbox.setSpacing(0)
        vbox.setContentsMargins(0, 0, 0, 0)
        self.setLayout(vbox)

        top_system_buttons = TopSystemButtons(main_window)
        vbox.addWidget(top_system_buttons)
        vbox.addStretch()
        hbox = QHBoxLayout()
        hbox.addSpacing(25)
        hbox.setSpacing(0)
        hbox.setContentsMargins(0, 0, 0, 0)
        vbox.addLayout(hbox)

        l = QLabel()
        hbox.addWidget(l)
        vbox.addStretch()
        vbox.addWidget(SelectMenu(main_window, items))

        main_window.communication.input_changed_signal.connect(l.setText)
        self.resizeEvent = functools.partial(main_window.resized, self,
                                             top_system_buttons)

        self.setGraphicsEffect(utils.get_shadow())
Esempio n. 15
0
    def init_ui(self):
        """Initialize the Edit Widget"""
        plot_window_button = QPushButton('Select Plot Window', self)
        plot_window_button.clicked.connect(self.select_plot)
        plot_button = QPushButton('Plot Data', self)
        plot_button.clicked.connect(self.plot)
        color_button = QPushButton('Change Color', self)
        color_button.clicked.connect(lambda: self.plot_window.color_change(self.line_box))
        style_button = QPushButton('Change Style', self)
        style_button.clicked.connect(lambda: self.plot_window.line_style_change(self.line_box))
        remove_button = QPushButton('Remove Plot', self)
        remove_button.clicked.connect(lambda: self.plot_window.remove_plot(self.line_box))
        button_vertical_box = QVBoxLayout()
        button_vertical_box.addWidget(self.line_box)
        button_vertical_box.addStretch(1)
        button_vertical_box.addWidget(plot_window_button)
        button_vertical_box.addWidget(color_button)
        button_vertical_box.addWidget(style_button)
        button_vertical_box.addWidget(plot_button)
        button_vertical_box.addWidget(remove_button)

        main_horizontal_box = QHBoxLayout()
        main_horizontal_box.addLayout(button_vertical_box)
        self.setLayout(main_horizontal_box)
        self.setGeometry(self.left, self.top, self.width, self.height)
Esempio n. 16
0
    def create_config(self):

        box0 = QGroupBox('History')
        self.index['max_dataset_history'] = FormInt()
        self.index['recording_dir'] = FormStr()

        form_layout = QFormLayout()
        form_layout.addRow('Max History Size',
                           self.index['max_dataset_history'])
        form_layout.addRow('Directory with recordings',
                           self.index['recording_dir'])
        box0.setLayout(form_layout)

        box1 = QGroupBox('Default values')
        self.index['y_distance_presets'] = FormList()
        self.index['y_scale_presets'] = FormList()
        self.index['window_length_presets'] = FormList()

        form_layout = QFormLayout()
        form_layout.addRow('Signal scaling, presets',
                           self.index['y_scale_presets'])
        form_layout.addRow('Distance between signals, presets',
                           self.index['y_distance_presets'])
        form_layout.addRow('Window length, presets',
                           self.index['window_length_presets'])
        box1.setLayout(form_layout)

        main_layout = QVBoxLayout()
        main_layout.addWidget(box0)
        main_layout.addWidget(box1)
        main_layout.addStretch(1)

        self.setLayout(main_layout)
    def test_should_resize_to_match_height_for_width_when_user_enters_text(self):
        size_hint     = self.auto_resizing_text_edit.sizeHint()
        parent_height = size_hint.height() + 200

        layout = QVBoxLayout()
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.auto_resizing_text_edit)
        layout.addStretch()

        parent = QWidget()
        self.auto_resizing_text_edit.setParent(parent)

        parent.resize(size_hint.width(), parent_height)
        parent.setLayout(layout)

        # The window needs to get shown for the size changes to be propagated to layout.
        # Show it minimized to avoid stealing focus from the console running the tests.
        parent.showMinimized()

        assert self.auto_resizing_text_edit.height(), size_hint.height()
        assert self.auto_resizing_text_edit.width(),  parent.width()

        self.auto_resizing_text_edit.setPlainText('a\nb\nc\d')
        new_height_hint = self.auto_resizing_text_edit.heightForWidth(self.auto_resizing_text_edit.width())
        application.processEvents()

        self.assertNotEqual(new_height_hint, size_hint.height())
        self.assertEqual(self.auto_resizing_text_edit.height(), new_height_hint)
        self.assertEqual(self.auto_resizing_text_edit.width(),  parent.width())
Esempio n. 18
0
 def __init__(self, tree, part, box):
     """Initializes the item.
     
     tree: is the score tree widget,
     part: is the Part instance that creates the widgets
     box: the QGroupBox that is created for this item in the stacked widget.
     
     """
     super(PartItem, self).__init__(tree)
     self.part = part()
     self.box = box
     layout = QVBoxLayout()
     box.setLayout(layout)
     self.part.createWidgets(layout)
     layout.addStretch(1)
     app.translateUI(self)
     
     flags = (
         Qt.ItemIsSelectable |
         Qt.ItemIsDragEnabled |
         Qt.ItemIsEnabled
     )
     if issubclass(part, parts._base.Container):
         flags |= Qt.ItemIsDropEnabled
     self.setFlags(flags)
Esempio n. 19
0
    def __init__(self, *args):
        super().__init__(BrickletTilt, *args)

        self.tilt = self.device

        self.cbe_tilt_state = CallbackEmulator(self.tilt.get_tilt_state,
                                               None,
                                               self.cb_tilt_state,
                                               self.increase_error_count)

        self.label = QLabel("Closed")
        self.closed_pixmap = load_masked_pixmap('plugin_system/plugins/tilt/tilt_closed.bmp')
        self.open_pixmap = load_masked_pixmap('plugin_system/plugins/tilt/tilt_open.bmp')
        self.closed_vibrationg_pixmap = load_masked_pixmap('plugin_system/plugins/tilt/tilt_closed_vibrating.bmp')

        self.image_label = QLabel("")
        self.image_label.setPixmap(self.closed_pixmap)

        layout = QVBoxLayout(self)
        layout.addStretch()

        h_layout1 = QHBoxLayout()
        h_layout1.addStretch()
        h_layout1.addWidget(self.label)
        h_layout1.addStretch()

        h_layout2 = QHBoxLayout()
        h_layout2.addStretch()
        h_layout2.addWidget(self.image_label)
        h_layout2.addStretch()

        layout.addLayout(h_layout1)
        layout.addLayout(h_layout2)
        layout.addStretch()
Esempio n. 20
0
    def __init__(self, name, stringlist=None, parent=None):
        super(StringListDlg, self).__init__(parent)

        self.name = name

        self.listWidget = QListWidget()
        if stringlist is not None:
            self.listWidget.addItems(stringlist)
            self.listWidget.setCurrentRow(0)
        buttonLayout = QVBoxLayout()
        for text, slot in (("&Add...", self.add),
                           ("&Edit...", self.edit),
                           ("&Remove...", self.remove),
                           ("&Up", self.up),
                           ("&Down", self.down),
                           ("&Sort", self.listWidget.sortItems),
                           ("Close", self.accept)):
            button = QPushButton(text)
            if not MAC:
                button.setFocusPolicy(Qt.NoFocus)
            if text == "Close":
                buttonLayout.addStretch()
            buttonLayout.addWidget(button)
            button.clicked.connect(slot)
#            self.connect(button, SIGNAL("clicked()"), slot)
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(buttonLayout)
        self.setLayout(layout)
        self.setWindowTitle("Edit {0} List".format(self.name))
Esempio n. 21
0
    def widgetObjectList(self):
        """Create objects list widget.
        """
        self.objectsTree = self.widgetTree()
        self.availableObjectsList = QListWidget(self)
        self.availableObjectsList.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.removeButton = QPushButton(self.tr('>>'))
        self.addButton = QPushButton(self.tr('<<'))

        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(self.addButton)
        vbox.addWidget(self.removeButton)
        vbox.addStretch(1)

        vboxSelected = QVBoxLayout()
        selectedLabel = QLabel(self.tr('Selected'))
        selectedLabel.setAlignment(QtCore.Qt.AlignCenter)
        vboxSelected.addWidget(selectedLabel)
        vboxSelected.addWidget(self.objectsTree)
        vboxAvailable = QVBoxLayout()
        availableLabel = QLabel(self.tr('Available'))
        availableLabel.setAlignment(QtCore.Qt.AlignCenter)
        vboxAvailable.addWidget(availableLabel)
        vboxAvailable.addWidget(self.availableObjectsList)
        hbox = QHBoxLayout()
        hbox.addLayout(vboxSelected)
        hbox.addLayout(vbox)
        hbox.addLayout(vboxAvailable)
        return hbox
Esempio n. 22
0
    def __init__(self):
        super().__init__()

        self.settings = QSettings('olle-orks.org', 'Bodenpython')

        self.setWindowTitle('Mikrokopter Bodenpython')
        self.communicator = None
        self.list_widget = None
        self.pingpong_widget = None
        self.serialport_selector = None

        saved_geometry = self.settings.value(self.SETTINGS_MAINWINDOW_GEOMETRY)
        if saved_geometry:
            self.restoreGeometry(saved_geometry)

        self.serialport_selector = SerialPortSelector(self.settings)
        self.serialport_selector.accepted.connect(self.serialport_selected)
        self.serialport_selector.rejected.connect(self.close)

        selector_layout = QHBoxLayout()
        selector_layout.addStretch()
        selector_layout.addWidget(self.serialport_selector)
        selector_layout.addStretch()

        central_widget = QWidget()
        central_layout = QVBoxLayout()
        central_layout.addStretch()
        central_layout.addLayout(selector_layout)
        central_layout.addStretch()
        central_widget.setLayout(central_layout)

        self.setCentralWidget(central_widget)

        QTimer.singleShot(0, self.set_window_icon)
Esempio n. 23
0
    def __init__(self, parent, settings_object):
        super().__init__()
        self.parent = parent
        self.settings_object = settings_object

        media_group = QGroupBox('Media Files')
        media_group_layout = QHBoxLayout()
        media_path_label = QLabel('Media Folder:')
        self.media_path_edit = QLineEdit(self.settings_object['output']['media_directory'])
        media_path_browse_button = QPushButton('Browse')

        media_path_browse_button.clicked.connect(self.browse_media_directory)
        self.media_path_edit.textEdited.connect(self.set_media_directory)

        media_group_layout.addWidget(media_path_label)
        media_group_layout.addWidget(self.media_path_edit)
        media_group_layout.addWidget(media_path_browse_button)
        media_group.setLayout(media_group_layout)

        schema_group = QGroupBox('Output File Naming Schema')

        main_layout = QVBoxLayout()
        main_layout.addWidget(media_group)
        main_layout.addWidget(schema_group)
        main_layout.addStretch(1)
        self.setLayout(main_layout)
Esempio n. 24
0
    def __init__(self, parent=None):
        super(BasicFilterPage, self).__init__(parent)

        self.blockCombo = QComboBox()
        self.deviceCombo = QComboBox()
        self.unitCombo = QComboBox()

        self.combos = {'block': self.blockCombo, \
                       'device': self.deviceCombo, \
                       'unit': self.unitCombo}

        groupLayout = QFormLayout()
        groupLayout.addRow("Skupina měření:", self.blockCombo)
        groupLayout.addRow("Přístroj:", self.deviceCombo)
        groupLayout.addRow("Veličina:", self.unitCombo)

        filterGroup = QGroupBox("Základní filtry")
        filterGroup.setLayout(groupLayout)

        self.deviatedValuesCheckbox = QCheckBox()
        valuesLayout = QFormLayout()
        valuesLayout.addRow("Mimo odchylku:", self.deviatedValuesCheckbox)

        valuesGroup = QGroupBox("Hodnoty")
        valuesGroup.setLayout(valuesLayout)

        layout = QVBoxLayout()
        layout.addWidget(filterGroup)
        layout.addSpacing(12)
        layout.addWidget(valuesGroup)
        layout.addStretch(1)

        self.setLayout(layout)
Esempio n. 25
0
    def __init__(self, parent=None):
        super(Login, self).__init__(parent)
        usr = QLabel(u"用户:")
        pwd = QLabel(u"密码:")
        self.usrLineEdit = QLineEdit()
        self.pwdLineEdit = QLineEdit()
        self.pwdLineEdit.setEchoMode(QLineEdit.Password)

        gridLayout = QGridLayout()
        gridLayout.addWidget(usr, 0, 0, 1, 1)
        gridLayout.addWidget(pwd, 1, 0, 1, 1)
        gridLayout.addWidget(self.usrLineEdit, 0, 1, 1, 3);
        gridLayout.addWidget(self.pwdLineEdit, 1, 1, 1, 3);

        okBtn = QPushButton(u"确定")
        cancelBtn = QPushButton(u"取消")
        btnLayout = QHBoxLayout()

        btnLayout.setSpacing(60)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)

        dlgLayout = QVBoxLayout()
        dlgLayout.setContentsMargins(40, 40, 40, 40)
        dlgLayout.addLayout(gridLayout)
        dlgLayout.addStretch(40)
        dlgLayout.addLayout(btnLayout)

        self.setLayout(dlgLayout)
        okBtn.clicked.connect(self.accept)
        cancelBtn.clicked.connect(self.reject)
        self.setWindowTitle(u"登录")
        self.resize(300, 200)
 def __init__(self):
     super().__init__()
     vbox = QVBoxLayout(self)
     self.setTitle("Python Project")
     frame = QFrame()
     frame.setLineWidth(2)
     vbox.addStretch(1)
     frame.setFrameShape(QFrame.StyledPanel)
     vbox.addWidget(frame)
     box = QGridLayout(frame)
     box.addWidget(QLabel("Project Name:"), 0, 0)
     self._line_project_name = QLineEdit()
     self.registerField("name*", self._line_project_name)
     box.addWidget(self._line_project_name, 0, 1)
     box.addWidget(QLabel("Create in:"), 1, 0)
     self.line = QLineEdit()
     self.registerField("path", self.line)
     choose_dir_action = self.line.addAction(
         QIcon(self.style().standardPixmap(
             self.style().SP_DirIcon)), QLineEdit.TrailingPosition)
     box.addWidget(self.line, 1, 1)
     box.addWidget(QLabel("Interpreter:"), 2, 0)
     line_interpreter = QComboBox()
     line_interpreter.setEditable(True)
     line_interpreter.addItems(utils.get_python())
     box.addWidget(line_interpreter, 2, 1)
     # from ninja_ide.utils import utils
     choose_dir_action.triggered.connect(self._choose_dir)
     self.line.setText(utils.get_home_dir())
Esempio n. 27
0
    def __init__(self, parent=None):
        super(LocationFilterPage, self).__init__(parent)

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

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

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

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

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

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

        self.setLayout(layout)
    def __init__(self):
        """The constructor initializes the class AboutDialog."""
        super().__init__()
        self.setAttribute(Qt.WA_DeleteOnClose)

        # initialize class constants
        self._BUTTON_MIN_WIDTH = 110
        self._OXYGEN_PATH_48 = os.path.join("resources", "icons", "oxygen", "48")

        # fonts and margins settings
        hlFont = QFont()
        hlFont.setBold(True)
        hlFont.setPointSize(14)

        # scientific logo
        logo = QLabel(pixmap=QPixmap(os.path.join(self._OXYGEN_PATH_48, "applications-science.png")))

        logoLayout = QVBoxLayout()
        logoLayout.addWidget(logo)
        logoLayout.addStretch()

        # begin the content
        # headline and description text
        self.headline = QLabel()
        self.headline.setFont(hlFont)
        self.description = QLabel(wordWrap=True)

        # the list with the open button
        self.listWidget = QListWidget()
        self.listWidget.setMinimumWidth(420)
        self.createArticles()

        self.openButton = QPushButton()
        self.openButton.clicked.connect(self.openAction)

        listLayout = QHBoxLayout()
        listLayout.addWidget(self.listWidget)
        listLayout.addWidget(self.openButton, alignment=Qt.AlignTop)

        # create a close button
        line = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.HLine)
        self.closeButton = QPushButton()
        self.closeButton.setFixedWidth(self._BUTTON_MIN_WIDTH)
        self.closeButton.clicked.connect(self.close)

        # content layout
        contentLayout = QVBoxLayout()
        contentLayout.addWidget(self.headline)
        contentLayout.addWidget(self.description)
        contentLayout.addLayout(listLayout)
        contentLayout.addWidget(line)
        contentLayout.addWidget(self.closeButton, alignment=Qt.AlignRight)

        # main layout
        layout = QHBoxLayout(self)
        layout.addLayout(logoLayout)
        layout.addLayout(contentLayout)

        # translate the graphical user interface
        self.retranslateUi()
    def __init__(self, parent, app):
        super().__init__()

        layout1 = QHBoxLayout()
        layout2 = QVBoxLayout()

        layout1.addStretch()
        layout1.addLayout(layout2)
        layout1.addStretch()

        label = QLabel(self)
        label.setText("Simple Project: <b>Display Environment Measurements on LCD</b>. Simply displays all measured values on LCD. Sources in all programming languages can be found <a href=\"http://www.tinkerforge.com/en/doc/Kits/WeatherStation/WeatherStation.html#display-environment-measurements-on-lcd\">here</a>.<br>")
        label.setTextFormat(Qt.RichText)
        label.setTextInteractionFlags(Qt.TextBrowserInteraction)
        label.setOpenExternalLinks(True)
        label.setWordWrap(True)
        label.setAlignment(Qt.AlignJustify)

        layout2.addSpacing(10)
        layout2.addWidget(label)
        layout2.addSpacing(10)

        self.lcdwidget = LCDWidget(self, app)

        layout2.addWidget(self.lcdwidget)
        layout2.addStretch()

        self.setLayout(layout1)

        self.qtcb_update_illuminance.connect(self.update_illuminance_data_slot)
        self.qtcb_update_air_pressure.connect(self.update_air_pressure_data_slot)
        self.qtcb_update_temperature.connect(self.update_temperature_data_slot)
        self.qtcb_update_humidity.connect(self.update_humidity_data_slot)
        self.qtcb_button_pressed.connect(self.button_pressed_slot)
Esempio n. 30
0
class Avance(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.parent = parent
        prm = parent.param


        ### Liste des options avancées de la calculatrice ###
        self.pave = QVBoxLayout()

        box = QGroupBox("Post-traitement")
        box_layout = QVBoxLayout()
        box.setLayout(box_layout)
        box_layout.addWidget(QLabel("Traitement automatiquement du résultat :"))
        self.traitement = QLineEdit()
        traitement = self.parent.param("appliquer_au_resultat") or '_'
        self.traitement.setText(traitement)
        self.traitement.setMinimumWidth(100)
        self.traitement.setToolTip("Fonction ou opérations à appliquer automatiquement au résultat (représenté par _). Ex: 'factoriser(_)'.")
        self.traitement.editingFinished.connect(self.EvtAppliquerResultat)
        box_layout.addWidget(self.traitement)
        self.pave.addWidget(box)
        self.setLayout(self.pave)
        self.pave.addStretch()


    def EvtAppliquerResultat(self, event=None):
        val = self.traitement.text().strip()
        if not val:
            self.traitement.setText('_')
            val = None
        elif val == '_':
            val = None
        self.parent.param("appliquer_au_resultat", val)
Esempio n. 31
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 ->
        self.change_name_horizontalLayout = QHBoxLayout()
        self.change_name_checkBox = QCheckBox(self.link_frame)
        self.change_name_horizontalLayout.addWidget(self.change_name_checkBox)

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

        self.link_verticalLayout.addLayout(self.change_name_horizontalLayout)

        # 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 = MyQDateTimeEdit(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 = MyQDateTimeEdit(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)
        #nomaxx# 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: '))
Esempio n. 32
0
    def __init__(self, window, plugin, keystore, device_id):
        title = _("{} Settings").format(plugin.device)
        super(SettingsDialog, self).__init__(window, title)
        self.setMaximumWidth(540)

        devmgr = plugin.device_manager()
        config = devmgr.config
        handler = keystore.handler
        thread = keystore.thread

        def invoke_client(method, *args, **kw_args):
            unpair_after = kw_args.pop('unpair_after', False)

            def task():
                client = devmgr.client_by_id(device_id)
                if not client:
                    raise RuntimeError("Device not connected")
                if method:
                    getattr(client, method)(*args, **kw_args)
                if unpair_after:
                    devmgr.unpair_id(device_id)
                return client.features

            thread.add(task, on_success=update)

        def update(features):
            self.features = features
            set_label_enabled()
            bl_hash = bh2u(features.bootloader_hash)
            bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
            noyes = [_("No"), _("Yes")]
            endis = [_("Enable Passphrases"), _("Disable Passphrases")]
            disen = [_("Disabled"), _("Enabled")]
            setchange = [_("Set a PIN"), _("Change PIN")]

            version = "%d.%d.%d" % (features.major_version,
                                    features.minor_version,
                                    features.patch_version)
            coins = ", ".join(coin.coin_name for coin in features.coins)

            device_label.setText(features.label)
            pin_set_label.setText(noyes[features.pin_protection])
            passphrases_label.setText(disen[features.passphrase_protection])
            bl_hash_label.setText(bl_hash)
            label_edit.setText(features.label)
            device_id_label.setText(features.device_id)
            initialized_label.setText(noyes[features.initialized])
            version_label.setText(version)
            coins_label.setText(coins)
            clear_pin_button.setVisible(features.pin_protection)
            clear_pin_warning.setVisible(features.pin_protection)
            pin_button.setText(setchange[features.pin_protection])
            pin_msg.setVisible(not features.pin_protection)
            passphrase_button.setText(endis[features.passphrase_protection])
            language_label.setText(features.language)

        def set_label_enabled():
            label_apply.setEnabled(label_edit.text() != self.features.label)

        def rename():
            invoke_client('change_label', label_edit.text())

        def toggle_passphrase():
            title = _("Confirm Toggle Passphrase Protection")
            currently_enabled = self.features.passphrase_protection
            if currently_enabled:
                msg = _("After disabling passphrases, you can only pair this "
                        "Axe Electrum wallet if it had an empty passphrase.  "
                        "If its passphrase was not empty, you will need to "
                        "create a new wallet with the install wizard.  You "
                        "can use this wallet again at any time by re-enabling "
                        "passphrases and entering its passphrase.")
            else:
                msg = _("Your current Axe Electrum wallet can only be used with "
                        "an empty passphrase.  You must create a separate "
                        "wallet with the install wizard for other passphrases "
                        "as each one generates a new set of addresses.")
            msg += "\n\n" + _("Are you sure you want to proceed?")
            if not self.question(msg, title=title):
                return
            invoke_client('toggle_passphrase', unpair_after=currently_enabled)

        def set_pin():
            invoke_client('set_pin', remove=False)

        def clear_pin():
            invoke_client('set_pin', remove=True)

        def wipe_device():
            wallet = window.wallet
            if wallet and sum(wallet.get_balance()):
                title = _("Confirm Device Wipe")
                msg = _("Are you SURE you want to wipe the device?\n"
                        "Your wallet still has Axe coins in it!")
                if not self.question(msg, title=title,
                                     icon=QMessageBox.Critical):
                    return
            invoke_client('wipe_device', unpair_after=True)

        def slider_moved():
            mins = timeout_slider.sliderPosition()
            timeout_minutes.setText(_("{:2d} minutes").format(mins))

        def slider_released():
            config.set_session_timeout(timeout_slider.sliderPosition() * 60)

        # Information tab
        info_tab = QWidget()
        info_layout = QVBoxLayout(info_tab)
        info_glayout = QGridLayout()
        info_glayout.setColumnStretch(2, 1)
        device_label = QLabel()
        pin_set_label = QLabel()
        passphrases_label = QLabel()
        version_label = QLabel()
        device_id_label = QLabel()
        bl_hash_label = QLabel()
        bl_hash_label.setWordWrap(True)
        coins_label = QLabel()
        coins_label.setWordWrap(True)
        language_label = QLabel()
        initialized_label = QLabel()
        rows = [
            (_("Device Label"), device_label),
            (_("PIN set"), pin_set_label),
            (_("Passphrases"), passphrases_label),
            (_("Firmware Version"), version_label),
            (_("Device ID"), device_id_label),
            (_("Bootloader Hash"), bl_hash_label),
            (_("Supported Coins"), coins_label),
            (_("Language"), language_label),
            (_("Initialized"), initialized_label),
        ]
        for row_num, (label, widget) in enumerate(rows):
            info_glayout.addWidget(QLabel(label), row_num, 0)
            info_glayout.addWidget(widget, row_num, 1)
        info_layout.addLayout(info_glayout)

        # Settings tab
        settings_tab = QWidget()
        settings_layout = QVBoxLayout(settings_tab)
        settings_glayout = QGridLayout()

        # Settings tab - Label
        label_msg = QLabel(_("Name this {}.  If you have multiple devices "
                             "their labels help distinguish them.")
                           .format(plugin.device))
        label_msg.setWordWrap(True)
        label_label = QLabel(_("Device Label"))
        label_edit = QLineEdit()
        label_edit.setMinimumWidth(150)
        label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
        label_apply = QPushButton(_("Apply"))
        label_apply.clicked.connect(rename)
        label_edit.textChanged.connect(set_label_enabled)
        settings_glayout.addWidget(label_label, 0, 0)
        settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
        settings_glayout.addWidget(label_apply, 0, 3)
        settings_glayout.addWidget(label_msg, 1, 1, 1, -1)

        # Settings tab - PIN
        pin_label = QLabel(_("PIN Protection"))
        pin_button = QPushButton()
        pin_button.clicked.connect(set_pin)
        settings_glayout.addWidget(pin_label, 2, 0)
        settings_glayout.addWidget(pin_button, 2, 1)
        pin_msg = QLabel(_("PIN protection is strongly recommended.  "
                           "A PIN is your only protection against someone "
                           "stealing your Axe coins if they obtain physical "
                           "access to your {}.").format(plugin.device))
        pin_msg.setWordWrap(True)
        pin_msg.setStyleSheet("color: red")
        settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)

        # Settings tab - Session Timeout
        timeout_label = QLabel(_("Session Timeout"))
        timeout_minutes = QLabel()
        timeout_slider = QSlider(Qt.Horizontal)
        timeout_slider.setRange(1, 60)
        timeout_slider.setSingleStep(1)
        timeout_slider.setTickInterval(5)
        timeout_slider.setTickPosition(QSlider.TicksBelow)
        timeout_slider.setTracking(True)
        timeout_msg = QLabel(
            _("Clear the session after the specified period "
              "of inactivity.  Once a session has timed out, "
              "your PIN and passphrase (if enabled) must be "
              "re-entered to use the device."))
        timeout_msg.setWordWrap(True)
        timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
        slider_moved()
        timeout_slider.valueChanged.connect(slider_moved)
        timeout_slider.sliderReleased.connect(slider_released)
        settings_glayout.addWidget(timeout_label, 6, 0)
        settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
        settings_glayout.addWidget(timeout_minutes, 6, 4)
        settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
        settings_layout.addLayout(settings_glayout)
        settings_layout.addStretch(1)

        # Advanced tab
        advanced_tab = QWidget()
        advanced_layout = QVBoxLayout(advanced_tab)
        advanced_glayout = QGridLayout()

        # Advanced tab - clear PIN
        clear_pin_button = QPushButton(_("Disable PIN"))
        clear_pin_button.clicked.connect(clear_pin)
        clear_pin_warning = QLabel(
            _("If you disable your PIN, anyone with physical access to your "
              "{} device can spend your Axe coins.").format(plugin.device))
        clear_pin_warning.setWordWrap(True)
        clear_pin_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(clear_pin_button, 0, 2)
        advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)

        # Advanced tab - toggle passphrase protection
        passphrase_button = QPushButton()
        passphrase_button.clicked.connect(toggle_passphrase)
        passphrase_msg = WWLabel(PASSPHRASE_HELP)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(passphrase_button, 3, 2)
        advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
        advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)

        # Advanced tab - wipe device
        wipe_device_button = QPushButton(_("Wipe Device"))
        wipe_device_button.clicked.connect(wipe_device)
        wipe_device_msg = QLabel(
            _("Wipe the device, removing all data from it.  The firmware "
              "is left unchanged."))
        wipe_device_msg.setWordWrap(True)
        wipe_device_warning = QLabel(
            _("Only wipe a device if you have the recovery seed written down "
              "and the device wallet(s) are empty, otherwise the Axe coins "
              "will be lost forever."))
        wipe_device_warning.setWordWrap(True)
        wipe_device_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(wipe_device_button, 6, 2)
        advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
        advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
        advanced_layout.addLayout(advanced_glayout)
        advanced_layout.addStretch(1)

        tabs = QTabWidget(self)
        tabs.addTab(info_tab, _("Information"))
        tabs.addTab(settings_tab, _("Settings"))
        tabs.addTab(advanced_tab, _("Advanced"))
        dialog_vbox = QVBoxLayout(self)
        dialog_vbox.addWidget(tabs)
        dialog_vbox.addLayout(Buttons(CloseButton(self)))

        # Update information
        invoke_client(None)
Esempio n. 33
0
    def __init__(self,
                 context: ListContext,
                 contact: ContactEntry,
                 identity: ContactIdentity,
                 parent: Any = None):
        super().__init__(parent)

        self._context = context
        self._contact = contact
        self._identity = identity

        self.setObjectName("ContactCard")

        avatar_label = QLabel("")
        avatar_label.setPixmap(QPixmap(icon_path("icons8-decision-80.png")))
        avatar_label.setObjectName("ContactAvatar")
        avatar_label.setToolTip(_("What your contact avatar looks like."))

        label = QLabel("...")
        label.setSizePolicy(QSizePolicy.MinimumExpanding,
                            QSizePolicy.Preferred)
        label.setAlignment(Qt.AlignHCenter)

        name_layout = QVBoxLayout()
        name_layout.setContentsMargins(0, 0, 0, 0)
        name_layout.addWidget(avatar_label)
        name_layout.addWidget(label)

        def _on_pay_button_clicked(checked: Optional[bool] = False) -> None:
            from . import payment
            # from importlib import reload
            # reload(payment)
            self.w = payment.PaymentWindow(self._context.wallet_api,
                                           self._identity.identity_id,
                                           parent=self)
            self.w.show()

        def _on_delete_button_clicked(checked: Optional[bool] = False) -> None:
            wallet_window = self._context.wallet_api.wallet_window
            if not wallet_window.question(_("Are you sure?")):
                return
            self._context.wallet_api.remove_contacts(
                [self._contact.contact_id])

        def _on_edit_button_clicked(checked: Optional[bool] = False) -> None:
            contact_key = (self._contact.contact_id,
                           self._identity.identity_id)
            edit_contact_dialog(self._context.wallet_api, contact_key)

            contact = self._context.wallet_api.get_contact(contact_key[0])
            identity = [
                ci for ci in contact.identities
                if ci.identity_id == contact_key[1]
            ][0]

            self._contact = contact
            self._identity = identity
            self._update()

        pay_button = QPushButton(_("Pay"), self)
        pay_button.clicked.connect(_on_pay_button_clicked)

        message_button = QPushButton(_("Message"), self)
        message_button.setEnabled(False)

        edit_button = QPushButton(_("Edit"), self)
        edit_button.clicked.connect(_on_edit_button_clicked)

        delete_button = QPushButton(_("Delete"), self)
        delete_button.clicked.connect(_on_delete_button_clicked)

        action_layout = QVBoxLayout()
        action_layout.setSpacing(0)
        action_layout.addStretch(1)
        action_layout.addWidget(pay_button)
        action_layout.addWidget(message_button)
        action_layout.addWidget(edit_button)
        action_layout.addWidget(delete_button)

        self._layout = QHBoxLayout()
        self._layout.setSpacing(8)
        self._layout.setContentsMargins(20, 10, 20, 10)
        self._layout.addLayout(name_layout)
        self._layout.addStretch(1)
        self._layout.addLayout(action_layout)
        self.setLayout(self._layout)

        self._avatar_label = avatar_label
        self._name_label = label

        self._update()
Esempio n. 34
0
layout_line1.addWidget(lb_Question,
                       alignment=(Qt.AlignHCenter | Qt.AlignVCenter))
layout_line2.addWidget(RadioGroupBox)
layout_line2.addWidget(AnsGroupBox)
AnsGroupBox.hide()

layout_line3.addStretch(1)
layout_line3.addWidget(btn_OK, stretch=2)
layout_line3.addStretch(1)

layout_card = QVBoxLayout()

layout_card.addLayout(layout_line1, stretch=2)
layout_card.addLayout(layout_line2, stretch=8)
layout_card.addStretch(1)
layout_card.addLayout(layout_line3, stretch=1)
layout_card.addStretch(1)
layout_card.setSpacing(5)


def show_result():
    RadioGroupBox.hide()
    AnsGroupBox.show()
    btn_OK.setText('Следующий вопрос')


def show_question():
    RadioGroupBox.show()
    AnsGroupBox.hide()
    btn_OK.setText('Ответить')
Esempio n. 35
0
class MainWidget(QWidget):
    """Main widget."""

    # images opened in program
    files = []
    image_added_signal = pyqtSignal(str)
    image_boxes = []
    images = []

    def __init__(self):
        """Init."""
        super().__init__()
        self.init_ui()

    def init_ui(self):
        """Initialize UI."""
        # import config
        self.config = import_config()

        self.resize(self.config["width"], self.config["height"])

        self.textbox = QTextEdit(self)

        # layout is made up by three layers of boxes,
        # the lowest layer is hboxes, then above them is vboxes.
        # Above vboxes there is a single top box top_hbox
        self.image_hbox = QHBoxLayout()
        self.vbox = QVBoxLayout()
        self.top_hbox = QHBoxLayout()

        self.vbox.addLayout(self.image_hbox)
        self.vbox.addStretch(0)
        self.vbox.addWidget(self.textbox)
        self.top_hbox.addLayout(self.vbox)

        for count in [0, 1, 2, 3]:
            self.image_boxes.append(
                ImageBox(self.config["default-image"], self))

        self.relayout()

    def relayout(self):
        """Redraw the whole display."""
        self.setLayout(self.top_hbox)

    def change_image(self, image_box):
        """Open a file explorer and change image."""
        file_path = self.open_filename_dialog()
        image_box.change_image(file_path)
        self.relayout()

    def open_filename_dialog(self):
        """Open a file explorer to open a file."""
        options = QFileDialog.Options()
        # options |= QFileDialog.DontUseNativeDialog
        # All Files (*);;
        filename, _ = QFileDialog.getOpenFileName(
            self,
            "Open File",
            ".",
            "Images (*.png *.jpg *.jpeg)",
            options=options)
        return filename

    def log_text_change_image(self, text):
        """Print log imformation in text box."""
        for image_box in self.image_boxes:
            image_box.change_image_after_function()
        # debug
        print("log_text:", text)
        self.textbox.append(text)
Esempio n. 36
0
class Modifiers(QDialog, Ui_DailogModifiers):
    def __init__(self, title: str, get_filters):
        super().__init__()
        self.title = title
        self.left = 10
        self.top = 10
        self.setupUi(self)
        self.setupWindow()
        self.show()
        self.get_filters = get_filters
        self.fields = []
        self.protocols = []
        self.vbox = None
        self.currentFilterlName = None
        self.currentFilterData = None
        self.filters_combo_box: QComboBox
        self.dictionary = {}

        for filtr in self.get_filters:
            x = [n.strip() for n in filtr[1]]
            for layer in conf.layers:
                for string_name in x:
                    if layer.__name__ == string_name:
                        protocol = layer

            self.filters_combo_box.addItem(str(filtr[0]), userData=filtr[1])
            print(filtr[0], filtr[1])

        self.filters_combo_box.model().sort(0)
        self.filters_combo_box.activated.connect(self.handleActivated)
        self.add_push_button.clicked.connect(self.createTabWithFilter)

        self.tab_widget.tabCloseRequested.connect(self.removeTab)
        self.tab_widget.setTabsClosable(True)

    def removeTab(self, index):
        widget = self.tab_widget.widget(index)
        if widget is not None:
            widget.deleteLater()
        self.tab_widget.removeTab(index)

    def setupWindow(self):
        self.setWindowTitle(self.title)
        self.tab_widget: QTabWidget
        self.vertical_layout: QVBoxLayout
        self.horizontal_layout: QHBoxLayout
        self.name_line_edit: QLineEdit
        self.add_push_button: QPushButton
        self.filters_combo_box: QComboBox
        self.dialog_buttons: QDialogButtonBox

    def getValues(self):

        self.tab_widget: QTabWidget
        tab_number = self.tab_widget.count()

        returned_list = [[]]

        for tab_num in range(0, self.tab_widget.count()):
            tab: QWidget = self.tab_widget.widget(tab_num)

            protocol_name = self.tab_widget.tabText(tab_num)

            returned_list[tab_num].append(protocol_name)

            fields = tab.findChildren(QLabel)
            values = tab.findChildren(QLineEdit)

            for field_num in range(0, len(fields)):
                tmp = [fields[field_num].text(), values[field_num].text()]
                returned_list[tab_num].append(tmp)

            returned_list.append([])

        del returned_list[-1]
        name = self.name_line_edit.text()
        self.dictionary[name] = returned_list

        # print(self.dictionary)
        return self.dictionary

    def handleActivated(self, index):
        self.currentFilterName = self.filters_combo_box.itemText(index)
        self.currentFilterData = self.filters_combo_box.itemData(index)
        print(self.currentFilterName)
        print(self.currentFilterData)

    def createTabWithFilter(self):
        """
            create space in new tab(tab_widget) for filter fields
            
        """

        if self.tab_widget.count() > 0:
            print("modyfikator może użyc tylko jeden filter")
            return False

        if self.currentFilterName == "" or self.currentFilterData is None:
            print("Wybierz poprawnycurrentFilterData filtr")
            return False
        """
        if not need_layers == None:
            
            for layer in need_layers:
                self.currentFilterName=layer
                self.current_tab = QWidget()
                self.current_tab.setObjectName("tab_"+str(self.currentFilterName))
        
                self.tab_widget.addTab(self.current_tab, self.currentFilterName)

                self.vert_tab = QtWidgets.QVBoxLayout(self.current_tab)
                self.vert_tab.setObjectName("ver_"+str(self.currentFilterName))
                print(self.vert_tab)
    
                self.mapProtocolFields()
                return True
           """

        for protocol_name in self.currentFilterData:
            for layer in conf.layers:
                protocol = None

                if layer.__name__ == protocol_name:
                    protocol = layer
                    print(protocol)

                self.current_tab = QWidget()
                self.current_tab.setObjectName("tab_" +
                                               str(self.currentFilterName))

                self.tab_widget.addTab(self.current_tab, protocol.__name__)

                self.vert_tab = QtWidgets.QVBoxLayout(self.current_tab)
                self.vert_tab.setObjectName("ver_" +
                                            str(self.currentFilterName))
                print(self.vert_tab)

                self.mapProtocolFields(protocol)

    def mapProtocolFields(self, protocol: Packet):
        """
            save to fields variable tuples contains 3 values on attribute 
                   (field_name, scapy_field_type, set/default_value) 
        """
        self.fields = []
        for i in protocol.fields_desc:
            self.fields.append(
                (i.name, type(i), getattr(self.currentFilterData, i.name, 0)))
            self.addFilter()

    def disable_text_box(self, state):
        print(state)
        if state == 0:
            pass
        else:
            pass
        pass

    def addFilter(self):
        self.vbox = QVBoxLayout()
        self.vbox.setObjectName("vbox_" + self.currentFilterName)

        for field in self.fields:

            hbox = QHBoxLayout()
            hbox.setObjectName(self.currentFilterName)

            # Dodaj QLabel o danej nazwie obiektu
            label = QLabel(str(field[0]))
            label.width = 200
            label.height = 30
            label.maximumHeight = 30
            label.maximumWidth = 200
            hbox.addWidget(label)

            hbox.addWidget(QLineEdit())

            self.vbox.addStretch(1)
            self.vbox.addLayout(hbox)

        self.vert_tab.addLayout(self.vbox)
        self.update()
Esempio n. 37
0
    def add_tx_stats(self, vbox):
        hbox_stats = QHBoxLayout()

        # left column
        vbox_left = QVBoxLayout()
        self.tx_desc = TxDetailLabel(word_wrap=True)
        vbox_left.addWidget(self.tx_desc)
        self.status_label = TxDetailLabel()
        vbox_left.addWidget(self.status_label)
        self.date_label = TxDetailLabel()
        vbox_left.addWidget(self.date_label)
        self.amount_label = TxDetailLabel()
        vbox_left.addWidget(self.amount_label)
        self.ln_amount_label = TxDetailLabel()
        vbox_left.addWidget(self.ln_amount_label)

        fee_hbox = QHBoxLayout()
        self.fee_label = TxDetailLabel()
        fee_hbox.addWidget(self.fee_label)
        self.fee_warning_icon = QLabel()
        pixmap = QPixmap(icon_path("warning"))
        pixmap_size = round(2 * char_width_in_lineedit())
        pixmap = pixmap.scaled(pixmap_size, pixmap_size, Qt.KeepAspectRatio,
                               Qt.SmoothTransformation)
        self.fee_warning_icon.setPixmap(pixmap)
        self.fee_warning_icon.setVisible(False)
        fee_hbox.addWidget(self.fee_warning_icon)
        fee_hbox.addStretch(1)
        vbox_left.addLayout(fee_hbox)

        vbox_left.addStretch(1)
        hbox_stats.addLayout(vbox_left, 50)

        # vertical line separator
        line_separator = QFrame()
        line_separator.setFrameShape(QFrame.VLine)
        line_separator.setFrameShadow(QFrame.Sunken)
        line_separator.setLineWidth(1)
        hbox_stats.addWidget(line_separator)

        # right column
        vbox_right = QVBoxLayout()
        self.size_label = TxDetailLabel()
        vbox_right.addWidget(self.size_label)
        self.rbf_label = TxDetailLabel()
        vbox_right.addWidget(self.rbf_label)
        self.rbf_cb = QCheckBox(_('Replace by fee'))
        self.rbf_cb.setChecked(bool(self.config.get('use_rbf', True)))
        vbox_right.addWidget(self.rbf_cb)

        self.locktime_final_label = TxDetailLabel()
        vbox_right.addWidget(self.locktime_final_label)

        locktime_setter_hbox = QHBoxLayout()
        locktime_setter_hbox.setContentsMargins(0, 0, 0, 0)
        locktime_setter_hbox.setSpacing(0)
        locktime_setter_label = TxDetailLabel()
        locktime_setter_label.setText("LockTime: ")
        self.locktime_e = LockTimeEdit()
        locktime_setter_hbox.addWidget(locktime_setter_label)
        locktime_setter_hbox.addWidget(self.locktime_e)
        locktime_setter_hbox.addStretch(1)
        self.locktime_setter_widget = QWidget()
        self.locktime_setter_widget.setLayout(locktime_setter_hbox)
        vbox_right.addWidget(self.locktime_setter_widget)

        self.block_height_label = TxDetailLabel()
        vbox_right.addWidget(self.block_height_label)
        vbox_right.addStretch(1)
        hbox_stats.addLayout(vbox_right, 50)

        vbox.addLayout(hbox_stats)

        # below columns
        self.block_hash_label = TxDetailLabel(word_wrap=True)
        vbox.addWidget(self.block_hash_label)

        # set visibility after parenting can be determined by Qt
        self.rbf_label.setVisible(self.finalized)
        self.rbf_cb.setVisible(not self.finalized)
        self.locktime_final_label.setVisible(self.finalized)
        self.locktime_setter_widget.setVisible(not self.finalized)
Esempio n. 38
0
class TestsWidget(QWidget):
    def __init__(self, parent=None) -> None:
        """Test tab widget.

        """
        super(TestsWidget, self).__init__(parent=parent)
        logger.debug(f"initialised {type(self)} with parent={parent}")

        # instructions
        self.instructions = self.parent().instructions

        # layout
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # layout > options group box
        self.options_groupbox = QGroupBox(self.instructions[9])
        self.layout.addWidget(self.options_groupbox)
        self.options_groupbox_grid = QGridLayout()
        self.options_groupbox.setLayout(self.options_groupbox_grid)

        # layout > options group box > proband ID selection box
        self.options_groupbox_grid.addWidget(QLabel(self.instructions[47]), 0,
                                             0)
        self.proband_id_box = QComboBox()
        self.options_groupbox_grid.addWidget(self.proband_id_box, 0, 1)
        self.proband_id_box.setEditable(False)
        self.options_groupbox_grid.addWidget(QLabel(self.instructions[46]), 1,
                                             0, 3, 2)

        # layout > options group box > fullscreen
        self.fullscreen_checkbox = QCheckBox(self.instructions[10], self)
        self.options_groupbox_grid.addWidget(self.fullscreen_checkbox, 4, 0, 1,
                                             2)

        # layout > options group box > resume
        self.resume_checkbox = QCheckBox(self.instructions[11], self)
        self.options_groupbox_grid.addWidget(self.resume_checkbox, 5, 0, 1, 2)

        # layout > options group box > language selection box
        self.options_groupbox_grid.addWidget(QLabel(self.instructions[48]), 7,
                                             0)
        self.language_box = QComboBox()
        self.options_groupbox_grid.addWidget(self.language_box, 7, 1)
        self.language_box.setEditable(False)

        # layout > test group box
        self.test_groupbox = QGroupBox(self.instructions[13])
        self.layout.addWidget(self.test_groupbox)
        self.test_groupbox_grid = QGridLayout()
        self.test_groupbox.setLayout(self.test_groupbox_grid)

        # layout > test group box > test selection box
        self.test_groupbox_grid.addWidget(QLabel(self.instructions[14]), 0, 0)
        self.test_name_box = QComboBox(self)
        self.test_groupbox_grid.addWidget(self.test_name_box, 0, 1)
        self.test_name_box.setEditable(False)

        # layout > test group box > run test button
        self.test_button = QPushButton(self.instructions[15], self)
        self.test_groupbox_grid.addWidget(self.test_button, 1, 0, 1, 2)

        # layout > batch group box
        self.batch_groupbox = QGroupBox(self.instructions[16])
        self.layout.addWidget(self.batch_groupbox)
        self.batch_groupbox_grid = QGridLayout()
        self.batch_groupbox.setLayout(self.batch_groupbox_grid)

        # layout > batch group box > batch selection box
        self.batch_groupbox_grid.addWidget(QLabel(self.instructions[17]), 0, 0)
        self.batch_name_box = QComboBox(self)
        self.batch_groupbox_grid.addWidget(self.batch_name_box, 0, 1)
        self.batch_name_box.setEditable(False)
        self.batch_groupbox_grid.addWidget(QLabel(self.instructions[21]), 1, 0,
                                           1, 2)

        # layout > batch group box > run batch button
        self.batch_button = QPushButton(self.instructions[18], self)
        self.batch_groupbox_grid.addWidget(self.batch_button, 2, 0, 1, 2)

        # layout > stretch factor
        self.layout.addStretch(1)

        # populate
        logger.debug("creating default keywords")
        keywords = ("proband_id", "test_name", "language", "fullscreen",
                    "resumable")
        kwds = self.parent().parent().kwds.items()
        self.kwds = {k: v for k, v in kwds if k in keywords}
        self.proband_id_box.addItems(["TEST"] + proband_pickles())
        self.fullscreen_checkbox.setChecked(self.kwds["fullscreen"])
        self.resume_checkbox.setChecked(self.kwds["resumable"])
        self.language_box.addItems(["en"])
        self.test_name_box.addItems([""] + sorted(tests_list))
        self.batch_name_box.addItems([""] + sorted(batches_list))

        # connect buttons
        self.__begin = self.parent().parent(
        ).switch_central_widget  # store ref
        self.test_button.clicked.connect(self._run_single_test)
        self.batch_button.clicked.connect(self._run_batch)

    def _run_single_test(self) -> None:
        """Run a single test."""
        logger.debug("called _run_single_test()")
        s = self.proband_id_box.currentText()
        if s:
            self.kwds["proband_id"] = s
            self.kwds["fullscreen"] = self.fullscreen_checkbox.isChecked()
            self.kwds["resumable"] = self.resume_checkbox.isChecked()
            self.kwds["language"] = self.language_box.currentText()
            self.kwds["test_names"] = [self.test_name_box.currentText()]
            self._update_maiwindow_kwds()
        rsp = self._show_confirmation_box()
        if rsp == QMessageBox.Ok:
            self._begin()

    def _run_batch(self) -> None:
        """Run a single test."""
        logger.debug("called _run_batch()")
        s = self.proband_id_box.currentText()
        if s:
            self.kwds["proband_id"] = s
            self.kwds["fullscreen"] = self.fullscreen_checkbox.isChecked()
            self.kwds["resumable"] = self.resume_checkbox.isChecked()
            self.kwds["language"] = self.language_box.currentText()
            batch = self.batch_name_box.currentText()
            if batch in batches_list:
                tests = get_tests_from_batch(batch)
                self.kwds["test_names"] = tests
                self._update_maiwindow_kwds()
        rsp = self._show_confirmation_box()
        if rsp == QMessageBox.Ok:
            self._begin()

    def _show_confirmation_box(self) -> int:
        """Display a pop-up message box."""
        logger.debug("called _show_confirmation_box()")
        message_box = QMessageBox()
        s = self.instructions[57] % (
            self.kwds["proband_id"],
            "\n".join(self.kwds["test_names"]),
        )
        message_box.setText(s)
        message_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        return message_box.exec_()

    def _begin(self) -> None:
        logger.debug("called _begin()")
        data = SimpleProcedure(proband_id=self.kwds["proband_id"],
                               test_name=self.kwds["test_names"][0])
        proband_exists = exists(data.path)
        if proband_exists and not self.kwds["resumable"]:
            message_box = QMessageBox()
            msg = get_error_messages(self.kwds["language"], "proband_exists")
            message_box.setText(msg)
            message_box.exec_()
        else:
            self.__begin()

    def _update_maiwindow_kwds(self) -> None:
        """The following is quite possibly the worst bit of code I've ever written."""
        logger.debug("called _update_maiwindow_kwds()")
        self.parent().parent().parent().parent().parent().kwds.update(
            self.kwds)
    def __init__(self, parent):
        super().__init__(parent)
        self._preferences = parent
        container = QVBoxLayout(self)
        # Groups
        group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_DISPLAY_WRAPPING)
        group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_DISPLAY)
        group3 = QGroupBox(translations.TR_PREFERENCES_EDITOR_DISPLAY_LINT)

        # Text wrapping
        vbox = QVBoxLayout(group1)
        self._check_text_wrapping = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_DISPLAY_ENABLE_TEXT_WRAPPING)
        vbox.addWidget(self._check_text_wrapping)
        self._check_margin_line = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_DISPLAY_RIGHT_MARGIN_LABEL)
        hbox = QHBoxLayout()
        hbox.addWidget(self._check_margin_line)
        self._spin_margin_line = QSpinBox()
        hbox.addWidget(self._spin_margin_line)
        self._check_margin_line_background = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_DISPLAY_RIGHT_MARGIN_BACKGROUND)
        hbox.addWidget(self._check_margin_line_background)
        vbox.addLayout(hbox)

        # Display features
        vbox = QVBoxLayout(group2)
        self._check_platform_eol = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE)
        vbox.addWidget(self._check_platform_eol)
        self._check_lineno = QCheckBox(translations.TR_DISPLAY_LINE_NUMBERS)
        vbox.addWidget(self._check_lineno)
        self._check_indentation_guides = QCheckBox(
            translations.TR_SHOW_INDENTATION_GUIDES)
        vbox.addWidget(self._check_indentation_guides)
        self._check_text_changes = QCheckBox(
            translations.TR_DISPLAY_TEXT_CHANGES)
        vbox.addWidget(self._check_text_changes)
        self._check_brace_matching = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_DISPLAY_HIGHLIGHT_BRACKETS)
        vbox.addWidget(self._check_brace_matching)
        hbox = QHBoxLayout()
        self._check_current_line = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_DISPLAY_HIGHLIGHT_CURRENT_LINE)
        self._combo_current_line = QComboBox()
        self._combo_current_line.addItems(["Full", "Simple"])
        self._check_current_line.stateChanged.connect(
            lambda state: self._combo_current_line.setEnabled(state))
        hbox.addWidget(self._check_current_line)
        hbox.addWidget(self._combo_current_line)
        vbox.addLayout(hbox)
        self._check_show_tabs = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES)
        vbox.addWidget(self._check_show_tabs)
        self._check_highlight_results = QCheckBox(
            translations.TR_HIGHLIGHT_RESULT_ON_SCROLLBAR)
        vbox.addWidget(self._check_highlight_results)
        self._check_center_on_scroll = QCheckBox(
            translations.TR_CENTER_ON_SCROLL)
        vbox.addWidget(self._check_center_on_scroll)

        # Linter
        vbox = QVBoxLayout(group3)
        self._check_find_errors = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS)
        vbox.addWidget(self._check_find_errors)
        self._check_show_tooltip_error = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS)
        vbox.addWidget(self._check_show_tooltip_error,
                       alignment=Qt.AlignCenter)
        self._check_highlight_pep8 = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8)
        vbox.addWidget(self._check_highlight_pep8)
        self._check_show_tooltip_pep8 = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8)
        vbox.addWidget(self._check_show_tooltip_pep8, alignment=Qt.AlignCenter)
        self._check_highlight_pep8.stateChanged.connect(
            lambda state: self._check_show_tooltip_pep8.setEnabled(state))

        container.addWidget(group1)
        container.addWidget(group2)
        container.addWidget(group3)
        container.addStretch(1)

        # Settings
        self._check_text_wrapping.setChecked(settings.ALLOW_WORD_WRAP)
        self._check_highlight_pep8.setChecked(settings.CHECK_STYLE)
        self._check_indentation_guides.setChecked(
            settings.SHOW_INDENTATION_GUIDES)
        self._check_find_errors.setChecked(settings.FIND_ERRORS)
        self._check_show_tooltip_pep8.setEnabled(settings.CHECK_STYLE)
        self._check_show_tabs.setChecked(settings.SHOW_TABS_AND_SPACES)
        self._check_margin_line.setChecked(settings.SHOW_MARGIN_LINE)
        self._check_text_changes.setChecked(settings.SHOW_TEXT_CHANGES)
        self._spin_margin_line.setValue(settings.MARGIN_LINE)
        self._check_margin_line_background.setChecked(
            settings.MARGIN_LINE_BACKGROUND)
        self._check_current_line.setChecked(settings.HIGHLIGHT_CURRENT_LINE)
        self._combo_current_line.setCurrentIndex(
            settings.HIGHLIGHT_CURRENT_LINE_MODE)
        self._check_brace_matching.setChecked(settings.BRACE_MATCHING)
        self._check_lineno.setChecked(settings.SHOW_LINE_NUMBERS)

        self._preferences.savePreferences.connect(self._save)
Esempio n. 40
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 = []
        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))

        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)
        tx_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)
        tx_widgets.append((batch_rbf_cb, None))

        # lightning
        lightning_widgets = []

        help_local_wt = _("""If this option is checked, Electrum will
run a local watchtower to watch your channels if your wallet is not
open. For this to work, your computer needs to be online regularly.""")
        local_wt_cb = QCheckBox(_("Run a local watchtower"))
        local_wt_cb.setToolTip(help_local_wt)
        local_wt_cb.setChecked(bool(self.config.get('run_local_watchtower', False)))
        def on_local_wt_checked(x):
            self.config.set_key('run_local_watchtower', bool(x))
        local_wt_cb.stateChanged.connect(on_local_wt_checked)
        lightning_widgets.append((local_wt_cb, None))

        help_persist = _("""If this option is checked, Electrum will persist as a daemon after
you close all your wallet windows. Use this to keep your local watchtower running""")
        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))

        # units
        units = base_units_list
        msg = (_('Base unit of your wallet.')
               + '\n1 DOI = 1000 mDOI. 1 mDOI = 1000 uDOI. 1 uDOI = 100 swartz.\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))

        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.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 swartz 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')),
            (lightning_widgets, _('Lightning')),
            (fiat_widgets, _('Fiat')),
            (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)
Esempio n. 41
0
    def __init__(self, parent=None, aw=None):
        super(StatisticsDlg, self).__init__(parent, aw)
        self.setWindowTitle(
            QApplication.translate("Form Caption", "Statistics", None))
        self.setModal(True)
        self.timez = QCheckBox(QApplication.translate("CheckBox", "Time",
                                                      None))
        self.bar = QCheckBox(QApplication.translate("CheckBox", "Bar", None))
        self.dt = QCheckBox(deltaLabelUTF8 + self.aw.qmc.mode)
        self.ror = QCheckBox(self.aw.qmc.mode +
                             QApplication.translate("CheckBox", "/min", None))
        self.area = QCheckBox(
            QApplication.translate("CheckBox", "Characteristics", None))
        self.ShowStatsSummary = QCheckBox(
            QApplication.translate("CheckBox", "Summary", None))
        self.ShowStatsSummary.setChecked(self.aw.qmc.statssummary)
        self.ShowStatsSummary.stateChanged.connect(
            self.changeStatsSummary)  #toggle
        #temp fix for possible bug self.aw.qmc.statisticsflags=[] > empty list out of range
        if self.aw.qmc.statisticsflags:
            if self.aw.qmc.statisticsflags[0]:
                self.timez.setChecked(True)
            if self.aw.qmc.statisticsflags[1]:
                self.bar.setChecked(True)
            if self.aw.qmc.statisticsflags[3]:
                self.area.setChecked(True)
            if self.aw.qmc.statisticsflags[4]:
                self.ror.setChecked(True)
            if self.aw.qmc.statisticsflags[6]:
                self.dt.setChecked(True)
        else:
            self.aw.qmc.statisticsflags = [1, 1, 0, 1, 1, 0, 1]
            self.timez.setChecked(True)
            self.bar.setChecked(True)
            self.area.setChecked(True)
            self.ror.setChecked(True)
            self.dt.setChecked(False)
        self.timez.stateChanged.connect(self.changeStatisticsflag)
        self.bar.stateChanged.connect(self.changeStatisticsflag)
        # flag 2 not used anymore
        self.area.stateChanged.connect(self.changeStatisticsflag)
        self.ror.stateChanged.connect(self.changeStatisticsflag)
        # flag 5 not used anymore
        self.dt.stateChanged.connect(self.changeStatisticsflag)

        # connect the ArtisanDialog standard OK/Cancel buttons
        self.dialogbuttons.accepted.connect(self.accept)
        self.dialogbuttons.removeButton(
            self.dialogbuttons.button(QDialogButtonBox.Cancel))
        flagsLayout = QGridLayout()
        flagsLayout.addWidget(self.timez, 0, 0)
        flagsLayout.addWidget(self.bar, 0, 1)
        flagsLayout.addWidget(self.dt, 0, 2)
        flagsLayout.addWidget(self.ror, 0, 3)
        flagsLayout.addWidget(self.area, 0, 4)
        flagsLayout.addWidget(self.ShowStatsSummary, 0, 5)

        beginlabel = QLabel(QApplication.translate("Label", "From", None))
        beginitems = [
            QApplication.translate("Label", "CHARGE", None),
            QApplication.translate("Label", "TP", None),
            QApplication.translate("Label", "DRY END", None),
            QApplication.translate("Label", "FC START", None)
        ]
        self.beginComboBox = QComboBox()
        self.beginComboBox.setFocusPolicy(Qt.NoFocus)
        self.beginComboBox.setMaximumWidth(120)
        self.beginComboBox.addItems(beginitems)
        self.beginComboBox.setCurrentIndex(self.aw.qmc.AUCbegin)
        baselabel = QLabel(QApplication.translate("Label", "Base", None))
        self.baseedit = QSpinBox()
        self.baseedit.setAlignment(Qt.AlignRight)
        self.baseedit.setRange(0, 999)
        self.baseedit.setValue(self.aw.qmc.AUCbase)
        if self.aw.qmc.mode == "F":
            self.baseedit.setSuffix(" F")
        else:
            self.baseedit.setSuffix(" C")
        self.baseFlag = QCheckBox(
            QApplication.translate("CheckBox", "From Event", None))
        self.baseedit.setEnabled(not self.aw.qmc.AUCbaseFlag)
        self.baseFlag.setChecked(self.aw.qmc.AUCbaseFlag)
        self.baseFlag.stateChanged.connect(self.switchAUCbase)
        targetlabel = QLabel(QApplication.translate("Label", "Target", None))
        self.targetedit = QSpinBox()
        self.targetedit.setAlignment(Qt.AlignRight)
        self.targetedit.setRange(0, 9999)
        self.targetedit.setValue(self.aw.qmc.AUCtarget)
        self.targetFlag = QCheckBox(
            QApplication.translate("CheckBox", "Background", None))
        self.targetedit.setEnabled(not self.aw.qmc.AUCtargetFlag)
        self.targetFlag.setChecked(self.aw.qmc.AUCtargetFlag)
        self.targetFlag.stateChanged.connect(self.switchAUCtarget)
        self.guideFlag = QCheckBox(
            QApplication.translate("CheckBox", "Guide", None))
        self.guideFlag.setChecked(self.aw.qmc.AUCguideFlag)
        self.AUClcdFlag = QCheckBox(
            QApplication.translate("CheckBox", "LCD", None))
        self.AUClcdFlag.setChecked(self.aw.qmc.AUClcdFlag)
        self.AUClcdFlag.stateChanged.connect(self.AUCLCFflagChanged)
        self.AUCshowFlag = QCheckBox(
            QApplication.translate("CheckBox", "Show Area", None))
        self.AUCshowFlag.setChecked(self.aw.qmc.AUCshowFlag)
        self.AUCshowFlag.stateChanged.connect(self.changeAUCshowFlag)

        statsmaxchrperlinelabel = QLabel(
            QApplication.translate("Label", "Max characters per line", None))
        self.statsmaxchrperlineedit = QSpinBox()
        self.statsmaxchrperlineedit.setAlignment(Qt.AlignRight)
        self.statsmaxchrperlineedit.setRange(1, 120)
        self.statsmaxchrperlineedit.setValue(self.aw.qmc.statsmaxchrperline)
        self.statsmaxchrperlineedit.setFocusPolicy(Qt.StrongFocus)
        statsmaxchrperlineHorizontal = QHBoxLayout()
        statsmaxchrperlineHorizontal.addWidget(statsmaxchrperlinelabel)
        statsmaxchrperlineHorizontal.addWidget(self.statsmaxchrperlineedit)
        statsmaxchrperlineHorizontal.addStretch()
        statsmaxchrperlineGroupLayout = QGroupBox(
            QApplication.translate("GroupBox", "Stats Summary", None))
        statsmaxchrperlineGroupLayout.setLayout(statsmaxchrperlineHorizontal)

        AUCgrid = QGridLayout()
        AUCgrid.addWidget(beginlabel, 0, 0, Qt.AlignRight)
        AUCgrid.addWidget(self.beginComboBox, 0, 1, 1, 2)
        AUCgrid.addWidget(baselabel, 1, 0, Qt.AlignRight)
        AUCgrid.addWidget(self.baseedit, 1, 1)
        AUCgrid.addWidget(self.baseFlag, 1, 2)
        AUCgrid.addWidget(targetlabel, 2, 0, Qt.AlignRight)
        AUCgrid.addWidget(self.targetedit, 2, 1)
        AUCgrid.addWidget(self.targetFlag, 2, 2)
        AUCgrid.setRowMinimumHeight(3, 20)

        aucFlagsLayout = QHBoxLayout()
        aucFlagsLayout.addStretch()
        aucFlagsLayout.addWidget(self.AUClcdFlag)
        aucFlagsLayout.addSpacing(10)
        aucFlagsLayout.addWidget(self.guideFlag)
        aucFlagsLayout.addSpacing(10)
        aucFlagsLayout.addWidget(self.AUCshowFlag)
        aucFlagsLayout.addStretch()

        AUCvertical = QVBoxLayout()
        AUCvertical.addLayout(AUCgrid)
        AUCvertical.addLayout(aucFlagsLayout)
        AUCvertical.addStretch()
        AUCgroupLayout = QGroupBox(
            QApplication.translate("GroupBox", "AUC", None))
        AUCgroupLayout.setLayout(AUCvertical)
        displayGroupLayout = QGroupBox(
            QApplication.translate("GroupBox", "Display", None))
        displayGroupLayout.setLayout(flagsLayout)
        buttonsLayout = QHBoxLayout()
        buttonsLayout.addWidget(self.dialogbuttons)
        vgroupLayout = QVBoxLayout()
        vgroupLayout.addWidget(AUCgroupLayout)
        vgroupLayout.addWidget(statsmaxchrperlineGroupLayout)
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(displayGroupLayout)
        mainLayout.addLayout(vgroupLayout)
        mainLayout.addStretch()
        mainLayout.addLayout(buttonsLayout)
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(mainLayout)
        self.dialogbuttons.button(QDialogButtonBox.Ok).setFocus()

        settings = QSettings()
        if settings.contains("StatisticsPosition"):
            self.move(settings.value("StatisticsPosition"))

        mainLayout.setSizeConstraint(QLayout.SetFixedSize)
Esempio n. 42
0
class _ArgIOOrderPanel(QDialog):
    """ The panel of I/O order list. """

    def __init__(self, parent):
        super().__init__(parent)
        self.setFixedSize(320, 280)
        self.setWindowTitle(parent.title)
        # init widgets
        self.order_list = QListWidget(self)
        self.order_list.setAlternatingRowColors(True)
        # init buttons
        self.btn_up = MiniSquareButton(icon=icon['MINI_UP'])
        self.btn_down = MiniSquareButton(icon=icon['MINI_DOWN'])
        self.btn_cancel = MiniSquareButton(icon=icon['MINI_CANCEL'])
        self.btn_confirm = MiniSquareButton(icon=icon['MINI_CONFIRM'])
        # buttons layout
        self.btn1_layout = QVBoxLayout()
        self.btn1_layout.addWidget(self.btn_up, alignment=Qt.AlignTop)
        self.btn1_layout.addWidget(self.btn_down, alignment=Qt.AlignTop)
        self.btn1_layout.addStretch(1)
        self.btn2_layout = QVBoxLayout()
        self.btn2_layout.addWidget(self.btn_cancel, alignment=Qt.AlignBottom)
        self.btn2_layout.addWidget(self.btn_confirm, alignment=Qt.AlignBottom)
        self.btn2_layout.addStretch(1)
        self.btn_layout = QVBoxLayout()
        self.btn_layout.addLayout(self.btn1_layout)
        self.btn_layout.addLayout(self.btn2_layout)
        # main layout
        self.layout = QHBoxLayout(self)
        self.layout.addWidget(self.order_list, alignment=Qt.AlignLeft)
        self.layout.addLayout(self.btn_layout)
        # init slots
        self.btn_up.clicked.connect(self._up_pressed_handler)
        self.btn_down.clicked.connect(self._down_pressed_handler)
        self.btn_cancel.clicked.connect(self._cancel_pressed_handler)
        self.btn_confirm.clicked.connect(self._confirm_pressed_handler)
        # temp
        self.semaphore: dict = None
        self.result: list = None

    def __call__(self, semaphore: dict):
        self.semaphore = semaphore
        self.initialize_semaphore()
        self.exec()
        return self.result

    def initialize_semaphore(self):
        # load items into list widget.
        self.order_list.clear()
        for key, vn_item in self.semaphore.items():
            self.order_list.addItem(
                _ArgIOOrderPanelListItem(vn_item.value, key=key)
            )

    def _up_pressed_handler(self):
        # selected or first item
        idx = self.order_list.currentRow()
        if idx > 0:
            item = self.order_list.takeItem(idx)
            self.order_list.insertItem(idx - 1, item)
            del item

    def _down_pressed_handler(self):
        idx = self.order_list.currentRow()
        if idx < self.order_list.count() - 1:
            item = self.order_list.takeItem(idx)
            self.order_list.insertItem(idx + 1, item)
            del item

    def _cancel_pressed_handler(self):
        # close and recover
        self.close()
        self.initialize_semaphore()
        self.semaphore = None
        self.result = None

    def _confirm_pressed_handler(self):
        # close and accept changes
        self.close()
        new_keys = []
        for row in range(self.order_list.count()):
            item = self.order_list.item(row)
            new_keys.append(item.key)
        self.result = new_keys
        self.semaphore = None
Esempio n. 43
0
    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)
Esempio n. 44
0
    def __init__(self, window, plugin, keystore, device_id):
        title = _("{} Settings").format(plugin.device)
        super(SettingsDialog, self).__init__(window, title)
        self.setMaximumWidth(540)

        devmgr = plugin.device_manager()
        config = devmgr.config
        handler = keystore.handler
        thread = keystore.thread
        hs_cols, hs_rows = (128, 64)

        def invoke_client(method, *args, **kw_args):
            unpair_after = kw_args.pop('unpair_after', False)

            def task():
                client = devmgr.client_by_id(device_id)
                if not client:
                    raise RuntimeError("Device not connected")
                if method:
                    getattr(client, method)(*args, **kw_args)
                if unpair_after:
                    devmgr.unpair_id(device_id)
                return client.features

            thread.add(task, on_success=update)

        def update(features):
            self.features = features
            set_label_enabled()
            if features.bootloader_hash:
                bl_hash = bh2u(features.bootloader_hash)
                bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
            else:
                bl_hash = "N/A"
            noyes = [_("No"), _("Yes")]
            endis = [_("Enable Passphrases"), _("Disable Passphrases")]
            disen = [_("Disabled"), _("Enabled")]
            setchange = [_("Set a PIN"), _("Change PIN")]

            version = "%d.%d.%d" % (features.major_version,
                                    features.minor_version,
                                    features.patch_version)

            device_label.setText(features.label)
            pin_set_label.setText(noyes[features.pin_protection])
            passphrases_label.setText(disen[features.passphrase_protection])
            bl_hash_label.setText(bl_hash)
            label_edit.setText(features.label)
            device_id_label.setText(features.device_id)
            initialized_label.setText(noyes[features.initialized])
            version_label.setText(version)
            clear_pin_button.setVisible(features.pin_protection)
            clear_pin_warning.setVisible(features.pin_protection)
            pin_button.setText(setchange[features.pin_protection])
            pin_msg.setVisible(not features.pin_protection)
            passphrase_button.setText(endis[features.passphrase_protection])
            language_label.setText(features.language)

        def set_label_enabled():
            label_apply.setEnabled(label_edit.text() != self.features.label)

        def rename():
            invoke_client('change_label', label_edit.text())

        def toggle_passphrase():
            title = _("Confirm Toggle Passphrase Protection")
            currently_enabled = self.features.passphrase_protection
            if currently_enabled:
                msg = _("After disabling passphrases, you can only pair this "
                        "Electrum wallet if it had an empty passphrase.  "
                        "If its passphrase was not empty, you will need to "
                        "create a new wallet with the install wizard.  You "
                        "can use this wallet again at any time by re-enabling "
                        "passphrases and entering its passphrase.")
            else:
                msg = _("Your current Electrum wallet can only be used with "
                        "an empty passphrase.  You must create a separate "
                        "wallet with the install wizard for other passphrases "
                        "as each one generates a new set of addresses.")
            msg += "\n\n" + _("Are you sure you want to proceed?")
            if not self.question(msg, title=title):
                return
            invoke_client('toggle_passphrase', unpair_after=currently_enabled)

        def change_homescreen():
            dialog = QFileDialog(self, _("Choose Homescreen"))
            filename, __ = dialog.getOpenFileName()
            if not filename:
                return  # user cancelled

            if filename.endswith('.toif'):
                img = open(filename, 'rb').read()
                if img[:8] != b'TOIf\x90\x00\x90\x00':
                    handler.show_error(
                        'File is not a TOIF file with size of 144x144')
                    return
            else:
                from PIL import Image  # FIXME
                im = Image.open(filename)
                if im.size != (128, 64):
                    handler.show_error('Image must be 128 x 64 pixels')
                    return
                im = im.convert('1')
                pix = im.load()
                img = bytearray(1024)
                for j in range(64):
                    for i in range(128):
                        if pix[i, j]:
                            o = (i + j * 128)
                            img[o // 8] |= (1 << (7 - o % 8))
                img = bytes(img)
            invoke_client('change_homescreen', img)

        def clear_homescreen():
            invoke_client('change_homescreen', b'\x00')

        def set_pin():
            invoke_client('set_pin', remove=False)

        def clear_pin():
            invoke_client('set_pin', remove=True)

        def wipe_device():
            wallet = window.wallet
            if wallet and sum(wallet.get_balance()):
                title = _("Confirm Device Wipe")
                msg = _("Are you SURE you want to wipe the device?\n"
                        "Your wallet still has MonetaryUnits in it!")
                if not self.question(
                        msg, title=title, icon=QMessageBox.Critical):
                    return
            invoke_client('wipe_device', unpair_after=True)

        def slider_moved():
            mins = timeout_slider.sliderPosition()
            timeout_minutes.setText(_("{:2d} minutes").format(mins))

        def slider_released():
            config.set_session_timeout(timeout_slider.sliderPosition() * 60)

        # Information tab
        info_tab = QWidget()
        info_layout = QVBoxLayout(info_tab)
        info_glayout = QGridLayout()
        info_glayout.setColumnStretch(2, 1)
        device_label = QLabel()
        pin_set_label = QLabel()
        passphrases_label = QLabel()
        version_label = QLabel()
        device_id_label = QLabel()
        bl_hash_label = QLabel()
        bl_hash_label.setWordWrap(True)
        language_label = QLabel()
        initialized_label = QLabel()
        rows = [
            (_("Device Label"), device_label),
            (_("PIN set"), pin_set_label),
            (_("Passphrases"), passphrases_label),
            (_("Firmware Version"), version_label),
            (_("Device ID"), device_id_label),
            (_("Bootloader Hash"), bl_hash_label),
            (_("Language"), language_label),
            (_("Initialized"), initialized_label),
        ]
        for row_num, (label, widget) in enumerate(rows):
            info_glayout.addWidget(QLabel(label), row_num, 0)
            info_glayout.addWidget(widget, row_num, 1)
        info_layout.addLayout(info_glayout)

        # Settings tab
        settings_tab = QWidget()
        settings_layout = QVBoxLayout(settings_tab)
        settings_glayout = QGridLayout()

        # Settings tab - Label
        label_msg = QLabel(
            _("Name this {}.  If you have multiple devices "
              "their labels help distinguish them.").format(plugin.device))
        label_msg.setWordWrap(True)
        label_label = QLabel(_("Device Label"))
        label_edit = QLineEdit()
        label_edit.setMinimumWidth(150)
        label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
        label_apply = QPushButton(_("Apply"))
        label_apply.clicked.connect(rename)
        label_edit.textChanged.connect(set_label_enabled)
        settings_glayout.addWidget(label_label, 0, 0)
        settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
        settings_glayout.addWidget(label_apply, 0, 3)
        settings_glayout.addWidget(label_msg, 1, 1, 1, -1)

        # Settings tab - PIN
        pin_label = QLabel(_("PIN Protection"))
        pin_button = QPushButton()
        pin_button.clicked.connect(set_pin)
        settings_glayout.addWidget(pin_label, 2, 0)
        settings_glayout.addWidget(pin_button, 2, 1)
        pin_msg = QLabel(
            _("PIN protection is strongly recommended.  "
              "A PIN is your only protection against someone "
              "stealing your MonetaryUnits if they obtain physical "
              "access to your {}.").format(plugin.device))
        pin_msg.setWordWrap(True)
        pin_msg.setStyleSheet("color: red")
        settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)

        # Settings tab - Homescreen
        homescreen_label = QLabel(_("Homescreen"))
        homescreen_change_button = QPushButton(_("Change..."))
        homescreen_clear_button = QPushButton(_("Reset"))
        homescreen_change_button.clicked.connect(change_homescreen)
        try:
            import PIL
        except ImportError:
            homescreen_change_button.setDisabled(True)
            homescreen_change_button.setToolTip(
                _("Required package 'PIL' is not available - Please install it or use the Trezor website instead."
                  ))
        homescreen_clear_button.clicked.connect(clear_homescreen)
        homescreen_msg = QLabel(
            _("You can set the homescreen on your "
              "device to personalize it.  You must "
              "choose a {} x {} monochrome black and "
              "white image.").format(hs_cols, hs_rows))
        homescreen_msg.setWordWrap(True)
        settings_glayout.addWidget(homescreen_label, 4, 0)
        settings_glayout.addWidget(homescreen_change_button, 4, 1)
        settings_glayout.addWidget(homescreen_clear_button, 4, 2)
        settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)

        # Settings tab - Session Timeout
        timeout_label = QLabel(_("Session Timeout"))
        timeout_minutes = QLabel()
        timeout_slider = QSlider(Qt.Horizontal)
        timeout_slider.setRange(1, 60)
        timeout_slider.setSingleStep(1)
        timeout_slider.setTickInterval(5)
        timeout_slider.setTickPosition(QSlider.TicksBelow)
        timeout_slider.setTracking(True)
        timeout_msg = QLabel(
            _("Clear the session after the specified period "
              "of inactivity.  Once a session has timed out, "
              "your PIN and passphrase (if enabled) must be "
              "re-entered to use the device."))
        timeout_msg.setWordWrap(True)
        timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
        slider_moved()
        timeout_slider.valueChanged.connect(slider_moved)
        timeout_slider.sliderReleased.connect(slider_released)
        settings_glayout.addWidget(timeout_label, 6, 0)
        settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
        settings_glayout.addWidget(timeout_minutes, 6, 4)
        settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
        settings_layout.addLayout(settings_glayout)
        settings_layout.addStretch(1)

        # Advanced tab
        advanced_tab = QWidget()
        advanced_layout = QVBoxLayout(advanced_tab)
        advanced_glayout = QGridLayout()

        # Advanced tab - clear PIN
        clear_pin_button = QPushButton(_("Disable PIN"))
        clear_pin_button.clicked.connect(clear_pin)
        clear_pin_warning = QLabel(
            _("If you disable your PIN, anyone with physical access to your "
              "{} device can spend your MonetaryUnits.").format(plugin.device))
        clear_pin_warning.setWordWrap(True)
        clear_pin_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(clear_pin_button, 0, 2)
        advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)

        # Advanced tab - toggle passphrase protection
        passphrase_button = QPushButton()
        passphrase_button.clicked.connect(toggle_passphrase)
        passphrase_msg = WWLabel(PASSPHRASE_HELP)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(passphrase_button, 3, 2)
        advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
        advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)

        # Advanced tab - wipe device
        wipe_device_button = QPushButton(_("Wipe Device"))
        wipe_device_button.clicked.connect(wipe_device)
        wipe_device_msg = QLabel(
            _("Wipe the device, removing all data from it.  The firmware "
              "is left unchanged."))
        wipe_device_msg.setWordWrap(True)
        wipe_device_warning = QLabel(
            _("Only wipe a device if you have the recovery seed written down "
              "and the device wallet(s) are empty, otherwise the MonetaryUnits "
              "will be lost forever."))
        wipe_device_warning.setWordWrap(True)
        wipe_device_warning.setStyleSheet("color: red")
        advanced_glayout.addWidget(wipe_device_button, 6, 2)
        advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
        advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
        advanced_layout.addLayout(advanced_glayout)
        advanced_layout.addStretch(1)

        tabs = QTabWidget(self)
        tabs.addTab(info_tab, _("Information"))
        tabs.addTab(settings_tab, _("Settings"))
        tabs.addTab(advanced_tab, _("Advanced"))
        dialog_vbox = QVBoxLayout(self)
        dialog_vbox.addWidget(tabs)
        dialog_vbox.addLayout(Buttons(CloseButton(self)))

        # Update information
        invoke_client(None)
Esempio n. 45
0
class PomodoroWindow(CenterWindow):
    def __init__(self, controller, issue_key, issue_title, tray_icon):
        super().__init__()
        self.center()
        self.setStyleSheet(QSS)
        self.controller = controller
        self.tray_icon = tray_icon
        if not os.path.exists(LOGGED_TIME_DIR):
            os.mkdir(LOGGED_TIME_DIR)
        self.LOG_PATH = os.path.join(
            LOGGED_TIME_DIR, '{}.txt'.format(issue_key)
        )
        self.setWindowTitle('Pomodoro Timer')
        self.settings = QSettings('Spherical', 'Jira Quick Reporter')
        pomodoro_settings = int(self.settings.value(POMODORO, 25))
        long_break_settings = int(self.settings.value(LONG_BREAK, 15))
        short_break_settings = int(self.settings.value(SHORT_BREAK, 5))

        self.time_dict = dict(
            short=QTime(0, short_break_settings, 0),
            long=QTime(0, long_break_settings, 0),
            pomodoro=QTime(0, pomodoro_settings, 0)
        )

        self.issue_key = issue_key
        self.issue_title = issue_title
        self.pomodoros_count = 0
        self.current_time_name = POMODORO
        self.is_active_timer = False
        self.logged_time = QTime(0, 0, 0)
        self.time = self.time_dict[POMODORO]
        self.time_in_seconds = QTime(0, 0, 0).secsTo(self.time)

        self.timer_box = QVBoxLayout()
        self.main_box = QHBoxLayout()
        self.setLayout(self.main_box)

        self.issue_label = QLabel(
            '{}: {}'.format(self.issue_key, self.issue_title)
        )
        self.issue_label.setAlignment(Qt.AlignCenter)
        self.issue_label.setObjectName('issue_label')
        self.issue_label.setWordWrap(True)
        self.issue_label.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Fixed
        )

        self.pbar = QProgressBar()
        self.pbar.setRange(0, self.time_in_seconds)
        self.pbar.setValue(0)
        self.pbar.setTextVisible(False)
        self.timer = QTimer()

        self.timer.timeout.connect(self.handle_timer)
        self.time_label = QLabel()
        self.time_label.setObjectName('time_label')
        self.time_label.setText(self.time.toString('mm:ss'))
        self.time_label.setAlignment(Qt.AlignCenter)

        self.btns_box = QHBoxLayout()
        self.start_btn = QPushButton('Start')
        self.start_btn.clicked.connect(self.toggle_timer)

        self.stop_btn = QPushButton('Stop')
        self.stop_btn.clicked.connect(self.toggle_timer)

        self.logwork_btn = QPushButton('Log work')
        self.logwork_btn.clicked.connect(
            lambda: self.controller.open_time_log(issue_key)
        )
        self.logwork_btn.setEnabled(False)

        self.btns_box.addWidget(self.start_btn)
        self.btns_box.addWidget(self.stop_btn)
        self.btns_box.addWidget(self.logwork_btn)

        self.pomodoros_box = QHBoxLayout()
        self.pomodoros_box.setSpacing(5)
        self.pomodoros_count_label = QLabel()
        self.pomodoros_count_label.setObjectName('pomodoros_count')

        self.timer_box.addWidget(self.issue_label)
        self.timer_box.addStretch()
        self.timer_box.addWidget(self.time_label)
        self.timer_box.addWidget(self.pbar, Qt.AlignCenter)
        self.timer_box.addLayout(self.btns_box)
        self.timer_box.addLayout(self.pomodoros_box)
        self.timer_box.addStretch()
        self.main_box.addLayout(self.timer_box)

        self.action_show_time = QAction(self)
        self.action_show_time.setEnabled(False)
        self.action_open_timer = QAction('Open timer', self)
        self.action_open_timer.triggered.connect(self.show)
        self.action_quit_timer = QAction('Quit timer', self)
        self.action_quit_timer.triggered.connect(self.quit)
        self.action_settings = QAction('Settings', self)

        self.settings_window = Settings(self)

        self.action_settings.triggered.connect(self.settings_window.show)
        self.action_reset = QAction('Reset timer', self)
        self.action_reset.triggered.connect(self.reset_timer)
        self.action_start_timer = QAction('Start', self)
        self.action_start_timer.triggered.connect(self.toggle_timer)
        self.action_stop_timer = QAction('Stop', self)
        self.action_stop_timer.triggered.connect(self.toggle_timer)
        self.action_log_work = QAction('Log work', self)
        self.action_log_work.triggered.connect(
            lambda: self.controller.open_time_log(issue_key)
        )
        self.action_log_work.setEnabled(False)

        self.tray_icon.contextMenu().addSeparator()
        self.tray_icon.contextMenu().addAction(self.action_show_time)
        self.action_show_time.setText(self.time.toString('mm:ss'))
        self.tray_icon.contextMenu().addAction(self.action_open_timer)
        self.tray_icon.contextMenu().addAction(self.action_settings)
        self.tray_icon.contextMenu().addAction(self.action_quit_timer)
        self.tray_icon.contextMenu().addSeparator()
        self.tray_icon.contextMenu().addAction(self.action_start_timer)
        self.tray_icon.contextMenu().addAction(self.action_stop_timer)
        self.tray_icon.contextMenu().addAction(self.action_reset)
        self.tray_icon.contextMenu().addAction(self.action_log_work)

    def log_work_if_file_exists(self):
        if os.path.exists(self.LOG_PATH):
            reply = QMessageBox.question(
                self,
                'Warning',
                'You have not logged your work.\n Do you want to log it?',
                QMessageBox.Yes | QMessageBox.No
            )
            if reply == QMessageBox.Yes:
                self.controller.open_time_log(self.issue_key)
            else:
                os.remove(self.LOG_PATH)

    def update_time_from_settings(self, minutes, time_name):
        if self.current_time_name != time_name:
            self.time_dict[time_name].setHMS(0, minutes, 0)
        elif not self.is_active_timer:
            self.time_dict[time_name].setHMS(0, minutes, 0)
            self.update_timer()
        elif self.time_dict[time_name].minute() > minutes:
            spent_time_seconds = self.time.secsTo(self.time_dict[time_name])
            if minutes <= spent_time_seconds // 60:
                self.stop_timer()
                QSound.play(RING_SOUND_PATH)
                self.set_timer()
            else:
                time_diff = self.time_dict[time_name].minute() - minutes
                self.change_timer(minutes, -time_diff)
        elif self.time_dict[time_name].minute() < minutes:
            time_diff = minutes - self.time_dict[time_name].minute()
            self.change_timer(minutes, time_diff)

    def change_timer(self, minutes, time_diff):
        self.time_dict[self.current_time_name].setHMS(0, minutes, 0)
        self.time = self.time.addSecs(time_diff * 60)
        self.time_in_seconds = minutes * 60
        self.pbar.setMaximum(self.time_in_seconds)
        self.time_label.setText(self.time.toString('mm:ss'))
        self.action_show_time.setText(self.time.toString('mm:ss'))

    def handle_timer(self):
        """
        Updates timer label and progress bar every second
        until time is over
        """

        value = self.pbar.value()
        if value < self.time_in_seconds:
            value += 1
            self.pbar.setValue(value)
            self.time = self.time.addSecs(-1)
            self.time_label.setText(self.time.toString('mm:ss'))
            self.action_show_time.setText(self.time.toString('mm:ss'))
            if not value % 60:
                self.log_time()
        else:
            self.stop_timer()
            QSound.play(RING_SOUND_PATH)
            if self.current_time_name != POMODORO:
                self.tray_icon.showMessage(
                    'Pomodoro',
                    'Your break is over',
                    msecs=2000)
            self.set_timer()

    def update_timer(self):
        self.time_in_seconds = QTime(0, 0, 0).secsTo(self.time)
        self.pbar.setMaximum(self.time_in_seconds)
        self.pbar.setValue(0)
        self.time_label.setText(self.time.toString('mm:ss'))
        self.action_show_time.setText(self.time.toString('mm:ss'))

    def set_pomodoro_timer(self):
        self.is_active_timer = False
        self.current_time_name = POMODORO
        self.time = self.time_dict[POMODORO]
        self.update_timer()

    def set_pomodoro_count(self):
        """
        Set pomodoro mark and number of past pomodoros
        """

        self.clear_pomodoros()
        label = QLabel()
        pixmap = QPixmap(POMODORO_MARK_PATH)
        label.setPixmap(pixmap)
        self.pomodoros_box.addWidget(self.pomodoros_count_label)
        self.pomodoros_count_label.setSizePolicy(
                QSizePolicy.Fixed, QSizePolicy.Expanding
            )
        self.pomodoros_box.addWidget(label)
        self.pomodoros_count_label.setText(str(self.pomodoros_count))

    def set_pomodoro_img(self):
        label = QLabel()
        pixmap = QPixmap(POMODORO_MARK_PATH)
        label.setPixmap(pixmap)
        if self.pomodoros_count > 1:
            self.pomodoros_box.itemAt(
                self.pomodoros_count - 2
            ).widget().setSizePolicy(
                QSizePolicy.Fixed, QSizePolicy.Expanding
            )
        self.pomodoros_box.addWidget(label)

    def clear_pomodoros(self):
        for _ in range(self.pomodoros_box.count()):
            self.pomodoros_box.itemAt(0).widget().setParent(None)

    def toggle_timer(self):
        sender = self.sender().text()
        if sender in ['Start', 'Resume']:
            self.start_timer()
        elif sender == 'Pause':
            self.pause_timer()
        else:
            self.stop_timer()
            self.set_pomodoro_timer()

    def log_time(self):
        self.logged_time = self.logged_time.addSecs(60)
        with open(self.LOG_PATH, 'w') as log_file:
            log_file.write(self.logged_time.toString('h:m'))

    def start_timer(self):
        self.is_active_timer = True
        # change style before a break
        if self.current_time_name != POMODORO:
            self.issue_label.setObjectName('issue_label_break')
            self.issue_label.setStyleSheet('issue_label_break')
            self.pbar.setObjectName('break')
            self.pbar.setStyleSheet('break')
            self.stop_btn.hide()
            self.start_btn.setText('Stop')
            self.action_start_timer.setEnabled(False)
        else:
            self.tray_icon.showMessage(
                'Pomodoro',
                'Focus on your task',
                msecs=2000
            )
            self.start_btn.setText('Pause')
            self.action_start_timer.setText('Pause')
        self.logwork_btn.setEnabled(False)
        self.action_log_work.setEnabled(False)
        self.timer.start(1000)

    def stop_timer(self):
        self.timer.stop()
        self.is_active_timer = False
        self.start_btn.setText('Start')
        self.action_start_timer.setText('Start')
        self.logwork_btn.setEnabled(True)
        self.action_log_work.setEnabled(True)
        if self.current_time_name != POMODORO:
            self.stop_btn.show()
            self.action_start_timer.setEnabled(True)

        # change style after a break
        self.issue_label.setObjectName('issue_label')
        self.issue_label.setStyleSheet('issue_label')
        self.pbar.setObjectName('')
        self.pbar.setStyleSheet('')

    def pause_timer(self):
        self.timer.stop()
        self.start_btn.setText('Resume')
        self.action_start_timer.setText('Resume')
        self.logwork_btn.setEnabled(True)
        self.action_log_work.setEnabled(True)

    def reset_timer(self):
        self.logwork_btn.setEnabled(False)
        self.action_log_work.setEnabled(False)
        self.stop_timer()
        self.pomodoros_count = 0
        self.logged_time.setHMS(0, 0, 0)
        self.clear_pomodoros()
        self.set_pomodoro_timer()
        if os.path.exists(self.LOG_PATH):
            os.remove(self.LOG_PATH)

    def set_pomodoro_mark(self):
        if self.pomodoros_count < 5:
            self.set_pomodoro_img()
        elif self.pomodoros_count == 5:
            self.set_pomodoro_count()
        else:
            self.pomodoros_count_label.setText(
                str(self.pomodoros_count)
            )

    def set_timer(self):
        """
        In this method decides which timer will go next
        """

        # if pomodoro time's up
        if self.current_time_name == POMODORO:
            self.pomodoros_count += 1
            self.set_pomodoro_mark()

            # if four pomodoros have completed
            if not self.pomodoros_count % 4:
                self.current_time_name = LONG_BREAK
            else:
                self.current_time_name = SHORT_BREAK
            dialog = BreakDialog(self.current_time_name)

            # close dialog after 4 seconds
            QTimer.singleShot(4000, dialog.close)

            # get break name (short, long or skip) from dialog
            self.current_time_name = dialog.exec()
            if self.current_time_name != POMODORO:
                self.time = self.time_dict[self.current_time_name]
                self.update_timer()
                self.start_timer()
                return

        # if break time's up
        self.set_pomodoro_timer()

    def quit(self):
        if os.path.exists(self.LOG_PATH):
            reply = QMessageBox.question(
                self,
                'Warning',
                'You did not log your work. \nAre you sure you want to exit?',
                QMessageBox.Yes, QMessageBox.No
            )
            if reply == QMessageBox.No:
                return False

        self.settings.setValue(
            POMODORO, self.time_dict[POMODORO].minute()
        )
        self.settings.setValue(
            LONG_BREAK, self.time_dict[LONG_BREAK].minute()
        )
        self.settings.setValue(
            SHORT_BREAK, self.time_dict[SHORT_BREAK].minute()
        )
        self.settings.sync()
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.close()
        return True

    def closeEvent(self, event):
        if self.testAttribute(Qt.WA_DeleteOnClose):
            self.controller.pomodoro_view = None
            event.accept()
        else:
            event.ignore()
            self.hide()
    def show_settings_dialog(self, window, success):
        if not success:
            window.show_message(_('Server not reachable.'))
            return

        wallet = window.wallet
        d = WindowModalDialog(window, _("TrustedCoin Information"))
        d.setMinimumSize(500, 200)
        vbox = QVBoxLayout(d)
        hbox = QHBoxLayout()

        logo = QLabel()
        logo.setPixmap(QPixmap(icon_path("trustedcoin-status.png")))
        msg = _('This wallet is protected by TrustedCoin\'s two-factor authentication.') + '<br/>'\
              + _("For more information, visit") + " <a href=\"https://api.trustedcoin.com/#/electrum-help\">https://api.trustedcoin.com/#/electrum-help</a>"
        label = QLabel(msg)
        label.setOpenExternalLinks(1)

        hbox.addStretch(10)
        hbox.addWidget(logo)
        hbox.addStretch(10)
        hbox.addWidget(label)
        hbox.addStretch(10)

        vbox.addLayout(hbox)
        vbox.addStretch(10)

        msg = _(
            'TrustedCoin charges a small fee to co-sign transactions. The fee depends on how many prepaid transactions you buy. An extra output is added to your transaction every time you run out of prepaid transactions.'
        ) + '<br/>'
        label = QLabel(msg)
        label.setWordWrap(1)
        vbox.addWidget(label)

        vbox.addStretch(10)
        grid = QGridLayout()
        vbox.addLayout(grid)

        price_per_tx = wallet.price_per_tx
        n_prepay = wallet.num_prepay(self.config)
        i = 0
        for k, v in sorted(price_per_tx.items()):
            if k == 1:
                continue
            grid.addWidget(QLabel("Pay every %d transactions:" % k), i, 0)
            grid.addWidget(
                QLabel(
                    window.format_amount(v / k) + ' ' + window.base_unit() +
                    "/tx"), i, 1)
            b = QRadioButton()
            b.setChecked(k == n_prepay)
            b.clicked.connect(lambda b, k=k: self.config.set_key(
                'trustedcoin_prepay', k, True))
            grid.addWidget(b, i, 2)
            i += 1

        n = wallet.billing_info.get('tx_remaining', 0)
        grid.addWidget(
            QLabel(_("Your wallet has {} prepaid transactions.").format(n)), i,
            0)
        vbox.addLayout(Buttons(CloseButton(d)))
        d.exec_()
Esempio n. 47
0
    def createMidBottomGroupBox(self):
        self.midBottomGroupBox = QGroupBox('Exposure Modes')

        self.autoExp = QRadioButton()
        self.autoExp.setText('auto')
        self.autoExp.toggled.connect(lambda: self.btnstate(self.autoExp))

        self.nightExp = QRadioButton()
        self.nightExp.setText('night')
        self.nightExp.toggled.connect(lambda: self.btnstate(self.nightExp))

        self.offExp = QRadioButton()
        self.offExp.setText('off')
        self.offExp.toggled.connect(lambda: self.btnstate(self.offExp))

        self.defaultExp = QRadioButton()
        self.defaultExp.setText('default')
        self.defaultExp.toggled.connect(lambda: self.btnstate(self.defaultExp))

        self.sportsExp = QRadioButton()
        self.sportsExp.setText('sports')
        self.sportsExp.toggled.connect(lambda: self.btnstate(self.sportsExp))

        self.longExp = QRadioButton()
        self.longExp.setText('verylong')
        self.longExp.toggled.connect(lambda: self.btnstate(self.longExp))

        self.spotExp = QRadioButton()
        self.spotExp.setText('spotlight')
        self.spotExp.toggled.connect(lambda: self.btnstate(self.spotExp))

        self.backExp = QRadioButton()
        self.backExp.setText('backlight')
        self.backExp.toggled.connect(lambda: self.btnstate(self.backExp))

        self.fireExp = QRadioButton()
        self.fireExp.setText('fireworks')
        self.fireExp.toggled.connect(lambda: self.btnstate(self.fireExp))

        self.antiExp = QRadioButton()
        self.antiExp.setText('antishake')
        self.antiExp.toggled.connect(lambda: self.btnstate(self.antiExp))

        self.fixedExp = QRadioButton()
        self.fixedExp.setText('fixedfps')
        self.fixedExp.toggled.connect(lambda: self.btnstate(self.fixedExp))

        self.beachExp = QRadioButton()
        self.beachExp.setText('beach')
        self.beachExp.toggled.connect(lambda: self.btnstate(self.beachExp))

        self.snowExp = QRadioButton()
        self.snowExp.setText('snow')
        self.snowExp.toggled.connect(lambda: self.btnstate(self.snowExp))

        self.nightpExp = QRadioButton()
        self.nightpExp.setText('nightpreview')
        self.nightpExp.toggled.connect(lambda: self.btnstate(self.nightpExp))

        self.defaultExp.setChecked(True)

        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.autoExp)
        hbox1.addWidget(self.longExp)
        hbox1.addWidget(self.nightExp)
        hbox1.addWidget(self.defaultExp)
        hbox1.addWidget(self.spotExp)
        hbox1.addWidget(self.sportsExp)
        hbox1.addWidget(self.offExp)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.backExp)
        hbox2.addWidget(self.fireExp)
        hbox2.addWidget(self.antiExp)
        hbox2.addWidget(self.fixedExp)
        hbox2.addWidget(self.beachExp)
        hbox2.addWidget(self.snowExp)
        hbox2.addWidget(self.nightpExp)

        layout = QVBoxLayout()
        layout.addLayout(hbox1)
        layout.addLayout(hbox2)
        layout.addStretch(1)
        self.midBottomGroupBox.setLayout(layout)
Esempio n. 48
0
class ExecTA(ElementMaster):

    pixmap_path = 'images/ExecTA.png'
    child_pos = (True, False)

    def __init__(self, row, column):

        self.row = row
        self.column = column

        ta_str = 'MA'
        ta_index = 0
        ta_config = (3, )
        log_state = False

        self.config = (ta_str, ta_index, ta_config, log_state)

        super().__init__(self.row, self.column, QPixmap(self.pixmap_path),
                         True, self.config)
        super().edit_sig.connect(self.edit)
        logging.debug('ExecTA called at row {}, column {}'.format(row, column))
        self.addFunction(TAFunction)

    def __setstate__(self, state):
        logging.debug('__setstate__() called ExecTA')
        self.row, self.column, self.config = state
        super().__init__(self.row, self.column, QPixmap(self.pixmap_path),
                         True, self.config)
        super().edit_sig.connect(self.edit)
        self.addFunction(TAFunction)

    def __getstate__(self):
        logging.debug('__getstate__() called ExecTA')
        return (self.row, self.column, self.config)

    def openEditor(self):
        logging.debug('openEditor() called ExecTA')

    def edit(self):

        logging.debug('edit() called ExecTA')

        ta_str, ta_index, ta_config, log_state = self.config

        self.basic_ta_layout = QVBoxLayout()
        self.confirm_button = QPushButton(QC.translate('', 'Ok'))

        self.interval_txt = QLabel()
        self.interval_txt.setText(
            QC.translate('', 'Choose technical analysis function'))

        # https://github.com/sammchardy/python-binance/blob/master/binance/client.py
        self.selectTA = QComboBox()
        self.selectTA.addItem(QC.translate('', 'Moving Average'),
                              QVariant('MA'))
        self.selectTA.addItem(QC.translate('', 'Exponential Moving Average'),
                              QVariant('EMA'))
        self.selectTA.addItem(QC.translate('', 'Stochastic Oscillator %K'),
                              QVariant('STOK'))
        self.selectTA.addItem(QC.translate('', 'Stochastic Oscillator %D'),
                              QVariant('STO'))
        self.selectTA.addItem(QC.translate('', 'Relative Strenght Index'),
                              QVariant('RSI'))
        """
        self.selectTA.addItem(QC.translate('', 'Momentum'), QVariant('MOM'))
        self.selectTA.addItem(QC.translate('', 'Rate of Change'), QVariant('ROC'))
        self.selectTA.addItem(QC.translate('', 'Average True Range'), QVariant('ATR'))
        self.selectTA.addItem(QC.translate('', 'Bollinger Bands'), QVariant('BBANDS'))
        self.selectTA.addItem(QC.translate('', 'Pivot Points, Support and Resitances'), QVariant('PPSR'))
        self.selectTA.addItem(QC.translate('', 'Trix'), QVariant('TRIX'))
        self.selectTA.addItem(QC.translate('', 'Average Directional Movement Index'), QVariant('ADX'))
        self.selectTA.addItem(QC.translate('', 'MACD, MACD Signal and MACD diffrence'), QVariant('MACD'))
        self.selectTA.addItem(QC.translate('', 'Mass Index'), QVariant('MI'))
        self.selectTA.addItem(QC.translate('', 'Vortex Indikator'), QVariant('VORTEX'))
        self.selectTA.addItem(QC.translate('', 'KST Oscillator'), QVariant('KST'))
        self.selectTA.addItem(QC.translate('', 'True Strenght Index'), QVariant('TSI'))
        self.selectTA.addItem(QC.translate('', 'Accumulation/Distribution'), QVariant('ACCDIST'))
        self.selectTA.addItem(QC.translate('', 'Chaikin Oscillator'), QVariant('CHAI'))
        self.selectTA.addItem(QC.translate('', 'Money Flow Index and Ratio'), QVariant('MFI'))
        self.selectTA.addItem(QC.translate('', 'On Balance Volume'), QVariant('OBV'))
        self.selectTA.addItem(QC.translate('', 'Force Index'), QVariant('FI'))
        self.selectTA.addItem(QC.translate('', 'Ease of Movement'), QVariant('EOM'))
        self.selectTA.addItem(QC.translate('', 'Commodity Channel Index'), QVariant('CCI'))
        """
        self.selectTA.setCurrentIndex(ta_index)

        self.variable_box = QStackedWidget()
        self.maInput()
        self.emaInput()
        self.stokInput()
        self.stoInput()
        self.rsiInput()
        self.loadLastConfig()

        logging.debug('edit() - {} elements in QStackedWidget'.format(
            self.variable_box.count()))

        self.link_line = QWidget()
        self.link_line_layout = QHBoxLayout(self.link_line)

        self.link_txt = QLabel()
        self.link_txt.setText(
            QC.translate('', 'Find information about technical analysis on'))

        self.link = QLabel()
        self.link.setText(
            '<a href="https://www.investopedia.com/walkthrough/forex/">Investopedia</a>'
        )
        self.link.setTextFormat(Qt.RichText)
        self.link.setTextInteractionFlags(Qt.TextBrowserInteraction)
        self.link.setOpenExternalLinks(True)

        self.link_line_layout.addWidget(self.link_txt)
        self.link_line_layout.addWidget(self.link)
        self.link_line_layout.addStretch(1)

        # hier logging option einfügen
        self.log_line = QWidget()
        self.ask_for_logging = QLabel()
        self.ask_for_logging.setText(QC.translate('', 'Log output?'))
        self.log_checkbox = QCheckBox()
        self.log_line_layout = QHBoxLayout(self.log_line)
        self.log_line_layout.addWidget(self.ask_for_logging)
        self.log_line_layout.addWidget(self.log_checkbox)
        self.log_line_layout.addStretch(1)

        if log_state:
            self.log_checkbox.setChecked(True)

        self.basic_ta_edit = ElementEditor(self)
        self.basic_ta_edit.setWindowTitle(QC.translate('', 'Edit TA function'))

        # signals and slots
        self.confirm_button.clicked.connect(self.basic_ta_edit.closeEvent)
        self.basic_ta_edit.window_closed.connect(self.edit_done)
        self.selectTA.currentIndexChanged.connect(self.indexChanged)

        self.basic_ta_layout.addWidget(self.interval_txt)
        self.basic_ta_layout.addWidget(self.selectTA)
        self.basic_ta_layout.addWidget(self.variable_box)
        self.basic_ta_layout.addStretch(1)
        self.basic_ta_layout.addWidget(self.log_line)
        self.basic_ta_layout.addWidget(self.link_line)
        self.basic_ta_layout.addWidget(self.confirm_button)
        self.basic_ta_edit.setLayout(self.basic_ta_layout)
        self.basic_ta_edit.show()

    def loadLastConfig(self):

        ta_str, ta_index, ta_config, log_state = self.config

        logging.debug(
            'loadLastConfig() called with ta_str = {}'.format(ta_str))

        self.variable_box.setCurrentIndex(ta_index)

        if ta_str == 'MA':
            self.ma_range_input.setText(str(ta_config[0]))
        elif ta_str == 'EMA':
            self.ema_range_input.setText(str(ta_config[0]))
        elif ta_str == 'STO':
            self.sto_range_input.setText(str(ta_config[0]))
        elif ta_str == 'RSI':
            self.rsi_range_input.setText(str(ta_config[0]))

    def maInput(self):

        self.ma_input = QWidget()
        self.ma_layout = QHBoxLayout(self.ma_input)

        self.ma_range_txt = QLabel()
        self.ma_range_txt.setText(QC.translate('', 'Enter time range MA'))

        self.ma_range_input = QLineEdit()
        self.ma_range_input.setValidator(QIntValidator(1, 999))
        self.ma_range_input.setPlaceholderText(
            QC.translate('', 'Default value: 3'))

        self.ma_layout.addWidget(self.ma_range_txt)
        self.ma_layout.addWidget(self.ma_range_input)

        self.variable_box.addWidget(self.ma_input)

    def emaInput(self):

        self.ema_input = QWidget()
        self.ema_layout = QHBoxLayout(self.ema_input)

        self.ema_range_txt = QLabel()
        self.ema_range_txt.setText(QC.translate('', 'Enter time range EMA'))

        self.ema_range_input = QLineEdit()
        self.ema_range_input.setValidator(QIntValidator(1, 999))
        self.ema_range_input.setPlaceholderText(
            QC.translate('', 'Default value: 3'))

        self.ema_layout.addWidget(self.ema_range_txt)
        self.ema_layout.addWidget(self.ema_range_input)

        self.variable_box.addWidget(self.ema_input)

    def stokInput(self):

        self.stok_input = QWidget()
        self.stok_layout = QHBoxLayout(self.stok_input)

        self.variable_box.addWidget(self.stok_input)

    def stoInput(self):

        self.sto_input = QWidget()
        self.sto_layout = QHBoxLayout(self.sto_input)

        self.sto_range_txt = QLabel()
        self.sto_range_txt.setText(QC.translate('', 'Enter MA period'))

        self.sto_range_input = QLineEdit()
        self.sto_range_input.setValidator(QIntValidator(1, 999))
        self.sto_range_input.setPlaceholderText(
            QC.translate('', 'Default value: 3'))

        self.sto_layout.addWidget(self.sto_range_txt)
        self.sto_layout.addWidget(self.sto_range_input)

        self.variable_box.addWidget(self.sto_input)

    def rsiInput(self):

        self.rsi_input = QWidget()
        self.rsi_layout = QHBoxLayout(self.rsi_input)

        self.rsi_range_txt = QLabel()
        self.rsi_range_txt.setText(QC.translate('', 'Enter periods'))

        self.rsi_range_input = QLineEdit()
        self.rsi_range_input.setValidator(QIntValidator(1, 999))
        self.rsi_range_input.setPlaceholderText(
            QC.translate('', 'Default value: 3'))

        self.rsi_layout.addWidget(self.rsi_range_txt)
        self.rsi_layout.addWidget(self.rsi_range_input)

        self.variable_box.addWidget(self.rsi_input)

    def indexChanged(self, event):

        current_index = event
        logging.debug('indexChanged() called {}'.format(current_index))
        self.variable_box.setCurrentIndex(current_index)

        if current_index == 0:

            logging.debug('Moving Average selected - {}'.format(
                self.selectTA.currentData()))

        elif current_index == 1:

            logging.debug('Exponential Moving Average selected')

    def edit_done(self):

        logging.debug('edit_done() called ExecTA')
        if self.selectTA.currentData() == 'MA':

            period = self.ma_range_input.text()

            if period == '':
                ta_config = (3, )
            else:
                ta_config = (int(period), )

            logging.debug(
                'edit_done() - Moving Average selected - {}'.format(ta_config))

        elif self.selectTA.currentData() == 'EMA':

            period = self.ema_range_input.text()

            if period == '':
                ta_config = (3, )
            else:
                ta_config = (int(period), )

            logging.debug(
                'edit_done() - Exponential Moving Average selected - {}'.
                format(ta_config))

        elif self.selectTA.currentData() == 'STO':

            period = self.sto_range_input.text()

            if period == '':
                ta_config = (3, )
            else:
                ta_config = (int(period), )

            logging.debug(
                'edit_done() - Stochastic Oscillator %D or EMA or RSI selected - {}'
                .format(ta_config))

        elif self.selectTA.currentData() == 'RSI':

            period = self.rsi_range_input.text()

            if period == '':
                ta_config = (3, )
            else:
                ta_config = (int(period), )

            logging.debug(
                'edit_done() - Relative Strenght Index selected - {}'.format(
                    ta_config))

        else:
            ta_config = None

        ta_str = self.selectTA.currentData()
        ta_index = self.selectTA.currentIndex()
        log_state = self.log_checkbox.isChecked()

        self.config = (ta_str, ta_index, ta_config, log_state)
        self.addFunction(TAFunction)
class GuiProjectDetailsMain(QWidget):
    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

        fPx = self.theTheme.fontPixelSize
        fPt = self.theTheme.fontPointSize
        vPx = self.mainConf.pxInt(4)
        hPx = self.mainConf.pxInt(12)

        # Header
        # ======

        self.bookTitle = QLabel(self.theProject.bookTitle)
        bookFont = self.bookTitle.font()
        bookFont.setPointSizeF(2.2 * fPt)
        bookFont.setWeight(QFont.Bold)
        self.bookTitle.setFont(bookFont)
        self.bookTitle.setAlignment(Qt.AlignHCenter)
        self.bookTitle.setWordWrap(True)

        self.projName = QLabel("Working Title: %s" % self.theProject.projName)
        workFont = self.projName.font()
        workFont.setPointSizeF(0.8 * fPt)
        workFont.setItalic(True)
        self.projName.setFont(workFont)
        self.projName.setAlignment(Qt.AlignHCenter)
        self.projName.setWordWrap(True)

        self.bookAuthors = QLabel("By %s" % self.theProject.getAuthors())
        authFont = self.bookAuthors.font()
        authFont.setPointSizeF(1.2 * fPt)
        self.bookAuthors.setFont(authFont)
        self.bookAuthors.setAlignment(Qt.AlignHCenter)
        self.bookAuthors.setWordWrap(True)

        # Stats
        # =====

        hCounts = self.theIndex.getNovelTitleCounts()
        nwCount = self.theIndex.getNovelWordCount()

        self.wordCountLbl = QLabel("<b>Words:</b>")
        self.wordCountVal = QLabel(f"{nwCount:n}")

        self.chapCountLbl = QLabel("<b>Chapters:</b>")
        self.chapCountVal = QLabel(f"{hCounts[2]:n}")

        self.sceneCountLbl = QLabel("<b>Scenes:</b>")
        self.sceneCountVal = QLabel(f"{hCounts[3]:n}")

        self.revCountLbl = QLabel("<b>Revisions:</b>")
        self.revCountVal = QLabel(f"{self.theProject.saveCount:n}")

        edTime = self.theProject.getCurrentEditTime()
        self.editTimeLbl = QLabel("<b>Editing Time:</b>")
        self.editTimeVal = QLabel(f"{edTime//3600:02d}:{edTime%3600//60:02d}")

        self.statsGrid = QGridLayout()
        self.statsGrid.addWidget(self.wordCountLbl, 0, 0, 1, 1, Qt.AlignRight)
        self.statsGrid.addWidget(self.wordCountVal, 0, 1, 1, 1, Qt.AlignLeft)
        self.statsGrid.addWidget(self.chapCountLbl, 1, 0, 1, 1, Qt.AlignRight)
        self.statsGrid.addWidget(self.chapCountVal, 1, 1, 1, 1, Qt.AlignLeft)
        self.statsGrid.addWidget(self.sceneCountLbl, 2, 0, 1, 1, Qt.AlignRight)
        self.statsGrid.addWidget(self.sceneCountVal, 2, 1, 1, 1, Qt.AlignLeft)
        self.statsGrid.addWidget(self.revCountLbl, 3, 0, 1, 1, Qt.AlignRight)
        self.statsGrid.addWidget(self.revCountVal, 3, 1, 1, 1, Qt.AlignLeft)
        self.statsGrid.addWidget(self.editTimeLbl, 4, 0, 1, 1, Qt.AlignRight)
        self.statsGrid.addWidget(self.editTimeVal, 4, 1, 1, 1, Qt.AlignLeft)
        self.statsGrid.setHorizontalSpacing(hPx)
        self.statsGrid.setVerticalSpacing(vPx)

        # Meta
        # ====

        self.projPathLbl = QLabel("<b>Path:</b>")
        self.projPathVal = QLineEdit()
        self.projPathVal.setText(self.theProject.projPath)
        self.projPathVal.setReadOnly(True)

        self.projPathBox = QHBoxLayout()
        self.projPathBox.addWidget(self.projPathLbl)
        self.projPathBox.addWidget(self.projPathVal)
        self.projPathBox.setSpacing(hPx)

        # Assemble
        # ========

        self.outerBox = QVBoxLayout()
        self.outerBox.addSpacing(fPx)
        self.outerBox.addWidget(self.bookTitle)
        self.outerBox.addWidget(self.projName)
        self.outerBox.addWidget(self.bookAuthors)
        self.outerBox.addSpacing(2 * fPx)
        self.outerBox.addLayout(self.statsGrid)
        self.outerBox.addSpacing(fPx)
        self.outerBox.addStretch(1)
        self.outerBox.addLayout(self.projPathBox)

        self.setLayout(self.outerBox)

        return
Esempio n. 50
0
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__()
        self.pageInfo = PageInfo("", "")
        self.setWindowTitle("河北腾云信息科技有限公司")
        self.icon = QtGui.QIcon()
        self.icon.addPixmap(QtGui.QPixmap("images/logo.ico"),
                            QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(self.icon)
        self.treeWidget = QTreeWidget()
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.root = QTreeWidgetItem(self.treeWidget)
        self.treeWidget.addTopLevelItem(self.root)
        # self.setStyleSheet(helper.CommonHelper.read_css('./css/style.css'))

        # 设置列数
        self.treeWidget.setColumnCount(1)
        # 设置树形控件头部的标题
        self.treeWidget.setHeaderLabels(['财税大数据平台'])
        self.treeWidget.setFixedWidth(500)

        self.rightWidget = QWidget()
        self.rightLayout = QVBoxLayout()

        self.dataBox = QGroupBox("数据库连接")
        self.dataBox.setStyleSheet("QGroupBox{border: 1px solid black;}")
        self.connectBtn = QPushButton("生成查找树")

        self.yearLab = QLabel("年份")
        self.yearEdit = QLineEdit()

        self.dataLayout = QGridLayout()
        self.dataLayout.setContentsMargins(10, 20, 10, 15)
        self.hostLab = QLabel("主机名或ip地址:")
        self.portLab = QLabel("端口:")
        self.userLab = QLabel("用户名:")
        self.passLab = QLabel("密码")
        self.dbLab = QLabel("数据库名:")
        self.charsetLab = QLabel("字符集:")

        self.hostEdit = QLineEdit()
        self.userEdit = QLineEdit()
        self.portEdit = QLineEdit()
        self.passEdit = QLineEdit()
        self.dbEdit = QLineEdit()
        self.charsetEdit = QLineEdit()

        self.hostEdit.setText("192.168.110.201")
        self.portEdit.setText("3306")
        self.userEdit.setText("root")
        self.passEdit.setEchoMode(QLineEdit.Password)
        self.passEdit.setText("tengyun2020")
        self.dbEdit.setText("fiscal_tax")
        self.charsetEdit.setText("utf8")
        self.yearEdit.setText("2019")

        self.pageTextInfo = []

        self.dataLayout.addWidget(self.hostLab, 0, 0)
        self.dataLayout.addWidget(self.hostEdit, 0, 1)
        self.dataLayout.addWidget(self.portLab, 0, 2)
        self.dataLayout.addWidget(self.portEdit, 0, 3)
        self.dataLayout.addWidget(self.userLab, 0, 4)
        self.dataLayout.addWidget(self.userEdit, 0, 5)
        self.dataLayout.addWidget(self.yearLab, 0, 6)
        self.dataLayout.addWidget(self.yearEdit, 0, 7)
        self.dataLayout.addWidget(self.passLab, 1, 0)
        self.dataLayout.addWidget(self.passEdit, 1, 1)
        self.dataLayout.addWidget(self.dbLab, 1, 2)
        self.dataLayout.addWidget(self.dbEdit, 1, 3)
        self.dataLayout.addWidget(self.charsetLab, 1, 4)
        self.dataLayout.addWidget(self.charsetEdit, 1, 5)
        self.dataLayout.addWidget(self.connectBtn, 1, 7, 1, 1)

        self.dataBox.setLayout(self.dataLayout)

        self.budgetBox = QGroupBox("预决算信息提取")
        self.budgetBox.setStyleSheet("QGroupBox{border: 1px solid black;}")

        self.comboBox = QComboBox()
        self.comboBox.addItem("一般公共预算收支科目")
        self.comboBox.addItem("政府性基金预算收支科目")
        self.comboBox.addItem("国有资本经营预算收支科目")
        self.comboBox.addItem("社会保险基金预算收支科目")
        self.comboBox.addItem("支出经济分类科目")
        # self.comboBox.addItem("一般公共预算收入科目")
        # self.comboBox.addItem("一般公共预算支出科目")
        # self.comboBox.addItem("政府性基金预算收入科目")
        # self.comboBox.addItem("政府性基金预算支出科目")
        # self.comboBox.addItem("国有资本经营预算收入科目")
        # self.comboBox.addItem("国有资本经营预算支出科目")
        # self.comboBox.addItem("社会保险基金预算收入科目")
        # self.comboBox.addItem("社会保险基金预算支出科目")
        self.comboBox.setStyleSheet("""
                    QComboBox {border:none;background:#000000;color:#ffffff;
                    padding-left:30px;font-size:16px "SimHei";}
                    QComboBox QAbstractItemView {background:#000000;color:#ffffff;padding-left:30px;} 
                    QComboBox QAbstractItemView::item {min-height:30px;font-size:16px "SimHei";}
         """)
        self.comboBox.setView(QListView())
        self.pathLab = QLabel("文件路径:")
        self.extractBtn = QPushButton("提取信息")
        self.genBtn = QPushButton("生成Excel")
        self.initBtn = QPushButton("清空文件")
        self.codeLab = QLabel("科目编码:")
        self.subLab = QLabel("科目名称:")
        self.budgetLab = QLabel("预算数:")
        self.actualLab = QLabel("决算数:")
        self.pageLab = QLabel("页码:")
        self.pageInfoBtn = QPushButton("页面信息")
        self.regxLab = QLabel("分割符:")
        self.posLab = QLabel("名称位置:")
        self.targetLab = QLabel("目标文件路径:")
        self.boundLab = QLabel("pdf无边框表格位置:")
        self.currentPageLab = QLabel("无边框表格页码:")

        self.pathEdit = LineEdit()
        self.codeEdit = QLineEdit()
        self.subEdit = QLineEdit()
        self.budgetEdit = QLineEdit()
        self.actualEdit = QLineEdit()
        self.pageEdit = QLineEdit()
        self.regxEdit = QLineEdit()
        self.posEdit = QLineEdit()
        self.targetEdit = LineEdit()
        self.boundEdit = QLineEdit()
        self.currentPageEdit = QLineEdit()

        current_page_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(r"^[1-9]\d*$"), self.currentPageEdit)
        self.currentPageEdit.setValidator(current_page_validator)

        page_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(r"(^[1-9]\d*)(-[1-9]\d*)||(^[1-9]\d*)(,[1-9]\d*)+"),
            self.pageEdit)
        self.pageEdit.setValidator(page_validator)

        sub_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(r"(^[1-9]\d*)(,[1-9]\d*)+"), self.subEdit)
        self.subEdit.setValidator(sub_validator)

        code_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(r"(^[1-9]\d*)(,[1-9]\d*)+"), self.codeEdit)
        self.codeEdit.setValidator(code_validator)

        budget_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(r"(^[1-9]\d*)(,[1-9]\d*)+"), self.budgetEdit)
        self.budgetEdit.setValidator(budget_validator)

        actual_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(r"(^[1-9]\d*)(,[1-9]\d*)+"), self.actualEdit)
        self.actualEdit.setValidator(actual_validator)

        bound_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(r"(^[0-9]\d*)(,[0-9]\d*)+"), self.boundEdit)
        self.boundEdit.setValidator(bound_validator)
        """
        self.pathEdit.setText("C:/Users/localhost/Desktop/bb/新乐市2019年政府预算公开附表.xlsx")
        self.targetEdit.setText("C:/Users/localhost/Desktop/cc")
        self.subEdit.setText("1")
        self.codeEdit.setText("")
        self.budgetEdit.setText("2")
        self.actualEdit.setText("")
        self.pageEdit.setText("1")
        self.boundEdit.setText("0,700,550,0")
        """
        self.checkBtn = QPushButton("查看")
        self.pathEdit.setObjectName("path")
        self.targetEdit.setObjectName("target")
        self.configEdit = QTextEdit()
        self.configEdit.setStyleSheet("""
            QTextEdit{font-size:14px;background:#3D1140;color:#FFFFFF;}
        """)
        self.configEdit.setFixedHeight(300)
        self.json_str = """
        {
            "一般公共预算收支科目":{
               "parsed":{ 
                    "page":"",
                    "code":"",
                    "budget":"",
                    "actual":"",
                    "type":""
                },
               "unparsed":{ 
                    "page":"",
                    "name":"",
                    "budget":"",
                    "actual":"",
                    "regex":{
                        "sep":"",
                        "pos":""
                    },
                    "type":""
                }
            },
            "政府性基金预算收支科目":{
            "parsed":{ 
                    "page":"",
                    "code":"",
                    "budget":"",
                    "actual":"",
                    "type":""
                },
               "unparsed":{ 
                    "page":"",
                    "name":"",
                    "budget":"",
                    "actual":"",
                    "regex":{
                        "sep":"",
                        "pos":""
                    },
                    "type":""
                }
            },
            "国有资本经营预算收支科目":{
              "parsed":{ 
                    "page":"",
                    "code":"",
                    "budget":"",
                    "actual":"",
                    "type":""
                },
               "unparsed":{ 
                    "page":"",
                    "name":"",
                    "budget":"",
                    "actual":"",
                    "regex":{
                        "sep":"",
                        "pos":""
                    },
                    "type":""
                }
            },
            "社会保险基金预算收支科目":{
               "parsed":{ 
                    "page":"",
                    "code":"",
                    "budget":"",
                    "actual":"",
                    "type":""
                },
               "unparsed":{ 
                    "page":"",
                    "name":"",
                    "budget":"",
                    "actual":"",
                    "regex":{
                        "sep":"",
                        "pos":""
                    },
                    "type":""
                }
            },
            "支出经济分类科目":{
             "parsed":{ 
                    "page":"",
                    "code":"",
                    "budget":"",
                    "actual":"",
                    "type":""
                },
               "unparsed":{ 
                    "page":"",
                    "name":"",
                    "budget":"",
                    "actual":"",
                    "regex":{
                        "sep":"",
                        "pos":""
                    },
                    "type":""
                }
            }
        }
        """
        self.configEdit.setText(
            json.dumps(json.loads(self.json_str),
                       indent=4,
                       sort_keys=False,
                       ensure_ascii=False))
        self.json = {
            "一般公共预算收支科目": {},
            "政府性基金预算收支科目": {},
            "国有资本经营预算收支科目": {},
            "社会保险基金预算收支科目": {},
            "支出经济分类科目": {}
        }
        self.page_settings = QPushButton("")

        self.budgetLayout = QGridLayout()
        self.budgetLayout.setContentsMargins(10, 20, 10, 15)
        self.budgetLayout.addWidget(self.pathLab, 0, 0)
        self.budgetLayout.addWidget(self.pathEdit, 0, 1, 1, 3)
        self.budgetLayout.addWidget(self.targetLab, 1, 0)
        self.budgetLayout.addWidget(self.targetEdit, 1, 1, 1, 3)

        self.spiderBox = QGroupBox("文件下载")
        self.urlLab = QLabel("下载页地址:")
        self.urlEdit = QLineEdit()
        self.downloadLab = QLabel("文件下载路径:")
        self.downloadEdit = LineEdit()
        self.downloadEdit.setObjectName("download")

        self.downloadBtn = QPushButton("下载当前页文件")
        self.spiderLayout = QGridLayout()
        self.spiderLayout.addWidget(self.urlLab, 0, 0)
        self.spiderLayout.addWidget(self.urlEdit, 0, 1)
        # self.spiderLayout.addSpacing(20)
        self.spiderLayout.addWidget(self.downloadLab, 1, 0)
        self.spiderLayout.addWidget(self.downloadEdit, 1, 1)
        self.spiderLayout.addWidget(self.downloadBtn, 1, 2)
        self.spiderBox.setLayout(self.spiderLayout)

        url_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(
                r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
            ), self.urlEdit)
        self.urlEdit.setValidator(url_validator)

        self.budgetLayout.addWidget(self.spiderBox, 3, 0, 4, 4)
        # self.budgetLayout.addWidget(self.configEdit, 2, 0, 6, 4)
        self.budgetLayout.addWidget(self.comboBox, 8, 0, 1, 4)
        self.budgetLayout.addWidget(self.subLab, 9, 0)
        self.budgetLayout.addWidget(self.subEdit, 9, 1)
        # self.budgetLayout.addWidget(self.regxLab, 3, 2)
        # self.budgetLayout.addWidget(self.regxEdit, 3, 3)
        # self.budgetLayout.addWidget(self.posLab, 4, 2)
        # self.budgetLayout.addWidget(self.posEdit, 4, 3)

        self.budgetLayout.addWidget(self.codeLab, 9, 2)
        self.budgetLayout.addWidget(self.codeEdit, 9, 3)

        self.budgetLayout.addWidget(self.budgetLab, 10, 0)
        self.budgetLayout.addWidget(self.budgetEdit, 10, 1)
        self.budgetLayout.addWidget(self.actualLab, 10, 2)
        self.budgetLayout.addWidget(self.actualEdit, 10, 3)

        self.budgetLayout.addWidget(self.pageLab, 11, 0)
        self.budgetLayout.addWidget(self.pageEdit, 11, 1)
        self.budgetLayout.addWidget(self.pageInfoBtn, 11, 4)

        self.budgetLayout.addWidget(self.boundLab, 12, 0)
        self.budgetLayout.addWidget(self.boundEdit, 12, 1)
        self.budgetLayout.addWidget(self.currentPageLab, 12, 2)
        self.budgetLayout.addWidget(self.currentPageEdit, 12, 3)
        self.budgetLayout.addWidget(self.checkBtn, 12, 4)

        self.btnWidget = QWidget()
        self.btnLayout = QHBoxLayout()
        self.btnLayout.addWidget(self.initBtn)
        self.btnLayout.addSpacing(20)
        self.btnLayout.addWidget(self.extractBtn)
        self.btnLayout.addSpacing(20)
        self.btnLayout.addWidget(self.genBtn)

        # self.testBtn = QPushButton("测试")
        # self.btnLayout.addSpacing(20)
        # self.btnLayout.addWidget(self.testBtn)

        self.btnWidget.setLayout(self.btnLayout)
        self.budgetLayout.addWidget(self.btnWidget, 13, 0, 1, 4)

        # self.budgetLayout.addWidget(self.initBtn, 10, 0)
        # self.budgetLayout.addWidget(self.extractBtn, 10, 1)
        # self.budgetLayout.addWidget(self.genBtn, 10, 3)
        for i in range(14):
            self.budgetLayout.setRowMinimumHeight(i, 25)
        self.budgetBox.setLayout(self.budgetLayout)

        self.rightLayout.addWidget(self.dataBox)
        self.rightLayout.addSpacing(20)
        self.rightLayout.addWidget(self.budgetBox)
        self.rightLayout.addStretch(1)
        self.rightWidget.setLayout(self.rightLayout)

        # 节点全部展开
        self.treeWidget.expandAll()
        self.leftWidget = QWidget()
        self.leftLayout = QHBoxLayout()
        self.leftLayout.addWidget(self.treeWidget)

        self.leftWidget.setLayout(self.leftLayout)
        self.mainLayout = QHBoxLayout()
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.setSpacing(0)

        self.mainLayout.addStretch(1)
        self.mainLayout.addWidget(self.leftWidget)
        self.mainLayout.addStretch(1)
        self.mainLayout.addWidget(self.rightWidget)
        self.mainLayout.addStretch(1)
        self.centralWidget.setLayout(self.mainLayout)
        self.setMinimumSize(1200, 800)
        # 查找树
        self.tree = MultiTree({
            "id": 0,
            "pid": -1,
            "name": "政府科目",
            "code": "0"
        })
        # 预声明子线程
        self.initThread = RunThread(self.root, self.tree, "2020")
        self.downloadThread = DownloadThread("", "")
        # 子树对应字典
        self.tree_dict = {}
        self.sheet_name_list = [
            "一般公共预算收支科目", "政府性基金预算收支科目", "国有资本经营预算收支科目", "社会保险基金预算收支科目",
            "支出经济分类科目"
        ]

        self.connectBtn.clicked.connect(self.on_connect_clicked)
        self.pathEdit.clicked.connect(self.on_edit_double_clicked)
        self.checkBtn.clicked.connect(self.on_check_btn_clicked)

        self.targetEdit.clicked.connect(self.on_edit_double_clicked)
        self.downloadEdit.clicked.connect(self.on_edit_double_clicked)
        self.extractBtn.clicked.connect(self.on_extract_clicked)
        self.initBtn.clicked.connect(self.on_init_btn_clicked)
        self.genBtn.clicked.connect(self.on_gen_btn_clicked)
        self.downloadBtn.clicked.connect(self.on_download_btn_clicked)
        self.pageInfoBtn.clicked.connect(self.on_page_info_btn_clicked)
        # self.testBtn.clicked.connect(self.find_code_by_name)

    @pyqtSlot()
    def on_page_info_btn_clicked(self):
        if self.pageEdit.text().strip() == "":
            QMessageBox.information(self, "提示", '    页码不能为空!    ')
            return
        page = process_param(self.pageEdit.text().strip())
        if len(page) > 0:
            suffix = self.pathEdit.text().split(".")[-1]
            if suffix.lower() == "doc" or suffix.lower(
            ) == "docx" or suffix.lower() == "pdf":
                pdf = camelot.read_pdf(self.pathEdit.text().strip().replace(
                    "docx", "pdf").replace("doc", "pdf"),
                                       flavor='stream',
                                       pages=str(page[0]))
                print(len(pdf))
                if len(pdf) > 0:
                    info = ""
                    for i, row in enumerate(pdf[0].df.values.tolist()):
                        info += ",".join(row) + "\n"
                    self.pageInfo = PageInfo(page[0], info)
                    self.pageInfo.setWindowModality(QtCore.Qt.ApplicationModal)
                    self.pageInfo.show()
            elif suffix.lower() == "xls" or suffix.lower() == "xlsx":
                wb = xlrd.open_workbook(self.pathEdit.text().strip())
                sheet_names = wb.sheet_names()
                info = "\n"
                for i, sheet_name in enumerate(sheet_names):
                    info += str(i + 1) + "\t" + sheet_name + "\n"
                self.pageInfo = PageInfo(page[0], info)
                self.pageInfo.setWindowModality(QtCore.Qt.ApplicationModal)
                self.pageInfo.show()
            else:
                pass

    @pyqtSlot()
    def on_download_btn_clicked(self):
        if self.urlEdit.text().strip() == "":
            QMessageBox.information(self, "提示", '    url地址不能为空!    ')
            return
        if self.downloadEdit.text().strip() == "":
            QMessageBox.information(self, "提示", '    文件夹地址不能为空!    ')
            return

        self.downloadThread = DownloadThread(
            url=self.urlEdit.text().strip(),
            path=self.downloadEdit.text().strip())
        self.downloadThread.resSignal.connect(
            lambda _msg: self.on_download_thread(_msg))
        self.downloadThread.start()

        # downloader = DownLoader(timeout=30, url=self.urlEdit.text().strip(), path=self.downloadEdit.text().strip())
        # downloader.download_file()
        # QMessageBox.information(self, "提示", '    文件下载完成!    ')
        # pass

    # @staticmethod
    # def check_excel_is_open(path):
    #     file_name = path.split("\\")[-1]
    #     print(file_name)
    #     print(path)
    #     print(path.replace(file_name, '~$' + file_name))
    #     if os.path.exists(path.replace(file_name, '~$' + file_name)):
    #         print("True")
    #         return True
    #     print("False")
    #     return False

    @pyqtSlot()
    def on_gen_btn_clicked(self):
        if len(self.json) > 0:
            # print(os.path.join(self.targetEdit.text().strip(), "预决算.xls"))
            # if self.check_excel_is_open(os.path.join(self.targetEdit.text().strip().replace("/", "\\"), "预决算.xls")):
            #     QMessageBox.information(self, "提示", '    Excel文件已经打开,请先关闭!    ')
            #     return
            excel_writer = Excel(
                os.path.join(self.targetEdit.text().strip().replace("/", "\\"),
                             "预决算.xls"), self.sheet_name_list, self.json)
            try:
                excel_writer.write_excel()
            except:
                QMessageBox.information(self, "提示", '    写入失败查看是否文件已经打开!    ')
                return

            QMessageBox.information(self, "提示", '    Json信息写入Excel成功!    ')

    @pyqtSlot()
    def on_init_btn_clicked(self):
        try:
            if self.targetEdit.text().strip() == "" or not os.path.isdir(
                    self.targetEdit.text().strip()):
                QMessageBox.information(self, "提示", '    输入不能为空,或者路径有错误!    ')
            else:
                self.json.clear()
                for file in os.listdir(self.targetEdit.text().strip().replace(
                        "/", "\\")):
                    # print(os.path.join(self.targetEdit.text().strip().replace("/", "\\"), file))
                    if os.path.isfile(
                            os.path.join(
                                self.targetEdit.text().strip().replace(
                                    "/", "\\"), file)):
                        try:
                            os.remove(
                                os.path.join(
                                    self.targetEdit.text().strip().replace(
                                        "/", "\\"), file))
                        except:
                            QMessageBox.information(self, "提示",
                                                    '    删除文件失败请查看是否打开!    ')
                            return
                QMessageBox.information(self, "提示", '    清空文件成功!    ')
        except Exception as e:
            QMessageBox.information(self, "提示", e)

    @pyqtSlot()
    def on_check_btn_clicked(self):
        # self.find_code_by_name()
        if self.currentPageEdit.text().strip() == "" or self.pathEdit.text(
        ).strip() == "":
            QMessageBox.information(self, "提示", '    输入不能为空!    ')
            return
        elif not self.pathEdit.text().strip().endswith(".pdf"):
            QMessageBox.information(self, "提示", '    只有PDF文件需要次操作!    ')
            return
        else:
            print(self.pathEdit.text().strip().replace('.docx',
                                                       '.pdf').replace(
                                                           ".doc", '.pdf'))
            pdf = camelot.read_pdf(self.pathEdit.text().strip().replace(
                '.docx', '.pdf').replace(".doc", '.pdf'),
                                   flavor='stream',
                                   pages=self.currentPageEdit.text().strip())
            if pdf:
                plt = camelot.plot(pdf[0], kind='textedge')
                plt.show()
                axis('tight')
                fig = pylab.gcf()
                fig.canvas.set_window_title(
                    "第" + self.currentPageEdit.text().strip() + "页表格解析示意图")

    @pyqtSlot()
    def on_extract_clicked(self):
        # print(self.tree_dict)
        # self.find_code("")
        #
        if len(self.tree_dict) == 0:
            QMessageBox.information(self, "提示", '    未生成查找树!    ')
            return
        if self.pathEdit.text().strip() == "" or self.targetEdit.text().strip(
        ) == "":
            QMessageBox.information(self, "提示", '    文件路径和目标路径不能为空!    ')
            return
        if self.pageEdit.text().strip() == "":
            QMessageBox.information(self, "提示", '    页码不能为空!    ')
            return
        if self.budgetEdit.text().strip() == "" and self.actualEdit.text(
        ).strip() == "":
            QMessageBox.information(self, "提示", '    预算数、决算数不能同时为空!    ')
            return
        if self.subEdit.text().strip() == "" and self.codeEdit.text().strip(
        ) == "":
            QMessageBox.information(self, "提示", '    科目名称和科目编码不能同时为空!    ')
            return
        if self.subEdit.text().strip() != "" and self.codeEdit.text().strip(
        ) != "":
            QMessageBox.information(self, "提示", '    科目名称和科目编码不能同时非空!    ')
            return
        try:
            process_file(self.pathEdit.text().strip())
            suffix = self.pathEdit.text().split(".")[-1]
            # print(self.pathEdit.text())
            page = process_param(self.pageEdit.text().strip())
            if suffix.lower() == "doc" or suffix.lower(
            ) == "docx" or suffix.lower() == "pdf":
                bound_info = self.boundEdit.text().strip()
                print(bound_info)
                if bound_info != "":
                    if bound_info.endswith(","):
                        bound_info = bound_info.rstrip(",")
                    # print(page)
                    if len(page) > 0:
                        # print((list(map(str, page))))
                        pdf = camelot.read_pdf(self.pathEdit.text().strip(),
                                               flavor='stream',
                                               pages=','.join(
                                                   list(map(str, page))),
                                               table_areas=[bound_info])
                        print(len(pdf))
                        for i in range(len(pdf)):
                            table_list = []
                            for row_data in pdf[i].df.values.tolist():
                                table_list.append(row_data)
                            self.parse(table_list)
                        QMessageBox.information(self, "提示", '    提取信息结束!    ')
                        print(self.json)
                else:
                    """
                    pdf = pdfplumber.open(self.pathEdit.text().strip())
                    # print(pdf.pages)
                    # print(len(pdf.pages))
                    # print(page)
                    for i, _page in enumerate(pdf.pages):
                        if i + 1 in page:
                            table_list = []
                            print(_page.extract_text())
                            for pdf_table in _page.extract_tables():
                                for row in pdf_table:
                                    table_list.append(row)
                                    print(row)
                            print(table_list)
                            self.parse(table_list)
                    """
                    if len(page) > 0:
                        # print((list(map(str, page))))
                        if suffix.lower() == "doc" or suffix.lower() == "docx":
                            pdf = camelot.read_pdf(
                                self.pathEdit.text().strip().replace(
                                    "." + suffix, ".pdf"),
                                flavor='stream',
                                pages=','.join(list(map(str, page))))
                        else:
                            pdf = camelot.read_pdf(
                                self.pathEdit.text().strip(),
                                flavor='stream',
                                pages=','.join(list(map(str, page))))
                        # print(len(pdf))
                        for i in range(len(pdf)):
                            table_list = []
                            for row_data in pdf[i].df.values.tolist():
                                table_list.append(row_data)
                            self.parse(table_list)
                    QMessageBox.information(self, "提示", '    提取信息结束!    ')

            elif suffix.lower() == "xls" or suffix.lower() == "xlsx":
                wb = xlrd.open_workbook(self.pathEdit.text().strip())
                sheet_names = wb.sheet_names()
                for i, sheet_name in enumerate(sheet_names):
                    # print(sheet_name)
                    if i + 1 in page:
                        table = wb.sheet_by_index(i)
                        table_list = []
                        print(table.nrows)

                        for ii in range(table.nrows):
                            # print(type(table.row_values(ii)))
                            # print(table.row_values(ii))
                            table_list.append(table.row_values(ii))
                        print(table_list)
                        self.parse(table_list)
                QMessageBox.information(self, "提示", '    提取信息结束!    ')
        except:
            QMessageBox.information(self, "提示", "提取信息失败请查看输入是否有误!")

    @pyqtSlot()
    def find_code_by_name(self):
        """
        Test of new method for finding the code
        :param name_list:
        :return:
        """
        pdf = camelot.read_pdf(r'C:\Users\localhost\Desktop\政府性基金预算支出表.pdf',
                               flavor='stream',
                               pages='1')
        for i in range(len(pdf)):
            name_list = []
            for row_data in pdf[i].df.values.tolist():
                name = re.sub(r'\s+', '', row_data[0])
                name = name.split("、")[-1]
                name = name.split(":")[-1]
                if name.strip() != "":
                    name_list.append(name.strip())
            self.tree.prepare_search_name(self.tree_dict.get("政府性基金预算收支科目"))
            res = []
            for name in name_list:
                res.append(self.tree.search_node_by_name(name, 0.8))
            for item in res:
                print(item)

        pass

    def backtracking(self, index, data_list, res=[]):
        if index == len(data_list) - 1:
            return
        if len(data_list[index]) == 0:
            return
        for data in data_list:
            res_temp = res[:]
            if len(res_temp) == 0:
                pass
            for item in res_temp:
                if data.get("pid") == item.get("id"):
                    pass

        pass

    def find_code(self, name_list):
        """
        print(self.comboBox.currentText())
        print(self.tree_dict.get(self.comboBox.currentText()))
        name_list = ["一般公共服务支出", "人大事务", "行政运行", "政协事务", "行政运行", "机关服务", "教育支出", "教育管理事务", "行政运行"]
        name_list = ["我拉个区", "一般公共服务支出", "援助其他地区支出", "垃圾", "一般公共服务", "国防支出", "公共安全支出", "教育支出"]
        name_list = ["一般公共服务支出", "援助其他地区支出", "一般公共服务", "国防支出", "公共安全支出", "教育支出"]
        """
        try:
            self.tree.prepare_search_name(
                self.tree_dict.get(self.comboBox.currentText()))
            res = []
            mark = ""
            for i, name in enumerate(name_list):
                search_res = self.tree.search_name(name)
                # print(search_res)
                # res.append(search_res)
                if len(search_res) == 1:
                    mark = search_res[0]
                    # print(i, search_res[0])
                    res.append((i, mark))
                elif len(search_res) > 1:
                    search_res.sort(key=lambda j: len(j))
                    for search_item in search_res:
                        if search_item.startswith(mark):
                            # print(i, search_item)
                            mark = search_item
                            res.append((i, mark))
                            break
                        elif len(search_item) == len(mark):
                            # print(i, search_item)
                            mark = search_item
                            res.append((i, mark))
                            break
            return res
        except Exception as e:
            QMessageBox.information(self, "提示", e)

    def parse(self, data_list):
        # print(data_list)
        try:
            if len(data_list) == 0:
                QMessageBox.information(self, "提示", '    表格解析失败!    ')
                return
            budget_num = process_param(self.budgetEdit.text().strip())
            actual_num = process_param(self.actualEdit.text().strip())
            if self.codeEdit.text().strip() != "":
                code_num = process_param(self.codeEdit.text().strip())
                if (len(budget_num) > 0 and len(budget_num) != len(code_num)
                    ) or (len(actual_num) > 0
                          and len(actual_num) != len(code_num)):
                    QMessageBox.information(self, "提示", '    长度不对应!    ')
                    return
                if (len(budget_num) > 0 and budget_num[-1] > len(data_list[0])
                    ) or (len(actual_num) > 0 and actual_num[-1] > len(
                        data_list[0])) or code_num[-1] > len(data_list[0]):
                    QMessageBox.information(self, "提示", '    列数越界!    ')
                    return
                for data in data_list:
                    for i in range(len(code_num)):
                        key = re.sub(r'\s+', '', str(data[code_num[i] - 1]))
                        # print(key)
                        if isinstance(data[code_num[i] - 1], float):
                            key = str(int(data[code_num[i] - 1]))
                        if key and key.isdigit():
                            if len(budget_num) > 0:
                                if self.json.get(self.comboBox.currentText().
                                                 strip()).get(key):
                                    self.json.get(self.comboBox.currentText(
                                    ).strip()).get(key).update(
                                        {"预算数": data[budget_num[i] - 1]})
                                else:
                                    self.json.get(self.comboBox.currentText(
                                    ).strip()).update({
                                        key: {
                                            "预算数": data[budget_num[i] - 1]
                                        }
                                    })
                            if len(actual_num) > 0:
                                if self.json.get(self.comboBox.currentText().
                                                 strip()).get(key):
                                    self.json.get(self.comboBox.currentText(
                                    ).strip()).get(key).update(
                                        {"决算数": data[actual_num[i] - 1]})
                                else:
                                    self.json.get(self.comboBox.currentText(
                                    ).strip()).update({
                                        key: {
                                            "决算数": data[actual_num[i] - 1]
                                        }
                                    })
            else:
                sub_num = process_param(self.subEdit.text().strip())
                if (len(budget_num) > 0 and len(budget_num) != len(sub_num)
                    ) or (len(actual_num) > 0
                          and len(actual_num) != len(sub_num)):
                    QMessageBox.information(self, "提示", '    长度不对应!    ')
                    return
                if (len(budget_num) > 0 and budget_num[-1] > len(data_list[0])
                    ) or (len(actual_num) > 0 and actual_num[-1] > len(
                        data_list[0])) or sub_num[-1] > len(data_list[0]):
                    QMessageBox.information(self, "提示", '    列数越界!    ')
                    return
                name_list = []
                for i in range(len(data_list)):
                    row_name = []
                    for j in range(len(sub_num)):
                        name = re.sub(r'\s+', '', data_list[i][sub_num[j] - 1])
                        name = name.split("、")[-1]
                        name = name.split(":")[-1]
                        row_name.append(name)
                    name_list.append(row_name)
                name_array = np.array(name_list)
                for j in range(len(sub_num)):
                    for index_code in self.find_code(name_array[:,
                                                                j].tolist()):
                        key = index_code[1]
                        if key.isdigit():
                            if len(budget_num) > 0:
                                if self.json.get(self.comboBox.currentText().
                                                 strip()).get(key):
                                    self.json.get(self.comboBox.currentText(
                                    ).strip()).get(key).update({
                                        "预算数":
                                        data_list[index_code[0]][budget_num[j]
                                                                 - 1]
                                    })
                                else:
                                    self.json.get(self.comboBox.currentText(
                                    ).strip()).update({
                                        key: {
                                            "预算数":
                                            data_list[index_code[0]][
                                                budget_num[j] - 1]
                                        }
                                    })
                            if len(actual_num) > 0:
                                print("------------>", actual_num[j] - 1,
                                      type(actual_num[j]))
                                print("___________", data_list[index_code[0]])
                                if self.json.get(self.comboBox.currentText().
                                                 strip()).get(key):
                                    self.json.get(self.comboBox.currentText(
                                    ).strip()).get(key).update({
                                        "决算数":
                                        data_list[index_code[0]][actual_num[j]
                                                                 - 1]
                                    })
                                else:
                                    self.json.get(self.comboBox.currentText(
                                    ).strip()).update({
                                        key: {
                                            "决算数":
                                            data_list[index_code[0]][
                                                actual_num[j] - 1]
                                        }
                                    })
        except Exception as e:
            QMessageBox.information(self, "提示", e)

    # def check_input(self, num, budget, actual, data):
    #     if (len(budget) > 0 and len(budget) != len(num)) or (
    #             len(actual) > 0 and len(actual) != len(num)):
    #         QMessageBox.information(self, "提示", '    长度不对应!    ')
    #         return
    #     if budget[-1] >= len(data[0]) or actual[-1] >= len(data[0]) or num[-1] >= len(
    #             data[0]):
    #         QMessageBox.information(self, "提示", '    列数越界!    ')
    #         return

    @pyqtSlot()
    def on_edit_double_clicked(self):
        if self.sender().objectName() == "path":
            filepath = QFileDialog.getOpenFileName(self, "请选择文件路径", "/")
            if filepath:
                self.pathEdit.setText(filepath[0].strip())
        elif self.sender().objectName() == "target":
            directory = QFileDialog.getExistingDirectory(self, "请选择文件夹路径", "/")
            if directory:
                self.targetEdit.setText(directory.strip())
        elif self.sender().objectName() == "download":
            directory = QFileDialog.getExistingDirectory(self, "请选择文件夹路径", "/")
            if directory:
                self.downloadEdit.setText(directory.strip())
        else:
            pass

    @pyqtSlot()
    def on_connect_clicked(self):
        print("connect button is clicked!")
        if self.hostEdit.text().strip() == "" or self.portEdit.text().strip(
        ) == "" or self.userEdit.text().strip() == "" or self.yearEdit.text(
        ).strip() == "" or self.passEdit.text().strip(
        ) == "" or self.dbEdit.text().strip() == "" or self.charsetEdit.text(
        ).strip() == "":
            QMessageBox.information(self, "提示", '    输入不能为空!    ')

        else:
            year = self.yearEdit.text().strip()
            self.tree = MultiTree({
                "id": 0,
                "pid": -1,
                "name": year + "年政府科目",
                "code": "0"
            })

            self.treeWidget.clear()
            self.root = QTreeWidgetItem(self.treeWidget)
            self.root.setText(0, year + "年树状结构生成中...")
            self.treeWidget.addTopLevelItem(self.root)

            self.initThread = RunThread(self.root, self.tree, year)
            self.initThread.resSignal.connect(
                lambda _year, _tree: self.on_init_thread(_year, _tree))
            self.initThread.start()

    @pyqtSlot()
    def on_download_thread(self, msg):
        if msg == "ok":
            QMessageBox.information(self, "提示", '    文件下载成功!    ')
        elif msg == "fail":
            QMessageBox.information(self, "提示", '    文件下载失败!    ')
        else:
            pass
            # QMessageBox.information(self, "提示", msg)

    @pyqtSlot()
    def on_init_thread(self, year, tree):
        self.tree = tree
        self.root.setText(0, year + "年树状结构")
        # 遍历树状结构
        # self.tree.traverse(self.tree)
        self.tree_dict.clear()
        self.generate_tree_dict()
        self.treeWidget.expandAll()

    def generate_tree_dict(self):
        self.tree_dict.update({
            "一般公共预算收入":
            self.tree.tree.children[0].children[0],
            "一般公共预算支出":
            self.tree.tree.children[0].children[1],
            "政府性基金预算收入":
            self.tree.tree.children[1].children[0],
            "政府性基金预算支出":
            self.tree.tree.children[1].children[1],
            "国有资本经营预算收入":
            self.tree.tree.children[2].children[0],
            "国有资本经营预算支出":
            self.tree.tree.children[2].children[1],
            "社会保险基金预算收入":
            self.tree.tree.children[3].children[0],
            "社会保险基金预算支出":
            self.tree.tree.children[3].children[1],
            "支出经济分类科目":
            self.tree.tree.children[4],
            "一般公共预算收支科目":
            self.tree.tree.children[0],
            "政府性基金预算收支科目":
            self.tree.tree.children[1],
            "国有资本经营预算收支科目":
            self.tree.tree.children[2],
            "社会保险基金预算收支科目":
            self.tree.tree.children[3]
        })
Esempio n. 51
0
    def __init__(self, pages: AllPages, windowSize: QSize,
                 printerService: PrinterService):
        super().__init__(pages, windowSize)
        mainLayout = QVBoxLayout()
        mainLayout.setContentsMargins(0, 0, 0, 0)
        self.printerService = printerService
        self.setLayout(mainLayout)

        #Titel
        mainLayout.addWidget(self.getTitleAsQLabel(TextKey.PAGE_CONFIG_TITLE))

        #Configs #######################################################################################################
        #Layout
        scroll_area_content_widget = QWidget()
        self.scroll_area = QScrollArea(self)
        self.scroll_area.setGeometry(0, 0, windowSize.width(),
                                     windowSize.height())
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll_area.setWidget(scroll_area_content_widget)

        mainContentLabel = QVBoxLayout()
        scroll_area_content_widget.setLayout(mainContentLabel)
        mainLayout.addWidget(self.scroll_area)

        #mainSaveDir
        titleFont = QFont()
        titleFont.setUnderline(True)
        mainSaveDirTitle = QLabel(
            textValue[TextKey.PAGE_CONFIG_MAIN_SAVE_DIR_TITLE])
        mainSaveDirTitle.setFont(titleFont)
        mainContentLabel.addWidget(mainSaveDirTitle)

        mainSaveDirLayout = QGridLayout()
        mainContentLabel.addLayout(mainSaveDirLayout)

        self.mainSaveDirLabel = QLineEdit()
        self.mainSaveDirLabel.setText(CfgService.get(CfgKey.MAIN_SAVE_DIR))
        self.mainSaveDirLabel.setReadOnly(True)
        mainSaveDirLayout.addWidget(self.mainSaveDirLabel, 0, 0)

        dirButton = QPushButton("...")
        dirButton.clicked.connect(self.open_file_dialog)
        mainSaveDirLayout.addWidget(dirButton, 0, 3)

        #ProjectName
        projectNameTitle = QLabel(
            textValue[TextKey.PAGE_CONFIG_PROJECT_NAME_TITLE])
        projectNameTitle.setFont(titleFont)
        mainContentLabel.addWidget(projectNameTitle)

        self.projectNameValue = QLineEdit()
        self.projectNameValue.setText(CfgService.get(CfgKey.PROJECTNAME))
        mainContentLabel.addWidget(self.projectNameValue)

        #Camera calibration
        cameraCalibration = QPushButton(
            textValue[TextKey.PAGE_CONFIG_CAMERA_CALIBRATION_BUTTON])
        cameraCalibration.clicked.connect(self.cameraCalibrationEvent)
        self.setContentButtonStyle(cameraCalibration)
        mainContentLabel.addWidget(cameraCalibration)

        #Server
        serverTitle = QLabel(
            textValue[TextKey.PAGE_CONFIG_SERVER_IPANDPORT_TITLE])
        serverTitle.setFont(titleFont)
        mainContentLabel.addWidget(serverTitle)

        serverLayout = QHBoxLayout()
        mainContentLabel.addLayout(serverLayout)
        self.serverIpValue = QLineEdit()
        self.serverIpValue.setText(CfgService.get(CfgKey.SERVER_IP))
        serverLayout.addWidget(self.serverIpValue)

        self.serverPortValue = QLineEdit()
        self.serverPortValue.setText(CfgService.get(CfgKey.SERVER_PORT))
        serverLayout.addWidget(self.serverPortValue)

        #WIFI
        wifiTitle = QLabel(textValue[TextKey.PAGE_CONFIG_WIFI_TITLE])
        wifiTitle.setFont(titleFont)
        mainContentLabel.addWidget(wifiTitle)

        serverLayout = QHBoxLayout()
        mainContentLabel.addLayout(serverLayout)
        self.wifiSSIDValue = QLineEdit()
        self.wifiSSIDValue.setText(CfgService.get(CfgKey.WIFI_SSID))
        serverLayout.addWidget(self.wifiSSIDValue)

        self.wifiPasswordValue = QLineEdit()
        self.wifiPasswordValue.setText(CfgService.get(CfgKey.WIFI_PASSWORD))
        serverLayout.addWidget(self.wifiPasswordValue)

        self.wifiProtocolValue = QLineEdit()
        self.wifiProtocolValue.setText(CfgService.get(CfgKey.WIFI_PROTOCOL))
        serverLayout.addWidget(self.wifiProtocolValue)

        wifiPicture = QPushButton(
            textValue[TextKey.PAGE_CONFIG_WIFI_PICTURE_BUTTON])
        wifiPicture.clicked.connect(self.saveWifiPicture)
        self.setContentButtonStyle(wifiPicture)
        mainContentLabel.addWidget(wifiPicture)

        # Printer -------------------------------------------------------------------------------
        printerTitle = QLabel(textValue[TextKey.PAGE_CONFIG_PRINTER_TITLE])
        printerTitle.setFont(titleFont)
        mainContentLabel.addWidget(printerTitle)

        # Printer enabled?
        printerDisabledLayout = QHBoxLayout()
        mainContentLabel.addLayout(printerDisabledLayout)

        self.printerDisabledLabel = QLabel()
        self.printerDisabledLabel.setText(
            textValue[TextKey.PAGE_CONFIG_SERVICE_STATUS])
        printerDisabledLayout.addWidget(self.printerDisabledLabel)

        self.printerDisabledButton = QPushButton()
        self.printerDisabledButton.setCheckable(True)
        isPrinterActivate = CfgService.get(CfgKey.PRINTER_IS_ACTIVE)
        self.printerDisabledButton.setChecked(isPrinterActivate)
        if isPrinterActivate:
            self.printerDisabledButton.setText(
                textValue[TextKey.PAGE_CONFIG_AKTIVATE])
        else:
            self.printerDisabledButton.setText(
                textValue[TextKey.PAGE_CONFIG_INAKTIVATE])
        self.printerDisabledButton.clicked.connect(self.activatePrinter)
        printerDisabledLayout.addWidget(self.printerDisabledButton)

        #Aktiviert Printer Web
        printerDisabledWebLayout = QHBoxLayout()
        mainContentLabel.addLayout(printerDisabledWebLayout)

        printerDisabledWebLabel = QLabel()
        printerDisabledWebLabel.setText(
            textValue[TextKey.PAGE_CONFIG_SERVICE_PRINTER_WEB])
        printerDisabledWebLayout.addWidget(printerDisabledWebLabel)

        self.printerDisabledWebButton = QPushButton()
        self.printerDisabledWebButton.setCheckable(True)
        isPrinterActivateWeb = CfgService.get(CfgKey.PRINTER_IS_ACTIVE_WEB)
        self.printerDisabledWebButton.setChecked(isPrinterActivateWeb)
        if isPrinterActivateWeb:
            self.printerDisabledWebButton.setText(
                textValue[TextKey.PAGE_CONFIG_AKTIVATE])
        else:
            self.printerDisabledWebButton.setText(
                textValue[TextKey.PAGE_CONFIG_INAKTIVATE])
        self.printerDisabledWebButton.clicked.connect(self.activatePrinterWeb)
        printerDisabledWebLayout.addWidget(self.printerDisabledWebButton)

        # Selected Printer
        printerSelectedLayout = QHBoxLayout()
        mainContentLabel.addLayout(printerSelectedLayout)

        printerSelectLabel = QLabel()
        printerSelectLabel.setText(
            textValue[TextKey.PAGE_CONFIG_PRINTER_SELECT_LABEL])
        printerSelectedLayout.addWidget(printerSelectLabel)

        self.printerSelectedComboBox = QComboBox()
        for printer in printerService.getPrinters():
            self.printerSelectedComboBox.addItem(str(printer))
        self.printerSelectedComboBox.currentIndexChanged.connect(
            self.selectionchangePrinter)
        printerSelectedLayout.addWidget(self.printerSelectedComboBox)

        #Paper format
        printerPaperFormatLayout = QHBoxLayout()
        mainContentLabel.addLayout(printerPaperFormatLayout)

        printerPaperFormatLabel = QLabel()
        printerPaperFormatLabel.setText(
            textValue[TextKey.PAGE_CONFIG_PRINTER_PAPER_FORMAT_LABEL])
        printerPaperFormatLayout.addWidget(printerPaperFormatLabel)

        printerPaperFormatValue = QLineEdit()
        printerPaperFormatValue.setText(
            CfgService.get(CfgKey.PRINTER_PAPER_FORMAT))
        printerPaperFormatValue.setReadOnly(True)
        printerPaperFormatLayout.addWidget(printerPaperFormatValue)

        #Printer hint -> startup the printer!
        printerHintLabel = QLabel()
        printerHintLabel.setText(
            textValue[TextKey.PAGE_CONFIG_PRINTER_POWER_ON_HINT])
        mainContentLabel.addWidget(printerHintLabel)

        # Greenscreen -------------------------------------------------------------------------------
        greenscreenTitle = QLabel(
            textValue[TextKey.PAGE_CONFIG_GREENSCREEN_TITLE])
        greenscreenTitle.setFont(titleFont)
        mainContentLabel.addWidget(greenscreenTitle)

        # Greenscreen enabled?
        greenscreenDisabledLayout = QHBoxLayout()
        mainContentLabel.addLayout(greenscreenDisabledLayout)

        self.greenscreenDisabledLabel = QLabel()
        self.greenscreenDisabledLabel.setText(
            textValue[TextKey.PAGE_CONFIG_SERVICE_STATUS])
        greenscreenDisabledLayout.addWidget(self.greenscreenDisabledLabel)

        self.greenscreenDisabledButton = QPushButton()
        self.greenscreenDisabledButton.setCheckable(True)
        self.greenscreenDisabledButton.clicked.connect(
            self.activateGreenscreen)
        greenscreenDisabledLayout.addWidget(self.greenscreenDisabledButton)

        #Greenscreen ColorPicker
        greenscreenColorPickerButton = QPushButton()
        greenscreenColorPickerButton.setText(
            textValue[TextKey.PAGE_CONFIG_GREENSCREEN_COLOR_PICER_BUTTON])
        greenscreenColorPickerButton.clicked.connect(
            self.greenscreenColorPickerEvent)
        mainContentLabel.addWidget(greenscreenColorPickerButton)

        greenscreenAverageColorLayout = QHBoxLayout()
        mainContentLabel.addLayout(greenscreenAverageColorLayout)

        greenscreenAverageColorLabel = QLabel()
        greenscreenAverageColorLabel.setText(
            textValue[TextKey.PAGE_CONFIG_GREENSCREEN_AVERAGE_COLOR_LABEL])
        greenscreenAverageColorLayout.addWidget(greenscreenAverageColorLabel)

        self.averageColorLabel = QLineEdit()
        self.averageColorLabel.setReadOnly(True)
        greenscreenAverageColorLayout.addWidget(self.averageColorLabel)

        #Navigation   ##################################################################################################
        mainContentLabel.addStretch()
        navigationLayout = QHBoxLayout()
        mainLayout.addLayout(navigationLayout)

        backButton = QPushButton(textValue[TextKey.PAGE_CONFIG_BACKBUTTON])
        backButton.clicked.connect(self.backPageEvent)
        self.setNavigationbuttonStyle(backButton)
        navigationLayout.addWidget(backButton)

        nextButton = QPushButton(textValue[TextKey.PAGE_CONFIG_NEXTBUTTON])
        nextButton.clicked.connect(self.nextPageEvent)
        self.setNavigationbuttonStyle(nextButton)
        navigationLayout.addWidget(nextButton)
Esempio n. 52
0
    def createMidTopGroupBox(self):
        self.midTopGroupBox = QGroupBox('Auto White Balance Modes')

        self.autoAwb = QRadioButton()
        self.autoAwb.setText('auto')
        self.autoAwb.toggled.connect(lambda: self.abtnstate(self.autoAwb))

        self.fluorAwb = QRadioButton()
        self.fluorAwb.setText('fluorescent')
        self.fluorAwb.toggled.connect(lambda: self.abtnstate(self.fluorAwb))

        self.incanAwb = QRadioButton()
        self.incanAwb.setText('incandescent')
        self.incanAwb.toggled.connect(lambda: self.abtnstate(self.incanAwb))

        self.offAwb = QRadioButton()
        self.offAwb.setText('off')
        self.offAwb.toggled.connect(lambda: self.abtnstate(self.offAwb))

        self.defaultAwb = QRadioButton()
        self.defaultAwb.setText('default')
        self.defaultAwb.toggled.connect(
            lambda: self.abtnstate(self.defaultAwb))

        self.sunAwb = QRadioButton()
        self.sunAwb.setText('sun')
        self.sunAwb.toggled.connect(lambda: self.abtnstate(self.sunAwb))

        self.cloudAwb = QRadioButton()
        self.cloudAwb.setText('cloud')
        self.cloudAwb.toggled.connect(lambda: self.abtnstate(self.cloudAwb))

        self.shadeAwb = QRadioButton()
        self.shadeAwb.setText('shade')
        self.shadeAwb.toggled.connect(lambda: self.abtnstate(self.shadeAwb))

        self.tungsAwb = QRadioButton()
        self.tungsAwb.setText('tungsten')
        self.tungsAwb.toggled.connect(lambda: self.abtnstate(self.tungsAwb))

        self.flashAwb = QRadioButton()
        self.flashAwb.setText('flash')
        self.flashAwb.toggled.connect(lambda: self.abtnstate(self.flashAwb))

        self.horizonAwb = QRadioButton()
        self.horizonAwb.setText('horizon')
        self.horizonAwb.toggled.connect(
            lambda: self.abtnstate(self.horizonAwb))

        self.defaultAwb.setChecked(True)

        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.autoAwb)
        hbox1.addWidget(self.fluorAwb)
        hbox1.addWidget(self.incanAwb)
        hbox1.addWidget(self.offAwb)
        hbox1.addWidget(self.defaultAwb)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.sunAwb)
        hbox2.addWidget(self.cloudAwb)
        hbox2.addWidget(self.shadeAwb)
        hbox2.addWidget(self.tungsAwb)
        hbox2.addWidget(self.flashAwb)
        hbox2.addWidget(self.horizonAwb)

        layout = QVBoxLayout()
        layout.addLayout(hbox1)
        layout.addLayout(hbox2)
        layout.addStretch(1)
        self.midTopGroupBox.setLayout(layout)
Esempio n. 53
0
class Detial(QWidget):
    def __init__(self, stu_mes):
        super().__init__()
        self.stu_mes = database.get_student_info(stu_mes['SID'])

        # 学号输入框
        account = QLabel()
        account.setText('学号')
        self.accountInput = QLineEdit()
        self.accountInput.setFixedSize(400, 40)
        self.accountInput.setText(self.stu_mes['SID'])
        self.accountInput.setTextMargins(5, 5, 5, 5)
        self.accountInput.setEnabled(False)
        accountLayout = QHBoxLayout()
        accountLayout.addStretch()
        accountLayout.addWidget(account)
        accountLayout.addWidget(self.accountInput)

        # 姓名输入框
        name = QLabel()
        name.setText('姓名')
        self.nameInput = QLineEdit()
        self.nameInput.setFixedSize(400, 40)
        self.nameInput.setText(self.stu_mes['SNAME'])
        self.nameInput.setTextMargins(5, 5, 5, 5)
        self.nameInput.setEnabled(False)
        nameLayout = QHBoxLayout()
        nameLayout.addStretch()
        nameLayout.addWidget(name)
        nameLayout.addWidget(self.nameInput)

        # 密码
        password = QLabel()
        password.setText('密码')
        self.passwordInput = QLineEdit()
        self.passwordInput.setFixedSize(400, 40)
        self.passwordInput.setText('******')
        self.passwordInput.setEchoMode(QLineEdit.Password)
        self.passwordInput.setTextMargins(5, 5, 5, 5)
        self.passwordInput.setEnabled(False)
        passwordLayout = QHBoxLayout()
        passwordLayout.addStretch()
        passwordLayout.addWidget(password)
        passwordLayout.addWidget(self.passwordInput)

        # 重复密码
        repPassword = QLabel()
        repPassword.setText('重复密码')
        self.repPasswordInput = QLineEdit()
        self.repPasswordInput.setFixedSize(400, 40)
        self.repPasswordInput.setText('******')
        self.repPasswordInput.setEchoMode(QLineEdit.Password)
        self.repPasswordInput.setTextMargins(5, 5, 5, 5)
        self.repPasswordInput.setEnabled(False)
        repPasswordLayout = QHBoxLayout()
        repPasswordLayout.addStretch()
        repPasswordLayout.addWidget(repPassword)
        repPasswordLayout.addWidget(self.repPasswordInput)

        # 最大借书数
        maxNum = QLabel()
        maxNum.setText('最大借书数')
        self.maxNumInput = QLineEdit()
        self.maxNumInput.setFixedSize(400, 40)
        self.maxNumInput.setText(str(self.stu_mes['MAX']))
        self.maxNumInput.setTextMargins(5, 5, 5, 5)
        self.maxNumInput.setEnabled(False)
        maxNumLayout = QHBoxLayout()
        maxNumLayout.addStretch()
        maxNumLayout.addWidget(maxNum)
        maxNumLayout.addWidget(self.maxNumInput)

        # 学院
        dept = QLabel()
        dept.setText('学院')
        self.deptInput = QLineEdit()
        self.deptInput.setFixedSize(400, 40)
        self.deptInput.setText(self.stu_mes['DEPARTMENT'])
        self.deptInput.setTextMargins(5, 5, 5, 5)
        self.deptInput.setEnabled(False)
        deptLayout = QHBoxLayout()
        deptLayout.addStretch()
        deptLayout.addWidget(dept)
        deptLayout.addWidget(self.deptInput)

        # 专业
        major = QLabel()
        major.setText('专业')
        self.majorInput = QLineEdit()
        self.majorInput.setFixedSize(400, 40)
        self.majorInput.setText(self.stu_mes['MAJOR'])
        self.majorInput.setTextMargins(5, 5, 5, 5)
        self.majorInput.setEnabled(False)
        majorLayout = QHBoxLayout()
        majorLayout.addStretch()
        majorLayout.addWidget(major)
        majorLayout.addWidget(self.majorInput)

        # 保存
        self.save = QToolButton()
        self.save.setText('保存')
        self.save.setFixedSize(100, 40)
        self.save.setEnabled(False)
        self.save.clicked.connect(self.saveFunction)

        # 修改
        self.modify = QToolButton()
        self.modify.setText('修改')
        self.modify.setFixedSize(100, 40)
        self.modify.clicked.connect(self.modifyFunction)

        btnLayout = QHBoxLayout()
        btnLayout.addSpacing(130)
        btnLayout.addWidget(self.modify)
        btnLayout.addWidget(self.save)
        btnLayout.addStretch()

        self.bodyLayout = QVBoxLayout()
        self.bodyLayout.addLayout(accountLayout)
        self.bodyLayout.addLayout(nameLayout)
        self.bodyLayout.addLayout(passwordLayout)
        self.bodyLayout.addLayout(repPasswordLayout)
        self.bodyLayout.addLayout(deptLayout)
        self.bodyLayout.addLayout(majorLayout)
        self.bodyLayout.addLayout(maxNumLayout)
        self.bodyLayout.addLayout(btnLayout)
        self.bodyLayout.addStretch()
        self.setLayout(self.bodyLayout)
        self.initUI()

    def saveFunction(self):
        if self.passwordInput.text() != self.repPasswordInput.text():
            print('密码不一致')
            return
        if not self.maxNumInput.text().isalnum():
            print('最大数量输入错误')
            return
        if self.passwordInput.text() != '******':
            self.stu_mes['PASSWORD'] = database.encrypt(
                self.passwordInput.text())
        self.stu_mes['SNAME'] = self.nameInput.text()
        self.stu_mes['DEPARTMENT'] = self.deptInput.text()
        self.stu_mes['MAJOR'] = self.majorInput.text()
        self.stu_mes['MAX'] = int(self.maxNumInput.text())
        if not database.update_student(self.stu_mes):
            print('更新失败')
            return
        self.save.setEnabled(False)
        self.nameInput.setEnabled(False)
        self.passwordInput.setEnabled(False)
        self.repPasswordInput.setEnabled(False)
        self.deptInput.setEnabled(False)
        self.majorInput.setEnabled(False)
        self.maxNumInput.setEnabled(False)
        self.setMyStyle()

    def modifyFunction(self):
        self.save.setEnabled(True)
        self.nameInput.setEnabled(True)
        self.passwordInput.setEnabled(True)
        self.repPasswordInput.setEnabled(True)
        self.deptInput.setEnabled(True)
        self.majorInput.setEnabled(True)
        self.maxNumInput.setEnabled(True)
        self.setStyleSheet('''
            QWidget{
                background-color: white;
            }
            QLabel{
                font-size: 20px;
                font-family: 微软雅黑;
            }
            QLineEdit{
                border: 1px solid rgba(229, 229, 229, 1);
                border-radius: 10px;
                color: black;
            }
            QToolButton{
                border-radius: 10px;
                background-color:rgba(52, 118, 176, 1);
                color: white;
                font-size: 25px;
                font-family: 微软雅黑;
            }
        ''')
        self.save.setStyleSheet('''
        *{
            background-color:rgba(52, 118, 176, 1);
        }
        ''')

    def initUI(self):
        self.setFixedSize(550, 600)
        self.setMyStyle()

    def setMyStyle(self):
        self.setStyleSheet('''
        QWidget{
            background-color: white;
        }
        QLabel{
            font-size: 20px;
            font-family: 微软雅黑;
        }
        QLineEdit{
            border: 1px solid rgba(229, 229, 229, 1);
            border-radius: 10px;
            color: grey;
        }
        QToolButton{
            border-radius: 10px;
            background-color:rgba(52, 118, 176, 1);
            color: white;
            font-size: 25px;
            font-family: 微软雅黑;
        }
        ''')
        self.save.setStyleSheet('''
        *{
            background-color: gray;
        }
        ''')
Esempio n. 54
0
    def initUI(self):
        self.setWindowTitle("登录蓝奏云")
        self.setWindowIcon(QIcon(SRC_DIR + "login.ico"))
        logo = QLabel()
        logo.setPixmap(QPixmap(SRC_DIR + "logo3.gif"))
        logo.setStyleSheet("background-color:rgb(0,153,255);")
        logo.setAlignment(Qt.AlignCenter)

        self.tabs = QTabWidget()
        self.auto_tab = QWidget()
        self.hand_tab = QWidget()

        # Add tabs
        self.tabs.addTab(self.auto_tab, "自动获取Cookie")
        self.tabs.addTab(self.hand_tab, "手动输入Cookie")
        self.auto_get_cookie_ok = AutoResizingTextEdit("🔶点击👇自动获取浏览器登录信息👇")
        self.auto_get_cookie_ok.setReadOnly(True)
        self.auto_get_cookie_btn = QPushButton("自动读取浏览器登录信息")
        auto_cookie_notice = '支持浏览器:Chrome, Chromium, Opera, Edge, Firefox'
        self.auto_get_cookie_btn.setToolTip(auto_cookie_notice)
        self.auto_get_cookie_btn.clicked.connect(self.call_auto_get_cookie)
        self.auto_get_cookie_btn.setStyleSheet(
            "QPushButton {min-width: 210px;max-width: 210px;}")

        self.name_lb = QLabel("&U 用户")
        self.name_lb.setAlignment(Qt.AlignCenter)
        self.name_ed = QLineEdit()
        self.name_lb.setBuddy(self.name_ed)

        self.pwd_lb = QLabel("&P 密码")
        self.pwd_lb.setAlignment(Qt.AlignCenter)
        self.pwd_ed = QLineEdit()
        self.pwd_ed.setEchoMode(QLineEdit.Password)
        self.pwd_lb.setBuddy(self.pwd_ed)

        self.cookie_lb = QLabel("&Cookie")
        self.cookie_ed = QTextEdit()
        notice = "由于滑动验证的存在,需要输入cookie,cookie请使用浏览器获取\n" + \
            "cookie会保存在本地,下次使用。其格式如下:\n ylogin=value1; phpdisk_info=value2"
        self.cookie_ed.setPlaceholderText(notice)
        self.cookie_lb.setBuddy(self.cookie_ed)

        self.show_input_cookie_btn = QPushButton("显示Cookie输入框")
        self.show_input_cookie_btn.setToolTip(notice)
        self.show_input_cookie_btn.setStyleSheet(
            "QPushButton {min-width: 110px;max-width: 110px;}")
        self.show_input_cookie_btn.clicked.connect(
            self.change_show_input_cookie)
        self.ok_btn = QPushButton("登录")
        self.ok_btn.clicked.connect(self.change_ok_btn)
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.change_cancel_btn)
        lb_line_1 = QLabel()
        lb_line_1.setText('<html><hr />切换用户</html>')
        lb_line_2 = QLabel()
        lb_line_2.setText('<html><hr /></html>')

        self.form = QFormLayout()
        self.form.setLabelAlignment(Qt.AlignRight)
        self.form.addRow(self.name_lb, self.name_ed)
        self.form.addRow(self.pwd_lb, self.pwd_ed)
        if is_windows:

            def set_assister_path():
                """设置辅助登录程序路径"""
                assister_path = QFileDialog.getOpenFileName(
                    self, "选择辅助登录程序路径", self._cwd, "EXE Files (*.exe)")
                if not assister_path[0]:
                    return None
                assister_path = os.path.normpath(
                    assister_path[0])  # windows backslash
                if assister_path == self._cookie_assister:
                    return None
                self.assister_ed.setText(assister_path)
                self._cookie_assister = assister_path

            self.assister_lb = QLabel("登录辅助程序")
            self.assister_lb.setAlignment(Qt.AlignCenter)
            self.assister_ed = MyLineEdit(self)
            self.assister_ed.setText(self._cookie_assister)
            self.assister_ed.clicked.connect(set_assister_path)
            self.assister_lb.setBuddy(self.assister_ed)
            self.form.addRow(self.assister_lb, self.assister_ed)

        hbox = QHBoxLayout()
        hbox.addWidget(self.show_input_cookie_btn)
        hbox.addStretch(1)
        hbox.addWidget(self.ok_btn)
        hbox.addWidget(self.cancel_btn)

        user_box = QHBoxLayout()
        self.user_num = 0
        self.user_btns = {}
        for user in self._config.users_name:
            user = str(user)  # TODO: 可能需要删掉
            self.user_btns[user] = QDoublePushButton(user)
            self.user_btns[user].setStyleSheet("QPushButton {border:none;}")
            if user == self._config.name:
                self.user_btns[user].setStyleSheet(
                    "QPushButton {background-color:rgb(0,153,2);}")
                self.tabs.setCurrentIndex(1)
            self.user_btns[user].setToolTip(f"点击选中,双击切换至用户:{user}")
            self.user_btns[user].doubleClicked.connect(self.choose_user)
            self.user_btns[user].clicked.connect(self.delete_chose_user)
            user_box.addWidget(self.user_btns[user])
            self.user_num += 1
            user_box.addStretch(1)

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(logo)
        vbox = QVBoxLayout()
        if self._config.name:
            vbox.addWidget(lb_line_1)
            user_box.setAlignment(Qt.AlignCenter)
            vbox.addLayout(user_box)
            vbox.addWidget(lb_line_2)
            if self.user_num > 1:
                self.del_user_btn = QPushButton("删除账户")
                self.del_user_btn.setIcon(QIcon(SRC_DIR + "delete.ico"))
                self.del_user_btn.setStyleSheet(
                    "QPushButton {min-width: 180px;max-width: 180px;}")
                self.del_user_btn.clicked.connect(self.call_del_chose_user)
                vbox.addWidget(self.del_user_btn)
            else:
                self.del_user_btn = None
            vbox.addStretch(1)

        vbox.addLayout(self.form)
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        vbox.setAlignment(Qt.AlignCenter)

        self.hand_tab.setLayout(vbox)
        auto_cookie_vbox = QVBoxLayout()
        auto_cookie_vbox.addWidget(self.auto_get_cookie_ok)
        auto_cookie_vbox.addWidget(self.auto_get_cookie_btn)
        auto_cookie_vbox.setAlignment(Qt.AlignCenter)
        self.auto_tab.setLayout(auto_cookie_vbox)
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
        self.update_selection(self._config.name)
Esempio n. 55
0
class StudentPage(QWidget):
    def __init__(self, stu_mes):
        super().__init__()
        self.focus = 0
        self.stu_mes = stu_mes
        self.initUI()

    def initUI(self):
        # 标题栏
        self.titleBar = QWidget()
        self.titleBar.setFixedSize(1250, 50)
        self.setTitleBar()

        # 分割
        self.body = QSplitter()
        self.setLeftMunu()
        self.content = None
        self.setContent()

        self.bodyLayout = QGridLayout()
        self.bodyLayout.addWidget(self.titleBar, 0, 0, 1, 7)
        self.bodyLayout.addWidget(self.body, 1, 0, 7, 7)
        self.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.bodyLayout)
        self.setFixedSize(1280, 720)
        self.setMyStyle()

    # 设置标题栏
    def setTitleBar(self):
        self.title = QLabel()
        self.title.setText('欢迎使用图书馆管理系统')
        self.title.setFixedHeight(30)

        self.account = QToolButton()
        self.account.setIcon(QIcon('icon/person.png'))
        self.account.setText(self.stu_mes['SID'])
        self.account.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.account.setFixedHeight(20)
        self.account.setEnabled(False)

        self.out = QToolButton()
        self.out.setText('退出')
        self.out.setFixedHeight(30)

        titleLayout = QHBoxLayout()
        titleLayout.addSpacing(100)
        titleLayout.addWidget(self.title)
        titleLayout.addWidget(self.account)
        titleLayout.addWidget(self.out)
        self.titleBar.setLayout(titleLayout)

    # 左侧菜单栏
    def setLeftMunu(self):
        # 查询按钮
        self.bookSearch = QToolButton()
        self.bookSearch.setText('图书查询')
        self.bookSearch.setFixedSize(160, 50)
        self.bookSearch.setIcon(QIcon('icon/book.png'))
        self.bookSearch.setIconSize(QSize(30, 30))
        self.bookSearch.clicked.connect(
            lambda: self.switch(0, self.bookSearch))
        self.bookSearch.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        # 借阅按钮
        self.borrow = QToolButton()
        self.borrow.setText('借阅信息')
        self.borrow.setFixedSize(160, 50)
        self.borrow.setIcon(QIcon('icon/borrowing.png'))
        self.borrow.setIconSize(QSize(30, 30))
        self.borrow.clicked.connect(lambda: self.switch(1, self.borrow))
        self.borrow.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        # 借阅历史
        self.history = QToolButton()
        self.history.setText('借阅历史')
        self.history.setFixedSize(160, 50)
        self.history.setIcon(QIcon('icon/history.png'))
        self.history.setIconSize(QSize(30, 30))
        self.history.clicked.connect(lambda: self.switch(2, self.history))
        self.history.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        # 个人信息
        self.detial = QToolButton()
        self.detial.setText('个人信息')
        self.detial.setFixedSize(160, 50)
        self.detial.setIcon(QIcon('icon/detial.png'))
        self.detial.setIconSize(QSize(30, 30))
        self.detial.clicked.connect(lambda: self.switch(3, self.detial))
        self.detial.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.btnList = [
            self.bookSearch, self.borrow, self.history, self.detial
        ]

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.bookSearch)
        self.layout.addWidget(self.borrow)
        self.layout.addWidget(self.history)
        self.layout.addWidget(self.detial)
        self.layout.addStretch()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        self.menu = QGroupBox()
        self.menu.setFixedSize(160, 500)
        self.menu.setLayout(self.layout)
        self.menu.setContentsMargins(0, 0, 0, 0)
        self.body.addWidget(self.menu)

    def switch(self, index, btn):
        self.focus = index
        for i in self.btnList:
            i.setStyleSheet('''
            *{
                background: white;
            }
            QToolButton:hover{
                background-color: rgba(230, 230, 230, 0.3);
            }
            ''')

        btn.setStyleSheet('''
        QToolButton{
            background-color: rgba(230, 230, 230, 0.7);
        }
        ''')
        self.setContent()

    # 设置右侧信息页
    def setContent(self):
        if self.content is not None:
            self.content.deleteLater()
        if self.focus == 0:
            self.content = Books(self.stu_mes)
        elif self.focus == 1:
            self.content = BorrowingBooks(self.stu_mes)
        elif self.focus == 2:
            self.content = History(self.stu_mes)
        else:
            self.content = Detial(self.stu_mes)
        self.body.addWidget(self.content)

    def setMyStyle(self):
        self.setStyleSheet('''
        QWidget{
            background-color: white;
        }
        ''')
        self.titleBar.setStyleSheet('''
        QWidget{
            background-color: rgba(44,44,44,1);
            border:1px solid black;
            border-radius: 10px;
        }
        ''')
        self.menu.setStyleSheet('''
        QWidget{
            border: 0px;
            border-right: 1px solid rgba(227, 227, 227, 1);
        }
        QToolButton{
            color: rgba(51, 90, 129, 1);
            font-family: 微软雅黑;
            font-size: 25px;
            border-right: 1px solid rgba(227, 227, 227, 1);
        }
        QToolButton:hover{
            background-color: rgba(230, 230, 230, 0.3);
        }
        ''')
        self.title.setStyleSheet('''
        *{
            color: white;
            font-family: 微软雅黑;
            font-size: 25px;
            border: 0px;
        }
        ''')
        self.account.setStyleSheet('''
        *{
            color: white;
            font-weight: 微软雅黑;
            font-size: 25px;
            border: 0px;
        }
        ''')
        self.out.setStyleSheet('''
        QToolButton{
            color: white;
            border:0px;
            font-size: 12px;
        }
        QToolButton:hover{
            color: rgba(11, 145, 255, 1);
        }
        ''')
Esempio n. 56
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.card = CardCreate()
        self.addfiles = QFileDialog(self, )
        self.label = QLabel('Wybrane zdjęcia')
        self.list = QListWidget()
        self.btn = QPushButton('Browse files')
        self.delbtn = QPushButton('Delete')
        self.startbtn = QPushButton('Start')
        self.closebtn = QPushButton('Close')
        self.vbox1 = QVBoxLayout()
        self.vbox2 = QVBoxLayout()
        self.vbox3 = QVBoxLayout()
        self.hbox = QHBoxLayout()
        self.hbox1 = QHBoxLayout()
        self.initui()

    def initui(self):
        self.vbox2.addStretch()
        self.vbox2.addWidget(self.btn)
        self.vbox2.addStretch()
        self.vbox2.addWidget(self.delbtn)
        self.vbox2.addStretch()
        self.vbox1.addStretch()
        self.vbox1.addWidget(self.label)
        self.vbox1.addWidget(self.list)
        self.vbox1.addStretch()
        self.hbox1.addStretch()
        self.hbox1.addWidget(self.closebtn)
        self.hbox1.addStretch()
        self.hbox1.addWidget(self.startbtn)
        self.hbox1.addStretch()
        self.hbox.addStretch()
        self.hbox.addLayout(self.vbox1)
        self.hbox.addLayout(self.vbox2)
        self.hbox.addStretch()
        self.vbox3.addStretch()
        self.vbox3.addLayout(self.hbox)
        self.vbox3.addLayout(self.hbox1)
        self.vbox3.addStretch()
        self.btn.clicked.connect(self.browse)
        self.delbtn.clicked.connect(self.deleteitem)
        self.startbtn.clicked.connect(self.start)
        self.closebtn.clicked.connect(self.close)
        self.setLayout(self.vbox3)
        self.show()

    def browse(self):
        self.addfiles = QFileDialog.getOpenFileNames(self, 'Open file', 'c\\')
        paths = self.addfiles[0]
        for path in paths:
            folder, file = os.path.split(path)
            file = (unidecode.unidecode(file)).replace('_', ' ')
            photoalbum[file] = path
            self.list.addItem(file)

    def deleteitem(self):
        selection = self.list.currentItem().text()
        self.list.takeItem(self.list.row(self.list.currentItem()))
        photoalbum.pop(selection)

    def start(self):
        for key, val in photoalbum.items():
            path, file = os.path.split(val)
            file_nodiacs = unidecode.unidecode(file)
            photo_path = os.path.join(path, file_nodiacs)
            os.rename(val, photo_path)

            image = cv2.imread(photo_path, cv2.IMREAD_COLOR)
            (h, w) = image.shape[0:2]
            if h >= 1080 or w >= 1920:
                self.card.resize(photo=photo_path, width=800)
                self.card.create(self.card.resized_photo)
            else:
                self.card.create(photo_path)
            if self.card.face is not None:
                self.card.face.save('Cards/ {}'.format(file), 'JPEG')
            else:
                print('Potwierdzam dla ' + str(photo_path))

            os.rename(photo_path, val)

    def close(self):
        sys.exit()
Esempio n. 57
0
class LoadReportWindow(QMainWindow):

    def __init__(self, parent=None):

        super(LoadReportWindow, self).__init__(parent)
        self.mywidget = QWidget(self)

        self.setMinimumSize(700, 250)
        self.setWindowTitle('Load Report')
        self.setWindowIcon(QIcon(r".\icon\excel1.ico"))
        # root = QFileInfo(__file__).absolutePath()
        # self.setWindowIcon(QIcon(root + "./icon/Text_Edit.ico"))

        self.job_list = None
        self.lis_name = None
        self.job_path = None
        self.res_path = None
        self.dll_path = None
        self.xml_path = None
        self.njl_path = None
        self.para_con = None
        self.othe_con = None

        self.title_font = QFont("Calibri", 10)
        self.title_font.setItalic(True)
        self.title_font.setBold(True)

        self.cont_font = QFont("Calibri", 9)
        self.cont_font.setItalic(False)
        self.cont_font.setBold(False)

        self.initUI()
        self.load_setting()
        self.center()

    def initUI(self):

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        helpMenu = menubar.addMenu('Help')

        saveAction = QAction(QIcon('./Icon/save.ico'), 'Save', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.triggered.connect(self.save_setting)
        fileMenu.addAction(saveAction)

        clearAction = QAction(QIcon('Icon/clear.ico'), 'Clear', self)
        clearAction.setShortcut('Ctrl+R')
        clearAction.triggered.connect(self.clear_setting)
        fileMenu.addAction(clearAction)

        exitAction = QAction(QIcon('Icon/exit.ico'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)
        fileMenu.addAction(exitAction)

        helpAction = QAction(QIcon('Icon/doc.ico'), 'User Manual', self)
        helpAction.setShortcut('Ctrl+H')
        helpAction.triggered.connect(self.user_manual)
        helpMenu.addAction(helpAction)

        # Blade
        # root axes
        self.label1 = QLabel("Fatigue ")
        self.label1.setFont(self.cont_font)
        self.line1 = MyQLineEdit()
        self.line1.setFont(self.cont_font)
        self.line1.setPlaceholderText("Pick 08_Fatigue")
        self.btn1 = QPushButton("...")
        self.btn1.setFont(self.cont_font)
        self.btn1.clicked.connect(self.load_fatigue)

        self.label2 = QLabel("Ultimate")
        self.label2.setFont(self.cont_font)
        self.line2 = MyQLineEdit()
        self.line2.setFont(self.cont_font)
        self.line2.setPlaceholderText("Pick 07_Ultimate")
        self.btn2 = QPushButton("...")
        self.btn2.setFont(self.cont_font)
        self.btn2.clicked.connect(self.load_ultimate)

        self.label3 = QLabel("Load Case Table")
        self.label3.setFont(self.cont_font)
        self.line3 = MyQLineEdit()
        self.line3.setFont(self.cont_font)
        self.line3.setPlaceholderText("Pick load case table")
        self.btn3 = QPushButton("...")
        self.btn3.setFont(self.cont_font)
        self.btn3.clicked.connect(self.load_lct)

        # output
        self.label4 = QLabel("Output path")
        self.label4.setFont(self.cont_font)
        self.line4 = MyQLineEdit()
        self.line4.setFont(self.cont_font)
        self.line4.setPlaceholderText("Pick output path")
        self.btn4 = QPushButton("...")
        self.btn4.setFont(self.cont_font)
        self.btn4.clicked.connect(self.load_output)

        self.btn5 = QPushButton("Generate load report input excel")
        self.btn5.setFont(self.cont_font)
        self.btn5.clicked.connect(self.generate_excel)

        self.group1 = QGroupBox('Main input')
        self.group1.setFont(self.title_font)
        self.grid1 = QGridLayout()
        # 起始行,起始列,占用行,占用列
        self.grid1.addWidget(self.label1, 0, 0, 1, 1)
        self.grid1.addWidget(self.line1, 0, 1, 1, 5)
        self.grid1.addWidget(self.btn1, 0, 6, 1, 1)
        self.grid1.addWidget(self.label2, 1, 0, 1, 1)
        self.grid1.addWidget(self.line2, 1, 1, 1, 5)
        self.grid1.addWidget(self.btn2, 1, 6, 1, 1)
        self.grid1.addWidget(self.label3, 2, 0, 1, 1)
        self.grid1.addWidget(self.line3, 2, 1, 1, 5)
        self.grid1.addWidget(self.btn3, 2, 6, 1, 1)

        self.group1.setLayout(self.grid1)

        # output
        self.group2 = QGroupBox('Output path')
        self.group2.setFont(self.title_font)
        self.grid2 = QGridLayout()
        # 起始行,起始列,占用行,占用列
        self.grid2.addWidget(self.label4, 0, 0, 1, 1)
        self.grid2.addWidget(self.line4, 0, 1, 1, 5)
        self.grid2.addWidget(self.btn4, 0, 6, 1, 1)
        self.group2.setLayout(self.grid2)

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.group1)
        self.main_layout.addWidget(self.group2)
        self.main_layout.addWidget(self.btn5)
        self.main_layout.addStretch(1)

        self.mywidget.setLayout(self.main_layout)
        self.setCentralWidget(self.mywidget)

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Escape:
            self.close()

    def save_setting(self):
        config = configparser.ConfigParser()
        config.read('config.ini', encoding='utf-8')

        if not config.has_section('Load Report'):
            config.add_section('Load Report')

        config['Load Report'] = {'Fatigue path':self.line1.text(),
                                 'Ultimate path':self.line2.text(),
                                 'Loadcase table':self.line3.text(),
                                 'Output path':self.line4.text()}

        with open("config.ini",'w') as f:
            config.write(f)

    def load_setting(self):
        config = configparser.ConfigParser()
        config.read('config.ini', encoding='utf-8')

        if config.has_section('Load Report'):
            self.line1.setText(config.get('Load Report','Fatigue path'))
            self.line2.setText(config.get('Load Report','Ultimate path'))
            self.line3.setText(config.get('Load Report','Loadcase table'))
            self.line4.setText(config.get('Load Report','Output path'))

    def clear_setting(self):
        self.line1.setText('')
        self.line2.setText('')
        self.line3.setText('')
        self.line4.setText('')

    def user_manual(self):
        os.startfile(os.getcwd()+os.sep+'user manual\Load Report.docx')

    def load_fatigue(self):
        root_path = QFileDialog.getExistingDirectory(self, "Choose fatigue result path", ".")

        if root_path:
            self.line1.setText(root_path.replace('/', '\\'))

    def load_ultimate(self):
        root_path = QFileDialog.getExistingDirectory(self, "Choose ultimate result path", ".")

        if root_path:
            self.line2.setText(root_path.replace('/', '\\'))

    def load_lct(self):
        lct_path = QFileDialog.getOpenFileName(self, "Choose load case table path", ".", "excel(*.xlsx)")

        if lct_path:
            self.line3.setText(lct_path.replace('/', '\\'))

    def load_output(self):
        output_path = QFileDialog.getExistingDirectory(self, "Choose output path", ".")

        if output_path:
            self.line4.setText(output_path.replace('/', '\\'))
            self.line4.home(True)

    # @pysnooper.snoop()
    def generate_excel(self):

        fat_path = self.line1.text()
        ult_path = self.line2.text()
        lct_path = self.line3.text()
        out_path = self.line4.text()

        # main
        fat_main  = os.path.join(fat_path, '05_Main')
        hub_path  = os.path.join(ult_path, r'\06_HR_Onlydlc8\Inclsf')
        ult_main  = os.path.join(ult_path, '08_Main_Inclsf')
        # blade root axes
        root_inclsf  = os.path.join(ult_path, '01_BRS_Inclsf')
        root_exclsf  = os.path.join(ult_path, '02_BRS_Exclsf')
        root_fatigue = os.path.join(fat_path, r'01_BRS\brs1')
        # blade root axes
        user_inclsf  = os.path.join(ult_path, '03_BUS_Inclsf')
        user_exclsf  = os.path.join(ult_path, '04_BUS_Inclsf')
        user_fatigue = os.path.join(fat_path, r'02_BUS\bus1')
        # tower
        tower_inclsf = os.path.join(ult_path, '10_Tower_Inclsf')
        tower_exclsf = os.path.join(ult_path, '11_Tower_Exclsf')
        tower_dlc12  = os.path.join(ult_path, '12_Tower_dlc12')
        tower_fatigue= os.path.join(fat_path, '06_Tower')

        # check fatigue path:
        if not os.path.isdir(fat_path):
            QMessageBox.about(self, 'warnning', 'Please choose a right fatigue path!')
        elif not os.path.isdir(ult_path):
            QMessageBox.about(self, 'warnning', 'Please choose a right ultimate path!')
        elif not os.path.isfile(lct_path):
            QMessageBox.about(self, 'warnning', 'Please choose a right load case table!')
        elif not os.path.isdir(out_path):
            QMessageBox.about(self, 'warnning', 'Please choose a right output path!')
        elif not os.path.isdir(fat_path):
            QMessageBox.about(self, 'warnning', 'Please make sure main fatigue result exist!\n%s' %fat_path)
        elif not os.path.isdir(ult_path):
            QMessageBox.about(self, 'warnning', 'Please make sure main ultimate result exist!\n%s' %ult_path)
        elif not os.path.isdir(hub_path):
            QMessageBox.about(self, 'warnning', 'Please make sure hub without dlc8x result exist!\n%s' %ult_path)
        elif not root_inclsf:
            QMessageBox.about(self,'warnning','Please make sure blade root axes result exist!\n%s' %root_inclsf)
        elif not root_exclsf:
            QMessageBox.about(self,'warnning','Please make sure blade root axes result exist!\n%s' %root_exclsf)
        elif not root_fatigue:
            QMessageBox.about(self,'warnning','Please make sure blade root axes result exist!\n%s' %root_fatigue)
        elif not user_inclsf:
            QMessageBox.about(self,'warnning','Please make sure blade user axes result exist!\n%s' %user_inclsf)
        elif not user_exclsf:
            QMessageBox.about(self,'warnning','Please make sure blade user axes result exist!\n%s' %user_exclsf)
        elif not user_fatigue:
            QMessageBox.about(self,'warnning','Please make sure blade user axes result exist!\n%s' %user_fatigue)
        elif not tower_inclsf:
            QMessageBox.about(self,'warnning','Please make sure tower result exist!\n%s' %tower_inclsf)
        elif not tower_exclsf:
            QMessageBox.about(self,'warnning','Please make sure tower result exist!\n%s' %tower_exclsf)
        elif not tower_dlc12:
            QMessageBox.about(self,'warnning','Please make sure tower result exist!\n%s' %tower_dlc12)
        elif not tower_fatigue:
            QMessageBox.about(self,'warnning','Please make sure tower result exist!\n%s' %tower_fatigue)
        else:
            # write compare result
            print('begin to write excel...')
            table = openpyxl.Workbook()
            try:
                sheet_name = 'Ultimate'
                table.create_sheet(sheet_name)
                br       = os.path.join(ult_main, 'br')
                ultimate = ReadPostMX(br, sheet_name, column_start=1, row_start=1, row_space=2, height_flag=False)
                ultimate.write_result(table)

                hs       = os.path.join(hub_path, 'hs')
                ultimate = ReadPostMX(hs, sheet_name, column_start=1, row_start=22, row_space=2, height_flag=False)
                ultimate.write_result(table)

                hr       = os.path.join(hub_path, 'hr')
                ultimate = ReadPostMX(hr, sheet_name, column_start=1, row_start=43, row_space=2, height_flag=False)
                ultimate.write_result(table)


                sheet_name = 'Fatigue'
                table.create_sheet(sheet_name)
                br      = os.path.join(fat_main, 'br1')
                fatigue = writeRainflow(br, content=('DEL',),row_start=2,col_start=8,height_flag=False)
                fatigue.write2excel(table, sheet_name)

                hs      = os.path.join(fat_main, 'hs')
                fatigue = writeRainflow(hs, content=('DEL',),row_start=16,col_start=8,height_flag=False)
                fatigue.write2excel(table, sheet_name)

                hr      = os.path.join(fat_main, 'hr')
                fatigue = writeRainflow(hr, content=('DEL',),row_start=30,col_start=8,height_flag=False)
                fatigue.write2excel(table, sheet_name)

                excel1_path = os.path.join(out_path, 'Compare_results.xlsx')
                if os.path.isfile(excel1_path):
                    os.remove(excel1_path)
                table.remove(table['Sheet'])
                table.save(excel1_path)
                print('%s is done!' %excel1_path)

                # write blade
                table      = openpyxl.Workbook()
                sheet_name = 'extreme root section'
                table.create_sheet(sheet_name)

                ultimate   = ReadPostMX(root_inclsf, sheet_name, 0, height_flag=True)
                ultimate.write_result(table)
                ultimate   = ReadPostMX(root_exclsf, sheet_name, 13, height_flag=True)
                ultimate.write_result(table)

                # sheet_name = 'extreme user section'
                # table.create_sheet(sheet_name)
                # ultimate   = ReadPostMX(user_inclsf, sheet_name, 0)
                # ultimate.write_result(table)
                # ultimate   = ReadPostMX(user_exclsf, sheet_name, 13)
                # ultimate.write_result(table)

                sheet_name = 'fatigue root section'
                table.create_sheet(sheet_name)
                fatigue    = writeRainflow(root_fatigue, content=('DEL',), row_space=3, height_flag=True)
                fatigue.write2excel(table, sheet_name)

                # sheet_name = 'fatigue user section'
                # table.create_sheet(sheet_name)
                # fatigue    = writeRainflow(user_fatigue, content=('DEL',))
                # fatigue.write2excel(table, sheet_name)

                excel2_path = os.path.join(out_path, 'Blade.xlsx')
                if os.path.isfile(excel2_path):
                    os.remove(excel2_path)
                table.remove(table['Sheet'])
                table.save(excel2_path)
                print('%s is done!' %excel2_path)

                # write tower
                table      = openpyxl.Workbook()
                sheet_name = 'extreme flange section'
                table.create_sheet(sheet_name)
                if 'Mbr' not in ''.join(os.listdir(tower_inclsf)):
                    ultimate = ReadPostMX(tower_inclsf, sheet_name, 0, height_flag=True)
                else:
                    ultimate = ReadPostMX(tower_inclsf, sheet_name, 0, height_flag=False)
                ultimate.write_result(table)

                if 'Mbr' not in ''.join(os.listdir(tower_exclsf)):
                    ultimate = ReadPostMX(tower_exclsf, sheet_name, 13, height_flag=True)
                else:
                    ultimate = ReadPostMX(tower_exclsf, sheet_name, 13, height_flag=False)
                ultimate.write_result(table)

                sheet_name = 'occurrence'
                table.create_sheet(sheet_name)
                Occurrence(lct_path, table, sheet_name)

                sheet_name = 'extreme flange section DLC12'
                table.create_sheet(sheet_name)
                if 'Mbr' not in ''.join(os.listdir(tower_dlc12)):
                    ultimate = ReadPostMX(tower_dlc12, sheet_name, 0, height_flag=True)
                else:
                    ultimate = ReadPostMX(tower_dlc12, sheet_name, 0, height_flag=False)
                ultimate.write_result(table)

                sheet_name = 'fatigue flange section'
                table.create_sheet(sheet_name)

                if 'Mbr' not in ''.join(os.listdir(tower_fatigue)):
                    fatigue = writeRainflow(tower_fatigue, content=('DEL',), height_flag=True)
                    fatigue.write2excel(table, sheet_name)
                else:
                    fatigue = writeRainflow(tower_fatigue, content=('DEL',), height_flag=False)
                    fatigue.write2excel(table, sheet_name)

                excel3_path = os.path.join(out_path, 'Tower.xlsx')
                if os.path.isfile(excel3_path):
                    os.remove(excel3_path)
                table.remove(table['Sheet'])
                table.save(excel3_path)
                print('%s is done!' %excel3_path)

                if os.path.isfile(excel1_path) and os.path.isfile(excel2_path) and os.path.isfile(excel3_path):
                    QMessageBox.about(self, 'Window', 'Generating excels is done!')

            except Exception as e:
                QMessageBox.about(self, 'Warnning', 'Error occurs when generating excels!\n%s' %e)

    def center(self):

        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
Esempio n. 58
0
class History(QGroupBox):
    def __init__(self, stu_mes):
        super().__init__()
        self.stu_mes = stu_mes
        self.body = QVBoxLayout()
        self.setTitleBar()
        self.setTable()
        self.setOut()
        self.body.addStretch()

        self.setLayout(self.body)
        self.initUI()

    # 标题栏
    def setTitleBar(self):
        self.title = QLabel()
        self.title.setText('借阅记录')
        self.title.setFixedHeight(25)
        titleLayout = QHBoxLayout()
        titleLayout.addSpacing(50)
        titleLayout.addWidget(self.title)
        self.titleBar = QWidget()
        self.titleBar.setFixedSize(900, 50)
        self.titleBar.setLayout(titleLayout)
        self.body.addWidget(self.titleBar)

    # 创建表格
    def setTable(self, val: dict = None):
        self.table = QTableWidget(1, 5)
        self.table.setFixedHeight(400)
        self.table.setContentsMargins(10, 10, 10, 10)
        self.table.verticalHeader().setVisible(False)
        self.table.horizontalHeader().setVisible(False)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table.setFocusPolicy(Qt.NoFocus)
        self.table.setColumnWidth(0, 200)
        self.table.setColumnWidth(1, 250)
        self.table.setColumnWidth(2, 175)
        self.table.setColumnWidth(3, 175)
        self.table.setColumnWidth(4, 100)

        self.table.setItem(0, 0, QTableWidgetItem('书号'))
        self.table.setItem(0, 1, QTableWidgetItem('书名'))
        self.table.setItem(0, 2, QTableWidgetItem('借书日期'))
        self.table.setItem(0, 3, QTableWidgetItem('还书日期'))
        self.table.setItem(0, 4, QTableWidgetItem('罚金'))

        for i in range(5):
            self.table.item(0, i).setTextAlignment(Qt.AlignCenter)
            self.table.item(0, i).setFont(QFont('微软雅黑', 15))

        self.list = database.get_log(self.stu_mes['SID'])
        for i in self.list:
            self.insertRow(i)
        self.body.addWidget(self.table)

    # 插入行
    def insertRow(self, val: list):
        itemBID = QTableWidgetItem(val[1])
        itemBID.setTextAlignment(Qt.AlignCenter)
        itemNAME = QTableWidgetItem('《' + val[2] + '》')
        itemNAME.setTextAlignment(Qt.AlignCenter)
        itemBEGIN = QTableWidgetItem(val[3])
        itemBEGIN.setTextAlignment(Qt.AlignCenter)
        itemBACK = QTableWidgetItem(val[4])
        itemBACK.setTextAlignment(Qt.AlignCenter)
        itemPUNISHED = QLabel()
        itemPUNISHED.setText(str(val[5]))
        itemPUNISHED.setAlignment(Qt.AlignCenter)
        if val[5] == 0:
            itemPUNISHED.setStyleSheet('''
                *{
                    color: green;
                    font-size: 20px;
                }
            ''')
        else:
            itemPUNISHED.setStyleSheet('''
                *{
                    color: red;
                    font-size: 20px;
                }
            ''')

        self.table.insertRow(1)
        self.table.setItem(1, 0, itemBID)
        self.table.setItem(1, 1, itemNAME)
        self.table.setItem(1, 2, itemBEGIN)
        self.table.setItem(1, 3, itemBACK)
        self.table.setCellWidget(1, 4, itemPUNISHED)

    # 导出文件
    def setOut(self):
        self.outButton = QToolButton()
        self.outButton.setText('导出')
        self.outButton.clicked.connect(self.outFunction)
        self.outButton.setFixedSize(100, 50)
        outLayout = QHBoxLayout()
        outLayout.addStretch()
        outLayout.addWidget(self.outButton)
        outWidget = QWidget()
        outWidget.setLayout(outLayout)

        self.body.addWidget(outWidget)

    def outFunction(self):
        import csv
        dirName = QFileDialog.getExistingDirectory(self, '选择文件夹')

        title = ['SID', 'BID', 'BNAME', 'BORROW_DATE', 'BACK_DATE', 'PUNISHED']
        with open(os.path.join(dirName, self.stu_mes['SID'] + '.csv'),
                  'w',
                  newline='') as f:
            writer = csv.writer(f)
            writer.writerow(title)
            for row in self.list:
                writer.writerow(row)

    def initUI(self):
        self.setFixedSize(1000, 600)
        self.setStyleSheet('''
        *{
            background-color: white;
            border:0px;
        }
        ''')
        self.titleBar.setStyleSheet('''
        QWidget {
            border:0;
            background-color: rgba(216, 216, 216, 1);
            border-radius: 20px;
            color: rgba(113, 118, 121, 1);
        }
        QLabel{
            font-size: 25px;
            font-family: 微软雅黑;
        }
        ''')
        self.table.setStyleSheet('''
            font-size:18px;
            color: black;
            background-color: white;
            font-family: 微软雅黑;
        ''')
        self.outButton.setStyleSheet('''
        QToolButton{
            border-radius: 10px;
            background-color:rgba(52, 118, 176, 1);
            color: white;
            font-size: 25px;
            font-family: 微软雅黑;
        }
        ''')
Esempio n. 59
0
class PointControler(QWidget):
    point_changed = pyqtSignal(float, float, float)

    def __init__(self, label=None, non_zero=False, horizontal=True):
        super(PointControler, self).__init__()
        self.non_zero = non_zero
        if horizontal:
            self.layout = QHBoxLayout()
        else:
            self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        if isinstance(label, str):
            self.layout.addWidget(QLabel(label))

        self.x = QLineEdit()
        self.x.setValidator(
            QDoubleValidator(-sys.float_info.max, sys.float_info.max, 2,
                             self.x))
        self.x.editingFinished.connect(self.on_point_change)
        self.layout.addWidget(self.x)

        self.y = QLineEdit()
        self.y.setValidator(
            QDoubleValidator(-sys.float_info.max, sys.float_info.max, 2,
                             self.x))
        self.y.editingFinished.connect(self.on_point_change)
        self.layout.addWidget(self.y)

        self.z = QLineEdit()
        self.z.setValidator(
            QDoubleValidator(-sys.float_info.max, sys.float_info.max, 2,
                             self.x))
        self.z.editingFinished.connect(self.on_point_change)
        self.layout.addWidget(self.z)

        self.layout.addStretch()

        self.msg = QMessageBox(
            QMessageBox.Warning, "Zero Vector",
            "This vector should not be zero. \n Update is paused until valid vector is provided.",
            QMessageBox.Ok, self)

    def get_numpy(self):
        return np.array(
            [float(self.x.text()),
             float(self.y.text()),
             float(self.z.text())])

    def on_point_change(self):
        x = float(self.x.text())
        y = float(self.y.text())
        z = float(self.z.text())
        self.x.setText("%.2f" % x)
        self.y.setText("%.2f" % y)
        self.z.setText("%.2f" % z)
        if self.non_zero:
            if x * x + y * y + z * z == 0:

                self.msg.exec()
                return
        self.point_changed.emit(x, y, z)

    def plain_set_point(self, x, y, z):
        self.x.setText("%.2f" % x)
        self.y.setText("%.2f" % y)
        self.z.setText("%.2f" % z)

    def set_point(self, x, y, z):
        self.x.setText("%.2f" % x)
        self.y.setText("%.2f" % y)
        self.z.setText("%.2f" % z)
        self.point_changed.emit(x, y, z)
Esempio n. 60
0
    def initUI(self):
        ################### layout design #############################################
        #라인에디터
        self.le_per = QLineEdit()
        self.le_pbr = QLineEdit()
        self.le_icr = QLineEdit()
        self.le_cRatio = QLineEdit()

        #체크박스, 잠금 설정 포함
        cb_per = QCheckBox('PER', self)  #PER
        cb_per.toggle()
        cb_per.stateChanged.connect(self.le_lock_per)

        cb_pbr = QCheckBox('PBR', self)  #PBR
        cb_pbr.toggle()
        cb_pbr.stateChanged.connect(self.le_lock_pbr)

        cb_icr = QCheckBox('이자보상배율', self)  #이자보상배율
        cb_icr.toggle()
        cb_icr.stateChanged.connect(self.le_lock_icr)

        cb_cRatio = QCheckBox('유동비율', self)  #유동비율
        cb_cRatio.toggle()
        cb_cRatio.stateChanged.connect(self.le_lock_cRatio)

        #결과 브라우저
        #self.tb_result=QTextBrowser()
        self.tv_result = QTableView()

        #검색 버튼
        btn_search = QPushButton('검색', self)
        btn_search.clicked.connect(self.crawl_data)

        #체크 박스 세로로 묶기
        vbox_cb = QVBoxLayout()
        vbox_cb.addWidget(cb_per)
        vbox_cb.addWidget(cb_pbr)
        vbox_cb.addWidget(cb_icr)
        vbox_cb.addWidget(cb_cRatio)

        #라인 에디터 세로로 묶기
        vbox_le = QVBoxLayout()
        vbox_le.addWidget(self.le_per)
        vbox_le.addWidget(self.le_pbr)
        vbox_le.addWidget(self.le_icr)
        vbox_le.addWidget(self.le_cRatio)

        #검색 버튼 세로로 묶기(빈공간 삽입)
        vbox_search = QVBoxLayout()
        vbox_search.addStretch(3)
        vbox_search.addWidget(btn_search)

        #윗단 검색 도구 묶기
        hbox_above = QHBoxLayout()
        hbox_above.addLayout(vbox_cb)
        hbox_above.addLayout(vbox_le)
        hbox_above.addStretch(5)
        hbox_above.addLayout(vbox_search)

        #검색 도구와 결과창 묶기
        vbox_all = QVBoxLayout()
        vbox_all.addLayout(hbox_above, 1)
        #vbox_all.addWidget(self.tb_result,5)
        vbox_all.addWidget(self.tv_result, 5)
        self.setLayout(vbox_all)
        ########################## layout design End ##################################
        ##########################Window output #######################################
        self.setWindowTitle('StockInfo_Search')
        self.setGeometry(800, 800, 800, 600)
        self.center()
        self.show()