コード例 #1
0
    def setupUi(self):
        # Remove seaborn dependency
        dark_gray = ".15"
        light_gray = ".8"
        style_dict = {
            "figure.facecolor":
            "white",
            "text.color":
            dark_gray,
            "axes.labelcolor":
            dark_gray,
            "axes.facecolor":
            "white",
            "axes.edgecolor":
            dark_gray,
            "axes.linewidth":
            1.25,
            "grid.color":
            light_gray,
            "legend.frameon":
            False,
            "legend.numpoints":
            1,
            "legend.scatterpoints":
            1,
            "xtick.direction":
            "out",
            "ytick.direction":
            "out",
            "xtick.color":
            dark_gray,
            "ytick.color":
            dark_gray,
            "xtick.major.size":
            6,
            "ytick.major.size":
            6,
            "xtick.minor.size":
            3,
            "ytick.minor.size":
            3,
            "axes.grid":
            False,
            "axes.axisbelow":
            True,
            "image.cmap":
            "rocket",
            "font.family": ["sans-serif"],
            "font.sans-serif": [
                "Arial", "DejaVu Sans", "Liberation Sans",
                "Bitstream Vera Sans", "sans-serif"
            ],
            "grid.linestyle":
            "-",
            "lines.solid_capstyle":
            "round",
        }
        mpl.rcParams.update(style_dict)

        self.setObjectName("self")
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setSpacing(0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.plotselecttabWidget = QTabWidget(self)
        self.plotselecttabWidget.setMaximumSize(QSize(22, 1000))
        self.plotselecttabWidget.setTabPosition(QTabWidget.West)
        self.plotselecttabWidget.setTabShape(QTabWidget.Triangular)
        self.plotselecttabWidget.setUsesScrollButtons(False)
        self.plotselecttabWidget.setDocumentMode(False)
        self.plotselecttabWidget.setTabsClosable(False)
        self.plotselecttabWidget.setObjectName("plotselecttabWidget")
        self.plotselecttabWidget.setStyleSheet(
            "QTabBar::tab { color:black; height: 40px; }")

        # Create a tab for all plots
        if (self.nplots > 1):
            self.tab = QWidget()
            self.tab.setMaximumSize(QSize(0, 0))
            self.plotselecttabWidget.addTab(self.tab, "All")
        else:
            self.plotselecttabWidget.setVisible(False)
        # Create a tab for each plot
        for i in range(self.nplots):
            self.tab = QWidget()
            self.tab.setMaximumSize(QSize(0, 0))
            self.plotselecttabWidget.addTab(self.tab, "%d" % (i + 1))
        self.horizontalLayout.addWidget(self.plotselecttabWidget)
        self.plotselecttabWidget.setCurrentIndex(0)

        self.plotcontainer = QVBoxLayout()
        self.plotcontainer.setObjectName("plotcontainer")
        self.horizontalLayout.addLayout(self.plotcontainer)

        # Create the multiplot figure
        gs = self.organizeplots(self.pot, self.nplots, self.ncols)
        self.axarr = []
        self.figure = plt.figure()
        for i in range(self.nplots):
            self.axarr.append(self.figure.add_subplot(gs[i]))

        self.set_bbox()

        self.canvas = FigureCanvasQTAgg(self.figure)
        self.canvas.setFocusPolicy(Qt.ClickFocus)
        self.canvas.setFocus()
        self.plotcontainer.addWidget(self.canvas)
        self.init_plot(0)

        connection_id = self.plotselecttabWidget.currentChanged.connect(
            self.handle_plottabChanged)
        axes = plt.gcf().axes
        for ax_i in axes:
            for side in ["top", "right"]:
                ax_i.spines[side].set_visible(False)

            ax_i.xaxis.tick_bottom()
            ax_i.yaxis.tick_left()
        self.hidden_tab = []
コード例 #2
0
    def initUI(self):

        #start geometrie
        self.width = 1200
        self.height = 800
        self.desktop = QApplication.desktop()
        self.desktop_size = QRect()
        self.desktop_size = self.desktop.screenGeometry()

        self.logger = logging.getLogger()
        self.logger.setLevel(self.log_level)
        self.log_date = datetime.datetime.now()

        self.mod_path = os.path.dirname(Pythonic.__file__)

        log_date_str = self.log_date.strftime('%Y_%m_%d')
        month = self.log_date.strftime('%b')
        year = self.log_date.strftime('%Y')
        home_dict = str(Path.home())
        file_path = '{}/Pythonic_{}/{}/log_{}.txt'.format(
            home_dict, year, month, log_date_str)
        self.ensure_file_path(file_path)

        file_handler = logging.FileHandler(file_path)
        file_handler.setLevel(self.log_level)
        file_handler.setFormatter(self.formatter)

        self.logger.addHandler(file_handler)

        # init language !
        self.translator = QTranslator(self.app)
        #self.translator.load('translations/spanish_es')
        self.translator.load(join(self.mod_path, 'translations/english_en.qm'))
        self.app.installTranslator(self.translator)
        #QC.installTranslator(self.translator)

        logging.debug('Translation: {}'.format(QC.translate('', 'Save')))

        # setup the default language here
        #self.changeTranslator('german_de.qm')

        self.x_position = self.desktop_size.width() / 2 - self.width / 2
        self.y_position = self.desktop_size.height() / 2 - self.height / 2

        self.setAcceptDrops(True)

        self.layout_v = QVBoxLayout()

        # main_layout contains the workingarea and the toolbox
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(0)
        self.main_layout.setContentsMargins(0, 0, 0, 0)

        self.bottom_border_layout = QHBoxLayout()
        self.bottom_border_layout.setSpacing(0)
        self.setContentsMargins(0, 0, 0, 0)

        # create class objects
        #self.exceptwindow = ExceptWindow(self)

        self.wrk_area_arr = []
        self.wrk_tabs_arr = []
        self.grd_ops_arr = []
        self.working_tabs = QTabWidget()
        self.working_tabs.setMinimumSize(300, 300)
        for i in range(self.number_of_grids):

            self.wrk_area_arr.append(WorkingArea())
            self.wrk_tabs_arr.append(QScrollArea())
            self.wrk_tabs_arr[i].setWidget(self.wrk_area_arr[i])
            self.wrk_tabs_arr[i].setWidgetResizable(True)

            #self.working_tabs.addTab(self.wrk_area_arr[i], QC.translate('', 'Grid {}'.format(i)))
            self.working_tabs.addTab(self.wrk_tabs_arr[i],
                                     QC.translate('', 'Grid {}'.format(i + 1)))

            self.grd_ops_arr.append(GridOperator(self.wrk_area_arr[i].grid, i))

        # init reference for the current grid which is in focus
        self.focus_grid = self.wrk_area_arr[0]
        self.wrk_tab_index = 0

        #self.working_area = WorkingArea()
        self.storagebar = StorageBar(self)
        self.menubar = MenuBar()
        self.toolbox_tab = QTabWidget()
        self.toolbox_tab.setSizePolicy(QSizePolicy.Minimum,
                                       QSizePolicy.Preferred)
        self.topMenuBar = topMenuBar()
        self.settings = Settings()
        self.infoWindow = InfoWindow()

        #self.gridoperator = GridOperator(self)

        self.toolbox_basics = BasicTools(self)
        self.toolbox_cryptos = CryptoTools(self)
        self.toolbox_connectivity = ConnectivityTools(self)
        self.toolbox_ml = MLTools(self)

        # add Tabs to the toolbox
        self.toolbox_tab.addTab(self.toolbox_basics, QC.translate('', 'Basic'))
        self.toolbox_tab.addTab(self.toolbox_cryptos,
                                QC.translate('', 'Cryptos'))
        self.toolbox_tab.addTab(self.toolbox_connectivity,
                                QC.translate('', 'Connectivity'))
        self.toolbox_tab.addTab(self.toolbox_ml,
                                QC.translate('', 'Machine Learning'))

        # signals and slots
        self.menubar.set_info_text.connect(self.setInfoText)
        self.menubar.start_debug.connect(self.startDebug)
        self.menubar.start_exec.connect(self.startExec)

        self.topMenuBar.switch_language.connect(self.changeTranslator)
        self.topMenuBar.close_signal.connect(self.closeEvent)
        self.topMenuBar.open_action.triggered.connect(
            self.menubar.openFileNameDialog)
        self.topMenuBar.save_action.triggered.connect(self.menubar.simpleSave)
        self.topMenuBar.save_as_action.triggered.connect(
            self.menubar.saveFileDialog)
        self.topMenuBar.new_action.triggered.connect(self.menubar.saveQuestion)
        self.topMenuBar.settings_action.triggered.connect(self.settings.show)
        self.topMenuBar.info_action.triggered.connect(self.showInfo)

        self.working_tabs.currentChanged.connect(self.wrkIndexChanged)

        self.menubar.stop_exec.connect(self.stopExecution)
        self.menubar.kill_proc.connect(self.killProcesses)
        self.menubar.load_file.connect(self.loadGrid)
        self.menubar.save_file.connect(self.saveGrid)
        self.menubar.clear_grid.connect(self.setupDefault)

        for i in range(self.number_of_grids):

            self.toolbox_cryptos.reg_tool.connect(self.wrk_area_arr[i].regType)
            self.toolbox_connectivity.reg_tool.connect(
                self.wrk_area_arr[i].regType)
            self.toolbox_ml.reg_tool.connect(self.wrk_area_arr[i].regType)
            self.toolbox_basics.reg_tool.connect(self.wrk_area_arr[i].regType)
            # hier auch noch anpassen
            self.storagebar.forward_config.connect(
                self.wrk_area_arr[i].receiveConfig)
            self.wrk_area_arr[i].finish_dropbox.connect(
                self.storagebar.finishDropBox)

            self.grd_ops_arr[i].update_logger.connect(self.update_logfile)
            self.grd_ops_arr[i].switch_grid.connect(self.receiveTarget)
            self.wrk_area_arr[i].query_grid_config_wrk.connect(
                self.queryGridConfiguration)

        # register tools
        self.toolbox_cryptos.register_tools()
        self.toolbox_basics.register_tools()
        self.toolbox_connectivity.register_tools()
        self.toolbox_ml.register_tools()

        self.scrollArea = QScrollArea()
        #self.scrollArea.setWidget(self.working_area)
        self.scrollArea.setWidget(self.working_tabs)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setMinimumSize(300, 300)

        self.scroll_dropBox = QScrollArea()
        self.scroll_dropBox.setWidget(self.storagebar)
        self.scroll_dropBox.setWidgetResizable(True)
        self.scroll_dropBox.setMaximumWidth(270)

        self.bottom_area = QWidget()
        self.bottom_area_layout = QHBoxLayout(self.bottom_area)
        self.bottom_area_layout.addWidget(self.scrollArea)
        self.bottom_area_layout.addWidget(self.scroll_dropBox)

        self.layout_v.addWidget(self.topMenuBar)
        self.layout_v.addWidget(self.menubar)
        self.layout_v.addWidget(self.toolbox_tab)
        self.layout_v.addWidget(self.bottom_area)

        self.main_widget = QWidget()
        self.main_widget.setLayout(self.layout_v)

        # add main widget to main layout
        self.main_layout.addWidget(self.main_widget, 0)
        self.main_layout.setSpacing(0)
        # resize button
        self.sizeGrip = QSizeGrip(self.main_widget)

        # bottom info text
        self.infoText = QLabel()
        self.infoText.setText('')

        # define the bottom border line
        self.bottom_border_layout.addWidget(self.infoText)
        self.bottom_border_layout.setSpacing(0)
        # left, top, right, bottom
        self.bottom_border_layout.setContentsMargins(5, 0, 5, 5)
        self.bottom_border_layout.addWidget(self.sizeGrip, 0, Qt.AlignRight)

        self.bottom_border = QWidget()
        self.bottom_border.setLayout(self.bottom_border_layout)
        self.main_layout.addWidget(self.bottom_border)

        self.setLayout(self.main_layout)
        self.setGeometry(self.x_position, self.y_position, self.width,
                         self.height)
コード例 #3
0
def load_strategy_slots(config_obj: Configuration):
    """
    This will initialize all the necessary strategy slots and add them to the configuration GUI. All the strategies
    are loaded from the config_obj.strategies dictionary.
    :param config_obj: Configuration QDialog object (from configuration.py)
    :return: None
    """
    # TODO: Refactor to remove pylint disable below.
    # pylint: disable=too-many-locals, too-many-statements, too-many-nested-blocks
    for strategy_key_name, strategy in config_obj.strategies.items():
        if strategy_key_name in config_obj.hiddenStrategies:  # Don't re-render hidden strategies.
            continue

        temp = strategy()
        strategy_name = temp.name
        parameters = temp.get_param_types()
        for tab in config_obj.categoryTabs:
            config_obj.strategyDict[tab,
                                    strategy_name] = tab_widget = QTabWidget()
            description_label = QLabel(
                f'Strategy description: {temp.description}')
            description_label.setWordWrap(True)

            layout = QVBoxLayout()
            layout.addWidget(description_label)

            scroll = QScrollArea(
            )  # Added a scroll area so user can scroll when additional slots are added.
            scroll.setWidgetResizable(True)

            if config_obj.get_caller_based_on_tab(tab) == OPTIMIZER:
                groupBox, group_box_layout = get_regular_groupbox_and_layout(
                    f'Enable {strategy_name} optimization?')
                config_obj.strategyDict[tab, strategy_name] = groupBox
                for index, parameter in enumerate(parameters, start=1):
                    # TODO: Refactor this logic.
                    if not isinstance(parameter, tuple) or \
                            isinstance(parameter, tuple) and parameter[1] in [int, float]:
                        if isinstance(parameter, tuple):
                            widget = QSpinBox if parameter[
                                1] == int else QDoubleSpinBox
                            step_val = 1 if widget == QSpinBox else 0.1
                        else:
                            widget = QSpinBox if parameter == int else QDoubleSpinBox
                            step_val = 1 if widget == QSpinBox else 0.1
                        config_obj.strategyDict[
                            strategy_name, index,
                            'start'] = start = get_default_widget(widget, 1)
                        config_obj.strategyDict[
                            strategy_name, index,
                            'end'] = end = get_default_widget(widget, 1)
                        config_obj.strategyDict[
                            strategy_name, index,
                            'step'] = step = get_default_widget(
                                widget, step_val)
                        if isinstance(parameter, tuple):
                            message = parameter[0]
                        else:
                            message = f"{strategy_name} {index}"
                        add_start_end_step_to_layout(group_box_layout, message,
                                                     start, end, step)
                    elif isinstance(parameter,
                                    tuple) and parameter[1] == tuple:
                        group_box_layout.addRow(QLabel(parameter[0]))
                        for option in parameter[2]:
                            config_obj.strategyDict[
                                strategy_name,
                                option] = checkBox = QCheckBox(option)
                            group_box_layout.addRow(checkBox)
                    else:
                        raise ValueError(
                            "Invalid type of parameter type provided.")
            else:
                groupBox, group_box_layout = get_regular_groupbox_and_layout(
                    f"Enable {strategy_name}?")
                config_obj.strategyDict[tab, strategy_name,
                                        'groupBox'] = groupBox

                status = QLabel()
                if temp.dynamic:
                    addButton, deleteButton = add_strategy_buttons(
                        config_obj.strategyDict, parameters, strategy_name,
                        group_box_layout, tab)
                    horizontal_layout = QHBoxLayout()
                    horizontal_layout.addWidget(addButton)
                    horizontal_layout.addWidget(deleteButton)
                    horizontal_layout.addWidget(status)
                    horizontal_layout.addStretch()
                    layout.addLayout(horizontal_layout)

                values, labels = create_strategy_inputs(
                    parameters, strategy_name, group_box_layout)
                config_obj.strategyDict[tab, strategy_name, 'values'] = values
                config_obj.strategyDict[tab, strategy_name, 'labels'] = labels
                config_obj.strategyDict[tab, strategy_name,
                                        'parameters'] = parameters
                config_obj.strategyDict[tab, strategy_name,
                                        'layout'] = group_box_layout
                config_obj.strategyDict[tab, strategy_name, 'status'] = status

            layout.addWidget(scroll)
            scroll.setWidget(groupBox)
            tab_widget.setLayout(layout)
            tab.addTab(tab_widget, strategy_name)
コード例 #4
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_rows, hs_cols = (64, 128)

        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 "
                        "ElectrumSV 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 ElectrumSV 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 bitcoins 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") % 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 bitcoins 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_rows, hs_cols))
        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 bitcoins.").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 bitcoins "
              "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)
コード例 #5
0
ファイル: pyQtDemo.py プロジェクト: wlssirius/Python
 def createTabGroupBox(self):
     self.tabs = QTabWidget() 
     self.tabs.setFixedWidth(1000)
     
     self.fig1, self.canvas1 = self.addPlotTab('Input and Output')
コード例 #6
0
    def __init__(self, parent=None, test=False):
        super(Preferences, self).__init__(parent)
        self.parent = parent
        self.test = test

        saveQL = QLabel('<html><b>' + self.tr('Save files') + '</b></html>')
        existQL = QLabel(self.tr('Existing files:'))
        self.exst_prefixQRB = QRadioButton(self.tr("Add '~' prefix"))
        self.exst_overwriteQRB = QRadioButton(self.tr('Overwrite'))
        exist_layout = utils.add_to_layout('h', self.exst_prefixQRB,
                                           self.exst_overwriteQRB)

        defaultQL = QLabel(self.tr('Default output destination:'))
        self.defaultQLE = QLineEdit()
        self.defaultQTB = QToolButton()
        self.defaultQTB.setText('...')
        deafult_fol_layout = utils.add_to_layout('h', self.defaultQLE,
                                                 self.defaultQTB)
        nameQL = QLabel('<html><b>' + self.tr('Name files') + '</b></html>')
        prefixQL = QLabel(self.tr('Prefix:'))
        suffixQL = QLabel(self.tr('Suffix:'))
        self.prefixQLE = QLineEdit()
        self.suffixQLE = QLineEdit()
        grid = utils.add_to_grid([prefixQL, self.prefixQLE],
                                 [suffixQL, self.suffixQLE])
        prefix_layout = utils.add_to_layout('h', grid, None)

        tabwidget1_layout = utils.add_to_layout('v', saveQL,
                                                QSpacerItem(14, 13), existQL,
                                                exist_layout,
                                                QSpacerItem(14, 13), defaultQL,
                                                deafult_fol_layout,
                                                QSpacerItem(13, 13), nameQL,
                                                QSpacerItem(14, 13),
                                                prefix_layout, None)

        ffmpegQL = QLabel('<html><b>FFmpeg</b></html>')
        ffmpeg_pathQL = QLabel(self.tr('Path to executable:'))
        self.ffmpegpathQLE = QLineEdit()

        default_cmd_ffmpegQL = QLabel(self.tr('Default command:'))
        self.ffmpegcmdQLE = QLineEdit()

        vidcodecsQL = QLabel('<html><b>' + self.tr('Video codecs') +
                             '</b></html>')
        self.vidcodecsQPTE = QPlainTextEdit()
        audcodecsQL = QLabel('<html><b>' + self.tr('Audio codecs') +
                             '</b></html>')
        self.audcodecsQPTE = QPlainTextEdit()
        extraformatsffmpegQL = QLabel('<html><b>' + self.tr('Extra formats') +
                                      '</b></html>')
        self.extraformatsffmpegQPTE = QPlainTextEdit()

        gridlayout = utils.add_to_grid(
            [vidcodecsQL, audcodecsQL, extraformatsffmpegQL], [
                self.vidcodecsQPTE, self.audcodecsQPTE,
                self.extraformatsffmpegQPTE
            ])

        defvidcodecsQPB = QPushButton(self.tr("Default video codecs"))
        defaudcodecsQPB = QPushButton(self.tr("Default audio codecs"))

        hlayout1 = utils.add_to_layout('h', None, defvidcodecsQPB,
                                       defaudcodecsQPB)

        tabwidget2_layout = utils.add_to_layout('v', ffmpegQL,
                                                QSpacerItem(14,
                                                            13), ffmpeg_pathQL,
                                                self.ffmpegpathQLE,
                                                default_cmd_ffmpegQL,
                                                self.ffmpegcmdQLE,
                                                QSpacerItem(20, 20),
                                                gridlayout, hlayout1, None)

        imagemagickQL = QLabel('<html><b>ImageMagick (convert)</b></html>')
        default_cmd_imageQL = QLabel(self.tr('Default options:'))
        self.imagecmdQLE = QLineEdit()

        extraformatsimageQL = QLabel('<html><b>' + self.tr('Extra formats') +
                                     '</b></html>')
        self.extraformatsimageQPTE = QPlainTextEdit()

        hlayout2 = utils.add_to_layout('h', self.extraformatsimageQPTE,
                                       QSpacerItem(220, 20))

        tabwidget3_layout = utils.add_to_layout('v', imagemagickQL,
                                                QSpacerItem(14, 13),
                                                default_cmd_imageQL,
                                                self.imagecmdQLE,
                                                QSpacerItem(20, 20),
                                                extraformatsimageQL, hlayout2,
                                                None)

        extraformatsdocumentQL = QLabel('<html><b>' +
                                        self.tr('Extra formats') +
                                        '</b></html>')
        self.extraformatsdocumentQPTE = QPlainTextEdit()

        hlayout3 = utils.add_to_layout('h', self.extraformatsdocumentQPTE,
                                       QSpacerItem(220, 20))

        tabwidget4_layout = utils.add_to_layout('v', extraformatsdocumentQL,
                                                hlayout3, None)

        widget1 = QWidget()
        widget1.setLayout(tabwidget1_layout)
        widget2 = QWidget()
        widget2.setLayout(tabwidget2_layout)
        widget3 = QWidget()
        widget3.setLayout(tabwidget3_layout)
        widget4 = QWidget()
        widget4.setLayout(tabwidget4_layout)
        tabWidget = QTabWidget()
        tabWidget.addTab(widget1, self.tr('General'))
        tabWidget.addTab(widget2, self.tr('Audio/Video'))
        tabWidget.addTab(widget3, self.tr('Images'))
        tabWidget.addTab(widget4, self.tr('Documents'))

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

        final_layout = utils.add_to_layout('v', tabWidget, None, buttonBox)
        self.setLayout(final_layout)

        self.defaultQTB.clicked.connect(self.open_dir)
        buttonBox.accepted.connect(self.save_settings)
        buttonBox.rejected.connect(self.reject)
        defvidcodecsQPB.clicked.connect(
            lambda: self.set_videocodecs(config.video_codecs))
        defaudcodecsQPB.clicked.connect(
            lambda: self.set_audiocodecs(config.audio_codecs))

        self.resize(400, 450)
        self.setWindowTitle(self.tr('Preferences'))

        QTimer.singleShot(0, self.load_settings)
コード例 #7
0
    def set_widgets(self):
        q_1_Font = QFont()
        q_1_Font.setPointSize(16)

        labelFont = QFont()
        labelFont.setPointSize(12)

        q_2_Font = QFont()
        q_2_Font.setPointSize(12)

        self.table_1_Font = QFont()
        self.table_1_Font.setPointSize(10)
        self.table_1_Font.setStyleName("Bold") 
        self.table_2_Font = QFont()
        self.table_2_Font.setPointSize(12)
        self.table_2_Font.setStyleName("Bold")

        self.headers = {'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0'}

        # ****************************************
        firstWidget = QWidget()

        taobaoLabel = QLabel()
        logImage = QImage("TBTracker_Ui/tb_log.webp").scaled(int(148 * 0.8), int(66 * 0.8))
        taobaoLabel.setPixmap(QPixmap.fromImage(logImage))
        self.searchLineEdit = QLineEdit()
        self.searchLineEdit.setFont(q_1_Font)
        searchButton = SearchButton()
        searchButton.setFont(q_1_Font)
        searchButton.clicked.connect(self.call_spider)

        searchRegionLayout = QHBoxLayout()
        searchRegionLayout.setContentsMargins(240, 0, 240, 0)
        searchRegionLayout.setSpacing(20)
        searchRegionLayout.addWidget(taobaoLabel)
        searchRegionLayout.addWidget(self.searchLineEdit)
        searchRegionLayout.addWidget(searchButton)
        
        self.taobaoDataTable = QTableWidget(0, 4)
        self.taobaoDataTable.horizontalHeader().hide()
        self.taobaoDataTable.verticalHeader().hide()
        self.taobaoDataTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.taobaoDataTable.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.progressBar = QProgressBar()
        
        self.productIDLineEdit = QLineEdit()
        self.productIDLineEdit.setFont(q_2_Font)
        productIDSaveButton = SaveButton()
        productIDSaveButton.setFont(q_2_Font)
        productIDSaveButton.clicked.connect(self.save_product_id)
        updateDataButton = UpdateButton()
        updateDataButton.setFont(q_2_Font)
        updateDataButton.clicked.connect(self.update_data)

        dataOperateLayout = QHBoxLayout()
        dataOperateLayout.setContentsMargins(500, 0, 0, 0)
        dataOperateLayout.addStretch()
        dataOperateLayout.setSpacing(20)
        dataOperateLayout.addWidget(self.productIDLineEdit)
        dataOperateLayout.addWidget(productIDSaveButton)
        dataOperateLayout.addWidget(updateDataButton)

        firstWidgetLayout = QVBoxLayout()
        firstWidgetLayout.setSpacing(10)
        firstWidgetLayout.addLayout(searchRegionLayout)
        firstWidgetLayout.addWidget(self.taobaoDataTable)
        firstWidgetLayout.addWidget(self.progressBar)
        firstWidgetLayout.addLayout(dataOperateLayout)

        firstWidget.setLayout(firstWidgetLayout)
        # ****************************************

        # ****************************************
        secondWidget = QWidget()
        self.DBTable = QTableWidget(0, 6)
        self.DBTable.setHorizontalHeaderLabels(["商品标识", "标题", "店铺名", "价格", "淘宝价", "是否删除数据?"])
        self.DBTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.DBTable.setSelectionMode(QAbstractItemView.NoSelection)
        self.DBTable.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.addButton = AddButton()
        self.addButton.clicked.connect(self.add_data)
        deleteButton = DeleteButton()
        deleteButton.clicked.connect(self.delete_data)

        DBOperateLayout = QHBoxLayout()
        DBOperateLayout.addStretch()
        DBOperateLayout.setSpacing(20)
        DBOperateLayout.addWidget(self.addButton)
        DBOperateLayout.addWidget(deleteButton)

        secondWidgetLayout = QVBoxLayout()
        secondWidgetLayout.setSpacing(10)
        secondWidgetLayout.addWidget(self.DBTable)
        secondWidgetLayout.addLayout(DBOperateLayout)

        secondWidget.setLayout(secondWidgetLayout)
        # ****************************************

        # ****************************************
        thirdWidget = QWidget()
        
        self.wordCloudLabel = QLabel()
        self.wordCloudLabel.setAlignment(Qt.AlignCenter)
        self.wordCloudLabel.setFrameStyle(QFrame.Panel | QFrame.Plain)
        self.wordCloudLabel.setLineWidth(2)
        self.wordCloudLabel.setPixmap(QPixmap.fromImage(QImage("TBTracker_Ui/WordCloud.png")))

        self.productTree = QTreeWidget()
        self.productTree.setColumnCount(2)
        self.productTree.setHeaderLabels(['商品标识','商品数量'])
        self.productTree.header().setSectionResizeMode(QHeaderView.Stretch)
        self.productTree.setSelectionMode(QAbstractItemView.NoSelection)
        productTreeLayout = QHBoxLayout()
        productTreeLayout.addWidget(self.productTree)

        upLayout = QHBoxLayout()
        upLayout.setSpacing(20)
        upLayout.addWidget(self.wordCloudLabel)
        upLayout.addLayout(productTreeLayout)

        exportButton = ExportButton()
        exportButton.clicked.connect(self.export_data)
        allSelectButton = AllSelectButton()
        allSelectButton.clicked.connect(self.select_all)
        dataExportLayout = QHBoxLayout()
        dataExportLayout.addStretch()
        dataExportLayout.setSpacing(20)
        dataExportLayout.addWidget(allSelectButton)
        dataExportLayout.addWidget(exportButton)

        thirdWidgetLayout = QVBoxLayout()
        thirdWidgetLayout.setSpacing(20)
        thirdWidgetLayout.setContentsMargins(50, 20, 50, 20)
        thirdWidgetLayout.addLayout(upLayout)
        thirdWidgetLayout.addLayout(dataExportLayout)
        
        thirdWidget.setLayout(thirdWidgetLayout)
        # ****************************************

        # ****************************************
        fourthWidget = QWidget()

        self.historyDataCanvas = HistoryDataCanvas()
        historyDataLayout = QVBoxLayout()
        historyDataLayout.addWidget(self.historyDataCanvas)

        self.selectCommodityButton = SelectCommodityButton()
        self.monthlyDataButton = MonthlyDataButton()
        self.yearlyDataButton = YearlyDataButton()
        manualUpdateButton = ManualUpdateButton()
        manualUpdateButton.clicked.connect(self.manual_update)
        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch()
        buttonLayout.setSpacing(30)
        buttonLayout.addWidget(self.selectCommodityButton)
        buttonLayout.addWidget(self.monthlyDataButton)
        buttonLayout.addWidget(self.yearlyDataButton)
        buttonLayout.addWidget(manualUpdateButton)
        
        fourthWidgetLayout = QVBoxLayout()
        fourthWidgetLayout.setSpacing(10)
        fourthWidgetLayout.setContentsMargins(50, 0, 50, 10)
        fourthWidgetLayout.addLayout(historyDataLayout)
        fourthWidgetLayout.addLayout(buttonLayout)

        fourthWidget.setLayout(fourthWidgetLayout)
        # ****************************************

        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(firstWidget, "数据爬虫")
        self.tabWidget.addTab(secondWidget, "数据后台")
        self.tabWidget.addTab(thirdWidget, "数据导出")
        self.tabWidget.addTab(fourthWidget, "数据跟踪")

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(50, 20, 50, 13)
        self.layout.addWidget(self.tabWidget)
コード例 #8
0
    def initUI(self):
        mainHBox = QHBoxLayout()
        # ====================== LEFT PANE ======================
        self.groupBoxNavMenu = create_group_box(self, "STEP II - Tweak Navigation Menu")

        self.navMenu = AnimTreeWidget()
        self.navMenu.itemClicked.connect(self.slotLcdAnimChecked)
        self.wizardGeneration = WizardGeneration(self.navMenu)

        hbox = QHBoxLayout()
        hbox.addWidget(self.navMenu)

        self.groupBoxNavMenu.setLayout(hbox)

        mainHBox.addWidget(self.groupBoxNavMenu)
        # ====================== RIGHT PANE ======================
        rightVBox = QVBoxLayout()

        # Statistics
        self.groupBoxAnimStat = create_group_box(self, "Statistics")

        labelAnimChecked = create_label(self, "Animations checked")
        self.lcdAnimChecked = create_lcd(self)

        hbox = QHBoxLayout()
        hbox.addWidget(labelAnimChecked)
        hbox.addWidget(self.lcdAnimChecked)

        self.groupBoxAnimStat.setLayout(hbox)

        # Loading
        self.groupBoxAnimLoad = create_group_box(self, "STEP I - Loading")

        buttonScanFolder = create_button(self, "Scan Folder", self.actionScanFolder)
        buttonLoadPlugin = create_button(self, "Load Plugin", self.actionLoadPlugin)

        hbox = QHBoxLayout()
        hbox.addWidget(buttonScanFolder)
        hbox.addWidget(buttonLoadPlugin)

        self.groupBoxAnimLoad.setLayout(hbox)

        # Generation
        self.groupBoxPluginGen = create_group_box(self, "STEP III - Generation")

        buttonGeneratePlugin = create_button(self, "Generate Plugin", self.actionGeneratePlugin)
        buttonSetInstallFolder = create_button(self, "Set Install Folder", self.actionSetInstallFolder)

        hbox = QHBoxLayout()
        hbox.addWidget(buttonGeneratePlugin)
        hbox.addWidget(buttonSetInstallFolder)

        self.groupBoxPluginGen.setLayout(hbox)

        # Generation
        self.groupBoxActions = create_group_box(self, "Utility")

        buttonCheckAll = create_button(self, "Check All", self.actionCheckAll)
        buttonUncheckAll = create_button(self, "Uncheck All", self.actionUncheckAll)
        buttonCleanup = create_button(self, "Cleanup", self.actionCleanup)
        buttonCleanup.setToolTip(" 1) - Remove all folders containing no animations\n"
                                 " 2) - Remove nested folders, when parent has the same name")

        hbox = QHBoxLayout()
        hbox.addWidget(buttonCheckAll)
        hbox.addWidget(buttonUncheckAll)
        hbox.addWidget(buttonCleanup)

        self.groupBoxActions.setLayout(hbox)

        # Widget
        self.tabWidget = QTabWidget(self)
        self.tabWidget.addTab(IconsViewer(self), "Icons List")
        self.tabWidget.setCurrentIndex(1)

        rightVBox.setSpacing(20)
        rightVBox.addWidget(self.groupBoxAnimStat)
        rightVBox.addWidget(self.groupBoxAnimLoad)
        rightVBox.addWidget(self.groupBoxPluginGen)
        rightVBox.addWidget(self.groupBoxActions)
        rightVBox.addWidget(self.tabWidget)

        mainHBox.addItem(rightVBox)
        mainHBox.setStretch(0, 3)
        mainHBox.setStretch(1, 1)
        mainHBox.setSpacing(10)
        self.mainLayout.addItem(mainHBox)
        return
コード例 #9
0
    def initUI(self):
        with open("../css/style.css") as f:
            self.setStyleSheet(f.read())

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

        mainLayout = QVBoxLayout()

        # SELECT FILE

        imagePreviewAndDataLayout = QHBoxLayout()

        self.imageLabel = QLabel(alignment=(Qt.AlignVCenter | Qt.AlignHCenter))
        self.imageLabel.setFixedSize(600, 500)
        self.imageLabel.setStyleSheet(
            "QLabel { border-style: solid; border-width: 2px; border-color: rgba(0, 0, 0, 0.1); }");
        imagePreviewAndDataLayout.addWidget(self.imageLabel)

        imageDataLayout = QVBoxLayout()

        imageLabelDataLayout = QVBoxLayout()
        imageLabelDataLayout.setAlignment(Qt.AlignTop)

        fileLabelLayout = QHBoxLayout()
        fileLabelLayout.addWidget(QLabel("File name: ", objectName='title', alignment=Qt.AlignLeft))
        self.fileNameLabel = QLabel("None", alignment=Qt.AlignRight)
        fileLabelLayout.addWidget(self.fileNameLabel)
        imageLabelDataLayout.addLayout(fileLabelLayout)

        fileDirLayout = QHBoxLayout()
        fileDirLayout.addWidget(QLabel("File path: ", objectName='title', alignment=Qt.AlignLeft))
        self.filePathLabel = QLabel("None", alignment=Qt.AlignRight)
        fileDirLayout.addWidget(self.filePathLabel)
        imageLabelDataLayout.addLayout(fileDirLayout)

        fileHeightLayout = QHBoxLayout()
        fileHeightLayout.addWidget(QLabel("Height: ", objectName='title', alignment=Qt.AlignLeft))
        self.fileHeightLabel = QLabel("None", alignment=Qt.AlignRight)
        fileHeightLayout.addWidget(self.fileHeightLabel)
        imageLabelDataLayout.addLayout(fileHeightLayout)

        fileWidthLayout = QHBoxLayout()
        fileWidthLayout.addWidget(QLabel("Width: ", objectName='title', alignment=Qt.AlignLeft))
        self.fileWidthLabel = QLabel("None", alignment=Qt.AlignRight)
        fileWidthLayout.addWidget(self.fileWidthLabel)
        imageLabelDataLayout.addLayout(fileWidthLayout)

        fileLayersLayout = QHBoxLayout()
        fileLayersLayout.addWidget(QLabel("Number of channels: ", objectName='title', alignment=Qt.AlignLeft))
        self.fileLayersLabel = QLabel("None", alignment=Qt.AlignRight)
        fileLayersLayout.addWidget(self.fileLayersLabel)
        imageLabelDataLayout.addLayout(fileLayersLayout)

        imageDataLayout.addLayout(imageLabelDataLayout)

        fileActionsLayout = QVBoxLayout()
        fileActionsLayout.setAlignment(Qt.AlignBottom)

        fileActionsLayout.setAlignment(Qt.AlignBottom)
        fileActionsLayout.addWidget(QPushButton("Change selected file", clicked=self.selectFileButton_clicked))

        fileActionsLayout.addWidget(
            QPushButton("Visualize and crop selected image", clicked=self.imageVisualizer_clicked))
        fileActionsLayout.addWidget(QPushButton("Open in OS image viewer", clicked=self.open_file_clicked))
        fileActionsLayout.addWidget(QPushButton("Grey level histogram", clicked=self.histogram_transformation_clicked))
        fileActionsLayout.addWidget(QPushButton("Reload from disk", clicked=self.reload_from_disk_clicked))
        imageDataLayout.addLayout(fileActionsLayout)

        imagePreviewAndDataLayout.addLayout(imageDataLayout)

        mainLayout.addLayout(imagePreviewAndDataLayout)
        # SELECT FILE

        # ALGORITHMS
        self.tabLayout = QTabWidget()
        pointOperationTab = QWidget()
        transformationTab = QWidget()
        noiseTab = QWidget()
        filterTab = QWidget()
        borderDetectionTab = QWidget()
        thresholdingTab = QWidget()
        objectDetectionTab = QWidget()

        algorithmsLayout = QHBoxLayout()

        algorithm2Button = QPushButton("Operations between Images")
        algorithm2Button.clicked.connect(self.operation_between_images)
        algorithmsLayout.addWidget(algorithm2Button)

        algorithm4Button = QPushButton("Equalization")
        algorithm4Button.clicked.connect(self.equalization)
        algorithmsLayout.addWidget(algorithm4Button)

        algorithm5Button = QPushButton("Dynamic range compression")
        algorithm5Button.clicked.connect(self.dynamic_range_compression_clicked)
        algorithmsLayout.addWidget(algorithm5Button)

        algorithm6Button = QPushButton("Gamma power function")
        algorithm6Button.clicked.connect(self.gamma_power_function_clicked)
        algorithmsLayout.addWidget(algorithm6Button)

        # algorithmsLayout.setEnabled(False)
        # mainLayout.addLayout(algorithmsLayout)
        pointOperationTab.setLayout(algorithmsLayout)
        self.tabLayout.addTab(pointOperationTab, "Point operations")

        # TRANSFORMATIONS
        transformationLayoutt = QHBoxLayout()

        toGrayscaleButton = QPushButton("To Grayscale")
        toGrayscaleButton.clicked.connect(self.to_grayscale)
        transformationLayoutt.addWidget(toGrayscaleButton)

        contrastButton = QPushButton("Contrast increment")
        contrastButton.clicked.connect(self.contrast_transformation_clicked)
        transformationLayoutt.addWidget(contrastButton)

        thresholdButton = QPushButton("Threshold")
        thresholdButton.clicked.connect(self.threshold_transformation_clicked)
        transformationLayoutt.addWidget(thresholdButton)

        negativeButton = QPushButton("Negative")
        negativeButton.clicked.connect(self.negative_transformation_clicked)
        transformationLayoutt.addWidget(negativeButton)

        # mainLayout.addLayout(transformationLayoutt)
        transformationTab.setLayout(transformationLayoutt)
        self.tabLayout.addTab(transformationTab, "Transformations")

        # Noises
        noiseLayout = QHBoxLayout()

        gaussian_button = QPushButton("Gaussian additive noise")
        gaussian_button.clicked.connect(self.gaussian_noise_clicked)
        noiseLayout.addWidget(gaussian_button)

        rayleigh_button = QPushButton("Rayleigh multiplicative noise")
        rayleigh_button.clicked.connect(self.rayleigh_noise_clicked)
        noiseLayout.addWidget(rayleigh_button)

        exponential_button = QPushButton("Exponential additive noise")
        exponential_button.clicked.connect(self.exponential_noise_clicked)
        noiseLayout.addWidget(exponential_button)

        salt_and_pepper_button = QPushButton("Salt and pepper noise")
        salt_and_pepper_button.clicked.connect(self.salt_and_pepper_clicked)
        noiseLayout.addWidget(salt_and_pepper_button)

        # mainLayout.addLayout(noiseLayout)
        noiseTab.setLayout(noiseLayout)
        self.tabLayout.addTab(noiseTab, "Noises")

        # Filters
        filterLayout = QHBoxLayout()

        mean_filter_button = QPushButton("Mean filter")
        mean_filter_button.clicked.connect(self.mean_filter_clicked)
        filterLayout.addWidget(mean_filter_button)

        median_filter_button = QPushButton("Median filter")
        median_filter_button.clicked.connect(self.median_filter_clicked)
        filterLayout.addWidget(median_filter_button)

        ponderated_median_filter_button = QPushButton("Ponderated (3x3) median filter")
        ponderated_median_filter_button.clicked.connect(self.ponderated_median_filter_clicked)
        filterLayout.addWidget(ponderated_median_filter_button)

        gaussian_filter_button = QPushButton("Gaussian filter")
        gaussian_filter_button.clicked.connect(self.gaussian_filter_clicked)
        filterLayout.addWidget(gaussian_filter_button)

        highpass_filter_button = QPushButton("Highpass filter")
        highpass_filter_button.clicked.connect(self.highpass_filter_clicked)
        filterLayout.addWidget(highpass_filter_button)

        isotropic_filter_button = QPushButton("Isotropic diffusion")
        isotropic_filter_button.clicked.connect(self.isotropic_diffusion_method_clicked)
        filterLayout.addWidget(isotropic_filter_button)

        anisotropic_filter_button = QPushButton("Anisotropic diffusion")
        anisotropic_filter_button.clicked.connect(self.anisotropic_diffusion_method_clicked)
        filterLayout.addWidget(anisotropic_filter_button)

        bilateral_filter_button = QPushButton("Bilateral filter")
        bilateral_filter_button.clicked.connect(self.bilateral_filter_clicked)
        filterLayout.addWidget(bilateral_filter_button)

        # mainLayout.addLayout(filterLayout)
        filterTab.setLayout(filterLayout)
        self.tabLayout.addTab(filterTab, "Filters")

        # Border detection
        borderDetectionLayout = QHBoxLayout()

        borderDetectionLayout.addWidget(QPushButton("Prewitt", clicked=self.prewitt_border_detection_clicked))
        borderDetectionLayout.addWidget(QPushButton("Sobel", clicked=self.sobel_border_detection_clicked))
        borderDetectionLayout.addWidget(QPushButton("Laplacian", clicked=self.laplace_border_detection_clicked))
        borderDetectionLayout.addWidget(
            QPushButton("Laplacian (Threshold)", clicked=self.laplace_threshold_border_detection_clicked))
        borderDetectionLayout.addWidget(QPushButton("Laplacian of Gaussian", clicked=self.log_border_detection_clicked))
        borderDetectionLayout.addWidget(
            QPushButton("Generic directional operator", clicked=self.generic_derivatives_border_detection_clicked))
        borderDetectionLayout.addWidget(
            QPushButton("Canny", clicked=self.canny_border_detection_clicked))
        borderDetectionLayout.addWidget(
            QPushButton("Susan", clicked=self.susan_border_detection_clicked))
        borderDetectionLayout.addWidget(
            QPushButton("Hough transform (line detection)", clicked=self.hough_transform_line_clicked))
        borderDetectionLayout.addWidget(
            QPushButton("Hough transform (circle detection)", clicked=self.hough_transform_circunference_clicked))
        borderDetectionLayout.addWidget(
            QPushButton("Segmentation method (video)", clicked=self.selectMultipleFilesButton_clicked))
        borderDetectionLayout.addWidget(
            QPushButton("Harris corner detection", clicked=self.harris_corner_detection_clicked))

        borderDetectionTab.setLayout(borderDetectionLayout)
        self.tabLayout.addTab(borderDetectionTab, "Border detection")

        # Thresholding
        thresholdingDetectionLayout = QHBoxLayout()

        thresholdingDetectionLayout.addWidget(QPushButton("Global", clicked=self.global_thresholding))
        thresholdingDetectionLayout.addWidget(QPushButton("Otsu", clicked=self.otsu_thresholding))

        thresholdingTab.setLayout(thresholdingDetectionLayout)
        self.tabLayout.addTab(thresholdingTab, "Thresholding")

        objectDetectionLayout = QHBoxLayout()

        siftButton = QPushButton("SIFT")
        siftButton.clicked.connect(self.sift_clicked)
        objectDetectionLayout.addWidget(siftButton)

        surfButton = QPushButton("SURF")
        surfButton.clicked.connect(self.surf_clicked)
        objectDetectionLayout.addWidget(surfButton)

        kazeButton = QPushButton("KAZE")
        kazeButton.clicked.connect(self.kaze_clicked)
        objectDetectionLayout.addWidget(kazeButton)

        akazeButton = QPushButton("AKAZE")
        akazeButton.clicked.connect(self.akaze_clicked)
        objectDetectionLayout.addWidget(akazeButton)

        objectDetectionTab.setLayout(objectDetectionLayout)
        self.tabLayout.addTab(objectDetectionTab, "Object detection")

        # ALGORITHMS

        mainLayout.addWidget(self.tabLayout)

        self.setLayout(mainLayout)
        self.show()
コード例 #10
0
    def __init__(self, parent):
        super(InfoDialog, self).__init__(parent)
        self.setWindowModality(Qt.WindowModal)

        layout = QVBoxLayout()
        layout.setSpacing(10)
        self.setLayout(layout)

        self.tab = QTabWidget()
        tab_general = QWidget()
        tab_toolcommands = QWidget()
        self.tab.addTab(tab_general, "")
        self.tab.addTab(tab_toolcommands, "")

        # general tab
        vbox = QVBoxLayout()
        vbox.setSpacing(4)
        tab_general.setLayout(vbox)

        hbox = QHBoxLayout()
        self.lilyname = QLineEdit()
        self.lilynameLabel = l = QLabel()
        l.setBuddy(self.lilyname)
        hbox.addWidget(l)
        hbox.addWidget(self.lilyname)
        vbox.addLayout(hbox)

        self.lilypond = widgets.urlrequester.UrlRequester()
        self.lilypond.setFileMode(QFileDialog.ExistingFile)
        self.lilypondLabel = l = QLabel()
        l.setBuddy(self.lilypond)
        vbox.addWidget(l)
        vbox.addWidget(self.lilypond)

        self.auto = QCheckBox()
        vbox.addWidget(self.auto)
        vbox.addStretch(1)

        # toolcommands tab
        grid = QGridLayout()
        grid.setSpacing(4)
        tab_toolcommands.setLayout(grid)

        self.ly_tool_widgets = {}
        row = 0
        for name, gui in self.toolnames():
            w = QLineEdit()
            l = QLabel()
            l.setBuddy(w)
            grid.addWidget(l, row, 0)
            grid.addWidget(w, row, 1)
            row += 1
            self.ly_tool_widgets[name] = (l, w)

        layout.addWidget(self.tab)
        layout.addWidget(widgets.Separator())
        b = self.buttons = QDialogButtonBox(self)
        layout.addWidget(b)

        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        userguide.addButton(b, "prefs_lilypond")
        app.translateUI(self)
        qutil.saveDialogSize(self, "/preferences/lilypond/lilypondinfo/dialog/size")
コード例 #11
0
ファイル: rr_viz_tabs.py プロジェクト: Ross-Robotics/rr_viz
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.main_window_layout = QVBoxLayout(self)

        self.main_window_tabs = QTabWidget()
        self.rr_interactive_tools_tab = QWidget()

        self.main_window_tabs.addTab(self.rr_interactive_tools_tab,
                                     "Ross Robotics")

        self.rr_interactive_tools_tab.h_layout = QHBoxLayout(self)
        self.rr_interactive_tools_tab.v_layout1 = QVBoxLayout(self)
        self.rr_interactive_tools_tab.v_layout2 = QVBoxLayout(self)

        # Set up rviz screens
        self.rr_interactive_tools_tab.v_layout1.addWidget(RvizTabs(self))

        self.rr_interactive_tools_tab.v_layout1.addWidget(
            EnvironmentalSensingModule(self))

        # Set up status labels
        self.status_h_layout = QHBoxLayout()
        self.connection_label_text = QLabel('Connection status:')
        self.connection_label_text.setFont(QFont('Ubuntu', 14, QFont.Bold))
        self.connection_label_text.setAlignment(Qt.AlignRight
                                                | Qt.AlignVCenter)

        self.connection_status = QLabel('Connection lost')
        self.connection_status.setFont(QFont('Ubuntu', 14, QFont.Bold))
        self.connection_status.setStyleSheet("color: red")
        self.connection_status.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.battery_label = QLabel('Battery Level:')
        self.battery_label.setFont(QFont('Ubuntu', 14, QFont.Bold))
        self.battery_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.battery_level = QLabel('N/A')
        self.battery_level.setFont(QFont('Ubuntu', 14, QFont.Bold))
        self.battery_level.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.status_h_layout.addWidget(self.connection_label_text, 3)
        self.status_h_layout.addWidget(self.connection_status, 3)

        self.status_h_layout.addWidget(self.battery_label, 3)
        self.status_h_layout.addWidget(self.battery_level, 1)

        self.rr_interactive_tools_tab.v_layout2.addLayout(
            self.status_h_layout, 1)

        # Add rr interactive tools to layout
        self.rr_interactive_tools_tab.v_layout2.addWidget(
            RRInteractiveTools(self), 7)

        # Set up logo
        self.logo_label = QLabel(self)
        logo_path = file_management.get_rrviz_resdir() + "/logo.png"
        logo_pixmap = QPixmap(logo_path)
        logo_scaled = logo_pixmap.scaledToWidth(300)
        self.logo_label.setPixmap(logo_scaled)

        self.logo_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)

        self.rr_interactive_tools_tab.v_layout2.addWidget(self.logo_label, 2)

        # Add vertical layouts to the horizontal layout
        self.rr_interactive_tools_tab.h_layout.addLayout(
            self.rr_interactive_tools_tab.v_layout1, 7)
        self.rr_interactive_tools_tab.h_layout.addLayout(
            self.rr_interactive_tools_tab.v_layout2, 3)

        self.rr_interactive_tools_tab.setLayout(
            self.rr_interactive_tools_tab.h_layout)

        self.main_window_layout.addWidget(self.main_window_tabs)
        self.setLayout(self.main_window_layout)

        # Set up topic subscribers
        self.battery_level_sub_name = "/vesc_driver/battery"
        self.battery_level_sub = rospy.Subscriber(self.battery_level_sub_name,
                                                  BatteryState,
                                                  self.battery_level_update)

        # Get Battery levels
        self.good_voltage = rospy.get_param("/battery/good_voltage", "31")
        self.ok_voltage = rospy.get_param("/battery/ok_voltage", "26")
        self.low_voltage = rospy.get_param("/battery/low_voltage", "22")

        # Variables required to detect if connected to ROS MASTER
        self.ros_loss_triggered = True
        self.rosMasterIP = '192.168.10.100'
        self.subprocess_command = 'fping -nV -t 50 ' + self.rosMasterIP
        self.fp_status = "alive"

        # Set up timer
        self.timer_period = 1500
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.ros_is_up)
        self.timer.start(self.timer_period)
コード例 #12
0
ファイル: compute_thermo.py プロジェクト: pk-organics/SEQCROW
    def _build_ui(self):
        #each group has an empty widget at the bottom so they resize the way I want while also having the
        #labels where I want them
        layout = QGridLayout()

        self.tab_widget = QTabWidget()
        layout.addWidget(self.tab_widget)

        #layout for absolute thermo stuff
        absolute_widget = QWidget()
        absolute_layout = QGridLayout(absolute_widget)

        #box for sp
        sp_area_widget = QGroupBox("Single-point")
        sp_layout = QGridLayout(sp_area_widget)

        self.sp_selector = FilereaderComboBox(self.session,
                                              otherItems=['energy'])
        self.sp_selector.currentIndexChanged.connect(self.set_sp)
        sp_layout.addWidget(self.sp_selector, 0, 0, 1, 3, Qt.AlignTop)

        nrg_label = QLabel("E =")
        sp_layout.addWidget(nrg_label, 1, 0, 1, 1,
                            Qt.AlignRight | Qt.AlignVCenter)

        self.sp_nrg_line = QLineEdit()
        self.sp_nrg_line.setReadOnly(True)
        self.sp_nrg_line.setToolTip("electronic energy")
        sp_layout.addWidget(self.sp_nrg_line, 1, 1, 1, 1, Qt.AlignTop)

        sp_layout.addWidget(QLabel("E<sub>h</sub>"), 1, 2, 1, 1,
                            Qt.AlignVCenter)

        sp_layout.addWidget(QWidget(), 2, 0)

        sp_layout.setColumnStretch(0, 0)
        sp_layout.setColumnStretch(1, 1)
        sp_layout.setRowStretch(0, 0)
        sp_layout.setRowStretch(1, 0)
        sp_layout.setRowStretch(2, 1)

        row = 0
        #box for thermo
        therm_area_widget = QGroupBox("Thermal corrections")
        thermo_layout = QGridLayout(therm_area_widget)

        self.thermo_selector = FilereaderComboBox(self.session,
                                                  otherItems=['frequency'])
        self.thermo_selector.currentIndexChanged.connect(self.set_thermo_mdl)
        thermo_layout.addWidget(self.thermo_selector, row, 0, 1, 3,
                                Qt.AlignTop)

        row += 1

        thermo_layout.addWidget(QLabel("T ="), row, 0, 1, 1,
                                Qt.AlignRight | Qt.AlignVCenter)

        self.temperature_line = QDoubleSpinBox()
        self.temperature_line.setMaximum(2**31 - 1)
        self.temperature_line.setValue(298.15)
        self.temperature_line.setSingleStep(10)
        self.temperature_line.setSuffix(" K")
        self.temperature_line.setMinimum(0)
        self.temperature_line.valueChanged.connect(self.set_thermo)
        thermo_layout.addWidget(self.temperature_line, row, 1, 1, 2,
                                Qt.AlignTop)

        row += 1

        thermo_layout.addWidget(QLabel("𝜔<sub>0</sub> ="), row, 0, 1, 1,
                                Qt.AlignRight | Qt.AlignVCenter)

        self.v0_edit = QDoubleSpinBox()
        self.v0_edit.setMaximum(4000)
        self.v0_edit.setValue(self.settings.w0)
        self.v0_edit.setSingleStep(25)
        self.v0_edit.setSuffix(" cm\u207b\u00b9")
        self.v0_edit.valueChanged.connect(self.set_thermo)
        self.v0_edit.setMinimum(0)
        self.v0_edit.setToolTip(
            "frequency parameter for quasi treatments of entropy")
        thermo_layout.addWidget(self.v0_edit, row, 1, 1, 2, Qt.AlignTop)

        row += 1

        thermo_layout.addWidget(QLabel("𝛿ZPE ="), row, 0, 1, 1,
                                Qt.AlignRight | Qt.AlignVCenter)

        self.zpe_line = QLineEdit()
        self.zpe_line.setReadOnly(True)
        self.zpe_line.setToolTip("zero-point energy correction")
        thermo_layout.addWidget(self.zpe_line, row, 1, 1, 1, Qt.AlignTop)

        thermo_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                                Qt.AlignVCenter)

        row += 1

        thermo_layout.addWidget(QLabel("𝛿H<sub>RRHO</sub> ="), row, 0, 1, 1,
                                Qt.AlignRight | Qt.AlignVCenter)

        self.enthalpy_line = QLineEdit()
        self.enthalpy_line.setReadOnly(True)
        self.enthalpy_line.setToolTip("RRHO enthalpy correction")
        thermo_layout.addWidget(self.enthalpy_line, row, 1, 1, 1, Qt.AlignTop)

        thermo_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                                Qt.AlignVCenter)

        row += 1

        thermo_layout.addWidget(QLabel("𝛿G<sub>RRHO</sub> ="), row, 0, 1, 1,
                                Qt.AlignRight | Qt.AlignVCenter)

        self.rrho_g_line = QLineEdit()
        self.rrho_g_line.setReadOnly(True)
        self.rrho_g_line.setToolTip(
            """RRHO free energy correction\nRotational motion is completely independent from vibrations\nNormal mode vibrations behave like harmonic oscillators"""
        )
        thermo_layout.addWidget(self.rrho_g_line, row, 1, 1, 1, Qt.AlignTop)

        thermo_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                                Qt.AlignVCenter)

        row += 1

        dqrrho_g_label = QLabel()
        dqrrho_g_label.setText(
            "<a href=\"Grimme's Quasi-RRHO\" style=\"text-decoration: none;\">𝛿G<sub>Quasi-RRHO</sub></a> ="
        )
        dqrrho_g_label.setTextFormat(Qt.RichText)
        dqrrho_g_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
        dqrrho_g_label.linkActivated.connect(self.open_link)
        dqrrho_g_label.setToolTip("click to open a relevant reference\n" + \
                                  "see the \"Computation of internal (gas‐phase) entropies\" section for a description of the method")

        thermo_layout.addWidget(dqrrho_g_label, row, 0, 1, 1,
                                Qt.AlignRight | Qt.AlignVCenter)

        self.qrrho_g_line = QLineEdit()
        self.qrrho_g_line.setReadOnly(True)
        self.qrrho_g_line.setToolTip("Quasi-RRHO free energy correction\n" + \
        "Vibrational entropy of each mode is weighted and complemented with rotational entropy\n" + \
        "The weighting is much lower for modes with frequencies less than 𝜔\u2080")
        thermo_layout.addWidget(self.qrrho_g_line, row, 1, 1, 1, Qt.AlignTop)

        thermo_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                                Qt.AlignVCenter)

        row += 1

        dqharm_g_label = QLabel("")
        dqharm_g_label.setText(
            "<a href=\"Truhlar's Quasi-Harmonic\" style=\"text-decoration: none;\">𝛿G<sub>Quasi-Harmonic</sub></a> ="
        )
        dqharm_g_label.setTextFormat(Qt.RichText)
        dqharm_g_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
        dqharm_g_label.linkActivated.connect(self.open_link)
        dqharm_g_label.setToolTip("click to open a relevant reference\n" + \
                                  "see the \"Computations\" section for a description of the method")

        thermo_layout.addWidget(dqharm_g_label, row, 0, 1, 1,
                                Qt.AlignRight | Qt.AlignVCenter)

        self.qharm_g_line = QLineEdit()
        self.qharm_g_line.setReadOnly(True)
        self.qharm_g_line.setToolTip("Quasi-hamonic free energy correction\n" + \
        "For entropy, real vibrational modes lower than 𝜔\u2080 are treated as 𝜔\u2080")
        thermo_layout.addWidget(self.qharm_g_line, row, 1, 1, 1, Qt.AlignTop)

        thermo_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                                Qt.AlignVCenter)

        thermo_layout.addWidget(QWidget(), row + 1, 0)

        thermo_layout.setColumnStretch(0, 0)
        thermo_layout.setColumnStretch(1, 1)
        for i in range(0, row):
            thermo_layout.setRowStretch(i, 0)

        thermo_layout.setRowStretch(row + 1, 1)

        row = 0
        # for for total
        sum_area_widget = QGroupBox("Thermochemistry")
        sum_layout = QGridLayout(sum_area_widget)

        sum_layout.addWidget(QLabel("ZPE ="), row, 0, 1, 1,
                             Qt.AlignRight | Qt.AlignVCenter)

        self.zpe_sum_line = QLineEdit()
        self.zpe_sum_line.setReadOnly(True)
        self.zpe_sum_line.setToolTip(
            "sum of electronic energy and ZPE correction")
        sum_layout.addWidget(self.zpe_sum_line, row, 1, 1, 1, Qt.AlignTop)

        sum_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                             Qt.AlignVCenter)

        row += 1

        sum_layout.addWidget(QLabel("H<sub>RRHO</sub> ="), row, 0, 1, 1,
                             Qt.AlignRight | Qt.AlignVCenter)

        self.h_sum_line = QLineEdit()
        self.h_sum_line.setReadOnly(True)
        self.h_sum_line.setToolTip(
            "sum of electronic energy and RRHO enthalpy correction")
        sum_layout.addWidget(self.h_sum_line, row, 1, 1, 1, Qt.AlignTop)

        sum_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                             Qt.AlignVCenter)

        row += 1

        sum_layout.addWidget(QLabel("G<sub>RRHO</sub> ="), row, 0, 1, 1,
                             Qt.AlignRight | Qt.AlignVCenter)

        self.rrho_g_sum_line = QLineEdit()
        self.rrho_g_sum_line.setReadOnly(True)
        self.rrho_g_sum_line.setToolTip(
            "sum of electronic energy and RRHO free energy correction\nRotational motion is completely independent from vibrations\nNormal mode vibrations behave like harmonic oscillators"
        )
        sum_layout.addWidget(self.rrho_g_sum_line, row, 1, 1, 1, Qt.AlignTop)

        sum_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                             Qt.AlignVCenter)

        row += 1

        sum_layout.addWidget(QLabel("G<sub>Quasi-RRHO</sub> ="), row, 0, 1, 1,
                             Qt.AlignRight | Qt.AlignVCenter)

        self.qrrho_g_sum_line = QLineEdit()
        self.qrrho_g_sum_line.setReadOnly(True)
        self.qrrho_g_sum_line.setToolTip("Sum of electronic energy and quasi-RRHO free energy correction\n" + \
        "Vibrational entropy of each mode is weighted and complemented with rotational entropy\n" + \
        "The weighting is much lower for modes with frequencies less than 𝜔\u2080")
        sum_layout.addWidget(self.qrrho_g_sum_line, row, 1, 1, 1, Qt.AlignTop)

        sum_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                             Qt.AlignVCenter)

        row += 1

        sum_layout.addWidget(QLabel("G<sub>Quasi-Harmonic</sub> ="), row, 0, 1,
                             1, Qt.AlignRight | Qt.AlignVCenter)

        self.qharm_g_sum_line = QLineEdit()
        self.qharm_g_sum_line.setReadOnly(True)
        self.qharm_g_sum_line.setToolTip("Sum of electronic energy and quasi-harmonic free energy correction\n" + \
        "For entropy, real vibrational modes lower than 𝜔\u2080 are treated as 𝜔\u2080")
        sum_layout.addWidget(self.qharm_g_sum_line, row, 1, 1, 1, Qt.AlignTop)

        sum_layout.addWidget(QLabel("E<sub>h</sub>"), row, 2, 1, 1,
                             Qt.AlignVCenter)

        sum_layout.addWidget(QWidget(), row + 1, 0)

        sum_layout.setColumnStretch(0, 0)
        for i in range(0, row):
            sum_layout.setRowStretch(i, 0)

        sum_layout.setRowStretch(row + 1, 1)

        splitter = QSplitter(Qt.Horizontal)
        splitter.setChildrenCollapsible(False)
        splitter.addWidget(sp_area_widget)
        splitter.addWidget(therm_area_widget)
        splitter.addWidget(sum_area_widget)

        absolute_layout.addWidget(splitter)

        self.status = QStatusBar()
        self.status.setSizeGripEnabled(False)
        self.status.setStyleSheet("color: red")
        absolute_layout.addWidget(self.status, 1, 0, 1, 1, Qt.AlignTop)

        self.tab_widget.addTab(absolute_widget, "absolute")

        relative_widget = QWidget()
        relative_layout = QGridLayout(relative_widget)

        size = [self.settings.ref_col_1, self.settings.ref_col_2]
        self.ref_group = ThermoGroup("reference group", self.session,
                                     self.nrg_fr, self.thermo_co, size)
        self.ref_group.changes.connect(self.calc_relative_thermo)
        relative_layout.addWidget(self.ref_group, 0, 0, 1, 3, Qt.AlignTop)

        size = [self.settings.other_col_1, self.settings.other_col_2]
        self.other_group = ThermoGroup("other group", self.session,
                                       self.nrg_fr, self.thermo_co, size)
        self.other_group.changes.connect(self.calc_relative_thermo)
        relative_layout.addWidget(self.other_group, 0, 3, 1, 3, Qt.AlignTop)

        self.relative_temperature = QDoubleSpinBox()
        self.relative_temperature.setMaximum(2**31 - 1)
        self.relative_temperature.setValue(self.settings.rel_temp)
        self.relative_temperature.setSingleStep(10)
        self.relative_temperature.setSuffix(" K")
        self.relative_temperature.setMinimum(0)
        self.relative_temperature.valueChanged.connect(
            self.calc_relative_thermo)
        relative_layout.addWidget(QLabel("T ="), 1, 0, 1, 1,
                                  Qt.AlignRight | Qt.AlignVCenter)
        relative_layout.addWidget(self.relative_temperature, 1, 1, 1, 5,
                                  Qt.AlignLeft | Qt.AlignVCenter)

        self.relative_v0 = QDoubleSpinBox()
        self.relative_v0.setMaximum(2**31 - 1)
        self.relative_v0.setValue(self.settings.w0)
        self.relative_v0.setSingleStep(25)
        self.relative_v0.setSuffix(" cm\u207b\u00b9")
        self.relative_v0.setMinimum(0)
        self.relative_v0.setToolTip(
            "frequency parameter for quasi treatments of entropy")
        self.relative_v0.valueChanged.connect(self.calc_relative_thermo)
        relative_layout.addWidget(QLabel("𝜔<sub>0</sub> ="), 2, 0, 1, 1,
                                  Qt.AlignRight | Qt.AlignVCenter)
        relative_layout.addWidget(self.relative_v0, 2, 1, 1, 5,
                                  Qt.AlignLeft | Qt.AlignVCenter)

        relative_layout.addWidget(
            QLabel("Boltzmann-weighted relative energies in kcal/mol:"), 3, 0,
            1, 6, Qt.AlignVCenter | Qt.AlignLeft)

        relative_layout.addWidget(QLabel("ΔE"), 4, 0,
                                  Qt.AlignTop | Qt.AlignVCenter)
        self.relative_dE = QLineEdit()
        self.relative_dE.setReadOnly(True)
        relative_layout.addWidget(self.relative_dE, 5, 0,
                                  Qt.AlignTop | Qt.AlignVCenter)

        relative_layout.addWidget(QLabel("ΔZPE"), 4, 1,
                                  Qt.AlignTop | Qt.AlignVCenter)
        self.relative_dZPVE = QLineEdit()
        self.relative_dZPVE.setReadOnly(True)
        relative_layout.addWidget(self.relative_dZPVE, 5, 1,
                                  Qt.AlignTop | Qt.AlignVCenter)

        relative_layout.addWidget(QLabel("ΔH<sub>RRHO</sub>"), 4, 2,
                                  Qt.AlignTop | Qt.AlignVCenter)
        self.relative_dH = QLineEdit()
        self.relative_dH.setReadOnly(True)
        relative_layout.addWidget(self.relative_dH, 5, 2,
                                  Qt.AlignTop | Qt.AlignVCenter)

        relative_layout.addWidget(QLabel("ΔG<sub>RRHO</sub>"), 4, 3,
                                  Qt.AlignTop | Qt.AlignVCenter)
        self.relative_dG = QLineEdit()
        self.relative_dG.setReadOnly(True)
        relative_layout.addWidget(self.relative_dG, 5, 3,
                                  Qt.AlignTop | Qt.AlignVCenter)

        relative_layout.addWidget(QLabel("ΔG<sub>Quasi-RRHO</sub>"), 4, 4,
                                  Qt.AlignTop | Qt.AlignVCenter)
        self.relative_dQRRHOG = QLineEdit()
        self.relative_dQRRHOG.setReadOnly(True)
        relative_layout.addWidget(self.relative_dQRRHOG, 5, 4,
                                  Qt.AlignTop | Qt.AlignVCenter)

        relative_layout.addWidget(QLabel("ΔG<sub>Quasi-Harmonic</sub>"), 4, 5,
                                  Qt.AlignTop | Qt.AlignVCenter)
        self.relative_dQHARMG = QLineEdit()
        self.relative_dQHARMG.setReadOnly(True)
        relative_layout.addWidget(self.relative_dQHARMG, 5, 5,
                                  Qt.AlignTop | Qt.AlignVCenter)

        relative_layout.setRowStretch(0, 1)
        relative_layout.setRowStretch(1, 0)
        relative_layout.setRowStretch(2, 0)
        relative_layout.setRowStretch(3, 0)
        relative_layout.setRowStretch(4, 0)
        relative_layout.setRowStretch(5, 0)

        self.tab_widget.addTab(relative_widget, "relative")

        #menu stuff
        menu = QMenuBar()

        export = menu.addMenu("&Export")
        copy = QAction("&Copy CSV to clipboard", self.tool_window.ui_area)
        copy.triggered.connect(self.copy_csv)
        shortcut = QKeySequence(Qt.CTRL + Qt.Key_C)
        copy.setShortcut(shortcut)
        export.addAction(copy)
        self.copy = copy

        save = QAction("&Save CSV...", self.tool_window.ui_area)
        save.triggered.connect(self.save_csv)
        #this shortcut interferes with main window's save shortcut
        #I've tried different shortcut contexts to no avail
        #thanks Qt...
        #shortcut = QKeySequence(Qt.CTRL + Qt.Key_S)
        #save.setShortcut(shortcut)
        #save.setShortcutContext(Qt.WidgetShortcut)
        export.addAction(save)

        delimiter = export.addMenu("Delimiter")

        comma = QAction("comma", self.tool_window.ui_area, checkable=True)
        comma.setChecked(self.settings.delimiter == "comma")
        comma.triggered.connect(lambda *args, delim="comma": self.settings.
                                __setattr__("delimiter", delim))
        delimiter.addAction(comma)

        tab = QAction("tab", self.tool_window.ui_area, checkable=True)
        tab.setChecked(self.settings.delimiter == "tab")
        tab.triggered.connect(lambda *args, delim="tab": self.settings.
                              __setattr__("delimiter", delim))
        delimiter.addAction(tab)

        space = QAction("space", self.tool_window.ui_area, checkable=True)
        space.setChecked(self.settings.delimiter == "space")
        space.triggered.connect(lambda *args, delim="space": self.settings.
                                __setattr__("delimiter", delim))
        delimiter.addAction(space)

        semicolon = QAction("semicolon",
                            self.tool_window.ui_area,
                            checkable=True)
        semicolon.setChecked(self.settings.delimiter == "semicolon")
        semicolon.triggered.connect(lambda *args, delim="semicolon": self.
                                    settings.__setattr__("delimiter", delim))
        delimiter.addAction(semicolon)

        add_header = QAction("&Include CSV header",
                             self.tool_window.ui_area,
                             checkable=True)
        add_header.setChecked(self.settings.include_header)
        add_header.triggered.connect(self.header_check)
        export.addAction(add_header)

        comma.triggered.connect(
            lambda *args, action=tab: action.setChecked(False))
        comma.triggered.connect(
            lambda *args, action=space: action.setChecked(False))
        comma.triggered.connect(
            lambda *args, action=semicolon: action.setChecked(False))

        tab.triggered.connect(
            lambda *args, action=comma: action.setChecked(False))
        tab.triggered.connect(
            lambda *args, action=space: action.setChecked(False))
        tab.triggered.connect(
            lambda *args, action=semicolon: action.setChecked(False))

        space.triggered.connect(
            lambda *args, action=comma: action.setChecked(False))
        space.triggered.connect(
            lambda *args, action=tab: action.setChecked(False))
        space.triggered.connect(
            lambda *args, action=semicolon: action.setChecked(False))

        semicolon.triggered.connect(
            lambda *args, action=comma: action.setChecked(False))
        semicolon.triggered.connect(
            lambda *args, action=tab: action.setChecked(False))
        semicolon.triggered.connect(
            lambda *args, action=space: action.setChecked(False))

        menu.setNativeMenuBar(False)
        self._menu = menu
        layout.setMenuBar(menu)

        self.tool_window.ui_area.setLayout(layout)

        self.tool_window.manage(None)
コード例 #13
0
ファイル: preferences.py プロジェクト: gitter-badger/eddy
    def __init__(self, mainwindow):
        """
        Initialize the Preferences dialog.
        :type mainwindow: QMainWindow
        """
        super().__init__(mainwindow)

        self.mainwindow = mainwindow

        ################################################################################################################
        #                                                                                                              #
        #   EDITOR TAB                                                                                                 #
        #                                                                                                              #
        ################################################################################################################

        self.diagramSizeF = SpinBox(self)
        self.diagramSizeF.setRange(2000, 1000000)
        self.diagramSizeF.setSingleStep(100)
        self.diagramSizeF.setValue(self.mainwindow.diagramSize)

        self.editorWidget = QWidget()
        self.editorLayout = QFormLayout(self.editorWidget)
        self.editorLayout.addRow('Diagram size', self.diagramSizeF)

        ################################################################################################################
        #                                                                                                              #
        #   MAIN WIDGET                                                                                                #
        #                                                                                                              #
        ################################################################################################################

        self.mainWidget = QTabWidget(self)
        self.mainWidget.addTab(self.editorWidget, 'Editor')

        ################################################################################################################
        #                                                                                                              #
        #   BUTTON BOX                                                                                                 #
        #                                                                                                              #
        ################################################################################################################

        self.buttonBox = QDialogButtonBox(
            QDialogButtonBox.Save | QDialogButtonBox.Close, Qt.Horizontal,
            self)

        ################################################################################################################
        #                                                                                                              #
        #   MAIN LAYOUT                                                                                                #
        #                                                                                                              #
        ################################################################################################################

        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.addWidget(self.mainWidget)
        self.mainLayout.addWidget(self.buttonBox, 0, Qt.AlignRight)

        self.setFixedSize(self.sizeHint())
        self.setWindowTitle('Preferences')

        ################################################################################################################
        #                                                                                                              #
        #   CONFIGURE SIGNALS                                                                                          #
        #                                                                                                              #
        ################################################################################################################

        connect(self.buttonBox.accepted, self.accept)
        connect(self.buttonBox.rejected, self.reject)
        connect(self.finished, self.completed)
コード例 #14
0
 def __init__(self, parent=None):
     super(TabDialog, self).__init__(parent)
     self.infos = []
     self.tabWidget = QTabWidget()
     self.tabWidget.setFixedSize(700, 500)
コード例 #15
0
ファイル: mainwindow.py プロジェクト: minlexx/pyevemon
 def init_layout(self):
     # tab container
     self.tabwidget = QTabWidget(self)
     self.setCentralWidget(self.tabwidget)
コード例 #16
0
    def __init__(self, parent: 'ElectrumWindow', config: 'SimpleConfig'):
        WindowModalDialog.__init__(self, parent, _('Preferences'))
        self.config = config
        self.window = parent
        self.need_restart = False
        self.fx = self.window.fx
        self.wallet = self.window.wallet

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # lightning
        lightning_widgets = []

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

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

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

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

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

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

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

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

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

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

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

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

        self.check_ssl_config()

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

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

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

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

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

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

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

        # units
        units = base_units_list
        msg = (
            _('Base unit of your wallet.') +
            '\n1 NMC = 1000 mNMC. 1 mNMC = 1000 uNMC. 1 uNMC = 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.window.decimal_point = base_unit_name_to_decimal_point(
                unit_result)
            self.config.set_key('decimal_point', self.window.decimal_point,
                                True)
            nz.setMaximum(self.window.decimal_point)
            self.window.history_list.update()
            self.window.request_list.update()
            self.window.address_list.update()
            for edit, amount in zip(edits, amounts):
                edit.setAmount(amount)
            self.window.update_status()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        def on_usechange(x):
            usechange_result = x == Qt.Checked
            if self.window.wallet.use_change != usechange_result:
                self.window.wallet.use_change = usechange_result
                self.window.wallet.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', False))
        outrounding_cb = QCheckBox(_('Enable output value rounding'))
        outrounding_cb.setToolTip(
            _('Set the value of the change output so that it has similar precision to the other outputs.'
              ) + '\n' + _('This might improve your privacy somewhat.') +
            '\n' +
            _('If enabled, at most 100 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')),
            (fee_widgets, _('Fees')),
            (tx_widgets, _('Transactions')),
            (lightning_widgets, _('Lightning')),
            (fiat_widgets, _('Fiat')),
            (services_widgets, _('Services')),
            (oa_widgets, _('OpenAlias')),
        ]
        for widgets, name in tabs_info:
            tab = QWidget()
            tab_vbox = QVBoxLayout(tab)
            grid = QGridLayout()
            for a, b in widgets:
                i = grid.rowCount()
                if b:
                    if a:
                        grid.addWidget(a, i, 0)
                    grid.addWidget(b, i, 1)
                else:
                    grid.addWidget(a, i, 0, 1, 2)
            tab_vbox.addLayout(grid)
            tab_vbox.addStretch(1)
            tabs.addTab(tab, name)

        vbox.addWidget(tabs)
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CloseButton(self)))
        self.setLayout(vbox)
コード例 #17
0
ファイル: about.py プロジェクト: winstc/linux-show-player
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setWindowTitle(translate('About', 'About Linux Show Player'))
        self.setMaximumSize(500, 420)
        self.setMinimumSize(500, 420)
        self.resize(500, 420)

        self.setLayout(QGridLayout())

        self.iconLabel = QLabel(self)
        self.iconLabel.setPixmap(
            QIcon.fromTheme('linux-show-player').pixmap(100, 100))
        self.layout().addWidget(self.iconLabel, 0, 0)

        self.shortInfo = QLabel(self)
        self.shortInfo.setAlignment(Qt.AlignCenter)
        self.shortInfo.setText('<h2>Linux Show Player   {0}</h2>'
                               'Copyright © Francesco Ceruti'.format(
                                   str(lisp.__version__)))
        self.layout().addWidget(self.shortInfo, 0, 1)

        self.layout().addWidget(QWidget(), 1, 0, 1, 2)

        # Information tabs
        self.tabWidget = QTabWidget(self)
        self.layout().addWidget(self.tabWidget, 2, 0, 1, 2)

        self.info = QTextBrowser(self)
        self.info.setOpenExternalLinks(True)
        self.info.setHtml('''
            <center><br />{0}<br /><br />
            <a href="{1}">{2}</a><br />
            <a href="{3}">{4}</a><br />
            <a href="{5}">{6}</a><br /><center>'''.format(
            translate('AboutDialog', self.DESCRIPTION), self.WEB_SITE,
            translate('AboutDialog', 'Web site'), self.USER_GROUP,
            translate('AboutDialog', 'Users  group'), self.SOURCE_CODE,
            translate('AboutDialog', 'Source code')))
        self.tabWidget.addTab(self.info, translate('AboutDialog', 'Info'))

        self.license = QTextBrowser(self)
        self.license.setOpenExternalLinks(True)
        self.license.setHtml(self.LICENSE)
        self.tabWidget.addTab(self.license, translate('AboutDialog',
                                                      'License'))

        self.contributors = QTextBrowser(self)
        self.contributors.setOpenExternalLinks(True)

        self.contributors.setHtml(self.__contributors())
        self.tabWidget.addTab(self.contributors,
                              translate('AboutDialog', 'Contributors'))

        # Ok button
        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok)
        self.buttons.accepted.connect(self.accept)
        self.layout().addWidget(self.buttons, 3, 1)

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

        self.layout().setRowStretch(0, 6)
        self.layout().setRowStretch(1, 1)
        self.layout().setRowStretch(2, 16)
        self.layout().setRowStretch(3, 3)

        self.buttons.setFocus()
コード例 #18
0
    def __init__(self, parent, protx_hash=None, alias=None):
        '''
        Show information about registred Masternodes with given prot_hash,
        or Masternodes in manager with given alias.
        '''
        super(Dip3MNInfoDialog, self).__init__(parent)
        self.setMinimumSize(950, 450)
        self.setWindowIcon(read_QIcon('electrum-axe.png'))

        self.parent = parent
        self.gui = parent.gui
        self.manager = parent.manager
        self.mn_list = parent.mn_list
        self.diff_updated.connect(self.on_diff_updated)
        self.info_updated.connect(self.on_info_updated)

        if alias:
            self.mn = self.manager.mns.get(alias)
        else:
            self.mn = None

        if self.mn:
            self.protx_hash = self.mn.protx_hash
            self.setWindowTitle(_('%s Dip3 Masternode Info') % alias)
        elif protx_hash:
            self.protx_hash = protx_hash
            self.setWindowTitle(
                _('%s... Dip3 Masternode Info') % protx_hash[:32])

        if self.mn_list and self.protx_hash:
            mn_list = self.mn_list
            sml_entry = mn_list.protx_mns.get(self.protx_hash, {})
            self.diff_info = sml_entry.as_dict() if sml_entry else {}
            self.mn_list.register_callback(self.on_mn_list_diff_updated,
                                           ['mn-list-diff-updated'])
            self.mn_list.register_callback(self.on_mn_list_info_updated,
                                           ['mn-list-info-updated'])
            self.info = mn_list.protx_info.get(self.protx_hash, {})
            if not self.info and self.gui.network.is_connected():
                self.gui.network.run_from_another_thread(
                    self.gui.network.request_protx_info(self.protx_hash))
        else:
            self.diff_info = {}
            self.info = {}

        layout = QGridLayout()
        self.setLayout(layout)
        self.tabs = QTabWidget(self)
        self.close_btn = b = QPushButton(_('Close'))
        b.setDefault(True)
        b.clicked.connect(self.close)
        layout.addWidget(self.tabs, 0, 0, 1, -1)
        layout.setColumnStretch(0, 1)
        layout.addWidget(b, 1, 1)

        if self.mn:
            self.mn_tab = QWidget()
            self.mn_label = QLabel(_('Wallet Masternode: %s') % self.mn.alias)
            self.mn_view = QTextEdit()
            self.mn_view.setReadOnly(True)
            self.mn_view.setText(pformat(self.mn.as_dict()))
            mn_vbox = QVBoxLayout()
            mn_vbox.addWidget(self.mn_label)
            mn_vbox.addWidget(self.mn_view)
            self.mn_tab.setLayout(mn_vbox)
            self.tabs.addTab(self.mn_tab, _('Wallet'))
        if self.protx_hash:
            self.diff_info_tab = QWidget()
            self.diff_info_view = QTextEdit()
            self.diff_info_view.setReadOnly(True)
            self.diff_info_view.setText(pformat(self.diff_info))
            diff_info_vbox = QVBoxLayout()
            diff_info_vbox.addWidget(self.diff_info_view)
            self.diff_info_tab.setLayout(diff_info_vbox)
            self.tabs.addTab(self.diff_info_tab,
                             _('protx.diff data (merkle '
                               'root verified)'))

            self.info_tab = QWidget()
            self.info_view = QTextEdit()
            self.info_view.setReadOnly(True)
            self.info_view.setText(pformat(self.info))
            info_vbox = QVBoxLayout()
            info_vbox.addWidget(self.info_view)
            self.info_tab.setLayout(info_vbox)
            self.tabs.addTab(self.info_tab, _('protx.info data (unverified)'))
コード例 #19
0
    def setupUi(self, MainWindow):
        resolution = QDesktopWidget().screenGeometry(self)
        # MainWindow.setGeometry(QRect(0,0,0,0))
        MainWindow.setFixedSize(resolution.size().width()*0.99, resolution.size().height()*0.90)#1200 800
        # self.setWindowState(Qt.WindowMaximized)
        print("resol : ", MainWindow.size())

        #메인 화면 색상py
        self.setStyleSheet("color: black;"
                        "background-color: white;")

        font = QFont()
        font.setFamily("NanumGothic")
        MainWindow.setFont(font)
        self.centralwidget = QWidget(MainWindow)
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(20, 20, 130, 35))
        font = QFont()
        font.setFamily("NanumGothic")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.button_add = QPushButton(self.centralwidget)
        self.button_add.setGeometry(QRect(MainWindow.size().width()*0.05, MainWindow.size().height() - 80, 131, 34))
        #버튼 스타일 변경
        self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_add.setFont(staticValues.buttonFont)

        self.button_modi = QPushButton(self.centralwidget)
        self.button_modi.setGeometry(QRect(MainWindow.size().width()*0.20, MainWindow.size().height() - 80, 131, 34))
        self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_modi.setFont(staticValues.buttonFont)

        self.button_del = QPushButton(self.centralwidget)
        self.button_del.setGeometry(QRect(MainWindow.size().width()*0.35, MainWindow.size().height() - 80, 131, 34))
        self.button_del.setStyleSheet(staticValues.redButtonStyleSheet)
        self.button_del.setFont(staticValues.buttonFont)

        self.button_upload = QPushButton(self.centralwidget)
        self.button_upload.setGeometry(QRect(MainWindow.size().width()*0.7, MainWindow.size().height() - 80, 131, 34))
        self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_upload.setFont(staticValues.buttonFont)

        self.tabWidget = QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QRect(10, 70, MainWindow.size().width()-15, MainWindow.size().height() - 180))
        self.tab = QWidget()
        self.tab.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab, "회원 목록")
        self.tableWidget = QTableWidget(self.tab)
        self.tableWidget.setGeometry(QRect(0, 0, self.tabWidget.size().width()-5, self.tabWidget.size().height()-25))
        self.tableWidget.setColumnCount(13)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근"
        , "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소"])

        self.tab2 = QWidget()
        self.tab2.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab2, "중복 회원")

        self.label_updateDate = QLabel(self.tab2)
        self.label_updateDate.setGeometry(QRect(20, 0, 250, 35))
        self.label_updateDate.setStyleSheet(""staticValues.disabledStyleSheet"")

        self.tableWidget2 = QTableWidget(self.tab2)
        self.tableWidget2.setGeometry(QRect(0, 30, self.tabWidget.size().width()-5, self.tabWidget.size().height()-55))
        self.tableWidget2.setColumnCount(3)
        self.tableWidget2.setRowCount(0)
        self.tableWidget2.setSelectionBehavior(QAbstractItemView.SelectRows)
        
        self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "현재 단톡방", "중복 단톡방"])
        
        
        self.edit_search = QLineEdit(self.centralwidget)
        self.edit_search.setGeometry(QRect(MainWindow.size().width()-280, 35, 200, 30))
        self.edit_search.setStyleSheet(staticValues.solidStyleSheet)
        

        self.button_search = QPushButton(self.centralwidget)
        self.button_search.setGeometry(QRect(MainWindow.size().width()-80, 35, 70, 30))
        self.button_search.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_search.setFont(staticValues.buttonFont)

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(MainWindow)
コード例 #20
0
    def __init__(self):
        QMainWindow.__init__(self)

        logger.debug("Initialising GUI ...")
        self.setObjectName("GuiMain")
        self.mainConf = nw.CONFIG
        self.threadPool = QThreadPool()

        # System Info
        # ===========

        logger.info("OS: %s" % self.mainConf.osType)
        logger.info("Kernel: %s" % self.mainConf.kernelVer)
        logger.info("Host: %s" % self.mainConf.hostName)
        logger.info("Qt5 Version: %s (%d)" %
                    (self.mainConf.verQtString, self.mainConf.verQtValue))
        logger.info("PyQt5 Version: %s (%d)" %
                    (self.mainConf.verPyQtString, self.mainConf.verPyQtValue))
        logger.info("Python Version: %s (0x%x)" %
                    (self.mainConf.verPyString, self.mainConf.verPyHexVal))

        # Core Classes
        # ============

        # Core Classes and settings
        self.theTheme = GuiTheme(self)
        self.theProject = NWProject(self)
        self.theIndex = NWIndex(self.theProject, self)
        self.hasProject = False
        self.isFocusMode = False

        # Prepare main window
        self.resize(*self.mainConf.getWinSize())
        self._setWindowTitle()
        self.setWindowIcon(QIcon(self.mainConf.appIcon))

        # Build the GUI
        # =============

        # Main GUI Elements
        self.statusBar = GuiMainStatus(self)
        self.treeView = GuiProjectTree(self)
        self.docEditor = GuiDocEditor(self)
        self.viewMeta = GuiDocViewDetails(self)
        self.docViewer = GuiDocViewer(self)
        self.treeMeta = GuiItemDetails(self)
        self.projView = GuiOutline(self)
        self.projMeta = GuiOutlineDetails(self)
        self.mainMenu = GuiMainMenu(self)

        # Minor Gui Elements
        self.statusIcons = []
        self.importIcons = []

        # Project Tree View
        self.treePane = QWidget()
        self.treeBox = QVBoxLayout()
        self.treeBox.setContentsMargins(0, 0, 0, 0)
        self.treeBox.addWidget(self.treeView)
        self.treeBox.addWidget(self.treeMeta)
        self.treePane.setLayout(self.treeBox)

        # Splitter : Document Viewer / Document Meta
        self.splitView = QSplitter(Qt.Vertical)
        self.splitView.addWidget(self.docViewer)
        self.splitView.addWidget(self.viewMeta)
        self.splitView.setSizes(self.mainConf.getViewPanePos())

        # Splitter : Document Editor / Document Viewer
        self.splitDocs = QSplitter(Qt.Horizontal)
        self.splitDocs.addWidget(self.docEditor)
        self.splitDocs.addWidget(self.splitView)

        # Splitter : Project Outlie / Outline Details
        self.splitOutline = QSplitter(Qt.Vertical)
        self.splitOutline.addWidget(self.projView)
        self.splitOutline.addWidget(self.projMeta)
        self.splitOutline.setSizes(self.mainConf.getOutlinePanePos())

        # Main Tabs : Edirot / Outline
        self.tabWidget = QTabWidget()
        self.tabWidget.setTabPosition(QTabWidget.East)
        self.tabWidget.setStyleSheet("QTabWidget::pane {border: 0;}")
        self.tabWidget.addTab(self.splitDocs, "Editor")
        self.tabWidget.addTab(self.splitOutline, "Outline")
        self.tabWidget.currentChanged.connect(self._mainTabChanged)

        # Splitter : Project Tree / Main Tabs
        xCM = self.mainConf.pxInt(4)
        self.splitMain = QSplitter(Qt.Horizontal)
        self.splitMain.setContentsMargins(xCM, xCM, xCM, xCM)
        self.splitMain.addWidget(self.treePane)
        self.splitMain.addWidget(self.tabWidget)
        self.splitMain.setSizes(self.mainConf.getMainPanePos())

        # Indices of All Splitter Widgets
        self.idxTree = self.splitMain.indexOf(self.treePane)
        self.idxMain = self.splitMain.indexOf(self.tabWidget)
        self.idxEditor = self.splitDocs.indexOf(self.docEditor)
        self.idxViewer = self.splitDocs.indexOf(self.splitView)
        self.idxViewDoc = self.splitView.indexOf(self.docViewer)
        self.idxViewMeta = self.splitView.indexOf(self.viewMeta)
        self.idxTabEdit = self.tabWidget.indexOf(self.splitDocs)
        self.idxTabProj = self.tabWidget.indexOf(self.splitOutline)

        # Splitter Behaviour
        self.splitMain.setCollapsible(self.idxTree, False)
        self.splitMain.setCollapsible(self.idxMain, False)
        self.splitDocs.setCollapsible(self.idxEditor, False)
        self.splitDocs.setCollapsible(self.idxViewer, True)
        self.splitView.setCollapsible(self.idxViewDoc, False)
        self.splitView.setCollapsible(self.idxViewMeta, False)

        # Editor / Viewer Default State
        self.splitView.setVisible(False)
        self.docEditor.closeSearch()

        # Initialise the Project Tree
        self.treeView.itemSelectionChanged.connect(self._treeSingleClick)
        self.treeView.itemDoubleClicked.connect(self._treeDoubleClick)
        self.rebuildTree()

        # Set Main Window Elements
        self.setMenuBar(self.mainMenu)
        self.setCentralWidget(self.splitMain)
        self.setStatusBar(self.statusBar)

        # Finalise Initialisation
        # =======================

        # Set Up Auto-Save Project Timer
        self.asProjTimer = QTimer()
        self.asProjTimer.timeout.connect(self._autoSaveProject)

        # Set Up Auto-Save Document Timer
        self.asDocTimer = QTimer()
        self.asDocTimer.timeout.connect(self._autoSaveDocument)

        # Shortcuts and Actions
        self._connectMenuActions()

        keyReturn = QShortcut(self.treeView)
        keyReturn.setKey(QKeySequence(Qt.Key_Return))
        keyReturn.activated.connect(self._treeKeyPressReturn)

        keyEscape = QShortcut(self)
        keyEscape.setKey(QKeySequence(Qt.Key_Escape))
        keyEscape.activated.connect(self._keyPressEscape)

        # Forward Functions
        self.setStatus = self.statusBar.setStatus
        self.setProjectStatus = self.statusBar.setProjectStatus

        # Force a show of the GUI
        self.show()

        # Check that config loaded fine
        self.reportConfErr()

        # Initialise Main GUI
        self.initMain()
        self.asProjTimer.start()
        self.asDocTimer.start()
        self.statusBar.clearStatus()

        # Handle Windows Mode
        self.showNormal()
        if self.mainConf.isFullScreen:
            self.toggleFullScreenMode()

        logger.debug("GUI initialisation complete")

        # Check if a project path was provided at command line, and if
        # not, open the project manager instead.
        if self.mainConf.cmdOpen is not None:
            logger.debug("Opening project from additional command line option")
            self.openProject(self.mainConf.cmdOpen)
        else:
            if self.mainConf.showGUI:
                self.showProjectLoadDialog()

        logger.debug("novelWriter is ready ...")
        self.setStatus("novelWriter is ready ...")

        return
コード例 #21
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

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

        #query = QtSql.QSqlQuery()
        #query.exec("CREATE TABLE createPatchDict(name, type, constructFrom, set, pointSync)")
        #print(self.con.lastError().text())

        #----- initial
        main_lbl = QLabel()

        patch_numb_lbl = QLabel()
        self.patch_numb_edit = QSpinBox()
        self.patch_numb_edit.setRange(1, 1000)
        self.patch_numb_edit.setFixedSize(100, 25)
        #print(self.con.tables())
        if 'createPatchDict' in self.con.tables():

            query = QtSql.QSqlQuery()
            query.exec("SELECT * FROM createPatchDict")
            if query.isActive():
                query.first()
                self.size = 0
                name_back_list = []
                type_back_list = []
                cF_back_list = []
                nets_back_list = []
                pS_back_list = []

                while query.isValid():
                    self.size += 1
                    name_res = query.value('name')
                    type_res = query.value('type')
                    cF_res = query.value('constructFrom')
                    nets_res = query.value('nets')
                    pS_res = query.value('pointSync')

                    name_back_list.append(name_res)
                    type_back_list.append(type_res)
                    cF_back_list.append(cF_res)
                    nets_back_list.append(nets_res)
                    pS_back_list.append(pS_res)

                    query.next()

            if self.size >= 1:
                #print(self.size)
                self.patch_numb_edit.setValue(self.size)

                pn = self.patch_numb_edit.value()
                patches_grid = QGridLayout()
                patches_lbl = QLabel()

                pointSync_lbl = QLabel()
                self.pointSync_edit = QComboBox()
                self.pointSync_edit.setFixedSize(150, 25)
                pointSync_list = ['false', 'true']
                self.pointSync_edit.addItems(pointSync_list)
                pointSync_hbox = QHBoxLayout()
                pointSync_hbox.addWidget(pointSync_lbl)
                pointSync_hbox.addWidget(self.pointSync_edit)

                patches_grid.addWidget(patches_lbl,
                                       0,
                                       0,
                                       alignment=QtCore.Qt.AlignCenter)
                patches_grid.addLayout(pointSync_hbox,
                                       1,
                                       0,
                                       alignment=QtCore.Qt.AlignCenter)

                k = 1
                v = 2
                y = 0

                self.name_edit_list = []
                self.type_edit_list = []
                self.constructFrom_edit_list = []
                self.set_edit_list = []

                while k <= pn:

                    name_lbl = QLabel()
                    name_hbox = QHBoxLayout()
                    name_edit = QLineEdit()
                    name_edit.setFixedSize(150, 25)
                    name_hbox.addWidget(name_lbl)
                    name_hbox.addWidget(name_edit)
                    name_edit.setText(name_back_list[y])

                    type_lbl = QLabel()
                    type_hbox = QHBoxLayout()
                    type_edit = QComboBox()
                    type_edit.setFixedSize(150, 25)
                    type_list = ["patch"]
                    type_edit.addItems(type_list)
                    type_hbox.addWidget(type_lbl)
                    type_hbox.addWidget(type_edit)
                    type_mas = type_edit.count()
                    for i in range(type_mas):
                        if type_edit.itemText(i) == type_back_list[y]:
                            type_edit.setCurrentIndex(i)

                    constructFrom_lbl = QLabel()
                    constructFrom_hbox = QHBoxLayout()
                    constructFrom_edit = QComboBox()
                    constructFrom_edit.setFixedSize(110, 25)
                    constructFrom_list = ["set"]
                    constructFrom_edit.addItems(constructFrom_list)
                    constructFrom_hbox.addWidget(constructFrom_lbl)
                    constructFrom_hbox.addWidget(constructFrom_edit)
                    constructFrom_mas = constructFrom_edit.count()
                    for i in range(constructFrom_mas):
                        if constructFrom_edit.itemText(i) == cF_back_list[y]:
                            constructFrom_edit.setCurrentIndex(i)

                    set_lbl = QLabel()
                    set_hbox = QHBoxLayout()
                    set_edit = QLineEdit()
                    set_edit.setFixedSize(140, 25)
                    set_hbox.addWidget(set_lbl)
                    set_hbox.addWidget(set_edit)
                    set_edit.setText(nets_back_list[y])

                    self.name_edit_list.append(name_edit)
                    self.type_edit_list.append(type_edit)
                    self.constructFrom_edit_list.append(constructFrom_edit)
                    self.set_edit_list.append(set_edit)

                    patch_grid = QGridLayout()
                    patch_grid.addLayout(name_hbox, 0, 0)
                    patch_grid.addLayout(type_hbox, 1, 0)
                    patch_grid.addLayout(constructFrom_hbox, 2, 0)
                    patch_grid.addLayout(set_hbox, 3, 0)

                    patch_frame = QFrame()
                    patch_frame.setFixedSize(250, 130)
                    patch_frame.setLayout(patch_grid)

                    if self.interface_lng_val == 'Russian':

                        name_lbl.setText("Имя патча:")
                        type_lbl.setText("Тип патча:")
                        constructFrom_lbl.setText("Конструирование:")
                        set_lbl.setText("Поверхность:")

                    elif self.interface_lng_val == 'English':

                        name_lbl.setText("Patch name:")
                        type_lbl.setText("Patch type:")
                        constructFrom_lbl.setText("Construct from:")
                        set_lbl.setText("Face set:")

                    patches_grid.addWidget(patch_frame,
                                           v,
                                           0,
                                           alignment=QtCore.Qt.AlignCenter)

                    k += 1
                    v += 1
                    y += 1

                patches_btnSave = QPushButton()
                patches_btnSave.setFixedSize(80, 25)

                buttons_hbox = QHBoxLayout()
                buttons_hbox.addWidget(patches_btnSave)

                patches_grid.addLayout(buttons_hbox,
                                       len(self.name_edit_list) + 3,
                                       0,
                                       alignment=QtCore.Qt.AlignCenter)
                patches_grid.setRowStretch(3, 6)

                self.patches_group = QGroupBox()
                self.patches_group.setLayout(patches_grid)

                prs_grid = QGridLayout()
                prs_grid.addWidget(patch_numb_lbl, 0, 0)
                prs_grid.addWidget(self.patch_numb_edit, 0, 1)

                prs_frame = QFrame()
                prs_frame.setFixedSize(250, 70)
                prs_frame.setLayout(prs_grid)

                initial_btnSave = QPushButton()
                initial_btnSave.setFixedSize(80, 25)

                buttons_hbox = QHBoxLayout()
                buttons_hbox.addWidget(initial_btnSave)

                initial_grid = QGridLayout()
                initial_grid.addWidget(main_lbl,
                                       0,
                                       0,
                                       alignment=QtCore.Qt.AlignCenter)
                initial_grid.addWidget(prs_frame,
                                       1,
                                       0,
                                       alignment=QtCore.Qt.AlignCenter)
                initial_grid.addLayout(buttons_hbox,
                                       2,
                                       0,
                                       alignment=QtCore.Qt.AlignCenter)
                initial_grid.setRowStretch(3, 6)

                self.initial_group = QGroupBox()
                self.initial_group.setLayout(initial_grid)

                self.tab = QTabWidget()
                self.tab.insertTab(0, self.initial_group, "&initial")
                self.tab.insertTab(1, self.patches_group, "&new_patches")
                patches_btnSave.clicked.connect(
                    self.on_patches_btnSave_clicked)
                initial_btnSave.clicked.connect(
                    self.on_initial_btnSave_clicked)

                if self.interface_lng_val == 'Russian':
                    patches_lbl.setText("Укажите параметры патчей")
                    patches_btnSave.setText("Записать")
                    pointSync_lbl.setText("Точка синхронизации:")

                elif self.interface_lng_val == 'English':
                    patches_btnSave.setText("Write")
                    patches_lbl.setText("Set patches parameters")
                    pointSync_lbl.setText("Synchronization point:")
        else:
            #self.par.listWidget.clear()
            #msg_lbl = QLabel('<span style="color:green">' + msg + '</span>')
            #self.par.item = QListWidgetItem()
            #self.par.listWidget.addItem(self.par.item)
            #self.par.listWidget.setItemWidget(self.par.item, msg_lbl)

            prs_grid = QGridLayout()
            prs_grid.addWidget(patch_numb_lbl, 0, 0)
            prs_grid.addWidget(self.patch_numb_edit, 0, 1)

            prs_frame = QFrame()
            prs_frame.setFixedSize(250, 70)
            prs_frame.setLayout(prs_grid)

            initial_btnSave = QPushButton()
            initial_btnSave.setFixedSize(80, 25)

            buttons_hbox = QHBoxLayout()
            buttons_hbox.addWidget(initial_btnSave)

            initial_grid = QGridLayout()
            initial_grid.addWidget(main_lbl,
                                   0,
                                   0,
                                   alignment=QtCore.Qt.AlignCenter)
            initial_grid.addWidget(prs_frame,
                                   1,
                                   0,
                                   alignment=QtCore.Qt.AlignCenter)
            initial_grid.addLayout(buttons_hbox,
                                   2,
                                   0,
                                   alignment=QtCore.Qt.AlignCenter)
            initial_grid.setRowStretch(3, 6)

            self.initial_group = QGroupBox()
            self.initial_group.setLayout(initial_grid)

            #-----new_patches

            ###табличный виджет для групп
            self.tab = QTabWidget()
            #initial_group, spe_edit, nospe_lbl, nospe_edit, initial_btnSave, cTM_edit, nov_edit, spp_edit, nop_lbl, nop_edit, nob_edit, mpp_lbl, mpp_edit, nompp_lbl, nompp_edit, vertices_visible, blocks_visible, edges_visible, patches_visible, mergepatchpairs_visible = initial_class.out_frame_func(int_lng, prj_path, mesh_name_txt)
            self.tab.insertTab(0, self.initial_group, "&initial")
            #spe_edit.stateChanged.connect(self.spe_state_changed)
            #spp_edit.stateChanged.connect(self.spp_state_changed)
            #mpp_edit.stateChanged.connect(self.mpp_state_changed)
            initial_btnSave.clicked.connect(self.on_initial_btnSave_clicked)

#-------------------------Главный фрейм формы с элементами--------------------------#

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

        if self.interface_lng_val == 'Russian':
            initial_btnSave.setText("Записать")
            btnSave.setText("Сохранить")
            main_lbl.setText('Укажите количество патчей')
            patch_numb_lbl.setText('Количество патчей:')
        elif self.interface_lng_val == 'English':
            initial_btnSave.setText("Write")
            btnSave.setText("Save")
            main_lbl.setText('Set patches number')
            patch_numb_lbl.setText('Patches number:')

        scrollLayout = QFormLayout()
        scrollArea = QScrollArea()
        scrollArea.setWidgetResizable(True)
        scrollArea.setWidget(self.tab)
        scrollArea.setFixedSize(650, 460)

        cPD_grid = QGridLayout()
        cPD_grid.addWidget(scrollArea, 0, 0, alignment=QtCore.Qt.AlignCenter)
        cPD_grid.addLayout(buttons_hbox, 1, 0, alignment=QtCore.Qt.AlignCenter)
        cPD_frame = QFrame()
        cPD_frame.setFixedSize(670, 510)
        cPD_frame.setStyleSheet(
            open("./styles/properties_form_style.qss", "r").read())
        cPD_frame.setFrameShape(QFrame.Panel)
        cPD_frame.setFrameShadow(QFrame.Sunken)
        cPD_frame.setLayout(cPD_grid)

        cPD_vbox = QVBoxLayout()
        cPD_vbox.addWidget(cPD_frame)

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

        form = QFormLayout()
        form.addRow(cPD_vbox)
        self.setLayout(form)
コード例 #22
0
    def build_gui(self):
        """Generates the GUI elements, and hooks everything up."""

        # Removes anim from combobox opening
        QApplication.setEffectEnabled(Qt.UI_AnimateCombo, False)

        # Sorts the parameters, so that favorite ones are added to the favorite widget.
        favorites = {i: self.settings[i] for i in self.settings.get_favorites()}
        options = {k: v for k, v in self.settings.parameters.items() if k not in favorites}

        # Create top level tab widget system for the UI
        self.tab_widget = QTabWidget(self)

        # Close signal
        self.onclose.connect(self.confirm)
        # Confirmation to close signal
        self.sendClose.connect(self.closeE)

        # First Tab | Main tab
        self.tab1 = MainTab(self.settings, self.tab_widget)

        self.tab1.start_btn.clicked.connect(self.queue_download)
        # Stop button stops downloads, and may clear queue.
        self.tab1.stop_btn.clicked.connect(self.stop_download)
        self.tab1.close_btn.clicked.connect(self.close)

        # Perform check if enough is present to start a download after user actions
        self.tab1.checkbox.stateChanged.connect(self.allow_start)
        self.tab1.url_input.textChanged.connect(self.allow_start)

        # Queue downloading
        self.tab1.url_input.returnPressed.connect(self.tab1.start_btn.click)

        # Change profile
        self.tab1.profile_dropdown.currentTextChanged.connect(self.load_profile)
        # Delete profile
        self.tab1.profile_dropdown.deleteItem.connect(self.delete_profile)

        # Tab 2 | Parameter Tab
        self.tab2 = ParameterTab(options, favorites, self.settings, self)

        # Connecting tab 2.
        self.tab2.open_folder_action.triggered.connect(self.open_folder)
        self.tab2.copy_action.triggered.connect(self.copy_to_cliboard)

        self.tab2.options.itemChanged.connect(self.parameter_updater)
        self.tab2.options.move_request.connect(self.move_item)
        self.tab2.options.itemRemoved.connect(self.item_removed)
        self.tab2.options.addOption.connect(self.add_option)

        self.tab2.favorites.itemChanged.connect(self.parameter_updater)
        self.tab2.favorites.move_request.connect(self.move_item)
        self.tab2.favorites.itemRemoved.connect(self.item_removed)
        self.tab2.favorites.addOption.connect(self.add_option)

        self.tab2.browse_btn.clicked.connect(self.savefile_dialog)
        self.tab2.save_profile_btn.clicked.connect(self.save_profile)

        # Tab 3 | Basic text editor
        self.tab3 = TextTab(parent=self)

        # When loadbutton is clicked, launch load textfile.
        self.tab3.loadButton.clicked.connect(self.load_text_from_file)
        # When savebutton clicked, save text to file.
        self.tab3.saveButton.clicked.connect(self.save_text_to_file)

        # Tab 4
        # Button to browse for .txt file to download files.
        self.tab4 = AboutTab(self.settings, parent=self)

        # Connect buttons to functions
        self.tab4.update_btn.clicked.connect(self.update_youtube_dl)
        self.tab4.dirinfo_btn.clicked.connect(self.dir_info)
        self.tab4.reset_btn.clicked.connect(self.reset_settings)
        self.tab4.location_btn.clicked.connect(self.textfile_dialog)
        self.tab4.debug_info.clicked.connect(self.toggle_debug)
        self.tab4.dl_mode_btn.clicked.connect(self.toggle_modes)

        # Future tab creation here! Currently 4 tabs
        # TODO: Move stylesheet applying to method, make color picking dialog to customize in realtime

        # Windows specific, only triggered in settings manually
        if self.settings.user_options['use_win_accent']:
            try:
                color = get_win_accent_color()
                bg_color = f"""
                QMainWindow {{
                    background-color: {color};
                }}
                QTabBar {{
                    background-color: {color};
                }}"""
            except (OSError, PermissionError):
                bg_color = ''
        else:
            bg_color = ''

        self.style_with_options = bg_color + f"""
                                QCheckBox::indicator:unchecked {{
                                    image: url({self.unchecked_icon});
                                }}

                                QCheckBox::indicator:checked {{
                                    image: url({self.checked_icon});
                                }}
                                QComboBox::down-arrow {{
                                    border-image: url({self.down_arrow_icon});
                                    height: {self.tab1.profile_dropdown.iconSize().height()}px;
                                    width: {self.tab1.profile_dropdown.iconSize().width()}px;
                                }}

                                QComboBox::down-arrow::on {{
                                    image: url({self.down_arrow_icon_clicked});
                                    height: {self.tab1.profile_dropdown.iconSize().height()}px;
                                    width: {self.tab1.profile_dropdown.iconSize().width()}px;
                                    
                                }}
                                
                                QTreeWidget::indicator:checked {{
                                    image: url({self.checked_icon});
                                }}
                                
                                QTreeWidget::indicator:unchecked {{
                                    image: url({self.unchecked_icon});
                                }}"""

        if not self.settings.user_options['show_collapse_arrows']:
            self.style_with_options += """
                                QTreeWidget::branch {{
                                    image: none;
                                    border-image: none;    
                                }}
                                
                                QTreeWidget::branch:has-siblings:!adjoins-item {{
                                    image: none;
                                    border-image: none;
                                }}
                                
                                QTreeWidget::branch:has-siblings:adjoins-item {{
                                    border-image: none;
                                    image: none;
                                }}
                                
                                QTreeWidget::branch:!has-children:!has-siblings:adjoins-item {{
                                    border-image: none;
                                    image: none;
                                }}
                                
                                """

        # Adds tabs to the tab widget
        self.tab_widget.addTab(self.tab1, 'Main')
        self.tab_widget.addTab(self.tab2, 'Param')
        self.tab_widget.addTab(self.tab3, 'List')
        self.tab_widget.addTab(self.tab4, 'About')

        # Sets the styling for GUI
        self.setStyleSheet(get_stylesheet() + self.style_with_options)

        self.setWindowTitle('Grabber')
        self.setWindowIcon(self.windowIcon)

        # Set base size.
        self.setMinimumWidth(340)
        self.setMinimumHeight(400)

        # Selects the text in the URL box when focus is gained
        if self.settings.user_options['select_on_focus']:
            self.gotfocus.connect(self.window_focus_event)
        else:
            self.tab1.url_input.setFocus()

        # Check for youtube
        if self.youtube_dl_path is None:
            self.tab4.update_btn.setDisabled(True)
            self.alert_message('Warning!', '\nNo youtube-dl.exe found! Add to path, '
                                           'or make sure it\'s in the same folder as this program. '
                                           'Then close and reopen this program.', '')
        # Sets the download items tooltips to the full file path.
        self.download_name_handler()

        # Ensures widets are in correct state at startup and when tab1.lineedit is changed.
        self.allow_start()
        # Shows the main window.
        self.setCentralWidget(self.tab_widget)

        self.show()

        # Below NEEDS to connect after show!!

        # Ensures size of parameter tab is right
        self.resizedByUser.connect(self.resize_contents)

        # Called after show, to ensure base size is consistent.
        self.tab2.enable_favorites(bool(favorites))

        # State changed
        self.downloader.stateChanged.connect(self.allow_start)
        self.tab_widget.currentChanged.connect(self.resize_contents)
コード例 #23
0
ファイル: BEI_Invoice.py プロジェクト: alangburl/BEI_Invoice
    def table(self, num):
        '''Setup the table for use with a new invoice
        '''
        self.start_flag = True
        self.actionPrint.setEnabled(True)

        self.actionSave.setEnabled(True)
        self.actionViewLaborBreakdown.setEnabled(True)
        self.actionBasicInfo.setEnabled(True)
        self.actionViewAllWindows.setEnabled(True)
        self.actionViewCutomer.setEnabled(True)
        self.actionViewCompany.setEnabled(True)
        self.docked = QMdiSubWindow()
        self.docked.setWindowTitle('Invoice {}'.format(num))
        self.num = num
        self.tabs = QTabWidget(self)
        self.parts = Parts_Tabs(num)
        self.tabs.addTab(self.parts, 'Parts')
        self.labor = Labor_Tabs(num)
        self.tabs.addTab(self.labor, 'Labor')
        self.docked.setWidget(self.tabs)

        self.parts.total.connect(self.calculate_totals)
        self.labor.labor_total.connect(self.calculate_totals)

        cust_display = QWidget(self)
        self.cust_label = QLabel('Customer: {}'.format(self.customer), self)
        self.cust_label.setFont(self.font)
        self.machine_label = QLabel('Machine: {}'.format(self.machine_text),
                                    self)
        self.machine_label.setFont(self.font)
        lay = QHBoxLayout()
        lay.addWidget(self.cust_label)
        lay.addWidget(self.machine_label)
        cust_display.setLayout(lay)

        #design and insert the totals table
        self.totals_table = Table(7, 2)
        self.totals_table.tableWidget.setItem(0, 0, QTableWidgetItem('Parts:'))
        self.totals_table.tableWidget.setItem(1, 0, QTableWidgetItem('Labor:'))
        self.totals_table.tableWidget.setItem(2, 0,
                                              QTableWidgetItem('Supplies:'))
        self.totals_table.tableWidget.setItem(3, 0,
                                              QTableWidgetItem('Freight:'))
        self.totals_table.tableWidget.setItem(4, 0,
                                              QTableWidgetItem('Subtotal:'))
        self.totals_table.tableWidget.setItem(
            5, 0, QTableWidgetItem('Tax: {:.2f}%'.format(self.tax * 100)))
        self.totals_table.tableWidget.setItem(6, 0, QTableWidgetItem('Total:'))
        #set up the comments section
        self.comments = QTextEdit(self)
        self.comments.setFont(self.font)
        self.comments.setSizePolicy(self.size_policy, self.size_policy)
        self.comments.setText('Comments:\n')

        self.additional_docking = QWidget(self)
        layout = QVBoxLayout(self)
        layout.addWidget(cust_display)
        layout.addWidget(self.totals_table)
        layout.addWidget(self.comments)
        self.additional_docking.setLayout(layout)

        self.docked2 = QMdiSubWindow()
        self.docked2.setWidget(self.additional_docking)
        self.docked2.setWindowTitle('Information')

        self.mdi = QMdiArea()
        self.mdi.addSubWindow(self.docked2)
        self.mdi.addSubWindow(self.docked)

        self.mdi.tileSubWindows()
        self.setCentralWidget(self.mdi)
コード例 #24
0
    def setupUi(self, MainWindow):
        MainWindow.resize(1200, 800)
        #메인 화면 색상py
        self.setStyleSheet("color: black;" "background-color: white;")

        font = QFont()
        font.setFamily("NanumGothic")
        MainWindow.setFont(font)
        self.centralwidget = QWidget(MainWindow)
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(20, 20, 101, 31))
        font = QFont()
        font.setFamily("NanumGothic")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.button_add = QPushButton(self.centralwidget)
        self.button_add.setGeometry(QRect(60, 730, 131, 34))
        #버튼 스타일 변경
        self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_add.setFont(staticValues.buttonFont)

        self.button_modi = QPushButton(self.centralwidget)
        self.button_modi.setGeometry(QRect(260, 730, 131, 34))
        self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_modi.setFont(staticValues.buttonFont)

        self.button_del = QPushButton(self.centralwidget)
        self.button_del.setGeometry(QRect(460, 730, 131, 34))
        self.button_del.setStyleSheet(staticValues.redButtonStyleSheet)
        self.button_del.setFont(staticValues.buttonFont)

        self.button_upload = QPushButton(self.centralwidget)
        self.button_upload.setGeometry(QRect(790, 730, 131, 34))
        self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_upload.setFont(staticValues.buttonFont)

        self.tabWidget = QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QRect(40, 70, 1121, 621))
        self.tab = QWidget()
        self.tab.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab, "회원 목록")
        self.tableWidget = QTableWidget(self.tab)
        self.tableWidget.setGeometry(QRect(0, 0, 1111, 591))
        self.tableWidget.setObjectName("회원 목록")
        self.tableWidget.setColumnCount(13)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.tableWidget.setHorizontalHeaderLabels([
            "회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근", "보유잔량", "총구매금액",
            "총판매금액", "수익", "평단가", "지갑주소"
        ])
        # self.tableView = QTableWidget()
        # self.tableView.setColumnCount(5)
        # self.tableView.setRowCount(3)

        # self.tab.layout.addWidget(self.tableView)
        # self.tab.setLayout(self.tab.layout)
        # self.tab_2 = QWidget()
        # self.tabWidget.addTab(self.tab_2, "")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(MainWindow)
コード例 #25
0
ファイル: PumpDlg.py プロジェクト: SPF-OST/pytrnsys_gui
    def __init__(self, pump: _pmp.Pump, parent=None):
        super(PumpDlg, self).__init__(parent)
        nameLabel = QLabel("Name:")
        self.block = pump
        self.le = QLineEdit(self.block.label.toPlainText())
        self.setWindowIcon(QIcon(pump.pixmap()))
        self.okButton = QPushButton("OK")
        self.cancelButton = QPushButton("Cancel")

        self.hFlipBoxLabel = QLabel("Horizontal Flip")
        self.vFlipBoxLabel = QLabel("Vertical Flip")
        self.hFlipBox = QCheckBox()
        self.vFlipBox = QCheckBox()

        self.vFlipBox.setTristate(False)
        self.hFlipBox.setTristate(False)
        self.hFlipBox.setCheckState(self.block.flippedH * 2)
        self.vFlipBox.setCheckState(self.block.flippedV * 2)

        flipLayout = QHBoxLayout()
        flipLayout.addWidget(self.hFlipBoxLabel)
        flipLayout.addWidget(self.hFlipBox)
        flipLayout.addWidget(self.vFlipBoxLabel)
        flipLayout.addWidget(self.vFlipBox)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch()
        buttonLayout.addWidget(self.okButton)
        buttonLayout.addWidget(self.cancelButton)
        tab1Layout = QGridLayout(self)
        tab1Layout.addWidget(nameLabel, 0, 0)
        tab1Layout.addWidget(self.le, 0, 1)
        tab1Layout.addLayout(flipLayout, 1, 0, 3, 0)

        positionLayout = QHBoxLayout()
        self.PumpPowerLabel = QLabel("Mass Flow Rate")
        self.LineEdit = QLineEdit(str(self.block.rndPwr))
        self.PumpPowerLabel2 = QLabel("kg/h")
        positionLayout.addWidget(self.PumpPowerLabel)
        positionLayout.addWidget(self.LineEdit)
        positionLayout.addWidget(self.PumpPowerLabel2)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        # Add tabs
        self.tabs.addTab(self.tab1, "Diagram")
        self.tabs.addTab(self.tab2, "Adjust Mass Flow Rate")
        self.tab1.setLayout(tab1Layout)
        self.tab2.setLayout(positionLayout)
        # self.tab2 = layout
        # self.tabs.resize(300, 200)

        # self.tabs.addTab(self.tab2, "Tab 2")
        self.layout2 = QGridLayout(self)
        self.layout2.addWidget(self.tabs, 0, 0)
        self.layout2.addLayout(buttonLayout, 2, 0, 3, 0)
        self.setLayout(self.layout2)

        self.okButton.clicked.connect(self.acceptedEdit)
        self.cancelButton.clicked.connect(self.cancel)
        self.hFlipBox.stateChanged.connect(self.setNewFlipStateH)
        self.vFlipBox.stateChanged.connect(self.setNewFlipStateV)
        self.setWindowTitle("Properties")
        self.show()
コード例 #26
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self)

        self.setWindowTitle("Ufo Wardriving")
        self.setWindowIcon(getQIcon("ufo.png"))
        self.statusBar().showMessage("I want to belive")
        self.mainWidget = QWidget(self)

        exitAction = QAction(getQIcon("exit.png"), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip(self.tr("Exit application"))
        exitAction.triggered.connect(qApp.quit)

        def donazione():
            webbrowser.open(
                "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JBQXLC8J5SWTA"
            )

        def homepage():
            webbrowser.open("http://www.thc-scripting.it/ufowardriving/")

        def showScanner():
            if scanWidget.isVisible() == 1:
                scanWidget.setVisible(0)
                scanWidget.timer.stop()
            else:
                if (platform.system() == 'Windows'):
                    cmd_test = "netsh wlan show networks mode=bssid"
                    try:
                        out = subprocess.check_output(cmd_test, shell=True)
                        scanWidget.setVisible(1)
                        scanWidget.timer.start()
                    except subprocess.CalledProcessError:
                        msgBox = QMessageBox()
                        msgBox.setWindowTitle(
                            self.tr("Windows Vista and later!"))
                        msgBox.setText(
                            self.
                            tr("Sorry, This feature is only for Windows Vista and later."
                               ))
                        msgBox.setIcon(QMessageBox.Warning)
                        msgBox.setDefaultButton(QMessageBox.Ok)
                        ret = msgBox.exec_()
                        return
                else:
                    scanWidget.setVisible(1)
                    scanWidget.timer.start()

        homeAction = QAction(getQIcon("home.png"),
                             self.tr("&Project home page"), self)
        homeAction.setShortcut('Ctrl+H')
        homeAction.setStatusTip(self.tr("Project home page"))
        homeAction.triggered.connect(homepage)

        donAction = QAction(getQIcon("donation.png"),
                            self.tr("Make a donation"), self)
        donAction.setShortcut('Ctrl+D')
        donAction.setStatusTip(self.tr("Donation"))
        donAction.triggered.connect(donazione)

        scanAction = QAction(getQIcon("wifi.png"), '&Scanner', self)
        scanAction.setShortcut('Ctrl+D')
        scanAction.setStatusTip(
            self.tr("Show the wifi scanner\nWarning!\nOnly for linux!"))
        scanAction.triggered.connect(showScanner)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu(self.tr("&File"))
        fileMenu.addAction(exitAction)

        toolsMenu = menubar.addMenu(self.tr("&Tools"))
        toolsMenu.addAction(scanAction)

        infoMenu = menubar.addMenu(self.tr("&Info"))
        infoMenu.addAction(homeAction)
        infoMenu.addAction(donAction)

        hBox = QHBoxLayout(self.mainWidget)
        hBox.setSpacing(5)

        self.tabWidget = QTabWidget(self.mainWidget)
        hBox.addWidget(self.tabWidget)

        scanWidget = scannerGuiWidget(self)
        hBox.addWidget(scanWidget)
        scanWidget.setVisible(0)

        self.fastwebTab = QWidget(self.tabWidget)
        self.speedTab = QWidget(self.tabWidget)
        self.teletuTab = QWidget(self.tabWidget)
        self.infostradaTab = QWidget(self.tabWidget)
        self.aliceTab = QWidget(self.tabWidget)
        self.dlinkTab = QWidget(self.tabWidget)
        self.huaweiTab = QWidget(self.tabWidget)
        self.jazztelTab = QWidget(self.tabWidget)
        self.yacomTab = QWidget(self.tabWidget)

        self.tabWidget.addTab(self.fastwebTab, getQIcon("fastweb.png"),
                              "Fastweb")
        self.tabWidget.addTab(self.speedTab, getQIcon("speedtouch.png"),
                              "Speedtouch")
        self.tabWidget.addTab(self.teletuTab, getQIcon("teletu.png"), "TeleTu")
        self.tabWidget.addTab(self.infostradaTab, getQIcon("infostrada.png"),
                              "Infostrada")
        self.tabWidget.addTab(self.aliceTab, getQIcon("alice.png"), "Alice")
        self.tabWidget.addTab(self.dlinkTab, getQIcon("dlink.png"), "DLink")
        self.tabWidget.addTab(self.huaweiTab, getQIcon("huawei.png"), "Huawei")
        self.tabWidget.addTab(self.jazztelTab, getQIcon("jazztel.png"),
                              "Jazztel")
        self.tabWidget.addTab(self.yacomTab, getQIcon("yacom.png"), "YaCom")

        vBoxlayoutFast = QVBoxLayout()
        vBoxlayoutSpeed = QVBoxLayout()
        vBoxlayoutInfostrada = QVBoxLayout()
        vBoxlayoutTeletu = QVBoxLayout()
        vBoxlayoutAlice = QVBoxLayout()
        vBoxlayoutDlink = QVBoxLayout()
        vBoxlayoutHuawei = QVBoxLayout()
        vBoxlayoutJazztel = QVBoxLayout()
        vBoxlayoutYacom = QVBoxLayout()

        self.fastGuiWidget = fastGuiWidget()
        self.speedGuiWidget = speedGuiWidget()
        self.infostradaGuiWidget = infostradaGuiWidget()
        self.teletuGuiWidget = teletuGuiWidget()
        self.aliceGuiWidget = aliceGuiWidget()
        self.dlinkGuiWidget = dlinkGuiWidget()
        self.huaweiGuiWidget = huaweiGuiWidget()
        self.jazztelGuiWidget = jazztelGuiWidget()
        self.yacomGuiWidget = yacomGuiWidget()

        vBoxlayoutFast.addWidget(self.fastGuiWidget)
        vBoxlayoutSpeed.addWidget(self.speedGuiWidget)
        vBoxlayoutInfostrada.addWidget(self.infostradaGuiWidget)
        vBoxlayoutTeletu.addWidget(self.teletuGuiWidget)
        vBoxlayoutAlice.addWidget(self.aliceGuiWidget)
        vBoxlayoutDlink.addWidget(self.dlinkGuiWidget)
        vBoxlayoutHuawei.addWidget(self.huaweiGuiWidget)
        vBoxlayoutJazztel.addWidget(self.jazztelGuiWidget)
        vBoxlayoutYacom.addWidget(self.yacomGuiWidget)

        self.fastwebTab.setLayout(vBoxlayoutFast)
        self.speedTab.setLayout(vBoxlayoutSpeed)
        self.infostradaTab.setLayout(vBoxlayoutInfostrada)
        self.teletuTab.setLayout(vBoxlayoutTeletu)
        self.aliceTab.setLayout(vBoxlayoutAlice)
        self.dlinkTab.setLayout(vBoxlayoutDlink)
        self.huaweiTab.setLayout(vBoxlayoutHuawei)
        self.jazztelTab.setLayout(vBoxlayoutJazztel)
        self.yacomTab.setLayout(vBoxlayoutYacom)

        self.mainWidget.setLayout(hBox)
        self.setCentralWidget(self.mainWidget)
コード例 #27
0
ファイル: minimal_DAT_GUI.py プロジェクト: baigouy/DAT
    def initUI(self):
        screen = QApplication.desktop().screenNumber(
            QApplication.desktop().cursor().pos())
        centerPoint = QApplication.desktop().screenGeometry(screen).center()

        # should fit in 1024x768 (old computer screens)
        window_width = 900
        window_height = 700
        self.setGeometry(
            QtCore.QRect(
                centerPoint.x() - int(window_width / 2),
                centerPoint.y() - int(window_height / 2), window_width,
                window_height))  # should I rather center on the screen

        # zoom parameters
        self.scale = 1.0
        self.min_scaling_factor = 0.1
        self.max_scaling_factor = 20
        self.zoom_increment = 0.05

        self.setWindowTitle(__NAME__ + ' v' + str(__VERSION__))

        self.paint = Createpaintwidget()

        # initiate 2D image for 2D display
        self.img = None

        self.list = QListWidget(
            self)  # a list that contains files to read or play with
        self.list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list.selectionModel().selectionChanged.connect(
            self.selectionChanged)  # connect it to sel change

        self.scrollArea = QScrollArea()
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.paint)
        self.paint.scrollArea = self.scrollArea

        self.table_widget = QWidget()
        table_widget_layout = QVBoxLayout()

        # Initialize tab screen
        self.tabs = QTabWidget(self)
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()

        # Add tabs
        self.tabs.addTab(self.tab1, "Mask neuron")
        self.tabs.addTab(self.tab2, "Mask cell body")
        self.tabs.addTab(self.tab3, "Segment dendrites")

        # listen to tab changes
        self.tabs.currentChanged.connect(self._onTabChange)

        # Create first tab
        self.tab1.layout = QGridLayout()
        self.tab1.layout.setAlignment(Qt.AlignTop)
        self.tab1.layout.setHorizontalSpacing(3)
        self.tab1.layout.setVerticalSpacing(3)
        self.tab1.layout.setContentsMargins(0, 0, 0, 0)

        label1_tab1 = QLabel('Step 1:')
        self.tab1.layout.addWidget(label1_tab1, 0, 0)

        self.local_threshold = QPushButton("Local threshold")
        self.local_threshold.clicked.connect(self.run_threshold_neuron)
        self.tab1.layout.addWidget(self.local_threshold, 0, 1)
        self.global_threshold = QPushButton("Global threshold")
        self.global_threshold.clicked.connect(self.run_threshold_neuron)
        self.tab1.layout.addWidget(self.global_threshold, 0, 2)
        self.local_n_global_threshold = QPushButton(
            "Local AND Global threshold")
        self.local_n_global_threshold.clicked.connect(
            self.run_threshold_neuron)
        self.tab1.layout.addWidget(self.local_n_global_threshold, 0, 3)

        self.extra_value_for_threshold = QSpinBox()
        self.extra_value_for_threshold.setSingleStep(1)
        self.extra_value_for_threshold.setRange(0, 1_000_000)
        self.extra_value_for_threshold.setValue(6)
        self.tab1.layout.addWidget(self.extra_value_for_threshold, 0, 4)

        self.threshold_method = QComboBox()
        self.threshold_method.addItem('Mean')
        self.threshold_method.addItem('Median')
        self.tab1.layout.addWidget(self.threshold_method, 0, 5)

        label2_tab1 = QLabel('Step 2 (optional):')
        self.tab1.layout.addWidget(label2_tab1, 1, 0)

        self.remove_pixel_blobs_smaller_or_equal = QPushButton(
            "Remove pixel blobs smaller or equal to")
        self.remove_pixel_blobs_smaller_or_equal.clicked.connect(
            self.remove_blobs)
        self.tab1.layout.addWidget(self.remove_pixel_blobs_smaller_or_equal, 1,
                                   1)

        self.remove_blobs_size = QSpinBox()
        self.remove_blobs_size.setSingleStep(1)
        self.remove_blobs_size.setRange(0, 1_000_000)
        self.remove_blobs_size.setValue(1)
        self.tab1.layout.addWidget(self.remove_blobs_size, 1, 2)

        label3_tab1 = QLabel('Step 3: Save')
        self.tab1.layout.addWidget(label3_tab1, 2, 0)

        self.tab1.setLayout(self.tab1.layout)

        self.tab2.layout = QGridLayout()
        self.tab2.layout.setAlignment(Qt.AlignTop)
        self.tab2.layout.setHorizontalSpacing(3)
        self.tab2.layout.setVerticalSpacing(3)
        self.tab2.layout.setContentsMargins(0, 0, 0, 0)

        label1_tab2 = QLabel('Step 1:')
        self.tab2.layout.addWidget(label1_tab2, 0, 0)

        self.detect_cell_body = QPushButton("Detect cell body")
        self.detect_cell_body.clicked.connect(self.detect_neuronal_cell_body)
        self.tab2.layout.addWidget(self.detect_cell_body, 0, 1)

        self.extraCutOff_cell_body = QSpinBox()
        self.extraCutOff_cell_body.setSingleStep(1)
        self.extraCutOff_cell_body.setRange(0, 1_000_000)
        self.extraCutOff_cell_body.setValue(5)
        self.tab2.layout.addWidget(self.extraCutOff_cell_body, 0, 2)

        erosion_label = QLabel('erosion rounds')
        self.tab2.layout.addWidget(erosion_label, 0, 3)

        self.nb_erosion_cellbody = QSpinBox()
        self.nb_erosion_cellbody.setSingleStep(1)
        self.nb_erosion_cellbody.setRange(0, 1_000_000)
        self.nb_erosion_cellbody.setValue(2)
        self.tab2.layout.addWidget(self.nb_erosion_cellbody, 0, 4)

        min_object_size_label = QLabel('minimum object size')
        self.tab2.layout.addWidget(min_object_size_label, 0, 5)

        self.min_obj_size_px = QSpinBox()
        self.min_obj_size_px.setSingleStep(1)
        self.min_obj_size_px.setRange(0, 1_000_000)
        self.min_obj_size_px.setValue(600)
        self.tab2.layout.addWidget(self.min_obj_size_px, 0, 6)

        fill_label = QLabel('fill up to')
        self.tab2.layout.addWidget(fill_label, 0, 7)

        self.fill_holes_up_to = QSpinBox()
        self.fill_holes_up_to.setSingleStep(1)
        self.fill_holes_up_to.setRange(0, 1_000_000)
        self.fill_holes_up_to.setValue(600)
        self.tab2.layout.addWidget(self.fill_holes_up_to, 0, 8)

        nb_dilation_cell_body_label = QLabel('nb dilation cell body')
        self.tab2.layout.addWidget(nb_dilation_cell_body_label, 0, 9)

        self.nb_dilation_cellbody = QSpinBox()
        self.nb_dilation_cellbody.setSingleStep(1)
        self.nb_dilation_cellbody.setRange(0, 1_000_000)
        self.nb_dilation_cellbody.setValue(2)
        self.tab2.layout.addWidget(self.nb_dilation_cellbody, 0, 10)

        label2_tab2 = QLabel('Step 2: Save')
        self.tab2.layout.addWidget(label2_tab2, 6, 0)

        self.tab2.setLayout(self.tab2.layout)

        self.tab3.layout = QGridLayout()
        self.tab3.layout.setAlignment(Qt.AlignTop)
        self.tab3.layout.setHorizontalSpacing(3)
        self.tab3.layout.setVerticalSpacing(3)
        self.tab3.layout.setContentsMargins(0, 0, 0, 0)

        label1_tab3 = QLabel('Step 1:')
        self.tab3.layout.addWidget(label1_tab3, 0, 0)

        self.wshed = QPushButton("Watershed")
        self.wshed.clicked.connect(self.watershed_segment_the_neuron)
        self.tab3.layout.addWidget(self.wshed, 0, 1)

        self.whsed_big_blur = QDoubleSpinBox()
        self.whsed_big_blur.setSingleStep(0.1)
        self.whsed_big_blur.setRange(0, 100)
        self.whsed_big_blur.setValue(2.1)
        self.tab3.layout.addWidget(self.whsed_big_blur, 0, 2)

        self.whsed_small_blur = QDoubleSpinBox()
        self.whsed_small_blur.setSingleStep(0.1)
        self.whsed_small_blur.setRange(0, 100)
        self.whsed_small_blur.setValue(1.4)
        self.tab3.layout.addWidget(self.whsed_small_blur, 0, 3)

        self.wshed_rm_small_cells = QSpinBox()
        self.wshed_rm_small_cells.setSingleStep(1)
        self.wshed_rm_small_cells.setRange(0, 1_000_000)
        self.wshed_rm_small_cells.setValue(10)
        self.tab3.layout.addWidget(self.wshed_rm_small_cells, 0, 4)

        self.jSpinner11 = QSpinBox()
        self.jSpinner11.setSingleStep(1)
        self.jSpinner11.setRange(0, 1_000_000)
        self.jSpinner11.setValue(10)
        self.tab3.layout.addWidget(self.jSpinner11, 0, 5)

        label1_bis_tab3 = QLabel('Alternative Step 1:')
        self.tab3.layout.addWidget(label1_bis_tab3, 1, 0)

        self.skel = QPushButton("Skeletonize")
        self.skel.clicked.connect(self.skeletonize_mask)
        self.tab3.layout.addWidget(self.skel, 1, 1)

        label2_tab3 = QLabel('Step 2:')
        self.tab3.layout.addWidget(label2_tab3, 2, 0)

        self.apply_cell_body = QPushButton("Apply cell body")
        self.apply_cell_body.clicked.connect(
            self.apply_cell_body_to_skeletonized_mask)
        self.tab3.layout.addWidget(self.apply_cell_body, 2, 1)

        label3_tab3 = QLabel('Step 3 (Optional):')
        self.tab3.layout.addWidget(label3_tab3, 3, 0)

        self.prune = QPushButton("Prune")
        self.prune.clicked.connect(self.prune_dendrites)
        self.tab3.layout.addWidget(self.prune, 3, 1)

        self.prune_length = QSpinBox()
        self.prune_length.setSingleStep(1)
        self.prune_length.setRange(0, 1_000_000)
        self.prune_length.setValue(3)
        self.tab3.layout.addWidget(self.prune_length, 3, 2)

        label4_tab3 = QLabel('Step 4 (Optional):')
        self.tab3.layout.addWidget(label4_tab3, 4, 0)

        self.find_neurons = QPushButton("Find neurons")
        self.find_neurons.clicked.connect(self.find_neurons_in_mask)
        self.tab3.layout.addWidget(self.find_neurons, 4, 1)

        self.find_neurons_min_size = QSpinBox()
        self.find_neurons_min_size.setSingleStep(1)
        self.find_neurons_min_size.setRange(0, 1_000_000)
        self.find_neurons_min_size.setValue(45)
        self.tab3.layout.addWidget(self.find_neurons_min_size, 4, 2)

        self.prune_unconnected_segments = QPushButton(
            "Prune unconnected segments (run 'Find neurons' first)")
        self.prune_unconnected_segments.clicked.connect(
            self.prune_neuron_unconnected_segments)
        self.tab3.layout.addWidget(self.prune_unconnected_segments, 4, 3)

        label6_tab3 = QLabel('Step 5: Save')
        self.tab3.layout.addWidget(label6_tab3, 5, 0)

        label5_tab3 = QLabel('Step 6:')
        self.tab3.layout.addWidget(label5_tab3, 6, 0)

        self.create_n_save_bonds = QPushButton("Segment dendrites")
        self.create_n_save_bonds.clicked.connect(self.save_segmented_bonds)
        self.tab3.layout.addWidget(self.create_n_save_bonds, 6, 1)

        self.tab3.setLayout(self.tab3.layout)

        # Add tabs to widget
        table_widget_layout.addWidget(self.tabs)
        self.table_widget.setLayout(table_widget_layout)

        self.Stack = QStackedWidget(self)
        self.Stack.addWidget(self.scrollArea)

        # create a grid that will contain all the GUI interface
        self.grid = QGridLayout()
        self.grid.addWidget(self.Stack, 0, 0)
        self.grid.addWidget(self.list, 0, 1)
        # The first parameter of the rowStretch method is the row number, the second is the stretch factor. So you need two calls to rowStretch, like this: --> below the first row is occupying 80% and the second 20%
        self.grid.setRowStretch(0, 75)
        self.grid.setRowStretch(2, 25)

        # first col 75% second col 25% of total width
        self.grid.setColumnStretch(0, 75)
        self.grid.setColumnStretch(1, 25)

        # void QGridLayout::addLayout(QLayout * layout, int row, int column, int rowSpan, int columnSpan, Qt::Alignment alignment = 0)
        self.grid.addWidget(self.table_widget, 2, 0, 1,
                            2)  # spans over one row and 2 columns

        # BEGIN TOOLBAR
        # pen spin box and connect
        self.penSize = QSpinBox()
        self.penSize.setSingleStep(1)
        self.penSize.setRange(1, 256)
        self.penSize.setValue(3)
        self.penSize.valueChanged.connect(self.penSizechange)

        self.channels = QComboBox()
        self.channels.addItem("merge")
        self.channels.currentIndexChanged.connect(self.channelChange)

        tb_drawing_pane = QToolBar()

        save_button = QToolButton()
        save_button.setText("Save")
        save_button.clicked.connect(self.save_current_mask)
        tb_drawing_pane.addWidget(save_button)

        tb_drawing_pane.addWidget(QLabel("Channels"))
        tb_drawing_pane.addWidget(self.channels)

        # tb.addAction("Save")
        #
        tb_drawing_pane.addWidget(QLabel("Pen size"))
        tb_drawing_pane.addWidget(self.penSize)

        self.grid.addWidget(tb_drawing_pane, 1, 0)
        # END toolbar

        # toolbar for the list
        tb_list = QToolBar()

        del_button = QToolButton()
        del_button.setText("Delete selection from list")
        del_button.clicked.connect(self.delete_from_list)
        tb_list.addWidget(del_button)

        self.grid.addWidget(tb_list, 1, 1)

        # self.setCentralWidget(self.scrollArea)
        self.setCentralWidget(QFrame())
        self.centralWidget().setLayout(self.grid)

        # self.statusBar().showMessage('Ready')
        statusBar = self.statusBar(
        )  # sets an empty status bar --> then can add messages in it
        self.paint.statusBar = statusBar

        # add progress bar to status bar
        self.progress = QProgressBar(self)
        self.progress.setGeometry(200, 80, 250, 20)
        statusBar.addWidget(self.progress)

        # Set up menu bar
        self.mainMenu = self.menuBar()

        self.zoomInAct = QAction(
            "Zoom &In (25%)",
            self,  # shortcut="Ctrl++",
            enabled=True,
            triggered=self.zoomIn)
        self.zoomOutAct = QAction(
            "Zoom &Out (25%)",
            self,  # shortcut="Ctrl+-",
            enabled=True,
            triggered=self.zoomOut)
        self.normalSizeAct = QAction(
            "&Normal Size",
            self,  # shortcut="Ctrl+S",
            enabled=True,
            triggered=self.defaultSize)

        self.viewMenu = QMenu("&View", self)
        self.viewMenu.addAction(self.zoomInAct)
        self.viewMenu.addAction(self.zoomOutAct)
        self.viewMenu.addAction(self.normalSizeAct)

        self.menuBar().addMenu(self.viewMenu)

        self.setMenuBar(self.mainMenu)

        # set drawing window fullscreen
        fullScreenShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_F), self)
        fullScreenShortcut.activated.connect(self.fullScreen)
        fullScreenShortcut.setContext(QtCore.Qt.ApplicationShortcut)

        escapeShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_Escape), self)
        escapeShortcut.activated.connect(self.escape)
        escapeShortcut.setContext(QtCore.Qt.ApplicationShortcut)

        # Show/Hide the mask
        escapeShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_H), self)
        escapeShortcut.activated.connect(self.showHideMask)
        escapeShortcut.setContext(QtCore.Qt.ApplicationShortcut)

        zoomPlus = QtWidgets.QShortcut("Ctrl+Shift+=", self)
        zoomPlus.activated.connect(self.zoomIn)
        zoomPlus.setContext(QtCore.Qt.ApplicationShortcut)

        zoomPlus2 = QtWidgets.QShortcut("Ctrl++", self)
        zoomPlus2.activated.connect(self.zoomIn)
        zoomPlus2.setContext(QtCore.Qt.ApplicationShortcut)

        zoomMinus = QtWidgets.QShortcut("Ctrl+Shift+-", self)
        zoomMinus.activated.connect(self.zoomOut)
        zoomMinus.setContext(QtCore.Qt.ApplicationShortcut)

        zoomMinus2 = QtWidgets.QShortcut("Ctrl+-", self)
        zoomMinus2.activated.connect(self.zoomOut)
        zoomMinus2.setContext(QtCore.Qt.ApplicationShortcut)

        spaceShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_Space), self)
        spaceShortcut.activated.connect(self.nextFrame)
        spaceShortcut.setContext(QtCore.Qt.ApplicationShortcut)

        backspaceShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_Backspace), self)
        backspaceShortcut.activated.connect(self.prevFrame)
        backspaceShortcut.setContext(QtCore.Qt.ApplicationShortcut)

        # connect enter keys to edit dendrites
        enterShortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_Return), self)
        enterShortcut.activated.connect(self.runSkel)
        enterShortcut.setContext(QtCore.Qt.ApplicationShortcut)
        enter2Shortcut = QtWidgets.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_Enter), self)
        enter2Shortcut.activated.connect(self.runSkel)
        enter2Shortcut.setContext(QtCore.Qt.ApplicationShortcut)

        #Qt.Key_Enter is the Enter located on the keypad:
        #Qt::Key_Return  0x01000004
        #Qt::Key_Enter   0x01000005  Typically located on the keypad.

        self.setAcceptDrops(True)  # KEEP IMPORTANT
コード例 #28
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 "
                        "Terracoin 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 Terracoin 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 terracoins 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 terracoins 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 terracoins.").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 terracoins "
              "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)
コード例 #29
0
    def __init__(self, network: Network, config: 'SimpleConfig', wizard=False):
        self.network = network
        self.config = config
        self.tor_proxy = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.fill_in_proxy_settings()
        self.update()
コード例 #30
0
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        #Fonts
        boldFont = QFont()
        boldFont.setBold(True)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QScrollArea()
        self.tab2 = QScrollArea()
        self.tab3 = QWidget()

        # Add tabs
        self.tabs.addTab(self.tab1, "Session Stats")
        self.tabs.addTab(self.tab2, "Total Stats")
        self.tabs.addTab(self.tab3, "Settings")

        #self.dataStruct = getDatastruct()

        #Set up update timer
        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self.updateTabs)
        self.update_timer.start(5000)

        sessionLength = 12
        #self.dataStruct['sessionStats'].pop('sessionLength', None)
        #sorted_totalStats = sorted(self.dataStruct['totalStats'].items(),key=lambda x:operator.getitem(x[1],'count'), reverse=True)
        #sorted_sessionStats = sorted(self.dataStruct['sessionStats'].items(),key=lambda x:operator.getitem(x[1],'count'), reverse=True)
        #print(self.dataStruct)
        self.lastLength = 0

        #Create Session stats tab with content
        self.content_widget = QWidget()
        self.tab1.setWidget(self.content_widget)
        self.tab2Layer = QGridLayout(self.content_widget)
        self.tab1.setWidgetResizable(True)
        self.leftColumn = QLabel('Instance Name:', self)
        self.leftColumn.setFont(boldFont)
        self.middleColumn = QLabel('Instance Count:', self)
        self.middleColumn.setFont(boldFont)
        self.rightColumn = QLabel('Avg Time in Instance(secs):', self)
        self.rightColumn.setFont(boldFont)
        self.tab2Layer.addWidget(self.leftColumn, 0, 0)
        self.tab2Layer.addWidget(self.middleColumn, 0, 1)
        self.tab2Layer.addWidget(self.rightColumn, 0, 2)
        #self.AddSessionDataForTab1(sorted_sessionStats)

        # Create second tab
        self.content_widget = QWidget()
        self.tab2.setWidget(self.content_widget)
        self.flay = QGridLayout(self.content_widget)
        self.tab2.setWidgetResizable(True)

        self.leftColumn = QLabel('Instance Name:', self)
        self.leftColumn.setFont(boldFont)
        self.middleColumn = QLabel('Instance Count:', self)
        self.middleColumn.setFont(boldFont)
        self.rightColumn = QLabel('Avg Time in Instance(secs):', self)
        self.rightColumn.setFont(boldFont)
        self.flay.addWidget(self.leftColumn, 0, 0)
        self.flay.addWidget(self.middleColumn, 0, 1)
        self.flay.addWidget(self.rightColumn, 0, 2)
        #self.AddTotalDataForTab2(sorted_totalStats)

        #Create third tab
        self.tab3.layout = QGridLayout(self)
        self.textbox = QLineEdit(self)
        self.textbox.resize(50, 40)
        self.pathLabel = QLabel('Client.txt location', self)
        self.browseButton = QPushButton('Browse')
        self.browseButton.clicked.connect(self.on_click)

        self.tab3.layout.addWidget(self.pathLabel, 0, 0)
        self.tab3.layout.addWidget(self.textbox, 0, 1)
        self.tab3.layout.addWidget(self.browseButton, 0, 2)
        self.tab3.setLayout(self.tab3.layout)

        print(self.textbox.text())

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
        self.tabs.resize(300, 100)