def get_text_widget(self):
        """
        Return text QWidget with QTextEdit

        :return: text QWidget
        :rtype: QWidget
        """

        text_widget = QWidget()
        text_widget.setObjectName('dialog')
        text_layout = QVBoxLayout()
        text_widget.setLayout(text_layout)

        self.text_edit.setPlaceholderText(_('type your text...'))
        self.text_edit.setText(self.old_text)
        text_layout.addWidget(self.text_edit)

        # Accept button
        accept_btn = QPushButton(_('Confirm'), self)
        accept_btn.clicked.connect(self.accept_text)
        accept_btn.setObjectName('valid')
        accept_btn.setMinimumHeight(30)
        text_layout.addWidget(accept_btn)

        return text_widget
    def get_text_widget(self, regexp):
        """
        Return text QWidget with QTextEdit

        :return: text QWidget
        :rtype: QWidget
        """

        text_widget = QWidget()
        text_widget.setObjectName('dialog')
        text_layout = QVBoxLayout()
        text_widget.setLayout(text_layout)

        text_layout.addWidget(self.valid_text)

        qreg_exp = QRegExp(regexp)
        self.validator.setRegExp(qreg_exp)
        self.line_edit.setPlaceholderText(_('type your text...'))
        self.line_edit.setText(self.old_text)
        self.line_edit.setValidator(self.validator)
        self.line_edit.setFixedHeight(25)
        self.line_edit.textChanged.connect(self.check_text)
        text_layout.addWidget(self.line_edit)

        # Accept button
        accept_btn = QPushButton(_('Confirm'), self)
        accept_btn.clicked.connect(self.accept_text)
        accept_btn.setObjectName('valid')
        accept_btn.setMinimumHeight(30)
        text_layout.addWidget(accept_btn)

        return text_widget
    def get_text_widget(self):
        """
        Return text QWidget with QTextEdit

        :return: text QWidget
        :rtype: QWidget
        """

        text_widget = QWidget()
        text_widget.setObjectName('dialog')
        text_layout = QVBoxLayout()
        text_widget.setLayout(text_layout)

        self.text_edit.setPlaceholderText(_('type your text...'))
        self.text_edit.setText(self.old_text)
        text_layout.addWidget(self.text_edit)

        # Accept button
        accept_btn = QPushButton(_('Confirm'), self)
        accept_btn.clicked.connect(self.accept_text)
        accept_btn.setObjectName('valid')
        accept_btn.setMinimumHeight(30)
        text_layout.addWidget(accept_btn)

        return text_widget
예제 #4
0
    def createStatusBar(self):
        statusBar = QWidget(self)
        statusBar.setObjectName('StatusBar')
        statusBar.setGeometry(STATUS_BAR_X, STATUS_BAR_Y, STATUS_BAR_WIDTH,
                              STATUS_BAR_HEIGHT)

        self.modeLabel = QLabel(self)
        self.modeLabel.setObjectName('ModeLabel')
        self.modeLabel.setAlignment(Qt.AlignCenter | Qt.AlignTop)
        self.modeLabel.setText('Undefined')
        self.modeLabel.setGeometry(STATUS_MODE_X, STATUS_MODE_Y,
                                   STATUS_MODE_WIDTH, STATUS_MODE_HEIGHT)
        MainController.getInstance().stateChangedSignal.connect(
            lambda mode: self.handleModeChange(mode))

        infoLabel = QLabel(self)
        infoLabel.setObjectName('InfoLabel')
        infoLabel.setAlignment(Qt.AlignCenter | Qt.AlignTop)
        infoLabel.setText('99.9 MHz')
        infoLabel.setGeometry(STATUS_INFO_X, STATUS_INFO_Y, STATUS_INFO_WIDTH,
                              STATUS_INFO_HEIGHT)
        MainController.getInstance().statusLabelChangedSignal.connect(
            lambda text: infoLabel.setText(text))

        timeLabel = QLabel(self)
        timeLabel.setObjectName('TimeLabel')
        timeLabel.setAlignment(Qt.AlignCenter | Qt.AlignTop)
        timeLabel.setText('17:22\t08.02.1993')
        timeLabel.setGeometry(STATUS_TIME_X, STATUS_TIME_Y, STATUS_TIME_WIDTH,
                              STATUS_TIME_HEIGHT)
        ''' 
    def get_text_widget(self, regexp):
        """
        Return text QWidget with QTextEdit

        :return: text QWidget
        :rtype: QWidget
        """

        text_widget = QWidget()
        text_widget.setObjectName('dialog')
        text_layout = QVBoxLayout()
        text_widget.setLayout(text_layout)

        text_layout.addWidget(self.valid_text)

        qreg_exp = QRegExp(regexp)
        self.validator.setRegExp(qreg_exp)
        self.line_edit.setPlaceholderText(_('type your text...'))
        self.line_edit.setText(self.old_text)
        self.line_edit.setValidator(self.validator)
        self.line_edit.setFixedHeight(25)
        self.line_edit.textChanged.connect(self.check_text)
        text_layout.addWidget(self.line_edit)

        # Accept button
        accept_btn = QPushButton(_('Confirm'), self)
        accept_btn.clicked.connect(self.accept_text)
        accept_btn.setObjectName('valid')
        accept_btn.setMinimumHeight(30)
        text_layout.addWidget(accept_btn)

        return text_widget
예제 #6
0
    def initialize(self):
        """
        Initialize QDialog for PasswordDialog

        """

        center_widget(self)

        # Main status_layout
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_layout)

        main_layout.addWidget(get_logo_widget(self, _('Edit Password')))

        pass_title = QLabel(_("Please type a new PASSWORD:"******"Your password must contain at least 5 characters."))
        self.help_label.setWordWrap(True)
        pass_layout.addWidget(self.help_label)

        # Accept button
        accept_btn = QPushButton('Confirm', self)
        accept_btn.clicked.connect(self.handle_confirm)
        accept_btn.setObjectName('valid')
        accept_btn.setMinimumHeight(30)
        pass_layout.addWidget(accept_btn)

        main_layout.addWidget(pass_widget)
    def initialize(self):
        """
        Initialize QMainWindow for App

        """

        logger.info('Display Alignak-App...')

        app_widget = QWidget()
        app_widget.setObjectName('dialog')
        app_layout = QGridLayout()
        app_layout.setContentsMargins(0, 0, 0, 0)
        app_widget.setLayout(app_layout)

        # Logo widget
        app_layout.addWidget(get_logo_widget(self, 'Alignak-App'), 0, 0, 1, 3)

        # Panel
        self.panel_widget.initialize()
        app_layout.addWidget(self.panel_widget, 1, 0, 1, 1)
        app_layout.addWidget(get_frame_separator(True), 1, 1, 1, 1)

        # Dock
        self.dock.initialize()
        app_layout.addWidget(self.dock, 1, 2, 1, 1)

        self.setCentralWidget(app_widget)
        self.setMinimumSize(1440, 900)
        center_widget(self)

        display = settings.get_config('Alignak-app', 'display')
        if "min" in display:
            self.show()
        elif "max" in display:
            self.showMaximized()
        else:
            pass

        if settings.get_config('Alignak-app', 'problems', boolean=True):
            self.panel_widget.tab_widget.setCurrentIndex(
                self.panel_widget.tab_widget.indexOf(
                    self.panel_widget.problems_widget))
            self.panel_widget.problems_widget.line_search.setFocus()
        else:
            self.panel_widget.synthesis_widget.line_search.setFocus()
    def initialize(self):
        """
        Initialize QMainWindow for App

        """

        logger.info('Display Alignak-App...')

        app_widget = QWidget()
        app_widget.setObjectName('dialog')
        app_layout = QGridLayout()
        app_layout.setContentsMargins(0, 0, 0, 0)
        app_widget.setLayout(app_layout)

        # Logo widget
        app_layout.addWidget(get_logo_widget(self, 'Alignak-App'), 0, 0, 1, 3)

        # Panel
        self.panel_widget.initialize()
        app_layout.addWidget(self.panel_widget, 1, 0, 1, 1)
        app_layout.addWidget(get_frame_separator(True), 1, 1, 1, 1)

        # Dock
        self.dock.initialize()
        app_layout.addWidget(self.dock, 1, 2, 1, 1)

        self.setCentralWidget(app_widget)
        self.setMinimumSize(1440, 900)
        center_widget(self)

        display = settings.get_config('Alignak-app', 'display')
        if "min" in display:
            self.show()
        elif "max" in display:
            self.showMaximized()
        else:
            pass

        if settings.get_config('Alignak-app', 'problems', boolean=True):
            self.panel_widget.tab_widget.setCurrentIndex(
                self.panel_widget.tab_widget.indexOf(self.panel_widget.problems_widget)
            )
            self.panel_widget.problems_widget.line_search.setFocus()
        else:
            self.panel_widget.synthesis_widget.line_search.setFocus()
예제 #9
0
    def get_event_widget(self, hostname, event):
        """
        Return event QWidget with icon, event text and event message

        :param hostname: name of host attached to event
        :type hostname: str
        :param event: data of an event
        :type event: dict
        :return: widget of event
        :rtype: QWidget
        """

        event_widget = QWidget()
        event_widget.setObjectName('history')
        event_widget.setToolTip(event['type'])
        event_layout = QGridLayout(event_widget)

        # Event icon
        icon_pixmap = self.get_icon_label(event)
        event_layout.addWidget(icon_pixmap, 0, 0, 2, 1)

        # Event type (with date)
        event_title = QLabel()
        event_title.setObjectName(
            History.get_history_icon_name(event['message'], event['type'])
        )
        local_timestamp = get_local_datetime_from_date(event['_updated'])
        created_since = get_diff_since_last_timestamp(local_timestamp.timestamp())

        event_type = self.get_event_type(event, hostname)
        event_type_dated = '%s      (%s)' % (event_type, created_since)
        event_title.setText(event_type_dated)
        event_layout.addWidget(event_title, 0, 1, 1, 1)

        # Event message
        event_msg = QLabel()
        event_msg.setWordWrap(True)
        event_msg.setText(event['message'])
        event_layout.addWidget(event_msg, 1, 1, 1, 1)

        return event_widget
    def get_message_widget(self, dialog, title, text):
        """
        Return colored message QWidget

        :param dialog: type of dialog ('text' or 'error')
        :type dialog: str
        :param title: title of text to display
        :type title: str
        :param text: text to display
        :type text: str
        :return: message QWidget
        :rtype: QWidget
        """

        # Token QWidget
        token_widget = QWidget()
        token_widget.setObjectName('dialog')
        token_layout = QVBoxLayout()
        token_widget.setLayout(token_layout)

        token_title = QLabel(title)
        token_title.setObjectName('itemtitle')
        token_layout.addWidget(token_title)
        token_layout.setAlignment(token_title, Qt.AlignCenter)

        token_label = QLabel(text)
        token_label.setObjectName(dialog)
        token_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        token_label.setWordWrap(True)
        token_layout.addWidget(token_label)

        # Login button
        accept_btn = QPushButton('OK', self)
        accept_btn.clicked.connect(self.accept)
        accept_btn.setObjectName('ok')
        accept_btn.setMinimumHeight(30)
        token_layout.addWidget(accept_btn)

        return token_widget
    def get_message_widget(self, dialog, title, text):
        """
        Return colored message QWidget

        :param dialog: type of dialog ('text' or 'error')
        :type dialog: str
        :param title: title of text to display
        :type title: str
        :param text: text to display
        :type text: str
        :return: message QWidget
        :rtype: QWidget
        """

        # Token QWidget
        token_widget = QWidget()
        token_widget.setObjectName('dialog')
        token_layout = QVBoxLayout()
        token_widget.setLayout(token_layout)

        token_title = QLabel(title)
        token_title.setObjectName('itemtitle')
        token_layout.addWidget(token_title)
        token_layout.setAlignment(token_title, Qt.AlignCenter)

        token_label = QLabel(text)
        token_label.setObjectName(dialog)
        token_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        token_label.setWordWrap(True)
        token_layout.addWidget(token_label)

        # Login button
        accept_btn = QPushButton('OK', self)
        accept_btn.clicked.connect(self.accept)
        accept_btn.setObjectName('ok')
        accept_btn.setMinimumHeight(30)
        token_layout.addWidget(accept_btn)

        return token_widget
예제 #12
0
 def setObjectName(self, *args):
     QWidget.setObjectName(self, *args)
     if hasattr(self, 'edit'):
         self.edit.initialize('regex_edit_' + str(self.objectName()))
예제 #13
0
class Config(QDialog):
    '''
    Configuration dialog for single book conversion. If accepted, has the
    following important attributes

    output_format - Output format (without a leading .)
    input_format  - Input format (without a leading .)
    opf_path - Path to OPF file with user specified metadata
    cover_path - Path to user specified cover (can be None)
    recommendations - A pickled list of 3 tuples in the same format as the
    recommendations member of the Input/Output plugins.
    '''
    def __init__(self,
                 parent,
                 db,
                 book_id,
                 preferred_input_format=None,
                 preferred_output_format=None):
        QDialog.__init__(self, parent)
        self.setupUi()
        self.opt_individual_saved_settings.setVisible(False)
        self.db, self.book_id = db, book_id

        self.setup_input_output_formats(self.db, self.book_id,
                                        preferred_input_format,
                                        preferred_output_format)
        self.setup_pipeline()

        self.input_formats.currentIndexChanged[native_string_type].connect(
            self.setup_pipeline)
        self.output_formats.currentIndexChanged[native_string_type].connect(
            self.setup_pipeline)
        self.groups.setSpacing(5)
        self.groups.activated[(QModelIndex)].connect(self.show_pane)
        self.groups.clicked[(QModelIndex)].connect(self.show_pane)
        self.groups.entered[(QModelIndex)].connect(self.show_group_help)
        rb = self.buttonBox.button(self.buttonBox.RestoreDefaults)
        rb.setText(_('Restore &defaults'))
        rb.clicked.connect(self.restore_defaults)
        self.groups.setMouseTracking(True)
        geom = gprefs.get('convert_single_dialog_geom', None)
        if geom:
            self.restoreGeometry(geom)
        else:
            self.resize(self.sizeHint())

    def setupUi(self):
        self.setObjectName("Dialog")
        self.resize(1024, 700)
        self.setWindowIcon(QIcon(I('convert.png')))
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.input_label = QLabel(self)
        self.input_label.setObjectName("input_label")
        self.horizontalLayout.addWidget(self.input_label)
        self.input_formats = QComboBox(self)
        self.input_formats.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self.input_formats.setMinimumContentsLength(5)
        self.input_formats.setObjectName("input_formats")
        self.horizontalLayout.addWidget(self.input_formats)
        self.opt_individual_saved_settings = QCheckBox(self)
        self.opt_individual_saved_settings.setObjectName(
            "opt_individual_saved_settings")
        self.horizontalLayout.addWidget(self.opt_individual_saved_settings)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.label_2 = QLabel(self)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.output_formats = QComboBox(self)
        self.output_formats.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self.output_formats.setMinimumContentsLength(5)
        self.output_formats.setObjectName("output_formats")
        self.horizontalLayout.addWidget(self.output_formats)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 2)
        self.groups = QListView(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.groups.sizePolicy().hasHeightForWidth())
        self.groups.setSizePolicy(sizePolicy)
        self.groups.setTabKeyNavigation(True)
        self.groups.setIconSize(QSize(48, 48))
        self.groups.setWordWrap(True)
        self.groups.setObjectName("groups")
        self.gridLayout.addWidget(self.groups, 1, 0, 3, 1)
        self.scrollArea = QScrollArea(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(4)
        sizePolicy.setVerticalStretch(10)
        sizePolicy.setHeightForWidth(
            self.scrollArea.sizePolicy().hasHeightForWidth())
        self.scrollArea.setSizePolicy(sizePolicy)
        self.scrollArea.setFrameShape(QFrame.NoFrame)
        self.scrollArea.setLineWidth(0)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QWidget()
        self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 810, 494))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.verticalLayout_3 = QVBoxLayout(self.scrollAreaWidgetContents)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.stack = QStackedWidget(self.scrollAreaWidgetContents)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.stack.sizePolicy().hasHeightForWidth())
        self.stack.setSizePolicy(sizePolicy)
        self.stack.setObjectName("stack")
        self.page = QWidget()
        self.page.setObjectName("page")
        self.stack.addWidget(self.page)
        self.page_2 = QWidget()
        self.page_2.setObjectName("page_2")
        self.stack.addWidget(self.page_2)
        self.verticalLayout_3.addWidget(self.stack)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.gridLayout.addWidget(self.scrollArea, 1, 1, 1, 1)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok
                                          | QDialogButtonBox.RestoreDefaults)
        self.buttonBox.setObjectName("buttonBox")
        self.gridLayout.addWidget(self.buttonBox, 3, 1, 1, 1)
        self.help = QTextEdit(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.help.sizePolicy().hasHeightForWidth())
        self.help.setSizePolicy(sizePolicy)
        self.help.setMaximumHeight(80)
        self.help.setObjectName("help")
        self.gridLayout.addWidget(self.help, 2, 1, 1, 1)
        self.input_label.setBuddy(self.input_formats)
        self.label_2.setBuddy(self.output_formats)
        self.input_label.setText(_("&Input format:"))
        self.opt_individual_saved_settings.setText(
            _("Use &saved conversion settings for individual books"))
        self.label_2.setText(_("&Output format:"))

        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def sizeHint(self):
        desktop = QCoreApplication.instance().desktop()
        geom = desktop.availableGeometry(self)
        nh, nw = max(300, geom.height() - 100), max(400, geom.width() - 70)
        return QSize(nw, nh)

    def restore_defaults(self):
        delete_specifics(self.db, self.book_id)
        self.setup_pipeline()

    @property
    def input_format(self):
        return unicode_type(self.input_formats.currentText()).lower()

    @property
    def output_format(self):
        return unicode_type(self.output_formats.currentText()).lower()

    @property
    def manually_fine_tune_toc(self):
        for i in range(self.stack.count()):
            w = self.stack.widget(i)
            if hasattr(w, 'manually_fine_tune_toc'):
                return w.manually_fine_tune_toc.isChecked()

    def setup_pipeline(self, *args):
        oidx = self.groups.currentIndex().row()
        input_format = self.input_format
        output_format = self.output_format
        self.plumber = create_dummy_plumber(input_format, output_format)

        def widget_factory(cls):
            return cls(self.stack, self.plumber.get_option_by_name,
                       self.plumber.get_option_help, self.db, self.book_id)

        self.mw = widget_factory(MetadataWidget)
        self.setWindowTitle(
            _('Convert') + ' ' + unicode_type(self.mw.title.text()))
        lf = widget_factory(LookAndFeelWidget)
        hw = widget_factory(HeuristicsWidget)
        sr = widget_factory(SearchAndReplaceWidget)
        ps = widget_factory(PageSetupWidget)
        sd = widget_factory(StructureDetectionWidget)
        toc = widget_factory(TOCWidget)
        from calibre.gui2.actions.toc_edit import SUPPORTED
        toc.manually_fine_tune_toc.setVisible(
            output_format.upper() in SUPPORTED)
        debug = widget_factory(DebugWidget)

        output_widget = self.plumber.output_plugin.gui_configuration_widget(
            self.stack, self.plumber.get_option_by_name,
            self.plumber.get_option_help, self.db, self.book_id)
        input_widget = self.plumber.input_plugin.gui_configuration_widget(
            self.stack, self.plumber.get_option_by_name,
            self.plumber.get_option_help, self.db, self.book_id)
        while True:
            c = self.stack.currentWidget()
            if not c:
                break
            self.stack.removeWidget(c)

        widgets = [self.mw, lf, hw, ps, sd, toc, sr]
        if input_widget is not None:
            widgets.append(input_widget)
        if output_widget is not None:
            widgets.append(output_widget)
        widgets.append(debug)
        for w in widgets:
            self.stack.addWidget(w)
            w.set_help_signal.connect(self.help.setPlainText)

        self._groups_model = GroupModel(widgets)
        self.groups.setModel(self._groups_model)

        idx = oidx if -1 < oidx < self._groups_model.rowCount() else 0
        self.groups.setCurrentIndex(self._groups_model.index(idx))
        self.stack.setCurrentIndex(idx)
        try:
            shutil.rmtree(self.plumber.archive_input_tdir, ignore_errors=True)
        except:
            pass

    def setup_input_output_formats(self, db, book_id, preferred_input_format,
                                   preferred_output_format):
        if preferred_output_format:
            preferred_output_format = preferred_output_format.upper()
        output_formats = get_output_formats(preferred_output_format)
        input_format, input_formats = get_input_format_for_book(
            db, book_id, preferred_input_format)
        preferred_output_format = preferred_output_format if \
            preferred_output_format in output_formats else \
            sort_formats_by_preference(output_formats,
                    [prefs['output_format']])[0]
        self.input_formats.addItems(
            (unicode_type(x.upper()) for x in input_formats))
        self.output_formats.addItems(
            (unicode_type(x.upper()) for x in output_formats))
        self.input_formats.setCurrentIndex(input_formats.index(input_format))
        self.output_formats.setCurrentIndex(
            output_formats.index(preferred_output_format))

    def show_pane(self, index):
        self.stack.setCurrentIndex(index.row())

    def accept(self):
        recs = GuiRecommendations()
        for w in self._groups_model.widgets:
            if not w.pre_commit_check():
                return
            x = w.commit(save_defaults=False)
            recs.update(x)
        self.opf_file, self.cover_file = self.mw.opf_file, self.mw.cover_file
        self._recommendations = recs
        if self.db is not None:
            recs['gui_preferred_input_format'] = self.input_format
            save_specifics(self.db, self.book_id, recs)
        self.break_cycles()
        QDialog.accept(self)

    def reject(self):
        self.break_cycles()
        QDialog.reject(self)

    def done(self, r):
        if self.isVisible():
            gprefs['convert_single_dialog_geom'] = \
                bytearray(self.saveGeometry())
        return QDialog.done(self, r)

    def break_cycles(self):
        for i in range(self.stack.count()):
            w = self.stack.widget(i)
            w.break_cycles()

    @property
    def recommendations(self):
        recs = [(k, v, OptionRecommendation.HIGH)
                for k, v in self._recommendations.items()]
        return recs

    def show_group_help(self, index):
        widget = self._groups_model.widgets[index.row()]
        self.help.setPlainText(widget.HELP)
    def get_proxy_widget(self):
        """
        Return the proxy QWidget

        :return: proxy QWidget
        :rtype: QWidget
        """

        proxy_widget = QWidget()
        proxy_widget.setObjectName('dialog')
        proxy_layout = QVBoxLayout(proxy_widget)

        # Title
        title_lbl = QLabel(_('Proxy Settings'))
        title_lbl.setObjectName('itemtitle')
        proxy_layout.addWidget(title_lbl)
        proxy_layout.setAlignment(title_lbl, Qt.AlignTop)

        # Description
        desc_label = QLabel(
            _('Here you can define your proxy. Be sure to enter a valid address.')
        )
        desc_label.setWordWrap(True)
        proxy_layout.addWidget(desc_label)

        # Proxy Settings
        proxy_lbl = QLabel(_('Proxy Address with Port'))
        proxy_layout.addWidget(proxy_lbl)

        proxy = settings.get_config('Alignak', 'proxy')
        self.proxy_address.setText(proxy)
        self.proxy_address.setPlaceholderText(_('proxy adress:port...'))
        self.proxy_address.setFixedHeight(25)
        proxy_layout.addWidget(self.proxy_address)

        # Proxy User
        proxy_user_lbl = QLabel(_('Proxy User (Optional)'))
        proxy_layout.addWidget(proxy_user_lbl)

        proxy_user = settings.get_config('Alignak', 'proxy_user')
        self.proxy_user.setText(proxy_user)
        self.proxy_user.setPlaceholderText(_('proxy user...'))
        self.proxy_user.setFixedHeight(25)
        proxy_layout.addWidget(self.proxy_user)

        # Proxy Password
        proxy_password_lbl = QLabel(_('Proxy Password (Optional)'))
        proxy_layout.addWidget(proxy_password_lbl)

        if settings.get_config('Alignak', 'proxy_password'):
            self.proxy_password.setText(settings.get_config('Alignak', 'proxy_password'))
        self.proxy_password.setPlaceholderText(_('proxy password...'))
        self.proxy_password.setFixedHeight(25)
        self.proxy_password.setEchoMode(QLineEdit.Password)
        proxy_layout.addWidget(self.proxy_password)

        # Valid Button
        valid_btn = QPushButton(_('Valid'))
        valid_btn.setObjectName('valid')
        valid_btn.setMinimumHeight(30)
        valid_btn.clicked.connect(self.accept_proxy)

        proxy_layout.addWidget(valid_btn)

        return proxy_widget
예제 #15
0
    def get_settings_widget(self):
        """
        Return the alignak settings QWidget

        :return: settings QWidget
        :rtype: QWidget
        """

        server_widget = QWidget()
        server_widget.setObjectName('dialog')
        server_layout = QVBoxLayout(server_widget)

        # Title
        title_lbl = QLabel(_('Alignak Backend'))
        title_lbl.setObjectName('itemtitle')
        server_layout.addWidget(title_lbl)
        server_layout.setAlignment(title_lbl, Qt.AlignTop)

        # Description
        desc_label = QLabel(
            _('Here you can define alignak settings. Be sure to enter a valid address.'
              ))
        desc_label.setWordWrap(True)
        server_layout.addWidget(desc_label)

        # Server URL
        server_lbl = QLabel(_('Server'))
        server_layout.addWidget(server_lbl)

        self.server_url.setText(settings.get_config('Alignak', 'url'))
        self.server_url.setPlaceholderText(_('alignak backend url...'))
        self.server_url.setFixedHeight(25)
        server_layout.addWidget(self.server_url)

        # Server Port
        port_lbl = QLabel(_('Port'))
        server_layout.addWidget(port_lbl)

        cur_port = settings.get_config('Alignak', 'backend').split(':')[2]
        self.server_port.setText(cur_port)
        self.server_port.setPlaceholderText(_('alignak backend port...'))
        self.server_port.setFixedHeight(25)
        server_layout.addWidget(self.server_port)

        # Server Processes (displayed only for Unix platforms)
        if 'win32' not in sys.platform:
            process_lbl = QLabel(_('Processes'))
            server_layout.addWidget(process_lbl)

            cur_proc = settings.get_config('Alignak', 'processes')
            self.server_proc.setText(cur_proc)
            self.server_proc.setPlaceholderText(
                _('alignak backend processes...'))
            self.server_proc.setFixedHeight(25)
            server_layout.addWidget(self.server_proc)

        # Web Service description
        server_layout.addStretch(1)
        webservice_lbl = QLabel(_('Web Service'))
        webservice_lbl.setObjectName('itemtitle')
        server_layout.addWidget(webservice_lbl)
        ws_desc_lbl = QLabel(
            _('Here you can define your alignak web service url, with port if needed'
              ))
        ws_desc_lbl.setWordWrap(True)
        server_layout.addWidget(ws_desc_lbl)

        # Web Service URL
        self.webservice_url.setText(
            settings.get_config('Alignak', 'webservice'))
        self.webservice_url.setPlaceholderText(_('alignak webservice url...'))
        self.webservice_url.setFixedHeight(25)
        server_layout.addWidget(self.webservice_url)

        # Valid Button
        valid_btn = QPushButton(_('Valid'))
        valid_btn.setObjectName('valid')
        valid_btn.setMinimumHeight(30)
        valid_btn.clicked.connect(self.accept)

        server_layout.addWidget(valid_btn)

        return server_widget
예제 #16
0
class MainIndex(QWidget):
    auto_pressed_sg = pyqtSignal(dict)
    home_pressed_sg = pyqtSignal()
    search_pressed_sg = pyqtSignal()

    def __init__(self, parent=None):
        super(MainIndex, self).__init__(parent)
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.h = self.screenRect.height()
        self.w = self.screenRect.width()
        self.xr = self.w / 930
        self.yr = self.h / 640
        self.zr = min(self.xr, self.yr)
        self.token = ''
        self.top_wi = QWidget(self)
        self.logo_la = QLabel(self.top_wi)
        self.manual_but = QPushButton(self)
        # self.manual_tex = QLabel(self)
        self.auto_but = QPushButton(self)
        # self.auto_tex = QLabel(self)
        self.home_but = QPushButton(self)
        # self.home_tex = QLabel(self)
        self.loading = QLabel(self)
        self.gif = QMovie('./resource/image/load.gif')
        self.set_ui()
        with open('mainindex.qss', 'r') as f:
            self.setStyleSheet(f.read())

    def set_ui(self):
        self.setWindowTitle('Hall')
        self.setObjectName('hall')
        self.resize(self.w, self.h)
        effect1 = QGraphicsDropShadowEffect()
        effect1.setOffset(10, 10)
        effect1.setColor(QColor(0, 0, 0, 80))
        effect1.setBlurRadius(20)
        effect2 = QGraphicsDropShadowEffect()
        effect2.setOffset(10, 10)
        effect2.setColor(QColor(0, 0, 0, 80))
        effect2.setBlurRadius(20)
        effect3 = QGraphicsDropShadowEffect()
        effect3.setOffset(10, 10)
        effect3.setColor(QColor(0, 0, 0, 80))
        effect3.setBlurRadius(20)
        self.top_wi.setObjectName('top')
        self.top_wi.resize(self.xr * 930, self.yr * 95)
        self.logo_la.setObjectName('logo')
        self.logo_la.resize(self.xr * 65, self.zr * 65)
        self.logo_la.move(self.xr * 29, self.yr * 16)
        self.manual_but.setObjectName('box')
        self.manual_but.resize(self.xr * 180, self.yr * 320)
        self.manual_but.move(self.xr * 112, self.yr * 194)
        self.manual_but.setText(change_vertical('战局搜索'))
        self.manual_but.setStyleSheet(
            'border-radius:{}px;font-size:{}px;'.format(
                self.zr * 20, int(self.zr * 30)))
        self.manual_but.setGraphicsEffect(effect1)
        self.manual_but.clicked.connect(self.search_press)
        # self.manual_tex.setObjectName('manual_tex')
        # self.manual_tex.resize(self.xr * 34, self.yr * 413)
        # self.manual_tex.move(self.xr * 68, self.yr * 152)
        # self.manual_tex.setText(change_vertical('是当一辈子的懦夫,还是三十秒的勇士?'))
        # self.manual_tex.setStyleSheet('font-size:{}px;'.format(int(self.zr * 17)))
        self.auto_but.setObjectName('box')
        self.auto_but.resize(self.xr * 180, self.yr * 320)
        self.auto_but.move(self.xr * 381, self.yr * 194)
        self.auto_but.setText(change_vertical('自动场'))
        self.auto_but.setStyleSheet(
            'border-radius:{}px;font-size:{}px;'.format(
                self.zr * 20, int(self.zr * 30)))
        self.auto_but.setGraphicsEffect(effect2)
        self.auto_but.clicked.connect(self.auto_press)
        # self.auto_tex.setObjectName('auto_tex')
        # self.auto_tex.resize(self.xr * 34, self.yr * 413)
        # self.auto_tex.move(self.xr * 340, self.yr * 152)
        # self.auto_tex.setText(change_vertical('机器就要由机器来终结'))
        # self.auto_tex.setStyleSheet('font-size:{}px;'.format(int(self.zr * 17)))
        self.home_but.setObjectName('box')
        self.home_but.resize(self.xr * 180, self.yr * 320)
        self.home_but.move(self.xr * 660, self.yr * 194)
        self.home_but.setText(change_vertical('沙之家'))
        self.home_but.setStyleSheet(
            'border-radius:{}px;font-size:{}px;'.format(
                self.zr * 20, int(self.zr * 30)))
        self.home_but.setGraphicsEffect(effect3)
        self.home_but.clicked.connect(self.home_press)
        # self.home_tex.setObjectName('home_tex')
        # self.home_tex.resize(self.xr * 34, self.yr * 413)
        # self.home_tex.move(self.xr * 610, self.yr * 152)
        # self.home_tex.setText(change_vertical('常回家看看!'))
        # self.home_tex.setStyleSheet('font-size:{}px;'.format(int(self.zr * 17)))
        self.loading.setObjectName('load')
        self.loading.resize(self.xr * 150, self.yr * 150)
        self.loading.move(self.xr * 760, self.yr * 500)
        self.loading.setScaledContents(True)
        self.loading.setMovie(self.gif)
        self.gif.start()

    def auto_press(self):
        res = play(self.token)
        if res["status"] == 0:
            self.auto_pressed_sg.emit(res)

    def home_press(self):
        self.home_pressed_sg.emit()

    def search_press(self):
        self.search_pressed_sg.emit()

    def get_token(self, t):
        self.token = t
    def get_settings_widget(self):
        """
        Return the alignak settings QWidget

        :return: settings QWidget
        :rtype: QWidget
        """

        server_widget = QWidget()
        server_widget.setObjectName('dialog')
        server_layout = QVBoxLayout(server_widget)

        # Title
        title_lbl = QLabel(_('Alignak Backend'))
        title_lbl.setObjectName('itemtitle')
        server_layout.addWidget(title_lbl)
        server_layout.setAlignment(title_lbl, Qt.AlignTop)

        # Description
        desc_label = QLabel(
            _('Here you can define alignak settings. Be sure to enter a valid address.')
        )
        desc_label.setWordWrap(True)
        server_layout.addWidget(desc_label)

        # Server URL
        server_lbl = QLabel(_('Server'))
        server_layout.addWidget(server_lbl)

        self.server_url.setText(settings.get_config('Alignak', 'url'))
        self.server_url.setPlaceholderText(_('alignak backend url...'))
        self.server_url.setFixedHeight(25)
        server_layout.addWidget(self.server_url)

        # Server Port
        port_lbl = QLabel(_('Port'))
        server_layout.addWidget(port_lbl)

        cur_port = settings.get_config('Alignak', 'backend').split(':')[2]
        self.server_port.setText(cur_port)
        self.server_port.setPlaceholderText(_('alignak backend port...'))
        self.server_port.setFixedHeight(25)
        server_layout.addWidget(self.server_port)

        # Server Processes (displayed only for Unix platforms)
        if 'win32' not in sys.platform:
            process_lbl = QLabel(_('Processes'))
            server_layout.addWidget(process_lbl)

            cur_proc = settings.get_config('Alignak', 'processes')
            self.server_proc.setText(cur_proc)
            self.server_proc.setPlaceholderText(_('alignak backend processes...'))
            self.server_proc.setFixedHeight(25)
            server_layout.addWidget(self.server_proc)

        # Web Service description
        server_layout.addStretch(1)
        webservice_lbl = QLabel(_('Web Service'))
        webservice_lbl.setObjectName('itemtitle')
        server_layout.addWidget(webservice_lbl)
        ws_desc_lbl = QLabel(
            _('Here you can define your alignak web service url, with port if needed')
        )
        ws_desc_lbl.setWordWrap(True)
        server_layout.addWidget(ws_desc_lbl)

        # Web Service URL
        self.webservice_url.setText(settings.get_config('Alignak', 'webservice'))
        self.webservice_url.setPlaceholderText(_('alignak webservice url...'))
        self.webservice_url.setFixedHeight(25)
        server_layout.addWidget(self.webservice_url)

        # Valid Button
        valid_btn = QPushButton(_('Valid'))
        valid_btn.setObjectName('valid')
        valid_btn.setMinimumHeight(30)
        valid_btn.clicked.connect(self.accept)

        server_layout.addWidget(valid_btn)

        return server_widget
예제 #18
0
    def initialize(self, item_type, item_name, comment):  # pylint: disable=too-many-locals
        """
        Initialize Downtime QDialog

        :param item_type: type of item to acknowledge : host | service
        :type item_type: str
        :param item_name: name of the item to acknowledge
        :type item_name: str
        :param comment: the default comment of action
        :type comment: str
        """

        logger.debug("Create Downtime QDialog...")

        # Main status_layout
        center_widget(self)
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)

        main_layout.addWidget(get_logo_widget(self, _('Request Downtime')))

        downtime_widget = QWidget()
        downtime_widget.setObjectName('dialog')
        downtime_layout = QGridLayout(downtime_widget)

        downtime_title = QLabel(_('Request a downtime'))
        downtime_title.setObjectName('itemtitle')
        downtime_layout.addWidget(downtime_title, 0, 0, 1, 3)

        host_label = QLabel('<b>%s:</b> %s' %
                            (item_type.capitalize(), item_name))
        downtime_layout.addWidget(host_label, 1, 0, 1, 1)

        options_label = QLabel(_('Downtime options:'))
        options_label.setObjectName('subtitle')
        downtime_layout.addWidget(options_label, 2, 0, 1, 1)

        self.fixed_toggle_btn.initialize()
        self.fixed_toggle_btn.update_btn_state(self.fixed)
        downtime_layout.addWidget(self.fixed_toggle_btn, 2, 1, 1, 1)

        fixed_label = QLabel(_('Fixed'))
        downtime_layout.addWidget(fixed_label, 2, 2, 1, 1)

        fixed_info = QLabel(
            _('If checked, downtime will start and end at the times specified'
              ' by the “start time” and “end time” fields.'))
        fixed_info.setWordWrap(True)
        downtime_layout.addWidget(fixed_info, 3, 0, 1, 3)

        duration_label = QLabel(_('Duration'))
        duration_label.setObjectName('subtitle')
        downtime_layout.addWidget(duration_label, 4, 0, 1, 1)

        duration_clock = QLabel()
        duration_clock.setPixmap(QPixmap(settings.get_image('time')))
        downtime_layout.addWidget(duration_clock, 4, 1, 1, 1)
        duration_clock.setFixedSize(16, 16)
        duration_clock.setScaledContents(True)

        self.duration.setTime(QTime(4, 00))
        self.duration.setDisplayFormat("HH'h'mm")
        downtime_layout.addWidget(self.duration, 4, 2, 1, 1)

        duration_info = QLabel(
            _('Sets the duration if it is a non-fixed downtime.'))
        downtime_layout.addWidget(duration_info, 5, 0, 1, 3)

        date_range_label = QLabel(_('Downtime date range'))
        date_range_label.setObjectName('subtitle')
        downtime_layout.addWidget(date_range_label, 6, 0, 1, 1)

        calendar_label = QLabel()
        calendar_label.setPixmap(QPixmap(settings.get_image('calendar')))
        calendar_label.setFixedSize(16, 16)
        calendar_label.setScaledContents(True)
        downtime_layout.addWidget(calendar_label, 6, 1, 1, 1)

        start_time_label = QLabel(_('Start time:'))
        downtime_layout.addWidget(start_time_label, 7, 0, 1, 1)

        self.start_time.setCalendarPopup(True)
        self.start_time.setDateTime(datetime.datetime.now())
        self.start_time.setDisplayFormat("dd/MM/yyyy HH'h'mm")
        downtime_layout.addWidget(self.start_time, 7, 1, 1, 2)

        end_time_label = QLabel(_('End time:'))
        downtime_layout.addWidget(end_time_label, 8, 0, 1, 1)

        self.end_time.setCalendarPopup(True)
        self.end_time.setDateTime(datetime.datetime.now() +
                                  datetime.timedelta(hours=2))
        self.end_time.setDisplayFormat("dd/MM/yyyy HH'h'mm")
        downtime_layout.addWidget(self.end_time, 8, 1, 1, 2)

        self.comment_edit.setText(comment)
        self.comment_edit.setMaximumHeight(60)
        downtime_layout.addWidget(self.comment_edit, 9, 0, 1, 3)

        request_btn = QPushButton(_('REQUEST DOWNTIME'), self)
        request_btn.clicked.connect(self.handle_accept)
        request_btn.setObjectName('valid')
        request_btn.setMinimumHeight(30)
        request_btn.setDefault(True)
        downtime_layout.addWidget(request_btn, 10, 0, 1, 3)

        main_layout.addWidget(downtime_widget)
예제 #19
0
    def initialize(self, item_type, item_name, comment):  # pylint: disable=too-many-locals
        """
        Initialize Acknowledge QDialog

        :param item_type: type of item to acknowledge : host | service
        :type item_type: str
        :param item_name: name of the item to acknowledge
        :type item_name: str
        :param comment: the default comment of action
        :type comment: str
        """

        logger.debug("Create Acknowledge QDialog...")

        # Main status_layout
        center_widget(self)
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)

        main_layout.addWidget(get_logo_widget(self, _('Request Acknowledge')))

        ack_widget = QWidget()
        ack_widget.setObjectName('dialog')
        ack_layout = QGridLayout(ack_widget)

        ack_title = QLabel(_('Request an acknowledge'))
        ack_title.setObjectName('itemtitle')
        ack_layout.addWidget(ack_title, 0, 0, 1, 2)

        host_label = QLabel('<b>%s:</b> %s' %
                            (item_type.capitalize(), item_name))
        ack_layout.addWidget(host_label, 1, 0, 1, 1)

        sticky_label = QLabel(_('Acknowledge is sticky:'))
        sticky_label.setObjectName('subtitle')
        ack_layout.addWidget(sticky_label, 2, 0, 1, 1)

        self.sticky_toggle_btn.initialize()
        self.sticky_toggle_btn.update_btn_state(self.sticky)
        ack_layout.addWidget(self.sticky_toggle_btn, 2, 1, 1, 1)

        sticky_info = QLabel(
            _('If checked, '
              'the acknowledge will remain until the element returns to an "OK" state.'
              ))
        sticky_info.setWordWrap(True)
        ack_layout.addWidget(sticky_info, 3, 0, 1, 2)

        notify_label = QLabel(_('Acknowledge notifies:'))
        notify_label.setObjectName('subtitle')
        ack_layout.addWidget(notify_label, 4, 0, 1, 1)

        self.notify_toggle_btn.initialize()
        self.notify_toggle_btn.update_btn_state(self.notify)
        ack_layout.addWidget(self.notify_toggle_btn, 4, 1, 1, 1)

        notify_info = QLabel(
            _('If checked, a notification will be sent out to the concerned contacts.'
              ))
        notify_info.setWordWrap(True)
        ack_layout.addWidget(notify_info, 5, 0, 1, 2)

        ack_comment = QLabel(_('Acknowledge comment:'))
        ack_comment.setObjectName('subtitle')
        ack_layout.addWidget(ack_comment, 6, 0, 1, 1)

        self.ack_comment_edit = QTextEdit()
        self.ack_comment_edit.setText(comment)
        self.ack_comment_edit.setMaximumHeight(60)
        ack_layout.addWidget(self.ack_comment_edit, 7, 0, 1, 2)

        request_btn = QPushButton(_('REQUEST ACKNOWLEDGE'), self)
        request_btn.clicked.connect(self.accept)
        request_btn.setObjectName('valid')
        request_btn.setMinimumHeight(30)
        request_btn.setDefault(True)
        ack_layout.addWidget(request_btn, 8, 0, 1, 2)

        main_layout.addWidget(ack_widget)
예제 #20
0
class ResultSingle(QWidget):
    result_exit_sg = pyqtSignal()

    def __init__(self, parent=None):
        super(ResultSingle, self).__init__(parent)
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.h = self.screenRect.height()
        self.w = self.screenRect.width()
        self.xr = self.w / 930
        self.yr = self.h / 640
        self.zr = min(self.xr, self.yr)
        self.back1_wi = QWidget(self)
        self.resexit_but = QPushButton(self)
        self.id_head = QLabel(self.back1_wi)
        self.role1 = QWidget(self.back1_wi)
        self.role1_detail = QWidget(self.role1)
        self.role4 = QWidget(self.back1_wi)
        self.role4_detail = QWidget(self.role4)
        self.role4_special = QLabel(self.role4)
        self.set_ui()
        with open('result.qss', 'r') as f:
            self.setStyleSheet(f.read())

    def set_ui(self):
        self.setWindowTitle('Result')
        self.setObjectName('result')
        self.resize(self.w, self.h)
        effect = QGraphicsDropShadowEffect()
        effect.setOffset(10, 10)
        effect.setColor(QColor(0, 0, 0, 80))
        effect.setBlurRadius(20)
        self.back1_wi.setObjectName('back')
        self.back1_wi.resize(self.xr * 793, self.yr * 534)
        self.back1_wi.move(self.xr * 69, self.yr * 53)
        self.back1_wi.setGraphicsEffect(effect)
        back_x = 69
        back_y = 53
        effect1 = QGraphicsDropShadowEffect()
        effect1.setOffset(10, 10)
        effect1.setColor(QColor(0, 0, 0, 80))
        effect1.setBlurRadius(20)
        effect4 = QGraphicsDropShadowEffect()
        effect4.setOffset(10, 10)
        effect4.setColor(QColor(0, 0, 0, 80))
        effect4.setBlurRadius(20)
        self.resexit_but.setObjectName('resexit')
        self.resexit_but.resize(self.zr * 38, self.zr * 38)
        self.resexit_but.move(self.xr * 834, self.yr * 36)
        self.resexit_but.clicked.connect(self.result_exit)
        self.resexit_but.setStyleSheet('border-radius:{}px;'.format(self.zr * 18))
        self.id_head.setObjectName('id_head')
        self.id_head.resize(self.xr * 350, self.yr * 140)
        self.id_head.move(self.xr * 225, self.yr * 195)
        # self.id_head.setText('战局ID:4396')
        self.id_head.setAlignment(Qt.AlignCenter)
        self.id_head.setStyleSheet('font-size:{}px;'.format(int(self.zr * 50)))
        self.role1.setObjectName('role')
        self.role1.resize(self.xr * 716, self.yr * 87)
        self.role1.move(self.xr * (108 - back_x), self.yr * (77 - back_y))
        self.role1.setGraphicsEffect(effect1)
        # self.role1_head.setText('test')
        self.role1_detail.setObjectName('role_detail')
        self.role1_detail.resize(self.xr * 606, self.yr * 87)
        self.role1_detail.move(self.xr * 110, self.yr * 0)
        self.role4.setObjectName('role')
        self.role4.resize(self.xr * 716, self.yr * 87)
        self.role4.move(self.xr * (108 - back_x), self.yr * (467 - back_y))
        self.role4.setGraphicsEffect(effect4)
        self.role4_detail.setObjectName('role_detail')
        self.role4_detail.resize(self.xr * 606, self.yr * 87)
        self.role4_detail.move(self.xr * 110, self.yr * 0)
        self.role4_special.setObjectName('role_special')
        self.role4_special.resize(self.xr * 88, self.yr * 36)
        self.role4_special.move(self.xr * 70, self.yr * 26)
        self.role4_special.setAlignment(Qt.AlignCenter)
        for i in range(1, 14):
            if i >= 9:
                xp = 416
                t = 9
            elif i >= 4:
                xp = 239
                t = 4
            else:
                xp = 108
                t = 1
            if i == 3 or i == 8 or i == 13:
                exec('self.role4_lv{}=QLabel(self.role4_detail)'.format(i))
                exec('self.role4_lv{}.resize(self.xr*46,self.yr*67)'.format(i))
                exec('self.role4_lv{}.move(self.xr*(xp+({}-t)*20)+90,self.yr*10)'.format(i, i))
                exec('self.role4_lv{}.setStyleSheet("font-size:{}px;")'.format(i, int(self.zr * 17)))
                # exec('self.role4_lv{}.setText(change_vertical(" 葫芦"))'.format(i))
                exec('self.role4_lv{}.setAlignment(Qt.AlignCenter)'.format(i))
            exec('self.role1_card{}=QLabel(self.role1_detail)'.format(i))
            exec('self.role1_card{}.setObjectName("card")'.format(i))
            exec('self.role1_card{}.resize(self.xr*46,self.yr*67)'.format(i))
            exec('self.role1_card{}.move(self.xr*i*33,self.yr*10)'.format(i))
            exec('self.role1_card{}.setScaledContents(True)'.format(i))
            exec('self.role4_card{}=QLabel(self.role4_detail)'.format(i))
            exec('self.role4_card{}.setObjectName("card")'.format(i))
            exec('self.role4_card{}.resize(self.xr*46,self.yr*67)'.format(i))
            exec('self.role4_card{}.move(self.xr*(xp+({}-t)*20),self.yr*10)'.format(i, i))
            exec('self.role4_card{}.setScaledContents(True)'.format(i))
        self.back1_wi.setStyleSheet(
            '#back{border-radius:' + str(self.zr * 25) + 'px;}#role{border-radius:' + str(
                self.zr * 18) + 'px;}#role_head{border-radius:' + str(self.zr * 15) + 'px;font-size:' + str(
                int(self.zr * 16)) + 'px;}#role_special{font-size:' + str(int(self.zr * 18)) + 'px;}')

    def result_exit(self):
        self.result_exit_sg.emit()

    def set_role(self, info):
        self.id_head.setText('战局ID:{}'.format(info['id']))
        self.role4_special.setText('{}'.format('散牌'))
        i = 1
        for card in info['origin_cards']:
            exec('self.role1_card{}.setPixmap(QPixmap("./resource/image/{}.jpg"))'.format(i, card))
            i += 1
        t = 3
        j = 1
        for de in info['cards']:
            exec('self.role4_lv{}.setText("{}")'.format(t, de['lv']))
            for card in de["card"]:
                exec('self.role4_card{}.setPixmap(QPixmap("./resource/image/{}.jpg"))'.format(j, card))
                j += 1
            t += 5
    def initialize(self):
        """
        Initialize QDialog

        """

        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_layout)

        about_widget = QWidget()
        about_widget.setObjectName('about')
        about_layout = QVBoxLayout(about_widget)

        # QDialog Title
        about_title = QLabel(_('About'))
        about_title.setFixedHeight(40)
        about_title.setObjectName('aboutheader')
        main_layout.addWidget(about_title)

        # Main About
        about_text = "%s\nVersion %s\nCopyright: %s" % \
            (__application__, __version__, __copyright__)
        main_about = QLabel(about_text)
        main_about.setObjectName('aboutmain')
        main_about.setToolTip(__application__)
        about_layout.addWidget(main_about)
        about_layout.setAlignment(main_about, Qt.AlignCenter)

        # Release notes
        release_data = QLabel(__releasenotes__)
        release_data.setObjectName('about')
        release_data.setToolTip(_('Release notes'))
        release_data.setWordWrap(True)
        about_layout.addWidget(release_data)

        # Homepage
        home_title = QLabel(_('Home page:'))
        home_title.setObjectName('abouttitle')
        home_title.setToolTip(_('Home page'))
        about_layout.addWidget(home_title)
        about_layout.addWidget(self.get_external_link_label(__project_url__))

        # User Doc
        doc_title = QLabel(_('User documentation'))
        doc_title.setObjectName('abouttitle')
        doc_title.setToolTip(_('User documentation'))
        about_layout.addWidget(doc_title)
        about_layout.addWidget(self.get_external_link_label(__doc_url__))

        # Alignak
        alignak_title = QLabel(_('About Alignak solution:'))
        alignak_title.setObjectName('abouttitle')
        alignak_title.setToolTip(_('About Alignak solution'))
        about_layout.addWidget(alignak_title)
        about_layout.addWidget(self.get_external_link_label(__alignak_url__))

        # Powered
        powered_title = QLabel(_('Powered by:'))
        powered_title.setObjectName('abouttitle')
        powered_title.setToolTip(_('PyQt5'))
        about_layout.addWidget(powered_title)
        powered_data = self.get_external_link_label('https://www.riverbankcomputing.com/', 'PyQt5')
        about_layout.addWidget(powered_data)

        main_layout.addWidget(about_widget)
    def get_notifications_widget(self, item_type, options):
        """
        Create QWidget with options and their icons

        :param item_type: define item type for options: host or service
        :type item_type: str
        :param options: list of notification options
        :type options: list
        :return: QWidget with options and icons
        :rtype: QWidget
        """

        options_widget = QWidget()
        options_widget.setObjectName('dialog')
        options_layout = QGridLayout(options_widget)

        options_title = QLabel(_("Options:"))
        options_title.setObjectName("itemtitle")
        options_layout.addWidget(options_title, 0, 0, 1, 2)
        options_layout.setAlignment(options_title, Qt.AlignCenter)

        # Get current options and QLabels
        item_options = list(options_values[item_type])
        options_labels = {}
        for option in item_options:
            options_labels[option] = QLabel()

        line = 1
        while item_options:
            if line == 2:
                alert_lbl = QLabel('Alerts:')
                alert_lbl.setObjectName('subtitle')
                options_layout.addWidget(alert_lbl, line, 0, 1, 2)
                line += 1
            else:
                # Current option
                opt = item_options.pop(0)

                # Title
                object_name = ''
                if opt not in ['n', 's', 'f']:
                    object_name = 'offset'
                object_name += 'option' + str(
                    self.get_selected_options(item_type, options)[opt])
                self.titles_labels[item_type][opt].setObjectName(object_name)
                options_layout.addWidget(self.titles_labels[item_type][opt],
                                         line, 0, 1, 1)

                # Icon
                options_labels[opt].setPixmap(
                    get_icon_pixmap(
                        self.get_selected_options(item_type, options)[opt],
                        ['checked', 'error']))
                options_labels[opt].setFixedSize(14, 14)
                options_labels[opt].setScaledContents(True)
                options_layout.addWidget(options_labels[opt], line, 1, 1, 1)
                line += 1

        # Login button
        accept_btn = QPushButton(_('OK'), self)
        accept_btn.clicked.connect(self.accept)
        accept_btn.setObjectName('ok')
        accept_btn.setMinimumHeight(30)
        options_layout.addWidget(accept_btn, line, 0, 1, 2)

        return options_widget
예제 #23
0
    def __init__(self, parent = None):
        super(MainWidget, self).__init__(parent)

        # member variables
        self._lTheorySpd = 0
        self._rTheorySpd = 0
        self._serialSend = SerialSend()

        # mainWindow properties
        self.setObjectName('MainWidget')
        self.setWindowIcon(QIcon(':/image/default/app.icon'))
        self.setWindowTitle('%s V%s' % (
                            qApp.applicationDisplayName(),
                            qApp.applicationVersion()))
        self.resize(800, 480)

        # mainWindow layout

        # top

        self.groupBoxTop = QGroupBox(self)
        self.groupBoxTop.setObjectName('groupBoxTop')

        # command dashboard
        buttonLeftPower = JSwitchButton(parent = self.groupBoxTop)
        buttonRightPower = JSwitchButton(parent = self.groupBoxTop)
        buttonSettings = QPushButton(self.groupBoxTop)
        buttonHistory = QPushButton(self.groupBoxTop)
        buttonQuit = QPushButton(self.groupBoxTop)

        buttonLeftPower.setObjectName('buttonLeftPower')
        buttonRightPower.setObjectName('buttonRightPower')
        buttonSettings.setObjectName('buttonSettings')
        buttonHistory.setObjectName('buttonHistory')
        buttonQuit.setObjectName('buttonQuit')

        areaPortState = QWidget(self)
        areaPortState.setObjectName('areaPortState')
        areaPortState.setStyleSheet('QWidget#areaPortState{border-radius:3px;'
                                    'border:1px solid #505050;'
                                    'background-color:rgba(64,64,64,50);}')
        vertLayoutPortState = QVBoxLayout(areaPortState)
        vertLayoutPortState.setContentsMargins(50, 2, 50, 2)
        vertLayoutPortState.setSpacing(3)

        buttonPortState = JSwitchButton(pixmap = QPixmap(':/carmonitor/image/button-port-state.png'), parent = areaPortState)
        buttonPortState.setObjectName('buttonPortState')
        vertLayoutPortState.addWidget(QLabel('串口', areaPortState), 0, Qt.AlignHCenter)
        vertLayoutPortState.addWidget(buttonPortState)

        #
        horiLayoutTop = QHBoxLayout(self.groupBoxTop)
        horiLayoutTop.setContentsMargins(0, 0, 0, 0)
        horiLayoutTop.addSpacing(25)
        horiLayoutTop.addWidget(buttonSettings, 0, Qt.AlignLeft)
        horiLayoutTop.addSpacing(20)
        horiLayoutTop.addWidget(buttonHistory, 0, Qt.AlignLeft)
        horiLayoutTop.addSpacing(65)
        horiLayoutTop.addWidget(buttonLeftPower)
        horiLayoutTop.addWidget(QLabel('左电源开关', self.groupBoxTop))
        horiLayoutTop.addStretch()
        horiLayoutTop.addWidget(areaPortState, 0, Qt.AlignTop)
        horiLayoutTop.addStretch()
        horiLayoutTop.addWidget(QLabel('右电源开关', self.groupBoxTop))
        horiLayoutTop.addWidget(buttonRightPower)
        horiLayoutTop.addSpacing(150)
        horiLayoutTop.addWidget(buttonQuit, 0, Qt.AlignRight)
        horiLayoutTop.addSpacing(25)

        # middle

        # curves
        self.curveLBP = CurveWidget(title = '左刹车压力(MPa)', parent = self)
        self.curveLRP = CurveWidget(title = '左转速(r/min)', parent = self)
        self.curveRBP = CurveWidget(title = '右刹车压力(MPa)', parent = self)
        self.curveRRP = CurveWidget(title = '右转速(r/min)', parent = self)

        self.curveLBP.setObjectName('curveLBP')
        self.curveLRP.setObjectName('curveLRP')
        self.curveRBP.setObjectName('curveRBP')
        self.curveRRP.setObjectName('curveRRP')

        # self.curveLBP.setAxisScale(QwtPlot.yLeft, 0, 30, 5)

        # areaMiddle
        self.areaMiddle = QWidget(self)
        self.areaMiddle.setObjectName('areaMiddle')
        self.areaMiddle.setFixedWidth(280)

        #
        groupBoxStatus = QGroupBox(self)
        groupBoxStatus.setObjectName('groupBoxStatus')

        # status-view
        gridLayoutStatus = QGridLayout(groupBoxStatus)
        gridLayoutStatus.setContentsMargins(5, 5, 5, 5)
        gridLayoutStatus.setHorizontalSpacing(8)
        gridLayoutStatus.setVerticalSpacing(3)

        # Brake-Command
        editLeftBrakeCmd = QLineEdit(groupBoxStatus)
        editRightBrakeCmd = QLineEdit(groupBoxStatus)
        editLeftBrakeCmd.setObjectName('editLeftBrakeCmd')
        editRightBrakeCmd.setObjectName('editRightBrakeCmd')
        editLeftBrakeCmd.setReadOnly(True)
        editRightBrakeCmd.setReadOnly(True)
        gridLayoutStatus.addWidget(QLabel('刹车指令:', groupBoxStatus),
                                   0, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(editLeftBrakeCmd, 1, 0, 1, 1)
        gridLayoutStatus.addWidget(editRightBrakeCmd, 1, 1, 1, 1)

        # Major Brake Pressure
        self.editMLeftBrakeP = QLineEdit(groupBoxStatus)
        self.editMRightBrakeP = QLineEdit(groupBoxStatus)
        self.editMLeftBrakeP.setObjectName('editMLeftBrakeP')
        self.editMRightBrakeP.setObjectName('editMRightBrakeP')
        self.editMLeftBrakeP.setReadOnly(True)
        self.editMRightBrakeP.setReadOnly(True)
        gridLayoutStatus.addWidget(QLabel('主刹车压力:', groupBoxStatus),
                                   2, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(self.editMLeftBrakeP, 3, 0, 1, 1)
        gridLayoutStatus.addWidget(self.editMRightBrakeP, 3, 1, 1, 1)

        # Assistant Brake Pressure
        self.editALeftBrakeP = QLineEdit(groupBoxStatus)
        self.editARightBrakeP = QLineEdit(groupBoxStatus)
        self.editALeftBrakeP.setObjectName('editALeftBrakeP')
        self.editARightBrakeP.setObjectName('editARightBrakeP')
        self.editALeftBrakeP.setReadOnly(True)
        self.editARightBrakeP.setReadOnly(True)
        gridLayoutStatus.addWidget(QLabel('副刹车压力:', groupBoxStatus),
                                   4, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(self.editALeftBrakeP, 5, 0, 1, 1)
        gridLayoutStatus.addWidget(self.editARightBrakeP, 5, 1, 1, 1)

        # Rotation Rate
        self.editLeftRotateRate = QLineEdit(groupBoxStatus)
        self.editRightRotateRate = QLineEdit(groupBoxStatus)
        self.editLeftRotateRate.setObjectName('editLeftRotateRate')
        self.editRightRotateRate.setObjectName('editRightRotateRate')
        gridLayoutStatus.addWidget(QLabel('实际转速:', groupBoxStatus),
                                   6, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(self.editLeftRotateRate, 7, 0, 1, 1)
        gridLayoutStatus.addWidget(self.editRightRotateRate, 7, 1, 1, 1)

        # Theory Rotation Rate
        self.editTheoryLeftRotateRate = QLineEdit(groupBoxStatus)
        self.editTheoryRightRotateRate = QLineEdit(groupBoxStatus)
        self.editTheoryLeftRotateRate.setObjectName('editTheoryLeftRotateRate')
        self.editTheoryRightRotateRate.setObjectName('editTheoryRightRotateRate')
        gridLayoutStatus.addWidget(QLabel('理论转速:', groupBoxStatus),
                                   8, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(self.editTheoryLeftRotateRate, 9, 0, 1, 1)
        gridLayoutStatus.addWidget(self.editTheoryRightRotateRate, 9, 1, 1, 1)

        #
        groupBoxCtrl = QGroupBox(self)
        groupBoxCtrl.setObjectName('groupBoxCtrl')

        # status-view
        gridLayoutCtrl = QGridLayout(groupBoxCtrl)
        gridLayoutCtrl.setContentsMargins(5, 5, 5, 5)
        gridLayoutCtrl.setSpacing(20)

        # left-button
        buttonLeftDashboard = JDashButton('左指令旋钮', groupBoxCtrl)
        buttonLeftSpeedGain = JDashButton('左转速增益', groupBoxCtrl)
        buttonLeftSpeedKnob = JDashButton('左转速增益', groupBoxCtrl)
        buttonLeftTracksip = JTracksipButton(parent = groupBoxCtrl)
        buttonLeftDashboard.setObjectName('buttonLeftDashboard')
        buttonLeftSpeedGain.setObjectName('buttonLeftSpeedGain')
        buttonLeftSpeedKnob.setObjectName('buttonLeftSpeedKnob')
        buttonLeftTracksip.setObjectName('buttonLeftTracksip')
        buttonLeftTracksip.setFixedSize(110, 45)

        # right-button
        buttonRightDashboard = JDashButton('右指令旋钮', groupBoxCtrl)
        buttonRightSpeedGain = JDashButton('右转速增益', groupBoxCtrl)
        buttonRightSpeedKnob = JDashButton('右转速增益', groupBoxCtrl)
        buttonRightTracksip = JTracksipButton(parent = groupBoxCtrl)
        buttonRightDashboard.setObjectName('buttonRightDashboard')
        buttonRightSpeedGain.setObjectName('buttonRightSpeedGain')
        buttonRightSpeedKnob.setObjectName('buttonRightSpeedKnob')
        buttonRightTracksip.setObjectName('buttonRightTracksip')
        buttonRightTracksip.setFixedSize(110, 45)

        horiLayoutTracksip = QHBoxLayout()
        horiLayoutTracksip.setContentsMargins(0, 0, 0, 0)
        horiLayoutTracksip.setSpacing(5)
        horiLayoutTracksip.addWidget(buttonLeftTracksip)
        horiLayoutTracksip.addWidget(QLabel('打滑', self), 0, Qt.AlignHCenter)
        horiLayoutTracksip.addWidget(buttonRightTracksip)
        gridLayoutCtrl.addLayout(horiLayoutTracksip, 0, 0, 1, 2)

        horiLayoutDashboard = QHBoxLayout()
        horiLayoutDashboard.setContentsMargins(0, 0, 0, 0)
        horiLayoutDashboard.setSpacing(5)
        horiLayoutDashboard.addWidget(buttonLeftDashboard)
        horiLayoutDashboard.addWidget(QLabel('    ', self), 0, Qt.AlignHCenter)
        horiLayoutDashboard.addWidget(buttonRightDashboard)
        gridLayoutCtrl.addLayout(horiLayoutDashboard, 1, 0, 1, 2)

        horiLayoutSpeedGain = QHBoxLayout()
        horiLayoutSpeedGain.setContentsMargins(0, 0, 0, 0)
        horiLayoutSpeedGain.setSpacing(5)
        horiLayoutSpeedGain.addWidget(buttonLeftSpeedGain)
        horiLayoutSpeedGain.addWidget(QLabel('(粗调)', self), 0, Qt.AlignHCenter)
        horiLayoutSpeedGain.addWidget(buttonRightSpeedGain)
        gridLayoutCtrl.addLayout(horiLayoutSpeedGain, 2, 0, 1, 2)


        horiLayoutSpeedKnob = QHBoxLayout()
        horiLayoutSpeedKnob.setContentsMargins(0, 0, 0, 0)
        horiLayoutSpeedKnob.setSpacing(5)
        horiLayoutSpeedKnob.addWidget(buttonLeftSpeedKnob)
        horiLayoutSpeedKnob.addWidget(QLabel('(细调)', self), 0, Qt.AlignHCenter)
        horiLayoutSpeedKnob.addWidget(buttonRightSpeedKnob)
        gridLayoutCtrl.addLayout(horiLayoutSpeedKnob, 3, 0, 1, 2)

        #
        vertLayoutMid = QVBoxLayout(self.areaMiddle)
        vertLayoutMid.setContentsMargins(0, 0, 0, 0)
        vertLayoutMid.setSpacing(0)
        vertLayoutMid.addWidget(groupBoxStatus)
        vertLayoutMid.addWidget(groupBoxCtrl)
        vertLayoutMid.addSpacing(20)

        #
        gridLayoutBottom = QGridLayout()
        gridLayoutBottom.setContentsMargins(0, 0, 0, 0)
        gridLayoutBottom.setSpacing(1)
        gridLayoutBottom.addWidget(self.curveLBP, 0, 0, 1, 1)
        gridLayoutBottom.addWidget(self.curveLRP, 1, 0, 1, 1)
        gridLayoutBottom.addWidget(self.areaMiddle, 0, 1, 2, 1)
        gridLayoutBottom.addWidget(self.curveRBP, 0, 2, 1, 1)
        gridLayoutBottom.addWidget(self.curveRRP, 1, 2, 1, 1)

        # main-layout
        vertLayoutMain = QVBoxLayout(self)
        vertLayoutMain.setContentsMargins(5, 5, 5, 5)
        vertLayoutMain.addWidget(self.groupBoxTop)
        vertLayoutMain.addLayout(gridLayoutBottom)

        # global properties
        qApp.setProperty('MainWidget', self)
        self._serialProxy = SerialPortProxy(self)
        self._serialProxy._serialSimulate = SerialSimulate(self._serialProxy)  #
        qApp.setProperty('SerialProxy', self._serialProxy)

        #
        buttonSettings.clicked.connect(self.onButtonSettingsClicked)
        buttonHistory.clicked.connect(self.onButtonHistoryClicked)
        buttonPortState.clicked.connect(self.onButtonPortStateClicked)
        buttonQuit.clicked.connect(self.onButtonQuitClicked)

        # curves
        self.curveLBP.doubleClicked.connect(self.onCurveDoubleClicked)
        self.curveLRP.doubleClicked.connect(self.onCurveDoubleClicked)
        self.curveRBP.doubleClicked.connect(self.onCurveDoubleClicked)
        self.curveRRP.doubleClicked.connect(self.onCurveDoubleClicked)

        # switch-power
        buttonLeftPower.stateChanged.connect(self.onButtonLeftPowerStateChanged)
        buttonRightPower.stateChanged.connect(self.onButtonRightPowerStateChanged)

        # switch-tracksip
        buttonLeftTracksip.stateChanged.connect(self.onButtonLeftTracksipStateChanged)
        buttonRightTracksip.stateChanged.connect(self.onButtonRightTracksipStateChanged)

        self._serialProxy.stateChanged.connect(self.onSerialStateChanged)
        self._serialProxy.serialPortError.connect(self.onSerialPortError)
        self._serialProxy.displayRespond.connect(self.onSerialDisplayRespond)

        #
        buttonLeftSpeedGain.clicked.connect(self.execSliderWidget)
        buttonLeftSpeedKnob.clicked.connect(self.execSliderWidget)
        buttonRightSpeedGain.clicked.connect(self.execSliderWidget)
        buttonRightSpeedKnob.clicked.connect(self.execSliderWidget)

        # final initialization

        self.editMLeftBrakeP.setText('0 MPa')
        self.editMRightBrakeP.setText('0 MPa')
        self.editALeftBrakeP.setText('0 MPa')
        self.editARightBrakeP.setText('0 MPa')

        self.editLeftRotateRate.setText('0 r/min')
        self.editRightRotateRate.setText('0 r/min')
        self.editTheoryLeftRotateRate.setText('0 r/min')
        self.editTheoryRightRotateRate.setText('0 r/min')

        #
        c_memset(self._serialSend, 0, ctypes.sizeof(self._serialSend))

        # SQL
        sqlName = applicationDirPath() \
            + '/../data/cm-' \
            + QDateTime.currentDateTime().toLocalTime().toString('yyyy-MM-dd-HH-mm-ss') \
            + '.db'
        if not DatabaseMgr().create(sqlName):
            assert(False)

        # start serialport
        self._serialProxy.start()

        #
        buttonLeftTracksip.setState(self._serialSend.ctrlWord.lTracksip)
        buttonRightTracksip.setState(self._serialSend.ctrlWord.lTracksip)
    def initialize(self):
        """
        Initialize QDialog

        """

        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_layout)

        about_widget = QWidget()
        about_widget.setObjectName('about')
        about_layout = QVBoxLayout(about_widget)

        # QDialog Title
        about_title = QLabel(_('About'))
        about_title.setFixedHeight(40)
        about_title.setObjectName('aboutheader')
        main_layout.addWidget(about_title)

        # Main About
        about_text = "%s\nVersion %s\nCopyright: %s" % \
            (__application__, __version__, __copyright__)
        main_about = QLabel(about_text)
        main_about.setObjectName('aboutmain')
        main_about.setToolTip(__application__)
        about_layout.addWidget(main_about)
        about_layout.setAlignment(main_about, Qt.AlignCenter)

        # Release notes
        release_data = QLabel(__releasenotes__)
        release_data.setObjectName('about')
        release_data.setToolTip(_('Release notes'))
        release_data.setWordWrap(True)
        about_layout.addWidget(release_data)

        # Homepage
        home_title = QLabel(_('Home page:'))
        home_title.setObjectName('abouttitle')
        home_title.setToolTip(_('Home page'))
        about_layout.addWidget(home_title)
        about_layout.addWidget(self.get_external_link_label(__project_url__))

        # User Doc
        doc_title = QLabel(_('User documentation'))
        doc_title.setObjectName('abouttitle')
        doc_title.setToolTip(_('User documentation'))
        about_layout.addWidget(doc_title)
        about_layout.addWidget(self.get_external_link_label(__doc_url__))

        # Alignak
        alignak_title = QLabel(_('About Alignak solution:'))
        alignak_title.setObjectName('abouttitle')
        alignak_title.setToolTip(_('About Alignak solution'))
        about_layout.addWidget(alignak_title)
        about_layout.addWidget(self.get_external_link_label(__alignak_url__))

        # Powered
        powered_title = QLabel(_('Powered by:'))
        powered_title.setObjectName('abouttitle')
        powered_title.setToolTip(_('PyQt5'))
        about_layout.addWidget(powered_title)
        powered_data = self.get_external_link_label(
            'https://www.riverbankcomputing.com/', 'PyQt5')
        about_layout.addWidget(powered_data)

        main_layout.addWidget(about_widget)
    def get_notifications_widget(self, item_type, options):
        """
        Create QWidget with options and their icons

        :param item_type: define item type for options: host or service
        :type item_type: str
        :param options: list of notification options
        :type options: list
        :return: QWidget with options and icons
        :rtype: QWidget
        """

        options_widget = QWidget()
        options_widget.setObjectName('dialog')
        options_layout = QGridLayout(options_widget)

        options_title = QLabel(_("Options:"))
        options_title.setObjectName("itemtitle")
        options_layout.addWidget(options_title, 0, 0, 1, 2)
        options_layout.setAlignment(options_title, Qt.AlignCenter)

        # Get current options and QLabels
        item_options = list(options_values[item_type])
        options_labels = {}
        for option in item_options:
            options_labels[option] = QLabel()

        line = 1
        while item_options:
            if line == 2:
                alert_lbl = QLabel('Alerts:')
                alert_lbl.setObjectName('subtitle')
                options_layout.addWidget(alert_lbl, line, 0, 1, 2)
                line += 1
            else:
                # Current option
                opt = item_options.pop(0)

                # Title
                object_name = ''
                if opt not in ['n', 's', 'f']:
                    object_name = 'offset'
                object_name += 'option' + str(self.get_selected_options(item_type, options)[opt])
                self.titles_labels[item_type][opt].setObjectName(object_name)
                options_layout.addWidget(self.titles_labels[item_type][opt], line, 0, 1, 1)

                # Icon
                options_labels[opt].setPixmap(get_icon_pixmap(
                    self.get_selected_options(item_type, options)[opt], ['checked', 'error']
                ))
                options_labels[opt].setFixedSize(14, 14)
                options_labels[opt].setScaledContents(True)
                options_layout.addWidget(options_labels[opt], line, 1, 1, 1)
                line += 1

        # Login button
        accept_btn = QPushButton(_('OK'), self)
        accept_btn.clicked.connect(self.accept)
        accept_btn.setObjectName('ok')
        accept_btn.setMinimumHeight(30)
        options_layout.addWidget(accept_btn, line, 0, 1, 2)

        return options_widget
예제 #26
0
class Index(QWidget):
    show_mainindex_sg = pyqtSignal(int, str)
    show_register_sg = pyqtSignal()

    def __init__(self, parent=None):
        super(Index, self).__init__(parent)
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.h = self.screenRect.height()
        self.w = self.screenRect.width()
        self.xr = self.w / 930
        self.yr = self.h / 640
        self.zr = min(self.xr, self.yr)
        self.top_wi = QWidget(self)
        self.logo_la = QLabel(self.top_wi)
        self.ind_wi = QWidget(self)
        self.login_but = QPushButton(self.ind_wi)
        self.joke_but = QPushButton(self.ind_wi)
        self.register_but = QPushButton(self.ind_wi)
        self.imp_la = QLabel(self.ind_wi)
        self.account_le = QLineEdit(self.ind_wi)
        self.psw_le = QLineEdit(self.ind_wi)
        self.loading = QLabel(self)
        self.gif = QMovie('./resource/image/load.gif')
        self.set_ui()
        with open('index.qss', 'r') as f:
            self.setStyleSheet(f.read())

    def set_ui(self):
        self.setWindowTitle('Login')
        self.setObjectName('index')
        self.resize(self.w, self.h)
        self.top_wi.setObjectName('top')
        self.top_wi.resize(930 * self.xr, 95 * self.yr)
        self.logo_la.setObjectName('logo')
        self.logo_la.resize(65 * self.xr, 65 * self.zr)
        self.logo_la.move(29 * self.xr, 16 * self.yr)
        effect = QGraphicsDropShadowEffect()
        effect.setOffset(10, 10)
        effect.setColor(QColor(0, 0, 0, 80))
        effect.setBlurRadius(20)
        self.ind_wi.setObjectName('login')
        self.ind_wi.resize(327 * self.xr, 388 * self.yr)
        self.ind_wi.move(300 * self.xr, 150 * self.yr)
        self.ind_wi.setGraphicsEffect(effect)
        self.joke_but.setObjectName('joke')
        self.joke_but.resize(130 * self.xr, 30 * self.yr)
        self.joke_but.move(76 * self.xr, 234 * self.yr)
        self.joke_but.setFlat(True)
        self.joke_but.setText('忘记密码?我也没办法')
        self.login_but.setObjectName('button')
        self.login_but.move(64 * self.xr, 260 * self.yr)
        self.login_but.resize(202 * self.xr, 45 * self.yr)
        self.login_but.setText('登陆')
        self.login_but.clicked.connect(self.login)
        self.register_but.setObjectName('button')
        self.register_but.move(64 * self.xr, 315 * self.yr)
        self.register_but.resize(202 * self.xr, 45 * self.yr)
        self.register_but.setText('注册')
        self.register_but.clicked.connect(self.show_register)
        self.imp_la.setObjectName('imp_label')
        self.imp_la.resize(100 * self.zr, 100 * self.zr)
        self.imp_la.move(115 * self.xr + 100 * (self.xr - self.zr) / 2, 15 * self.yr)
        self.imp_la.setStyleSheet('border-radius:{}px;'.format(self.zr * 49))
        self.account_le.setObjectName('input')
        self.account_le.setTextMargins(20, 0, 0, 0)
        self.account_le.resize(213 * self.xr, 45 * self.yr)
        self.account_le.move(59 * self.xr, 126 * self.yr)
        self.account_le.setPlaceholderText('账号')
        self.psw_le.setObjectName('input')
        self.psw_le.setTextMargins(20, 0, 0, 0)
        self.psw_le.resize(213 * self.xr, 45 * self.yr)
        self.psw_le.move(59 * self.xr, 181 * self.yr)
        self.psw_le.setPlaceholderText('密码')
        self.psw_le.setEchoMode(QLineEdit.Password)
        self.loading.setObjectName('load')
        self.loading.resize(self.xr * 150, self.yr * 150)
        self.loading.move(self.xr * 760, self.yr * 500)
        self.loading.setScaledContents(True)
        self.loading.setMovie(self.gif)
        self.gif.start()
        self.ind_wi.setStyleSheet('#input{border-radius:' + str(self.zr * 20) + 'px;}' + '#button{border-radius:' + str(
            self.zr * 20) + 'px;' + 'font-size:' + str(int(self.zr * 18)) + 'px;}')

    def login(self):
        account_p = self.account_le.text()
        psw_p = self.psw_le.text()
        dic = login(account_p, psw_p)
        if dic['status'] == 0:
            self.show_mainindex_sg.emit(dic['data']['user_id'], dic['data']['token'])
        elif dic['status'] == 1:
            self.account_le.clear()
            self.psw_le.clear()
            self.account_le.setStyleSheet('border:4px solid;border-color:red;')
            self.account_le.setPlaceholderText('网络超时')
        else:
            self.account_le.clear()
            self.psw_le.clear()
            self.account_le.setStyleSheet('border:4px solid;border-color:red;')
            self.account_le.setPlaceholderText('账号不存在或密码错误')

    def show_register(self):
        self.show_register_sg.emit()
예제 #27
0
class MainWidget(QWidget):
    '''
    class MainWidget
    '''
    def __init__(self, parent = None):
        super(MainWidget, self).__init__(parent)

        # member variables
        self._lTheorySpd = 0
        self._rTheorySpd = 0
        self._serialSend = SerialSend()

        # mainWindow properties
        self.setObjectName('MainWidget')
        self.setWindowIcon(QIcon(':/image/default/app.icon'))
        self.setWindowTitle('%s V%s' % (
                            qApp.applicationDisplayName(),
                            qApp.applicationVersion()))
        self.resize(800, 480)

        # mainWindow layout

        # top

        self.groupBoxTop = QGroupBox(self)
        self.groupBoxTop.setObjectName('groupBoxTop')

        # command dashboard
        buttonLeftPower = JSwitchButton(parent = self.groupBoxTop)
        buttonRightPower = JSwitchButton(parent = self.groupBoxTop)
        buttonSettings = QPushButton(self.groupBoxTop)
        buttonHistory = QPushButton(self.groupBoxTop)
        buttonQuit = QPushButton(self.groupBoxTop)

        buttonLeftPower.setObjectName('buttonLeftPower')
        buttonRightPower.setObjectName('buttonRightPower')
        buttonSettings.setObjectName('buttonSettings')
        buttonHistory.setObjectName('buttonHistory')
        buttonQuit.setObjectName('buttonQuit')

        areaPortState = QWidget(self)
        areaPortState.setObjectName('areaPortState')
        areaPortState.setStyleSheet('QWidget#areaPortState{border-radius:3px;'
                                    'border:1px solid #505050;'
                                    'background-color:rgba(64,64,64,50);}')
        vertLayoutPortState = QVBoxLayout(areaPortState)
        vertLayoutPortState.setContentsMargins(50, 2, 50, 2)
        vertLayoutPortState.setSpacing(3)

        buttonPortState = JSwitchButton(pixmap = QPixmap(':/carmonitor/image/button-port-state.png'), parent = areaPortState)
        buttonPortState.setObjectName('buttonPortState')
        vertLayoutPortState.addWidget(QLabel('串口', areaPortState), 0, Qt.AlignHCenter)
        vertLayoutPortState.addWidget(buttonPortState)

        #
        horiLayoutTop = QHBoxLayout(self.groupBoxTop)
        horiLayoutTop.setContentsMargins(0, 0, 0, 0)
        horiLayoutTop.addSpacing(25)
        horiLayoutTop.addWidget(buttonSettings, 0, Qt.AlignLeft)
        horiLayoutTop.addSpacing(20)
        horiLayoutTop.addWidget(buttonHistory, 0, Qt.AlignLeft)
        horiLayoutTop.addSpacing(65)
        horiLayoutTop.addWidget(buttonLeftPower)
        horiLayoutTop.addWidget(QLabel('左电源开关', self.groupBoxTop))
        horiLayoutTop.addStretch()
        horiLayoutTop.addWidget(areaPortState, 0, Qt.AlignTop)
        horiLayoutTop.addStretch()
        horiLayoutTop.addWidget(QLabel('右电源开关', self.groupBoxTop))
        horiLayoutTop.addWidget(buttonRightPower)
        horiLayoutTop.addSpacing(150)
        horiLayoutTop.addWidget(buttonQuit, 0, Qt.AlignRight)
        horiLayoutTop.addSpacing(25)

        # middle

        # curves
        self.curveLBP = CurveWidget(title = '左刹车压力(MPa)', parent = self)
        self.curveLRP = CurveWidget(title = '左转速(r/min)', parent = self)
        self.curveRBP = CurveWidget(title = '右刹车压力(MPa)', parent = self)
        self.curveRRP = CurveWidget(title = '右转速(r/min)', parent = self)

        self.curveLBP.setObjectName('curveLBP')
        self.curveLRP.setObjectName('curveLRP')
        self.curveRBP.setObjectName('curveRBP')
        self.curveRRP.setObjectName('curveRRP')

        # self.curveLBP.setAxisScale(QwtPlot.yLeft, 0, 30, 5)

        # areaMiddle
        self.areaMiddle = QWidget(self)
        self.areaMiddle.setObjectName('areaMiddle')
        self.areaMiddle.setFixedWidth(280)

        #
        groupBoxStatus = QGroupBox(self)
        groupBoxStatus.setObjectName('groupBoxStatus')

        # status-view
        gridLayoutStatus = QGridLayout(groupBoxStatus)
        gridLayoutStatus.setContentsMargins(5, 5, 5, 5)
        gridLayoutStatus.setHorizontalSpacing(8)
        gridLayoutStatus.setVerticalSpacing(3)

        # Brake-Command
        editLeftBrakeCmd = QLineEdit(groupBoxStatus)
        editRightBrakeCmd = QLineEdit(groupBoxStatus)
        editLeftBrakeCmd.setObjectName('editLeftBrakeCmd')
        editRightBrakeCmd.setObjectName('editRightBrakeCmd')
        editLeftBrakeCmd.setReadOnly(True)
        editRightBrakeCmd.setReadOnly(True)
        gridLayoutStatus.addWidget(QLabel('刹车指令:', groupBoxStatus),
                                   0, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(editLeftBrakeCmd, 1, 0, 1, 1)
        gridLayoutStatus.addWidget(editRightBrakeCmd, 1, 1, 1, 1)

        # Major Brake Pressure
        self.editMLeftBrakeP = QLineEdit(groupBoxStatus)
        self.editMRightBrakeP = QLineEdit(groupBoxStatus)
        self.editMLeftBrakeP.setObjectName('editMLeftBrakeP')
        self.editMRightBrakeP.setObjectName('editMRightBrakeP')
        self.editMLeftBrakeP.setReadOnly(True)
        self.editMRightBrakeP.setReadOnly(True)
        gridLayoutStatus.addWidget(QLabel('主刹车压力:', groupBoxStatus),
                                   2, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(self.editMLeftBrakeP, 3, 0, 1, 1)
        gridLayoutStatus.addWidget(self.editMRightBrakeP, 3, 1, 1, 1)

        # Assistant Brake Pressure
        self.editALeftBrakeP = QLineEdit(groupBoxStatus)
        self.editARightBrakeP = QLineEdit(groupBoxStatus)
        self.editALeftBrakeP.setObjectName('editALeftBrakeP')
        self.editARightBrakeP.setObjectName('editARightBrakeP')
        self.editALeftBrakeP.setReadOnly(True)
        self.editARightBrakeP.setReadOnly(True)
        gridLayoutStatus.addWidget(QLabel('副刹车压力:', groupBoxStatus),
                                   4, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(self.editALeftBrakeP, 5, 0, 1, 1)
        gridLayoutStatus.addWidget(self.editARightBrakeP, 5, 1, 1, 1)

        # Rotation Rate
        self.editLeftRotateRate = QLineEdit(groupBoxStatus)
        self.editRightRotateRate = QLineEdit(groupBoxStatus)
        self.editLeftRotateRate.setObjectName('editLeftRotateRate')
        self.editRightRotateRate.setObjectName('editRightRotateRate')
        gridLayoutStatus.addWidget(QLabel('实际转速:', groupBoxStatus),
                                   6, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(self.editLeftRotateRate, 7, 0, 1, 1)
        gridLayoutStatus.addWidget(self.editRightRotateRate, 7, 1, 1, 1)

        # Theory Rotation Rate
        self.editTheoryLeftRotateRate = QLineEdit(groupBoxStatus)
        self.editTheoryRightRotateRate = QLineEdit(groupBoxStatus)
        self.editTheoryLeftRotateRate.setObjectName('editTheoryLeftRotateRate')
        self.editTheoryRightRotateRate.setObjectName('editTheoryRightRotateRate')
        gridLayoutStatus.addWidget(QLabel('理论转速:', groupBoxStatus),
                                   8, 0, 1, 2, Qt.AlignCenter)
        gridLayoutStatus.addWidget(self.editTheoryLeftRotateRate, 9, 0, 1, 1)
        gridLayoutStatus.addWidget(self.editTheoryRightRotateRate, 9, 1, 1, 1)

        #
        groupBoxCtrl = QGroupBox(self)
        groupBoxCtrl.setObjectName('groupBoxCtrl')

        # status-view
        gridLayoutCtrl = QGridLayout(groupBoxCtrl)
        gridLayoutCtrl.setContentsMargins(5, 5, 5, 5)
        gridLayoutCtrl.setSpacing(20)

        # left-button
        buttonLeftDashboard = JDashButton('左指令旋钮', groupBoxCtrl)
        buttonLeftSpeedGain = JDashButton('左转速增益', groupBoxCtrl)
        buttonLeftSpeedKnob = JDashButton('左转速增益', groupBoxCtrl)
        buttonLeftTracksip = JTracksipButton(parent = groupBoxCtrl)
        buttonLeftDashboard.setObjectName('buttonLeftDashboard')
        buttonLeftSpeedGain.setObjectName('buttonLeftSpeedGain')
        buttonLeftSpeedKnob.setObjectName('buttonLeftSpeedKnob')
        buttonLeftTracksip.setObjectName('buttonLeftTracksip')
        buttonLeftTracksip.setFixedSize(110, 45)

        # right-button
        buttonRightDashboard = JDashButton('右指令旋钮', groupBoxCtrl)
        buttonRightSpeedGain = JDashButton('右转速增益', groupBoxCtrl)
        buttonRightSpeedKnob = JDashButton('右转速增益', groupBoxCtrl)
        buttonRightTracksip = JTracksipButton(parent = groupBoxCtrl)
        buttonRightDashboard.setObjectName('buttonRightDashboard')
        buttonRightSpeedGain.setObjectName('buttonRightSpeedGain')
        buttonRightSpeedKnob.setObjectName('buttonRightSpeedKnob')
        buttonRightTracksip.setObjectName('buttonRightTracksip')
        buttonRightTracksip.setFixedSize(110, 45)

        horiLayoutTracksip = QHBoxLayout()
        horiLayoutTracksip.setContentsMargins(0, 0, 0, 0)
        horiLayoutTracksip.setSpacing(5)
        horiLayoutTracksip.addWidget(buttonLeftTracksip)
        horiLayoutTracksip.addWidget(QLabel('打滑', self), 0, Qt.AlignHCenter)
        horiLayoutTracksip.addWidget(buttonRightTracksip)
        gridLayoutCtrl.addLayout(horiLayoutTracksip, 0, 0, 1, 2)

        horiLayoutDashboard = QHBoxLayout()
        horiLayoutDashboard.setContentsMargins(0, 0, 0, 0)
        horiLayoutDashboard.setSpacing(5)
        horiLayoutDashboard.addWidget(buttonLeftDashboard)
        horiLayoutDashboard.addWidget(QLabel('    ', self), 0, Qt.AlignHCenter)
        horiLayoutDashboard.addWidget(buttonRightDashboard)
        gridLayoutCtrl.addLayout(horiLayoutDashboard, 1, 0, 1, 2)

        horiLayoutSpeedGain = QHBoxLayout()
        horiLayoutSpeedGain.setContentsMargins(0, 0, 0, 0)
        horiLayoutSpeedGain.setSpacing(5)
        horiLayoutSpeedGain.addWidget(buttonLeftSpeedGain)
        horiLayoutSpeedGain.addWidget(QLabel('(粗调)', self), 0, Qt.AlignHCenter)
        horiLayoutSpeedGain.addWidget(buttonRightSpeedGain)
        gridLayoutCtrl.addLayout(horiLayoutSpeedGain, 2, 0, 1, 2)


        horiLayoutSpeedKnob = QHBoxLayout()
        horiLayoutSpeedKnob.setContentsMargins(0, 0, 0, 0)
        horiLayoutSpeedKnob.setSpacing(5)
        horiLayoutSpeedKnob.addWidget(buttonLeftSpeedKnob)
        horiLayoutSpeedKnob.addWidget(QLabel('(细调)', self), 0, Qt.AlignHCenter)
        horiLayoutSpeedKnob.addWidget(buttonRightSpeedKnob)
        gridLayoutCtrl.addLayout(horiLayoutSpeedKnob, 3, 0, 1, 2)

        #
        vertLayoutMid = QVBoxLayout(self.areaMiddle)
        vertLayoutMid.setContentsMargins(0, 0, 0, 0)
        vertLayoutMid.setSpacing(0)
        vertLayoutMid.addWidget(groupBoxStatus)
        vertLayoutMid.addWidget(groupBoxCtrl)
        vertLayoutMid.addSpacing(20)

        #
        gridLayoutBottom = QGridLayout()
        gridLayoutBottom.setContentsMargins(0, 0, 0, 0)
        gridLayoutBottom.setSpacing(1)
        gridLayoutBottom.addWidget(self.curveLBP, 0, 0, 1, 1)
        gridLayoutBottom.addWidget(self.curveLRP, 1, 0, 1, 1)
        gridLayoutBottom.addWidget(self.areaMiddle, 0, 1, 2, 1)
        gridLayoutBottom.addWidget(self.curveRBP, 0, 2, 1, 1)
        gridLayoutBottom.addWidget(self.curveRRP, 1, 2, 1, 1)

        # main-layout
        vertLayoutMain = QVBoxLayout(self)
        vertLayoutMain.setContentsMargins(5, 5, 5, 5)
        vertLayoutMain.addWidget(self.groupBoxTop)
        vertLayoutMain.addLayout(gridLayoutBottom)

        # global properties
        qApp.setProperty('MainWidget', self)
        self._serialProxy = SerialPortProxy(self)
        self._serialProxy._serialSimulate = SerialSimulate(self._serialProxy)  #
        qApp.setProperty('SerialProxy', self._serialProxy)

        #
        buttonSettings.clicked.connect(self.onButtonSettingsClicked)
        buttonHistory.clicked.connect(self.onButtonHistoryClicked)
        buttonPortState.clicked.connect(self.onButtonPortStateClicked)
        buttonQuit.clicked.connect(self.onButtonQuitClicked)

        # curves
        self.curveLBP.doubleClicked.connect(self.onCurveDoubleClicked)
        self.curveLRP.doubleClicked.connect(self.onCurveDoubleClicked)
        self.curveRBP.doubleClicked.connect(self.onCurveDoubleClicked)
        self.curveRRP.doubleClicked.connect(self.onCurveDoubleClicked)

        # switch-power
        buttonLeftPower.stateChanged.connect(self.onButtonLeftPowerStateChanged)
        buttonRightPower.stateChanged.connect(self.onButtonRightPowerStateChanged)

        # switch-tracksip
        buttonLeftTracksip.stateChanged.connect(self.onButtonLeftTracksipStateChanged)
        buttonRightTracksip.stateChanged.connect(self.onButtonRightTracksipStateChanged)

        self._serialProxy.stateChanged.connect(self.onSerialStateChanged)
        self._serialProxy.serialPortError.connect(self.onSerialPortError)
        self._serialProxy.displayRespond.connect(self.onSerialDisplayRespond)

        #
        buttonLeftSpeedGain.clicked.connect(self.execSliderWidget)
        buttonLeftSpeedKnob.clicked.connect(self.execSliderWidget)
        buttonRightSpeedGain.clicked.connect(self.execSliderWidget)
        buttonRightSpeedKnob.clicked.connect(self.execSliderWidget)

        # final initialization

        self.editMLeftBrakeP.setText('0 MPa')
        self.editMRightBrakeP.setText('0 MPa')
        self.editALeftBrakeP.setText('0 MPa')
        self.editARightBrakeP.setText('0 MPa')

        self.editLeftRotateRate.setText('0 r/min')
        self.editRightRotateRate.setText('0 r/min')
        self.editTheoryLeftRotateRate.setText('0 r/min')
        self.editTheoryRightRotateRate.setText('0 r/min')

        #
        c_memset(self._serialSend, 0, ctypes.sizeof(self._serialSend))

        # SQL
        sqlName = applicationDirPath() \
            + '/../data/cm-' \
            + QDateTime.currentDateTime().toLocalTime().toString('yyyy-MM-dd-HH-mm-ss') \
            + '.db'
        if not DatabaseMgr().create(sqlName):
            assert(False)

        # start serialport
        self._serialProxy.start()

        #
        buttonLeftTracksip.setState(self._serialSend.ctrlWord.lTracksip)
        buttonRightTracksip.setState(self._serialSend.ctrlWord.lTracksip)

    def onButtonSettingsClicked(self):
        self._serialProxy.save()
        #
        settingsWidget = SettingsWidget(self)
        settingsWidget.exec_()

        self._serialProxy.restore()

    def onButtonHistoryClicked(self):
        self._serialProxy.save()
        DatabaseMgr().save()
        #
        historyWidget = HistoryWidget(self)
        historyWidget.showMaximized()
        historyWidget.exec_()

        DatabaseMgr().restore()
        self._serialProxy.restore()

    def onButtonPortStateClicked(self, checked):
        if checked:
            self._serialProxy.start()
        else:
            self._serialProxy.stop()

    def onButtonQuitClicked(self):
        if QMessageBox.warning(self, '警告', '你确定要退出软件吗?',
                               QMessageBox.Ok | QMessageBox.No) == QMessageBox.Ok:
            self.close()

    def onCurveDoubleClicked(self, checked):
        objectName = self.sender().objectName()
        if objectName == 'curveLBP':
            self.groupBoxTop.setVisible(checked)
            self.areaMiddle.setVisible(checked)
            self.curveLRP.setVisible(checked)
            self.curveRBP.setVisible(checked)
            self.curveRRP.setVisible(checked)
        elif objectName == 'curveLRP':
            self.groupBoxTop.setVisible(checked)
            self.areaMiddle.setVisible(checked)
            self.curveLBP.setVisible(checked)
            self.curveRBP.setVisible(checked)
            self.curveRRP.setVisible(checked)
        elif objectName == 'curveRBP':
            self.groupBoxTop.setVisible(checked)
            self.areaMiddle.setVisible(checked)
            self.curveLBP.setVisible(checked)
            self.curveLRP.setVisible(checked)
            self.curveRRP.setVisible(checked)
        elif objectName == 'curveRRP':
            self.groupBoxTop.setVisible(checked)
            self.areaMiddle.setVisible(checked)
            self.curveLBP.setVisible(checked)
            self.curveLRP.setVisible(checked)
            self.curveRBP.setVisible(checked)

    def onButtonLeftPowerStateChanged(self, checked):
        self._serialSend.ctrlWord.lPowerSw = checked
        self._serialSend.sum = SerialPortProxy.serialPortSendSum(self._serialSend)
        self._serialProxy.writeData(self._serialSend)

    def onButtonRightPowerStateChanged(self, checked):
        self._serialSend.ctrlWord.rPowerSw = checked
        self._serialSend.sum = SerialPortProxy.serialPortSendSum(self._serialSend)
        self._serialProxy.writeData(self._serialSend)

    def onButtonLeftTracksipStateChanged(self, checked):
        self._serialSend.ctrlWord.lTracksip = checked
        self._serialSend.sum = SerialPortProxy.serialPortSendSum(self._serialSend)
        self._serialProxy.writeData(self._serialSend)

    def onButtonRightTracksipStateChanged(self, checked):
        self._serialSend.ctrlWord.rTracksip = checked
        self._serialSend.sum = SerialPortProxy.serialPortSendSum(self._serialSend)
        self._serialProxy.writeData(self._serialSend)

    def onSerialStateChanged(self, info):
        text = '串口: [%s] %s' % (self._serialProxy.config().__str__(), info)
        print(text)

    def onSerialDisplayRespond(self, data, dateTime):
        # Major Brake Pressure
        suffix = self.editMLeftBrakeP.text().split(' ')[1]
        self.editMLeftBrakeP.setText('%.2f %s' % (data.lMBrakeP * 1.0, suffix))
        suffix = self.editMRightBrakeP.text().split(' ')[1]
        self.editMRightBrakeP.setText('%.2f %s' % (data.rMBrakeP * 1.0, suffix))
        # Minor Brake Pressure
        suffix = self.editALeftBrakeP.text().split(' ')[1]
        self.editALeftBrakeP.setText('%.2f %s' % (data.lABrakeP * 1.0, suffix))
        suffix = self.editARightBrakeP.text().split(' ')[1]
        self.editARightBrakeP.setText('%.2f %s' % (data.rABrakeP * 1.0, suffix))
        # Rotation Rate
        suffix = self.editLeftRotateRate.text().split(' ')[1]
        self.editLeftRotateRate.setText('%d %s' % (data.lWheelSpd * 1.0, suffix))
        suffix = self.editRightRotateRate.text().split(' ')[1]
        self.editRightRotateRate.setText('%d %s' % (data.rWheelSpd * 1.0, suffix))

        # curves
        timeT = dateTime.toMSecsSinceEpoch()

        # curve - LBP
        self.curveLBP.curve(0).sheft(QPoint(timeT, data.lMBrakeP))
        self.curveLBP.curve(1).sheft(QPoint(timeT, data.lABrakeP))
        # curve - LRP
        self.curveLRP.curve(0).sheft(QPoint(timeT, data.lWheelSpd))
        self.curveLRP.curve(1).sheft(QPoint(timeT, self._lTheorySpd))
        # curve - RBP
        self.curveRBP.curve(0).sheft(QPoint(timeT, data.rMBrakeP))
        self.curveRBP.curve(1).sheft(QPoint(timeT, data.rABrakeP))
        # curve - RRP
        self.curveRRP.curve(0).sheft(QPoint(timeT, data.rWheelSpd))
        self.curveRRP.curve(1).sheft(QPoint(timeT, self._rTheorySpd))

        if not DatabaseMgr().write(data, self._lTheorySpd, self._rTheorySpd, timeT):
            assert(False)

    def onSerialPortError(self, error, info):
        buttonPortState = self.findChild(JSwitchButton, 'buttonPortState')
        if not buttonPortState:
            return
        if error == QSerialPort.NoError:
            buttonPortState.setState(True)
        else:
            buttonPortState.setState(False)
        text = '串口: [%s] %s' % (self._serialProxy.config().__str__(), info)
        print(text)

    def execSliderWidget(self):
        sliderWidget = SliderWidget(self.sender().text(), self)
        objName = self.sender().objectName()
        if objName == 'buttonLeftSpeedGain':
            lineEdit = self.findChild(QLineEdit, 'editTheoryLeftRotateRate')
            text = lineEdit.text().split(' ')
            suffix = ' ' + text[1]
            curValue = float(text[0])
            sliderWidget.setRange(0, 3000)
            # sliderWidget.setDecimals(2)
            # sliderWidget.setSingleStep(0.01)
            sliderWidget.setSuffix(suffix)
            sliderWidget.setValue(curValue)

            def valueChanged(value):
                self._lTheorySpd = value
                buttonLeftSpeedSwitch = self.findChild(QPushButton, 'buttonLeftSpeedSwitch')
                if buttonLeftSpeedSwitch:
                    buttonLeftSpeedSwitch.setText('左转速关' if value == 0.0 else '左转速开');
                lineEdit.setText(('%.2f' % value) + suffix)

                # send
                self._serialSend.index += 1
                self._serialSend.lWheelSpd = int(value * 42.94967296)
                self._serialSend.sum = SerialPortProxy.serialPortSendSum(self._serialSend)
                self._serialProxy.writeData(self._serialSend)

            sliderWidget.valueChanged.connect(valueChanged)

        elif objName == 'buttonRightSpeedGain':
            lineEdit = self.findChild(QLineEdit, 'editTheoryRightRotateRate')
            text = lineEdit.text().split(' ')
            suffix = ' ' + text[1]
            curValue = float(text[0])
            sliderWidget.setRange(0, 3000)
            # sliderWidget.setDecimals(2)
            # sliderWidget.setSingleStep(0.01)
            sliderWidget.setSuffix(suffix)
            sliderWidget.setValue(curValue)

            def valueChanged(value):
                self._rTheorySpd = value
                buttonRightSpeedSwitch = self.findChild(QPushButton, 'buttonRightSpeedSwitch')
                if buttonRightSpeedSwitch:
                    buttonRightSpeedSwitch.setText('右转速关' if value == 0.0 else '右转速开')
                lineEdit.setText(('%.2f' % value) + suffix)

                # send
                self._serialSend.index += 1
                self._serialSend.rWheelSpd = int(value * 42.94967296)
                self._serialSend.sum = SerialPortProxy.serialPortSendSum(self._serialSend)
                self._serialProxy.writeData(self._serialSend)

            sliderWidget.valueChanged.connect(valueChanged)

        elif objName == 'buttonLeftSpeedKnob':
            lineEdit = self.findChild(QLineEdit, 'editTheoryLeftRotateRate')
            text = lineEdit.text().split(' ')
            suffix = ' ' + text[1]
            curValue = float(text[0])
            minValue = max(0, curValue - 50)
            maxValue = min(3000, curValue + 50)
            if maxValue < 100:
                maxValue = minValue + 100
            if minValue > 3000 - 100:
                minValue = maxValue - 100
            sliderWidget.setRange(minValue, maxValue)
            # sliderWidget.setDecimals(2)
            # sliderWidget.setSingleStep(0.01)
            sliderWidget.setSuffix(suffix)
            sliderWidget.setValue(curValue)

            def valueChanged(value):
                self._lTheorySpd = value
                buttonLeftSpeedSwitch = self.findChild(QPushButton, 'buttonLeftSpeedSwitch')
                if buttonLeftSpeedSwitch:
                    buttonLeftSpeedSwitch.setText('左转速关' if value == 0.0 else '左转速开')
                lineEdit.setText(('%.2f' % value) + suffix)

                # send
                self._serialSend.index += 1
                self._serialSend.lWheelSpd = int(value * 42.94967296)
                self._serialSend.sum = SerialPortProxy.serialPortSendSum(self._serialSend)
                self._serialProxy.writeData(self._serialSend)

            sliderWidget.valueChanged.connect(valueChanged)

        elif objName == 'buttonRightSpeedKnob':
            lineEdit = self.findChild(QLineEdit, 'editTheoryRightRotateRate')
            text = lineEdit.text().split(' ')
            suffix = ' ' + text[1]
            curValue = float(text[0])
            minValue = max(0, curValue - 50)
            maxValue = min(3000, curValue + 50)
            if maxValue < 100:
                maxValue = minValue + 100
            if minValue > 3000 - 100:
                minValue = maxValue - 100
            sliderWidget.setRange(minValue, maxValue)
            # sliderWidget.setDecimals(2)
            # sliderWidget.setSingleStep(0.01)
            sliderWidget.setSuffix(suffix)
            sliderWidget.setValue(curValue)

            def valueChanged(value):
                self._rTheorySpd = value
                buttonRightSpeedSwitch = self.findChild(QPushButton, 'buttonRightSpeedSwitch')
                if buttonRightSpeedSwitch:
                    buttonRightSpeedSwitch.setText('右转速关' if value == 0.0 else '右转速开');
                lineEdit.setText(('%.2f' % value) + suffix)

                # send
                self._serialSend.index += 1
                self._serialSend.rWheelSpd = int(value * 42.94967296)
                self._serialSend.sum = SerialPortProxy.serialPortSendSum(self._serialSend)
                self._serialProxy.writeData(self._serialSend)

            sliderWidget.valueChanged.connect(valueChanged)

        else:
            pass

        sliderWidget.exec_()
예제 #28
0
 def setObjectName(self, *args):
     QWidget.setObjectName(self, *args)
     if hasattr(self, 'edit'):
         self.edit.initialize('xpath_edit_' +
                              unicode_type(self.objectName()))
예제 #29
0
class SingleRank(QWidget):
    single_rk_comeback_sg = pyqtSignal()
    detail_sg = pyqtSignal(str)

    def __init__(self, parent=None):
        super(SingleRank, self).__init__(parent)
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.h = self.screenRect.height()
        self.w = self.screenRect.width()
        self.xr = self.w / 930
        self.yr = self.h / 640
        self.zr = min(self.xr, self.yr)
        self.inlist = {}
        self.back2_wi = QWidget(self)
        self.rankexit_but = QPushButton(self)
        self.header1 = QLabel(self.back2_wi)
        self.comeback_but = QPushButton(self.back2_wi)
        self.next_but = QPushButton(self.back2_wi)
        self.table = QWidget(self.back2_wi)
        self.tablein = QGridLayout()
        self.headers = ['对局id', '分数', '时间', '详情']
        self.set_ui()
        with open('rank.qss', 'r') as f:
            self.setStyleSheet(f.read())

    def set_ui(self):
        self.setWindowTitle('SingleRank')
        self.setObjectName('singlerank')
        self.resize(self.w, self.h)
        effect = QGraphicsDropShadowEffect()
        effect.setOffset(10, 10)
        effect.setColor(QColor(0, 0, 0, 80))
        effect.setBlurRadius(20)
        effect1 = QGraphicsDropShadowEffect()
        effect1.setOffset(10, 10)
        effect1.setColor(QColor(0, 0, 0, 80))
        effect1.setBlurRadius(20)
        self.back2_wi.setObjectName('back')
        self.back2_wi.resize(self.xr * 793, self.yr * 534)
        self.back2_wi.move(self.xr * 69, self.yr * 53)
        self.back2_wi.setGraphicsEffect(effect)
        self.header1.setObjectName('header')
        self.header1.resize(self.xr * 172, self.yr * 36)
        self.header1.move(self.xr * 24, self.yr * 10)
        self.header1.setText('过往战绩')
        self.header1.setAlignment(Qt.AlignCenter)
        self.comeback_but.setObjectName('comeback')
        self.comeback_but.resize(self.xr * 80, self.yr * 36)
        self.comeback_but.move(self.xr * 67, self.yr * 467)
        self.comeback_but.setText('返回')
        self.comeback_but.clicked.connect(self.come_back)
        self.comeback_but.setGraphicsEffect(effect1)
        self.next_but.setObjectName('next')
        self.next_but.resize(self.zr * 38, self.zr * 38)
        self.next_but.move(self.xr * 725, self.yr * 468)
        self.next_but.setStyleSheet('border-radius:{}px;'.format(self.zr * 18))
        self.next_but.clicked.connect(self.next)
        self.table.setObjectName('table')
        self.table.resize(self.xr * 746, self.yr * 382)
        self.table.move(self.xr * 24, self.yr * 61)
        self.tablein.setSpacing(0)
        self.tablein.setContentsMargins(0, 0, 0, 0)
        self.table.setLayout(self.tablein)
        li = ['#f5f0e3', '#cccccc']
        for i in range(0, 5):
            for j in range(0, 4):
                if j == 3 and i != 0:
                    exec('self.tableheader{}_{} = QPushButton()'.format(i, j))
                    exec(
                        'self.tableheader{}_{}.setMinimumHeight(self.yr *382/5)'
                        .format(i, j))
                    exec('self.tableheader{}_{}.setText("详情")'.format(i, j))
                    exec(
                        'self.tableheader{}_{}.clicked.connect(self.details{})'
                        .format(i, j, i))
                else:
                    exec('self.tableheader{}_{} = QLabel()'.format(i, j))
                    exec('self.tableheader{}_{}.setAlignment(Qt.AlignCenter)'.
                         format(i, j))
                if i == 0:
                    exec('self.tableheader{}_{}.setObjectName("table_head")'.
                         format(i, j))
                    exec('self.tableheader{}_{}.setText("{}")'.format(
                        i, j, self.headers[j]))
                else:
                    exec('self.tableheader{}_{}.setObjectName("table_unit")'.
                         format(i, j))
                exec(
                    'self.tableheader{}_{}.setStyleSheet("background-color:{};")'
                    .format(i, j, li[(i + j) % 2]))
                exec('self.tablein.addWidget(self.tableheader{}_{}, {}, {})'.
                     format(i, j, i, j))
        self.back2_wi.setStyleSheet('#back{border-radius:' +
                                    str(self.zr * 20) +
                                    'px;}#header{border-radius:' +
                                    str(self.zr * 15) + 'px;font-size:' +
                                    str(int(self.zr * 18)) +
                                    'px;}#comeback{border-radius:' +
                                    str(self.zr * 15) + 'px;font-size:' +
                                    str(int(self.zr * 16)) +
                                    'px;}#table_unit{font-size:' +
                                    str(int(self.zr * 18)) +
                                    'px;}#table_head{font-size:' +
                                    str(int(self.zr * 20)) +
                                    'px;font-weight:bold}')

    def come_back(self):
        self.single_rk_comeback_sg.emit()

    def get_list(self, info):
        if len(info) >= 4:
            li = info[:4]
            self.inlist = info[4:]
        else:
            li = info
            self.inlist = info
        self.set_table(li)

    def set_table(self, mp):
        lens = len(mp)
        for i in range(1, lens + 1):
            self.next_but.setEnabled(True)
            exec('self.tableheader{}_0.setText("{}")'.format(
                i, mp[i - 1]['id']))
            exec('self.tableheader{}_1.setText("{}")'.format(
                i, mp[i - 1]['score']))
            exec('self.tableheader{}_2.setText("{}")'.format(
                i, mp[i - 1]['time']))
        if lens < 4:
            for i in range(lens + 1, 5):
                self.next_but.setEnabled(False)
                exec('self.tableheader{}_0.clear()'.format(i))
                exec('self.tableheader{}_1.clear()'.format(i))
                exec('self.tableheader{}_2.clear()'.format(i))

    def next(self):
        if len(self.inlist) >= 4:
            li = self.inlist[:4]
            self.inlist = self.inlist[4:]
        else:
            li = self.inlist
        self.set_table(li)

    def details1(self):
        if self.tableheader1_0.text() != '':
            self.detail_sg.emit(self.tableheader1_0.text())

    def details2(self):
        if self.tableheader2_0.text() != '':
            self.detail_sg.emit(self.tableheader2_0.text())

    def details3(self):
        if self.tableheader3_0.text() != '':
            self.detail_sg.emit(self.tableheader3_0.text())

    def details4(self):
        if self.tableheader4_0.text() != '':
            self.detail_sg.emit(self.tableheader4_0.text())
    def initialize(self, item_type, item_name, comment):  # pylint: disable=too-many-locals
        """
        Initialize Downtime QDialog

        :param item_type: type of item to acknowledge : host | service
        :type item_type: str
        :param item_name: name of the item to acknowledge
        :type item_name: str
        :param comment: the default comment of action
        :type comment: str
        """

        logger.debug("Create Downtime QDialog...")

        # Main status_layout
        center_widget(self)
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)

        main_layout.addWidget(get_logo_widget(self, _('Request Downtime')))

        downtime_widget = QWidget()
        downtime_widget.setObjectName('dialog')
        downtime_layout = QGridLayout(downtime_widget)

        downtime_title = QLabel(_('Request a downtime'))
        downtime_title.setObjectName('itemtitle')
        downtime_layout.addWidget(downtime_title, 0, 0, 1, 3)

        host_label = QLabel('<b>%s:</b> %s' % (item_type.capitalize(), item_name))
        downtime_layout.addWidget(host_label, 1, 0, 1, 1)

        options_label = QLabel(_('Downtime options:'))
        options_label.setObjectName('subtitle')
        downtime_layout.addWidget(options_label, 2, 0, 1, 1)

        self.fixed_toggle_btn.initialize()
        self.fixed_toggle_btn.update_btn_state(self.fixed)
        downtime_layout.addWidget(self.fixed_toggle_btn, 2, 1, 1, 1)

        fixed_label = QLabel(_('Fixed'))
        downtime_layout.addWidget(fixed_label, 2, 2, 1, 1)

        fixed_info = QLabel(
            _(
                'If checked, downtime will start and end at the times specified'
                ' by the “start time” and “end time” fields.'
            )
        )
        fixed_info.setWordWrap(True)
        downtime_layout.addWidget(fixed_info, 3, 0, 1, 3)

        duration_label = QLabel(_('Duration'))
        duration_label.setObjectName('subtitle')
        downtime_layout.addWidget(duration_label, 4, 0, 1, 1)

        duration_clock = QLabel()
        duration_clock.setPixmap(QPixmap(settings.get_image('time')))
        downtime_layout.addWidget(duration_clock, 4, 1, 1, 1)
        duration_clock.setFixedSize(16, 16)
        duration_clock.setScaledContents(True)

        self.duration.setTime(QTime(4, 00))
        self.duration.setDisplayFormat("HH'h'mm")
        downtime_layout.addWidget(self.duration, 4, 2, 1, 1)

        duration_info = QLabel(
            _('Sets the duration if it is a non-fixed downtime.')
        )
        downtime_layout.addWidget(duration_info, 5, 0, 1, 3)

        date_range_label = QLabel(_('Downtime date range'))
        date_range_label.setObjectName('subtitle')
        downtime_layout.addWidget(date_range_label, 6, 0, 1, 1)

        calendar_label = QLabel()
        calendar_label.setPixmap(QPixmap(settings.get_image('calendar')))
        calendar_label.setFixedSize(16, 16)
        calendar_label.setScaledContents(True)
        downtime_layout.addWidget(calendar_label, 6, 1, 1, 1)

        start_time_label = QLabel(_('Start time:'))
        downtime_layout.addWidget(start_time_label, 7, 0, 1, 1)

        self.start_time.setCalendarPopup(True)
        self.start_time.setDateTime(datetime.datetime.now())
        self.start_time.setDisplayFormat("dd/MM/yyyy HH'h'mm")
        downtime_layout.addWidget(self.start_time, 7, 1, 1, 2)

        end_time_label = QLabel(_('End time:'))
        downtime_layout.addWidget(end_time_label, 8, 0, 1, 1)

        self.end_time.setCalendarPopup(True)
        self.end_time.setDateTime(datetime.datetime.now() + datetime.timedelta(hours=2))
        self.end_time.setDisplayFormat("dd/MM/yyyy HH'h'mm")
        downtime_layout.addWidget(self.end_time, 8, 1, 1, 2)

        self.comment_edit.setText(comment)
        self.comment_edit.setMaximumHeight(60)
        downtime_layout.addWidget(self.comment_edit, 9, 0, 1, 3)

        request_btn = QPushButton(_('REQUEST DOWNTIME'), self)
        request_btn.clicked.connect(self.handle_accept)
        request_btn.setObjectName('valid')
        request_btn.setMinimumHeight(30)
        request_btn.setDefault(True)
        downtime_layout.addWidget(request_btn, 10, 0, 1, 3)

        main_layout.addWidget(downtime_widget)
예제 #31
0
class Ui(QApplication):
    def __init__(self):
        super().__init__(argv)
        self.w = QMainWindow()
        self.w.setMinimumWidth(300)
        self.w.setMinimumHeight(300)
        # self.w.setWindowTitle(tr("Отправка запросов на ВС АУГО"))
        self.cw = QScrollArea()
        # self.__create_ui()
        self.__showed = False
        self.__wgts = {}
        self.cb = QComboBox()
        self.individuals = []
        self.entities = []
        self.documents = []
        self.doc_files = []
        self.__setupUi(self.w)
        self.w.showMaximized()

    def report_error(self, msg=None):
        if not msg:
            etype, value, tb = exc_info()
            trace = ''.join(format_exception(etype, value, tb))
            delim_len = 40
            msg = ("*" * delim_len + "\n%s\n" + "*" * delim_len) % trace
            error(msg)
        mb = QMessageBox(QMessageBox.Critical, tr('Ошибка'),
                         str(exc_info()[1]))
        mb.setDetailedText(msg)
        mb.exec()

    def __create_ui(self):
        self.l = QGridLayout()
        self.t = QTableWidget(0, 3)
        self.t.setHorizontalHeaderLabels(
            ('№ дела (обращения)', 'Дата приёма', 'Дата отправки в СМЭВ'))
        self.t.resizeColumnsToContents()
        self.l.addWidget(self.t, 0, 0, 1, 2)
        w = QWidget()
        hl = QHBoxLayout(w)
        hl.setDirection(QHBoxLayout.LeftToRight)
        hl.addWidget(QWidget())
        ok_b = QPushButton(tr('Добавить запрос'))
        ok_b.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)
        ok_b.clicked.connect(self.__show_form)
        hl.addWidget(ok_b)
        w.setLayout(hl)
        self.l.addWidget(w, 1, 0, 1, 2)
        w = QWidget()
        w.setLayout(self.l)
        self.cw.setWidget(w)
        # self.cw.setLayout(self.l)
        # self.w.setCentralWidget(self.cw)
        w = QWidget()
        l = QVBoxLayout()
        l.addWidget(self.cw)
        w.setLayout(l)
        self.w.setCentralWidget(w)

    def __setupUi(self, mainWindow):
        mainWindow.setObjectName("MainWindow")
        self.centralwidget = QWidget(mainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.scrollArea = QScrollArea(self.centralwidget)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QWidget()
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.gridLayout = QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout.setObjectName("gridLayout")
        self.__show_form()
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.horizontalLayout.addWidget(self.scrollArea)
        mainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(mainWindow)
        self.menubar.setObjectName("menubar")
        self.menu = QMenu(self.menubar)
        self.menu.setObjectName("menu")
        mainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(mainWindow)
        self.statusbar.setObjectName("statusbar")
        mainWindow.setStatusBar(self.statusbar)
        self.action_1 = QAction(mainWindow)
        self.action_1.setObjectName("action")
        self.action_1.triggered.connect(self.send)
        self.action = QAction(mainWindow)
        self.action.setObjectName("action")
        self.action.triggered.connect(self.on_action_triggered)
        self.action_2 = QAction(mainWindow)
        self.action_2.setObjectName("action_2")
        self.action_3 = QAction(mainWindow)
        self.action_3.setObjectName("action_3")
        self.action_3.triggered.connect(self.get_response)
        self.menu.addAction(self.action)
        self.menubar.addAction(self.action_1)
        self.menubar.addAction(self.action_2)
        self.menubar.addAction(self.action_3)
        self.menubar.addAction(self.menu.menuAction())

        self.__retranslateUi(mainWindow)
        QMetaObject.connectSlotsByName(mainWindow)

    @pyqtSlot(bool)
    def get_response(self):
        try:
            from dmsic import Integration
            i = Integration(self)
            res = i.get_response()[0]
            if res:
                QMessageBox.information(self.w, tr("Получен ответ"), str(res))
        except:
            self.report_error()

    @pyqtSlot(bool)
    def send(self):
        try:
            from dmsic import Integration
            i = Integration(self)
            declar = {}
            for k, v in self.__wgts.items():
                if k in ('object_address', 'AppliedDocument', 'legal_entity',
                         'person'):
                    a = {}
                    for key, val in v.items():
                        if val.metaObject().className() == 'QDateEdit':
                            a[key] = datetime.strptime(val.text(), '%d.%m.%Y')
                        else:
                            a[key] = val.text()
                    declar[k] = a
                else:
                    if v.metaObject().className() == 'QDateEdit':
                        declar[k] = datetime.strptime(v.text(), '%d.%m.%Y')
                    else:
                        declar[k] = v.text()
            a = declar[
                'AppliedDocument'] if 'AppliedDocument' in declar else []
            for v in self.documents:
                d = {}
                for key, val in v.items():
                    if val.metaObject().className() == 'QDateEdit':
                        d[key] = datetime.strptime(val.text(), '%d.%m.%Y')
                    else:
                        d[key] = val.text()
                if not self.doc_files:
                    raise Exception('Добавте файл документа')
                d['file_name'] = self.doc_files[self.documents.index(v)]
                a.append(d)
            declar['AppliedDocument'] = a
            a = declar['person'] if 'person' in declar else []
            for v in self.individuals:
                ind = {}
                for key, val in v.items():
                    if key in ('address', 'fact_address'):
                        adr = {}
                        for k, vl in val.items():
                            adr[k] = vl.text()
                        ind[key] = adr
                    else:
                        if val.metaObject().className() == 'QDateEdit':
                            ind[key] = datetime.strptime(
                                val.text(), '%d.%m.%Y')
                        else:
                            ind[key] = val.text()
                a.append(ind)
            declar['person'] = a
            a = declar['legal_entity'] if 'legal_entity' in declar else []
            for v in self.entities:
                ent = {}
                for key, val in v.items():
                    if key == 'address':
                        adr = {}
                        for k, vl in val.items():
                            adr[k] = vl.text()
                        ent[key] = adr
                    else:
                        if val.metaObject().className() == 'QDateEdit':
                            ent[key] = datetime.strptime(
                                val.text(), '%d.%m.%Y')
                        else:
                            ent[key] = val.text()
                a.append(ent)
            declar['legal_entity'] = a
            i.send(declar)
            mb = QMessageBox(self.w)
            mb.information(self.w, tr('Готово'), tr('Запрос отправлен'))
        except:
            self.report_error()

    @pyqtSlot(bool)
    def on_action_triggered(self):
        a = Ui_Dialog()
        d = QDialog()
        a.setupUi(d)
        d.exec()

    def __retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(
            _translate("MainWindow", "Отправка запросов на ВС АУГО"))
        # self.pushButton.setText(_translate("MainWindow", "Добавить"))
        self.menu.setTitle(_translate("MainWindow", "Справка"))
        self.action_1.setText(_translate("MainWindow", "Отправить"))
        self.action_2.setText(_translate("MainWindow", "Настройка"))
        self.action.setText(_translate("MainWindow", "О программе"))
        self.action_3.setText(_translate("MainWindow", "Получить ответ"))

    @pyqtSlot(bool)
    def __show_form(self):
        if self.__showed:
            return

        self.gridLayout.addWidget(
            QLabel(tr('№ дела (обращения) <em style="color: red">*</em>')))
        w = QLineEdit()
        self.gridLayout.addWidget(w)
        w.setFocus()
        self.__wgts['declar_number'] = w
        self.gridLayout.addWidget(
            QLabel(
                tr('Услуга (код или номер, или наименование)<em style="color: red">*</em>'
                   )))
        w = QLineEdit()
        self.gridLayout.addWidget(w)
        self.__wgts['service'] = w
        self.gridLayout.addWidget(
            QLabel(
                tr('Дата регистрации запроса <em style="color: red">*</em>')))
        de = QDateEdit(QDate().currentDate())
        de.setCalendarPopup(True)
        self.gridLayout.addWidget(de)
        self.__wgts['register_date'] = de
        self.gridLayout.addWidget(
            QLabel(
                tr('Плановый срок предоставления услуги <em style="color: red">*</em>'
                   )))
        de = QDateEdit()
        self.__wgts['register_date'].dateChanged.connect(de.setMinimumDate)
        de.setCalendarPopup(True)
        de.setMinimumDate(self.__wgts['register_date'].date())
        self.gridLayout.addWidget(de)
        self.__wgts['end_date'] = de

        gb = QGroupBox(tr('Место нахождения объекта услуги'))
        gb_l = QGridLayout()
        self.__wgts['object_address'] = self.__add_address(gb_l)
        gb.setLayout(gb_l)
        self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2)

        doc = {}
        gb = QGroupBox(tr('Приложенный документ *'))
        gb_l = QGridLayout()
        gb_l.addWidget(
            QLabel(tr('Наименование документа <em style="color: red">*</em>')))
        w = QLineEdit()
        w.setMaxLength(1024)
        gb_l.addWidget(w, 0, 1, 1, 1)
        doc['title'] = w
        gb_l.addWidget(
            QLabel(tr('Номер документа <em style="color: red">*</em>')))
        w = QLineEdit()
        w.setMaxLength(50)
        gb_l.addWidget(w)
        doc['number'] = w
        gb_l.addWidget(
            QLabel(tr('Дата документа <em style="color: red">*</em>')))
        w = QDateEdit()
        w.setCalendarPopup(True)
        gb_l.addWidget(w)
        doc['date'] = w
        gb_l.addWidget(
            QLabel(
                tr('Прямая ссылка на файл. Поддерживаются только пртоколы '
                   'HTTP, FTP <em style="color: red">*</em>')))
        w = QLineEdit()
        gb_l.addWidget(w)
        doc['url'] = w
        gb.setLayout(gb_l)
        self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2)
        self.documents.append(doc)

        gb = QGroupBox(tr('Заявители *'))
        self.dec_layout = QGridLayout()
        self.cb = QComboBox()
        self.cb.addItems(('Физическое лицо',
                          'Юридическое лицо/Индивидуальный предприниматель'))
        self.dec_layout.addWidget(self.cb)
        b = QPushButton(tr('Добавить'))
        b.clicked.connect(self.add_declarant)
        self.dec_layout.addWidget(b, 0, 1, 1, 1)
        gb.setLayout(self.dec_layout)
        self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2)

        b = QPushButton(tr('Добавить файл документа'))
        b.clicked.connect(self.__add_doc_file)
        self.gridLayout.addWidget(b)
        self.file_label = QLabel()
        self.gridLayout.addWidget(self.file_label)
        self.warn_label = QLabel(tr("Не удаляйте файл до отправки запроса"))
        self.warn_label.setStyleSheet('color: red')
        self.warn_label.setVisible(False)
        self.gridLayout.addWidget(self.warn_label,
                                  self.gridLayout.rowCount() + 1, 0, 1, 2)

        self.__showed = True

    @pyqtSlot(bool)
    def __add_doc_file(self):
        file_name = QFileDialog.getOpenFileName(
            caption=tr('Выбурите файл'),
            filter=tr('Файлы pdf (*.pdf);;Все файлы (*.*)'))[0]
        self.file_label.setText(file_name)
        if self.doc_files:
            self.doc_files = []
        self.doc_files.append(file_name)
        self.warn_label.setVisible(True)

    def __add_address(self, gb_l):
        wgts = {}
        gb_l.addWidget(QLabel(tr('Почтовый индекс')))
        w = QLineEdit()
        gb_l.addWidget(w, 0, 1, 1, 1)
        wgts['Postal_Code'] = w
        gb_l.addWidget(QLabel(tr('Регион')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Region'] = w
        gb_l.addWidget(QLabel(tr('Район')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['District'] = w
        gb_l.addWidget(QLabel(tr('Муниципальное образование')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['City'] = w
        gb_l.addWidget(QLabel(tr('Городской район')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Urban_District'] = w
        gb_l.addWidget(QLabel(tr('Сельсовет')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Soviet_Village'] = w
        gb_l.addWidget(
            QLabel(tr('Населенный пункт <em style="color: red">*</em>')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Locality'] = w
        cb = QComboBox()
        cb.addItems(('Вариант 1', 'Вариант 2'))
        gb_l.addWidget(cb)
        st = QStackedWidget()
        p1 = QWidget()
        l = QGridLayout()
        l.setSpacing(3)
        l.addWidget(QLabel(tr('Улица <em style="color: red">*</em>')))
        w = QLineEdit()
        l.addWidget(w, 0, 1, 1, 1)
        wgts["Street"] = w
        l.addWidget(QLabel(tr('Дом <em style="color: red">*</em>')))
        w = QLineEdit()
        l.addWidget(w)
        wgts["House"] = w
        p1.setLayout(l)
        st.addWidget(p1)
        p2 = QWidget()
        l = QGridLayout()
        l.setSpacing(3)
        l.addWidget(QLabel(tr('Ориентир')))
        w = QLineEdit()
        l.addWidget(w, 0, 1, 1, 1)
        wgts["Reference_point"] = w
        p2.setLayout(l)
        st.addWidget(p2)
        gb_l.addWidget(st, 9, 0, 1, 2)
        cb.activated.connect(st.setCurrentIndex)
        gb_l.addWidget(QLabel(tr('Корпус')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Housing'] = w
        gb_l.addWidget(QLabel(tr('Строение')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Building'] = w
        gb_l.addWidget(QLabel(tr('Квартира')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Apartment'] = w
        return wgts

    @pyqtSlot(bool)
    def add_declarant(self, var=True, gl=None):
        if not gl:
            gl = self.dec_layout
        dc = {}
        gb_l = QGridLayout()
        if self.cb.currentIndex() == 0 or gl != self.dec_layout:
            # Add Individual
            gb = QGroupBox(tr('Физическое лицо *'))
            gb_l.addWidget(QLabel(tr('Фамилия <em style="color: red">*</em>')))
            w = QLineEdit()
            gb_l.addWidget(w, 0, 1, 1, 1)
            dc['surname'] = w
            gb_l.addWidget(QLabel(tr('Имя <em style="color: red">*</em>')))
            w = QLineEdit()
            gb_l.addWidget(w)
            dc['first_name'] = w
            gb_l.addWidget(QLabel(tr('Отчество')))
            w = QLineEdit()
            gb_l.addWidget(w)
            dc['patronymic'] = w

            adr = QGroupBox(tr('Адрес регистрации *'))
            adr_l = QGridLayout()
            dc['address'] = self.__add_address(adr_l)
            adr.setLayout(adr_l)
            gb_l.addWidget(adr, gb_l.rowCount() + 1, 0, 1, 2)

            gb.setLayout(gb_l)
            gl.addWidget(gb, gl.rowCount() + 1, 0, 1, 2)
            self.individuals.append(dc)
        else:
            # Add LegalEntity
            gb = QGroupBox(
                tr('Юридическое лицо/Индивидуальный предприниматель *'))
            gb_l.addWidget(
                QLabel(
                    tr('Краткое наименование ЮЛ <em style="color: red">*</em>')
                ))
            w = QLineEdit()
            gb_l.addWidget(w, 0, 1, 1, 1)
            dc['name'] = w

            adr = QGroupBox(tr('Юридический адрес *'))
            adr_l = QGridLayout()
            dc['address'] = self.__add_address(adr_l)
            adr.setLayout(adr_l)
            gb_l.addWidget(adr, gb_l.rowCount() + 1, 0, 1, 2)

            gb.setLayout(gb_l)
            gl.addWidget(gb, gl.rowCount() + 1, 0, 1, 2)
            self.entities.append(dc)
예제 #32
0
class Home(QWidget):
    home_exit_sg = pyqtSignal()
    rank_sg = pyqtSignal(list)
    single_rank_sg = pyqtSignal(list)

    def __init__(self, parent=None):
        super(Home, self).__init__(parent)
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.h = self.screenRect.height()
        self.w = self.screenRect.width()
        self.xr = self.w / 930
        self.yr = self.h / 640
        self.zr = min(self.xr, self.yr)
        self.id_p = 0
        self.token = ''
        self.vertical_img = QLabel(self)
        self.role_data_wi = QWidget(self)
        self.rankexit_but = QPushButton(self)
        self.role_header = QLabel(self.role_data_wi)
        self.role_name = QLabel(self.role_data_wi)
        self.role_rank = QPushButton(self.role_data_wi)
        self.ranking = QPushButton(self.role_data_wi)
        self.role_details = QWidget(self.role_data_wi)
        self.bigcard_la = QLabel(self.role_details)
        self.bigcard_wi = QWidget(self.role_details)
        self.rate_la = QLabel(self.role_details)
        self.rate_wi = QLabel(self.role_details)
        self.role_special = QLabel(self.bigcard_wi)
        self.set_ui()
        with open('home.qss', 'r') as f:
            self.setStyleSheet(f.read())

    def set_ui(self):
        self.setWindowTitle('Home')
        self.setObjectName('home')
        self.resize(self.w, self.h)
        effect = QGraphicsDropShadowEffect()
        effect.setOffset(10, 10)
        effect.setColor(QColor(0, 0, 0, 80))
        effect.setBlurRadius(20)
        self.vertical_img.setObjectName('vertical')
        self.vertical_img.resize(self.xr * 205, self.yr * 534)
        self.vertical_img.move(self.xr * 79, self.yr * 39)
        self.role_data_wi.setObjectName('role_data_wi')
        self.role_data_wi.resize(self.xr * 552, self.yr * 534)
        self.role_data_wi.move(self.xr * 320, self.yr * 39)
        self.role_data_wi.setGraphicsEffect(effect)
        self.rankexit_but.setObjectName('resexit')
        self.rankexit_but.resize(self.zr * 38, self.zr * 38)
        self.rankexit_but.move(self.xr * 852, self.yr * 22)
        self.rankexit_but.clicked.connect(self.home_exit)
        self.rankexit_but.setStyleSheet('border-radius:{}px;'.format(self.zr *
                                                                     18))
        self.role_header.setObjectName('role_header')
        self.role_header.resize(self.zr * 70, self.zr * 70)
        self.role_header.move(self.xr * 38, self.yr * 10)
        self.role_name.setObjectName('role_name')
        self.role_name.resize(self.xr * 129, self.yr * 43)
        self.role_name.move(self.xr * 129, self.yr * 21)
        self.role_name.setStyleSheet('border-radius:{}px;'.format(self.zr *
                                                                  18))
        effect1 = QGraphicsDropShadowEffect()
        effect1.setOffset(10, 10)
        effect1.setColor(QColor(0, 0, 0, 80))
        effect1.setBlurRadius(20)
        effect2 = QGraphicsDropShadowEffect()
        effect2.setOffset(10, 10)
        effect2.setColor(QColor(0, 0, 0, 80))
        effect2.setBlurRadius(20)
        self.role_rank.setObjectName('button')
        self.role_rank.resize(self.xr * 120, self.yr * 31)
        self.role_rank.move(self.xr * 269, self.yr * 27)
        self.role_rank.setText('个人战绩')
        self.role_rank.setGraphicsEffect(effect1)
        self.role_rank.clicked.connect(self.show_single_rank)
        self.ranking.setObjectName('button')
        self.ranking.resize(self.xr * 120, self.yr * 31)
        self.ranking.move(self.xr * 399, self.yr * 27)
        self.ranking.setText('排行榜')
        self.ranking.setGraphicsEffect(effect2)
        self.ranking.clicked.connect(self.show_rank)
        self.role_details.setObjectName('role_details')
        self.role_details.resize(self.xr * 500, self.yr * 435)
        self.role_details.move(self.xr * 28, self.yr * 89)
        self.bigcard_la.setObjectName('icon')
        self.bigcard_la.resize(self.xr * 120, self.yr * 23)
        self.bigcard_la.move(self.xr * 12, self.yr * 34)
        self.bigcard_la.setText('最近大牌')
        self.bigcard_la.setAlignment(Qt.AlignCenter)
        self.bigcard_wi.setObjectName('bigcard')
        self.bigcard_wi.resize(self.xr * 477, self.yr * 120)
        self.bigcard_wi.move(self.xr * 12, self.yr * 84)
        for i in range(1, 14):
            if i >= 9:
                xp = 330
                t = 9
            elif i >= 4:
                xp = 190
                t = 4
            else:
                xp = 90
                t = 1
            exec('self.role_card{}=QLabel(self.bigcard_wi)'.format(i))
            exec('self.role_card{}.setObjectName("card")'.format(i))
            exec('self.role_card{}.resize(self.xr*40,self.yr*60)'.format(i))
            exec('self.role_card{}.move(self.xr*(xp+({}-t)*20),self.yr*26)'.
                 format(i, i))
        self.role_special.setObjectName('role_special')
        self.role_special.resize(self.xr * 65, self.yr * 32)
        self.role_special.move(self.xr * 15, self.yr * 40)
        self.rate_la.setObjectName('icon')
        self.rate_la.resize(self.xr * 120, self.yr * 23)
        self.rate_la.move(self.xr * 12, self.yr * 234)
        self.rate_la.setText('近期趋势')
        self.rate_la.setAlignment(Qt.AlignCenter)
        self.rate_wi.setObjectName('rate')
        self.rate_wi.resize(self.xr * 477, self.yr * 120)
        self.rate_wi.move(self.xr * 12, self.yr * 284)
        self.role_data_wi.setStyleSheet('#role_data_wi{border-radius:' +
                                        str(self.zr * 20) +
                                        'px;}#role_header{border-radius:' +
                                        str(self.zr * 30) +
                                        'px;}#button{border-radius:' +
                                        str(self.zr * 15) + 'px;font-size:' +
                                        str(int(self.zr * 15)) +
                                        'px;}#icon{border-radius:' +
                                        str(self.zr * 10) + 'px;font-size:' +
                                        str(int(self.zr * 15)) + 'px;}')

    def home_exit(self):
        self.home_exit_sg.emit()

    def show_rank(self):
        res = rank()
        if res['status'] == 0:
            self.rank_sg.emit(res['details'])

    def show_single_rank(self):
        res = srank(self.id_p, self.token)
        if res['status'] == 0:
            self.single_rank_sg.emit(res['details'])

    def get_id(self, s):
        self.id_p = s

    def get_token(self, t):
        self.token = t
예제 #33
0
    def create_widget(self):
        """
        Create widget login

        """

        # Main status_layout
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)

        main_layout.addWidget(get_logo_widget(self, _('Login'), exitapp=True))

        # Login QWidget
        login_widget = QWidget(self)
        login_widget.setObjectName('dialog')
        login_layout = QGridLayout()
        login_widget.setLayout(login_layout)

        # _ = init_localization()
        title = QLabel(_('Welcome to Alignak-app'))
        title.setObjectName('itemtitle')
        title.setContentsMargins(1, 1, 1, 1)
        login_layout.addWidget(title, 0, 0, 1, 2)
        login_layout.setAlignment(title, Qt.AlignCenter)

        version = QLabel(_('Version %s') % __version__)
        version.setObjectName('subtitle')
        login_layout.addWidget(version, 1, 0, 1, 2)
        login_layout.setAlignment(version, Qt.AlignCenter | Qt.AlignTop)

        # Alignak server
        login_label = QLabel(_('Configure Alignak server'))
        login_layout.addWidget(login_label, 2, 0, 1, 1)
        login_layout.setAlignment(login_label, Qt.AlignRight)

        server_btn = QPushButton()
        server_btn.clicked.connect(self.handle_server)
        server_btn.setFixedSize(35, 35)
        server_btn.setIcon(QIcon(settings.get_image('server_settings')))
        server_btn.setToolTip(_('Configure Alignak Server'))
        login_layout.addWidget(server_btn, 2, 1, 1, 1)

        # Proxy settings
        proxy_lbl = QLabel(_('Configure Proxy'))
        login_layout.addWidget(proxy_lbl, 3, 0, 1, 1)
        login_layout.setAlignment(proxy_lbl, Qt.AlignRight)

        proxy_btn = QPushButton()
        proxy_btn.setIcon(QIcon(settings.get_image('password')))
        proxy_btn.setToolTip(_('Configure your Proxy'))
        proxy_btn.setFixedSize(35, 35)
        proxy_btn.clicked.connect(self.handle_proxy)
        login_layout.addWidget(proxy_btn, 3, 1, 1, 1)

        # Connection label
        connection_lbl = QLabel()
        connection_lbl.setText(_('<b>Log-in</b> to use the application'))
        connection_lbl.setWordWrap(True)
        login_layout.addWidget(connection_lbl, 4, 0, 1, 2)

        # Username field
        self.username_line.setFixedHeight(25)
        self.username_line.setPlaceholderText(_('username...'))
        login_layout.addWidget(self.username_line, 5, 0, 1, 2)

        # Password field
        self.password_line.setFixedHeight(25)
        self.password_line.setPlaceholderText(_('password...'))
        self.password_line.setEchoMode(QLineEdit.Password)
        login_layout.addWidget(self.password_line, 6, 0, 1, 2)

        # Login button
        login_button = QPushButton(_('LOGIN'), self)
        login_button.clicked.connect(self.accept_login)
        login_button.setObjectName('valid')
        login_button.setMinimumHeight(30)
        login_button.setDefault(True)
        login_layout.addWidget(login_button, 7, 0, 1, 2)

        main_layout.addWidget(login_widget)
        self.setLayout(main_layout)

        center_widget(self)

        if settings.get_config('Alignak', 'proxy_user'):
            self.handle_proxy()
예제 #34
0
class Register(QWidget):
    register_ok_sg = pyqtSignal()

    def __init__(self, parent=None):
        super(Register, self).__init__(parent)
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.h = self.screenRect.height()
        self.w = self.screenRect.width()
        self.xr = self.w / 930
        self.yr = self.h / 640
        self.zr = min(self.xr, self.yr)
        self.top_wi = QWidget(self)
        self.logo_la = QLabel(self.top_wi)
        self.ind_wi = QWidget(self)
        self.register_but = QPushButton(self.ind_wi)
        self.imp_la = QLabel(self.ind_wi)
        self.account_le = QLineEdit(self.ind_wi)
        self.psw_le = QLineEdit(self.ind_wi)
        self.name_le = QLineEdit(self.ind_wi)
        self.set_ui()
        with open('index.qss', 'r') as f:
            self.setStyleSheet(f.read())

    def set_ui(self):
        self.setWindowTitle('Register')
        self.setObjectName('register')
        self.resize(self.w, self.h)
        self.top_wi.setObjectName('top')
        self.top_wi.resize(930 * self.xr, 95 * self.yr)
        self.logo_la.setObjectName('logo')
        self.logo_la.resize(65 * self.xr, 65 * self.zr)
        self.logo_la.move(29 * self.xr, 16 * self.yr)
        effect = QGraphicsDropShadowEffect()
        effect.setOffset(10, 10)
        effect.setColor(QColor(0, 0, 0, 80))
        effect.setBlurRadius(20)
        self.ind_wi.setObjectName('login')
        self.ind_wi.resize(327 * self.xr, 388 * self.yr)
        self.ind_wi.move(300 * self.xr, 150 * self.yr)
        self.ind_wi.setGraphicsEffect(effect)
        self.register_but.setObjectName('button')
        self.register_but.move(64 * self.xr, 315 * self.yr)
        self.register_but.resize(202 * self.xr, 45 * self.yr)
        self.register_but.setText('注册新用户')
        self.register_but.clicked.connect(self.register)
        self.imp_la.setObjectName('imp_label')
        self.imp_la.resize(100 * self.zr, 100 * self.zr)
        self.imp_la.move(115 * self.xr + 100 * (self.xr - self.zr) / 2,
                         15 * self.yr)
        self.imp_la.setStyleSheet('border-radius:{}px;'.format(self.zr * 49))
        self.account_le.setObjectName('input')
        self.account_le.setTextMargins(20, 0, 0, 0)
        self.account_le.resize(213 * self.xr, 45 * self.yr)
        self.account_le.move(59 * self.xr, 126 * self.yr)
        self.account_le.setPlaceholderText('账号')
        self.psw_le.setObjectName('input')
        self.psw_le.setTextMargins(20, 0, 0, 0)
        self.psw_le.resize(213 * self.xr, 45 * self.yr)
        self.psw_le.move(59 * self.xr, 181 * self.yr)
        self.psw_le.setPlaceholderText('密码')
        self.psw_le.setEchoMode(QLineEdit.Password)
        self.name_le.setObjectName('input')
        self.name_le.setTextMargins(20, 0, 0, 0)
        self.name_le.resize(213 * self.xr, 45 * self.yr)
        self.name_le.move(59 * self.xr, 236 * self.yr)
        self.name_le.setPlaceholderText('昵称')
        self.ind_wi.setStyleSheet('#input{border-radius:' + str(self.zr * 20) +
                                  'px;}' + '#button{border-radius:' +
                                  str(self.zr * 20) + 'px;' + 'font-size:' +
                                  str(int(self.zr * 18)) + 'px;}')

    def register(self):
        account_p = self.account_le.text()
        psw_p = self.psw_le.text()
        # name_p = self.name_le.text()
        dic = register(account_p, psw_p)
        if dic['status'] == 1001:
            self.account_le.clear()
            self.psw_le.clear()
            self.account_le.setStyleSheet('border:4px solid;border-color:red;')
            self.account_le.setPlaceholderText('账号已存在')
        elif dic['status'] == 0:
            self.register_ok_sg.emit()
        else:
            self.account_le.clear()
            self.psw_le.clear()
            self.account_le.setStyleSheet('border:4px solid;border-color:red;')
            self.account_le.setPlaceholderText('未知错误')
예제 #35
0
 def setObjectName(self, *args):
     QWidget.setObjectName(self, *args)
     if hasattr(self, 'edit'):
         self.edit.initialize('xpath_edit_'+unicode(self.objectName()))
    def initialize(self, item_type, item_name, comment):  # pylint: disable=too-many-locals
        """
        Initialize Acknowledge QDialog

        :param item_type: type of item to acknowledge : host | service
        :type item_type: str
        :param item_name: name of the item to acknowledge
        :type item_name: str
        :param comment: the default comment of action
        :type comment: str
        """

        logger.debug("Create Acknowledge QDialog...")

        # Main status_layout
        center_widget(self)
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)

        main_layout.addWidget(get_logo_widget(self, _('Request Acknowledge')))

        ack_widget = QWidget()
        ack_widget.setObjectName('dialog')
        ack_layout = QGridLayout(ack_widget)

        ack_title = QLabel(_('Request an acknowledge'))
        ack_title.setObjectName('itemtitle')
        ack_layout.addWidget(ack_title, 0, 0, 1, 2)

        host_label = QLabel('<b>%s:</b> %s' % (item_type.capitalize(), item_name))
        ack_layout.addWidget(host_label, 1, 0, 1, 1)

        sticky_label = QLabel(_('Acknowledge is sticky:'))
        sticky_label.setObjectName('subtitle')
        ack_layout.addWidget(sticky_label, 2, 0, 1, 1)

        self.sticky_toggle_btn.initialize()
        self.sticky_toggle_btn.update_btn_state(self.sticky)
        ack_layout.addWidget(self.sticky_toggle_btn, 2, 1, 1, 1)

        sticky_info = QLabel(
            _(
                'If checked, '
                'the acknowledge will remain until the element returns to an "OK" state.'
            )
        )
        sticky_info.setWordWrap(True)
        ack_layout.addWidget(sticky_info, 3, 0, 1, 2)

        notify_label = QLabel(_('Acknowledge notifies:'))
        notify_label.setObjectName('subtitle')
        ack_layout.addWidget(notify_label, 4, 0, 1, 1)

        self.notify_toggle_btn.initialize()
        self.notify_toggle_btn.update_btn_state(self.notify)
        ack_layout.addWidget(self.notify_toggle_btn, 4, 1, 1, 1)

        notify_info = QLabel(
            _('If checked, a notification will be sent out to the concerned contacts.')
        )
        notify_info.setWordWrap(True)
        ack_layout.addWidget(notify_info, 5, 0, 1, 2)

        ack_comment = QLabel(_('Acknowledge comment:'))
        ack_comment.setObjectName('subtitle')
        ack_layout.addWidget(ack_comment, 6, 0, 1, 1)

        self.ack_comment_edit = QTextEdit()
        self.ack_comment_edit.setText(comment)
        self.ack_comment_edit.setMaximumHeight(60)
        ack_layout.addWidget(self.ack_comment_edit, 7, 0, 1, 2)

        request_btn = QPushButton(_('REQUEST ACKNOWLEDGE'), self)
        request_btn.clicked.connect(self.accept)
        request_btn.setObjectName('valid')
        request_btn.setMinimumHeight(30)
        request_btn.setDefault(True)
        ack_layout.addWidget(request_btn, 8, 0, 1, 2)

        main_layout.addWidget(ack_widget)