def createCalibrationControls():
    gb = QGroupBox("Calibration")

    #------------------------------------------
    layout = QGridLayout()

    arduino = createArduinoCalibrationControls()
    pc = createPcCalibrationControls()
    gui = createGuiCalibration()

    layout.addWidget(arduino, 0, 0, 1, 1)
    layout.addWidget(pc, 1, 0, 1, 1)
    layout.addWidget(gui, 0, 1, 2, 1)

    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(5)

    upper = QWidget()
    upper.setLayout(layout)

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

    vbox = QVBoxLayout()

    vbox.addWidget(upper)
    vbox.addStretch(1)

    vbox.setContentsMargins(0, 0, 0, 0)
    vbox.setSpacing(0)

    gb.setLayout(vbox)
    return gb
Example #2
0
class MetadataSelectorDropDown(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self._drop_down = ComboBox(self)
        self._drop_down.currentIndexChanged.connect(self._update_current)

        self._layout = QGridLayout(self)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.addWidget(self._drop_down)

        self.selectedIdChanged.connect(self._handle_selected_id_changed)
        self.selectedId = None

    selectedIdChanged = pyqtSignal(str)

    selectedId = AutoProperty(str)

    def setModel(self, model):
        self._drop_down.setModel(model)
        model.dataChanged.connect(self._handle_selected_id_changed)

    def _update_current(self, index):
        model_index = self._drop_down.model().createIndex(index, 0)
        self.selectedId = self._drop_down.model().data(model_index, DataRole)

    def _handle_selected_id_changed(self):
        model = self._drop_down.model()
        for i in range(model.rowCount()):
            model_index = model.createIndex(i, 0)
            if model.data(model_index, DataRole) == self.selectedId:
                self._drop_down.setCurrentIndex(i)
                return
    def initialize(self):
        """
        Initialize QWidget

        """

        layout = QGridLayout()
        self.setLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)

        # Services dashboard
        self.services_dashboard.initialize()
        for state in self.services_dashboard.states_btns:
            self.services_dashboard.states_btns[state].clicked.connect(
                lambda _, s=state: self.filter_services(state=s)
            )
        layout.addWidget(self.services_dashboard, 0, 0, 1, 2)
        layout.addWidget(get_frame_separator(), 1, 0, 1, 2)

        # Services QTreeWidget
        self.services_tree_widget.setIconSize(QSize(32, 32))
        self.services_tree_widget.setAlternatingRowColors(True)
        self.services_tree_widget.header().close()
        layout.addWidget(self.services_tree_widget, 2, 0, 1, 1)

        # Services QListWidget
        self.services_list_widget.clicked.connect(self.update_service_data)
        self.services_list_widget.hide()
        layout.addWidget(self.services_list_widget, 2, 0, 1, 1)

        # Service DataWidget
        self.service_data_widget.initialize()
        layout.addWidget(self.service_data_widget, 2, 1, 1, 1)
Example #4
0
    def initialize(self):
        """
        Initialize QWidget

        """

        layout = QGridLayout()
        self.setLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)

        # Services dashboard
        self.services_dashboard.initialize()
        for state in self.services_dashboard.states_btns:
            self.services_dashboard.states_btns[state].clicked.connect(
                lambda _, s=state: self.filter_services(state=s))
        layout.addWidget(self.services_dashboard, 0, 0, 1, 2)
        layout.addWidget(get_frame_separator(), 1, 0, 1, 2)

        # Services QTreeWidget
        self.services_tree_widget.setIconSize(QSize(32, 32))
        self.services_tree_widget.setAlternatingRowColors(True)
        self.services_tree_widget.header().close()
        layout.addWidget(self.services_tree_widget, 2, 0, 1, 1)

        # Services QListWidget
        self.services_list_widget.clicked.connect(self.update_service_data)
        self.services_list_widget.hide()
        layout.addWidget(self.services_list_widget, 2, 0, 1, 1)

        # Service DataWidget
        self.service_data_widget.initialize()
        layout.addWidget(self.service_data_widget, 2, 1, 1, 1)
Example #5
0
class PopoutWidget(QWidget):
    def __init__(self,
                 parent,
                 content,
                 background_color,
                 foreground_color,
                 background_opacity=0.8):
        QWidget.__init__(self, parent)
        self._layout = QGridLayout(self)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.addWidget(content, 0, 0, Qt.AlignTop)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        stylesheet = """
PopoutWidget {{
    background-color: {background_color}
}}

QLabel {{
    color: {foreground_color}
}}"""

        self.setStyleSheet(
            stylesheet.format(background_color=format_color(
                background_color, opacity=background_opacity),
                              foreground_color=format_color(foreground_color)))
def createNavigationControls():
    gb = QGroupBox("Navigation Controls")

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

    layout = QGridLayout()

    pause_both_btn = QPushButton("Pause vector && time")
    pause_btn = QPushButton("Pause vector")
    pause_time_btn = QPushButton("Pause time")
    continue_btn = QPushButton("Continue")
    release_btn = QPushButton("Release")
    cwHalfStep_btn = QPushButton("=> half step")
    ccwHalfStep_btn = QPushButton("<= half step")
    ccwDir_btn = QPushButton("CCW direction")
    cwDir_btn = QPushButton("CW direction")

    continue_btn.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

    pause_both_btn.clicked.connect(pause_vector_and_time)
    pause_btn.clicked.connect(lambda: send_cmd(["p"]))
    pause_time_btn.clicked.connect(tracker.pause_time)
    continue_btn.clicked.connect(continue_)
    release_btn.clicked.connect(lambda: send_cmd(["r"]))
    cwHalfStep_btn.clicked.connect(lambda: send_cmd([">", "h", "<"]))
    ccwHalfStep_btn.clicked.connect(lambda: send_cmd(["<", "h"]))
    ccwDir_btn.clicked.connect(lambda: send_cmd(["<"]))
    cwDir_btn.clicked.connect(lambda: send_cmd([">"]))

    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)
    layout.setVerticalSpacing(0)

    layout.addWidget(pause_both_btn, 0, 0)
    layout.addWidget(pause_btn, 1, 0)
    layout.addWidget(pause_time_btn, 2, 0)
    layout.addWidget(continue_btn, 0, 1, 3, 1)
    layout.addWidget(ccwHalfStep_btn, 3, 0)
    layout.addWidget(cwHalfStep_btn, 3, 1)
    layout.addWidget(ccwDir_btn, 4, 0)
    layout.addWidget(cwDir_btn, 4, 1)
    layout.addWidget(createGotoControls(), 5, 0, 1, 2)
    layout.addWidget(release_btn, 6, 0, 1, 2)

    upper = QWidget()
    upper.setLayout(layout)

    #-------------------------------------------
    vbox = QVBoxLayout()

    vbox.addWidget(upper)
    vbox.addStretch(1)

    vbox.setContentsMargins(0, 0, 0, 0)
    vbox.setSpacing(0)

    gb.setLayout(vbox)
    return gb
Example #7
0
class GuiHeader(QWidget):
    def __init__(self, caller, *args, **kwargs):
        QWidget.__init__(self)
        myFont = QFont("Times", italic=True)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        # --- 1) Check Box
        self.centralBox = QGridLayout()
        self.centralBox.setContentsMargins(0, 0, 0, 5)
        # --- 1a) Select & Check RPC
        label1 = QLabel("PIVX server")
        self.centralBox.addWidget(label1, 0, 0)
        self.rpcClientsBox = QComboBox()
        self.rpcClientsBox.setToolTip(
            "Select RPC server.\nLocal must be configured.")
        rpcClients = ["Local Wallet"]
        self.rpcClientsBox.addItems(rpcClients)
        self.centralBox.addWidget(self.rpcClientsBox, 0, 1)
        self.button_checkRpc = QPushButton("Connect")
        self.button_checkRpc.setToolTip("try to connect to RPC server")
        self.button_checkRpc.clicked.connect(caller.onCheckRpc)
        self.centralBox.addWidget(self.button_checkRpc, 0, 2)
        self.rpcLed = QLabel()
        self.rpcLed.setToolTip("status: %s" % caller.rpcStatusMess)
        self.rpcLed.setPixmap(caller.ledGrayH_icon)
        self.centralBox.addWidget(self.rpcLed, 0, 3)
        label2 = QLabel("Last Ping Block:")
        self.centralBox.addWidget(label2, 0, 4)
        self.lastBlockLabel = QLabel()
        self.lastBlockLabel.setFont(myFont)
        self.centralBox.addWidget(self.lastBlockLabel, 0, 5)
        # -- 1b) Select & Check hardware
        label3 = QLabel("HW device")
        self.centralBox.addWidget(label3, 1, 0)
        self.hwDevices = QComboBox()
        self.hwDevices.setToolTip("Select hardware device")
        hwDevices = ["Ledger Nano S"]
        self.hwDevices.addItems(hwDevices)
        self.centralBox.addWidget(self.hwDevices, 1, 1)
        self.button_checkHw = QPushButton("Connect")
        self.button_checkHw.setToolTip("try to connect to Hardware Wallet")
        self.button_checkHw.clicked.connect(caller.onCheckHw)
        self.centralBox.addWidget(self.button_checkHw, 1, 2)
        self.hwLed = QLabel()
        self.hwLed.setToolTip("status: %s" % caller.hwStatusMess)
        self.hwLed.setPixmap(caller.ledGrayH_icon)
        self.centralBox.addWidget(self.hwLed, 1, 3)
        layout.addLayout(self.centralBox)
        layout.addStretch(1)
        # --- 3) logo
        Logo = QLabel()
        Logo_file = os.path.join(caller.imgDir, 'pet4lLogo_horiz.png')
        Logo.setPixmap(
            QPixmap(Logo_file).scaledToHeight(87, Qt.SmoothTransformation))
        layout.addWidget(Logo)
        self.setLayout(layout)
Example #8
0
File: align.py Project: ligm74/LiGM
    def __init__(self, color_caption):
        TestableWidget.__init__(self)
        self.setWindowFlags(Qt.Popup)
        self._text = self.tr("Alignment text")

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

        b = "border: 1px solid #9b9b9b;"
        self._styles = {
            "border": b,
            "border_blue": "border: 0px solid blue;",
            "frame": 'QFrame[frameShape="4"]{color: #9b9b9b;}'
        }

        self.setStyleSheet(self._styles["frame"])

        # -- CAPTION ----------------------------------
        caption = QFrame(self, flags=Qt.WindowFlags())
        caption_layout = QHBoxLayout()
        self._lbl_caption = QLabel(self._text)
        self._lbl_caption.setStyleSheet(self._styles["border_blue"])
        caption_layout.addWidget(self._lbl_caption, alignment=Qt.Alignment())
        caption.setLayout(caption_layout)
        caption_layout.setContentsMargins(9, 5, 9, 5)
        caption.setStyleSheet(
            f"background-color: {color_caption}; {self._styles['border']}")

        # -- CELLS GRID -------------------------------
        cellsbox = QFrame(self, flags=Qt.WindowFlags())
        cells = QGridLayout()
        cellsbox.setLayout(cells)
        cells.setContentsMargins(9, 0, 9, 9)
        self._clrbtn = []
        for i in range(1, 4):
            for j in range(1, 5):
                self._clrbtn.append(QToolButton())
                self._clrbtn[-1].clicked.connect(
                    lambda z, y=i, x=j: self.select_align_(x, y))
                self._clrbtn[-1].setAutoRaise(True)

                sz = 48
                self._clrbtn[-1].setFixedSize(sz, sz)
                self._clrbtn[-1].setIconSize(QSize(sz, sz))

                self._clrbtn[-1].setIcon(QIcon(img(f"editor/a{i}{j}.png")))
                # noinspection PyArgumentList
                cells.addWidget(self._clrbtn[-1], i - 1, j - 1)

        # ---------------------------------------------
        main_layout.addWidget(caption, alignment=Qt.Alignment())
        main_layout.addWidget(cellsbox, alignment=Qt.Alignment())

        self.setLayout(main_layout)
Example #9
0
 def makeControlWidgets(self, parent):
     """Creates control widgets for the colormap's internal parameters.
     "parent" is a parent widget.
     Returns None if no controls are required"""
     top = QWidget(parent)
     layout = QGridLayout(top)
     layout.setContentsMargins(0, 0, 0, 0)
     for irow, icol, control in ((0, 0, self.gamma), (0, 1, self.color), (1, 0, self.cycles), (1, 1, self.hue)):
         control.makeControlWidgets(top, layout, irow, icol)
         control.valueChanged.connect(self.emitChange)
         control.valueMoved.connect(self.emitPreview)
     return top
Example #10
0
 def __init__(self, parent, modal=True, flags=Qt.WindowFlags()):
     QDialog.__init__(self, parent, flags)
     self.model = None
     self._model_dir = None
     self.setModal(modal)
     self.setWindowTitle("Add FITS brick")
     lo = QVBoxLayout(self)
     lo.setContentsMargins(10, 10, 10, 10)
     lo.setSpacing(5)
     # file selector
     self.wfile = FileSelector(self,
                               label="FITS filename:",
                               dialog_label="FITS file",
                               default_suffix="fits",
                               file_types="FITS files (*.fits *.FITS)",
                               file_mode=QFileDialog.ExistingFile)
     lo.addWidget(self.wfile)
     # overwrite or add mode
     lo1 = QGridLayout()
     lo.addLayout(lo1)
     lo1.setContentsMargins(0, 0, 0, 0)
     lo1.addWidget(QLabel("Padding factor:", self), 0, 0)
     self.wpad = QLineEdit("2", self)
     self.wpad.setValidator(QDoubleValidator(self))
     lo1.addWidget(self.wpad, 0, 1)
     lo1.addWidget(QLabel("Assign source name:", self), 1, 0)
     self.wname = QLineEdit(self)
     lo1.addWidget(self.wname, 1, 1)
     # OK/cancel buttons
     lo.addSpacing(10)
     lo2 = QHBoxLayout()
     lo.addLayout(lo2)
     lo2.setContentsMargins(0, 0, 0, 0)
     lo2.setContentsMargins(5, 5, 5, 5)
     self.wokbtn = QPushButton("OK", self)
     self.wokbtn.setMinimumWidth(128)
     self.wokbtn.clicked.connect(self.accept)
     self.wokbtn.setEnabled(False)
     cancelbtn = QPushButton("Cancel", self)
     cancelbtn.setMinimumWidth(128)
     cancelbtn.clicked.connect(self.reject)
     lo2.addWidget(self.wokbtn)
     lo2.addStretch(1)
     lo2.addWidget(cancelbtn)
     self.setMinimumWidth(384)
     # signals
     self.wfile.filenameSelected.connect(self._fileSelected)
     # internal state
     self.qerrmsg = QErrorMessage(self)
def createControlWidgets():
    gb = QGroupBox()

    layout = QGridLayout()

    layout.addWidget(createSpeedControls(), 0, 0, 1, 1)
    layout.addWidget(createCalibrationControls(), 0, 1, 1, 1)
    layout.addWidget(createGuiControls(), 1, 1, 1, 1)
    layout.addWidget(createNavigationControls(), 0, 2, 2, 1)

    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(5)

    upper = QWidget()
    upper.setLayout(layout)

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

    lower = createMonitorControls()

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

    vbox = QVBoxLayout()

    vbox.addWidget(upper)
    vbox.addWidget(lower)
    vbox.addStretch(1)

    vbox.setContentsMargins(0, 0, 0, 0)
    vbox.setSpacing(0)

    right = QWidget()
    right.setLayout(vbox)

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

    layout = QHBoxLayout()

    layout.addStretch(1)
    layout.addWidget(right)

    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)

    gb.setLayout(layout)
    gb.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
    gb.setMaximumHeight(400)
    return gb
    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()
Example #14
0
class MessageWindow(QWindow):
  def __init__(self, text, title = 'Hey, there!', type = True, parent = None, flags = Qt.WindowFlags()):
    super().__init__(parent = parent, flags = flags)
    # set grid layout
    self.window_grid_layout = QGridLayout()
    self.window_grid_layout.setContentsMargins(0, 0, 0, 0)
    self.init_layout(title)
    self.init_widgets(type, text)
    self.finish_layout()
    pass

  def init_layout(self, title):
    self.resize(self.BOX_WIDTH, self.BOX_HEIGHT)
    self.move(self.BOX_X, self.BOX_Y)
    self.setWindowTitle(title)
    pass

  def init_widgets(self, type, text):
    self.icon_label = QLabel()
    if type == True:
      self.icon_label.setText('Information')
    else:
      self.icon_label.setText('ERROR')
    self.icon_label.setFont(QFont('Ubuntu', 30, QFont.Bold))
    self.icon_label.setAlignment(Qt.AlignCenter)

    self.message = QLabel()
    self.message.setText(text)
    self.message.setFont(QFont('Ubuntu', 14))
    self.message.setAlignment(Qt.AlignCenter)
    self.message.setWordWrap(True)
    self.window_grid_layout.addWidget(self.icon_label, 0, 0, 1, 3)
    self.window_grid_layout.addWidget(self.message, 1, 0, 1, 3)
    pass

  def finish_layout(self):
    self.setLayout(self.window_grid_layout)
    pass
  
  pass
Example #15
0
class SearchFrame(QFrame):
    """ A frame with a label and a text entry. The text is provided to
    the application upwards to perform in-page search.

    NAV20

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

        self.search_grid = QGridLayout(self)
        self.search_grid.setSpacing(0)
        self.search_grid.setContentsMargins(0, 0, 0, 0)
        self.label = QLabel("Find in page:")
        self.search_line = QLineEdit()
        self.search_grid.addWidget(self.label, 0, 0)
        self.search_grid.addWidget(self.search_line, 0, 1)
        self.setVisible(False)

        set_shortcuts([
            ("Ctrl+H", self, self.search_line.backspace),
        ])
Example #16
0
class SearchFrame(QFrame):
    """ A frame with a label and a text entry. The text is provided to
    the application upwards to perform in-page search.

    NAV20

    """

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

        self.search_grid = QGridLayout(self)
        self.search_grid.setSpacing(0)
        self.search_grid.setContentsMargins(0, 0, 0, 0)
        self.label = QLabel("Find in page:")
        self.search_line = QLineEdit()
        self.search_grid.addWidget(self.label, 0, 0)
        self.search_grid.addWidget(self.search_line, 0, 1)
        self.setVisible(False)

        set_shortcuts([
            ("Ctrl+H", self, self.search_line.backspace),
            ])
class PlotToolbarOptions(QWidget):
    def __init__(self,
                 parent,
                 series_style,
                 theme_manager,
                 plot,
                 options=None,
                 legend_control=None,
                 right_padding=0.0,
                 has_extra_tools=False):
        QWidget.__init__(self, parent)
        self._theme_manager = theme_manager
        self._plot = plot
        self._toolbar_container = ToolbarContainer(plot)

        self._background_color_qt = _to_qt_color(
            series_style.get_color_from_key('axes_background'))
        self._foreground_color_qt = _to_qt_color(
            series_style.get_color_from_key('axes_foreground'))
        interpolation = interpolate_rgb(self._background_color_qt,
                                        self._foreground_color_qt, 3)
        self._icon_hover_color = interpolation[1]

        self._toolbar = PlotToolbarWidget(self._toolbar_container, plot,
                                          self._foreground_color_qt,
                                          self._icon_hover_color)
        self._toolbar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self._layout = QGridLayout(self)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
        self._layout.addWidget(plot, 0, 0, 1, 3)
        self._background_opacity = 0.8
        plot.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        if options is not None:
            if isinstance(options, PlotOptionsView):
                plot.setOptionsView(options)
            self._options = self._add_popout(ToolType.options, options)
        else:
            self._options = None

        if legend_control is not None:
            if isinstance(legend_control, LegendControlView):
                plot.setLegendControl(legend_control)
            self._legend_control = self._add_popout(ToolType.legend,
                                                    legend_control)
            legend_control.hasHiddenSeriesChanged.connect(
                self._handle_has_hidden_series_changed)
        else:
            self._legend_control = None

        self._toolbar_layout = QVBoxLayout(self._toolbar_container)
        self._toolbar_layout.addWidget(self._toolbar, Qt.AlignTop)

        self._layout.addWidget(self._toolbar_container, 0, 1,
                               Qt.AlignRight | Qt.AlignTop)
        self._layout.setColumnStretch(0, 1)
        self._layout.setColumnStretch(1, 0)
        if right_padding > 0:
            self._padding_widget = QWidget(self)
            self._padding_widget.setVisible(False)
            self._layout.addWidget(self._padding_widget, 0, 2)
            self._layout.setColumnMinimumWidth(2, right_padding)
        else:
            self._padding_widget = None

        if not has_extra_tools:
            self._toolbar_layout.addStretch()

    def _handle_has_hidden_series_changed(self, has_hidden):
        color = None if not has_hidden else self._theme_manager.get_color(
            'highlight')
        self._toolbar.setColor(ToolType.legend, color)

    def _handle_tool_activated(self, tool_type, view):
        def _(tool, active):
            if tool == tool_type:
                view.setVisible(active)
                if self._padding_widget:
                    self._padding_widget.setVisible(active)
                if active:
                    self._toolbar_container.setStyleSheet(
                        "ToolbarContainer {{ background-color: {} }}".format(
                            format_color(self._background_color_qt,
                                         ColorFormat.rgba_string_256,
                                         self._background_opacity)))
                    self._layout.setAlignment(self._toolbar_container,
                                              Qt.AlignRight)
                    if self._padding_widget:
                        self._padding_widget.setStyleSheet(
                            "QWidget {{ background-color: {} }}".format(
                                format_color(self._background_color_qt,
                                             ColorFormat.rgba_string_256,
                                             self._background_opacity)))
                else:
                    self._layout.setAlignment(self._toolbar_container,
                                              Qt.AlignRight | Qt.AlignTop)
                    self._toolbar_container.setStyleSheet("")
                    if self._padding_widget:
                        self._padding_widget.setStyleSheet("")

        return _

    def addTool(self, tool_widget):
        self._toolbar_layout.addWidget(HLine(self._plot), Qt.AlignTop)
        self._toolbar_layout.addWidget(tool_widget,
                                       Qt.AlignTop | Qt.AlignCenter)
        self._toolbar_layout.addStretch()

    @property
    def icon_color(self):
        return self._foreground_color_qt

    @property
    def icon_hover_color(self):
        return self._icon_hover_color

    @property
    def toolbar(self):
        return self._toolbar

    def _add_popout(self, tool_type, view):
        popout = PopoutWidget(self, view, self._background_color_qt,
                              self._foreground_color_qt,
                              self._background_opacity)
        popout.setVisible(False)
        self._layout.addWidget(popout, 0, 0, Qt.AlignRight)
        self._toolbar.toolActivated.connect(
            self._handle_tool_activated(tool_type, popout))
        return popout
Example #18
0
class QAnalyzeUI(QWindow):
  def __init__(self, parent = None, flags = Qt.WindowFlags()):
    super().__init__(parent = parent, flags = flags)
    # set grid layout
    self.window_grid_layout = QGridLayout()
    self.window_grid_layout.setContentsMargins(0, 0, 0, 0)
    self.init_layout()
    self.init_widgets()
    self.finish_layout()
    self.events_of_window()
    self.message_box = MessageWindow(text = 'Here goes something you must attention before it\'s too late', title = 'Hey, there!', type = True)
    self.error_box = MessageWindow(text = 'It seems something wrong here...', title = 'Hey, STOP!', type = False)
    # alg settings
    self.alg = AnalyzeAlg()
    pass

  def init_layout(self):
    self.resize(self.WINDOW_INIT_WIDTH, self.WINDOW_INIT_HEIGHT)
    self.move(self.X, self.Y)
    self.setWindowTitle('genrmany energy analysis')
    self.setWindowIcon(qta.icon('fa5s.broadcast-tower', color='white'))
    # basic function
    pass

  def init_widgets(self):
    # basic functions
    self.about_btn = QPushButton(qta.icon('fa5s.lightbulb', color = 'black'), 'About')
    self.window_grid_layout.addWidget(self.about_btn, 0, 0, 1, 5)
    
    self.exit_btn = QPushButton(qta.icon('fa5s.skull', color = 'red'), 'Exit')
    self.window_grid_layout.addWidget(self.exit_btn, 0, 6, 1, 5)

    self.all_data_btn = QPushButton(qta.icon('fa5s.database', color = 'skyblue'), 'View ALL consumption')
    self.window_grid_layout.addWidget(self.all_data_btn, 1, 1, 2, 3)

    self.year_data_btn = QPushButton(qta.icon('fa5s.calendar', color = 'navy'), 'View consumption in 2006')
    self.window_grid_layout.addWidget(self.year_data_btn, 1, 7, 2, 3)

    self.season_data_btn = QPushButton(qta.icon('fa5s.crow', color = 'black'), 'View consumption in SEASON')
    self.window_grid_layout.addWidget(self.season_data_btn, 3, 1, 2, 3)

    self.week_data_btn = QPushButton(qta.icon('fa5s.calendar-alt', color = 'crimson'), 'View consumption in WEEK')
    self.window_grid_layout.addWidget(self.week_data_btn, 3, 7, 2, 3)

    self.all_solar_btn = QPushButton(qta.icon('fa5s.cloud-sun', color = 'orange'), 'View ALL solar')
    self.window_grid_layout.addWidget(self.all_solar_btn, 5, 1, 2, 3)

    self.season_solar_btn = QPushButton(qta.icon('fa5s.cloud', color = 'grey'), 'View solar in SEASON')
    self.window_grid_layout.addWidget(self.season_solar_btn, 5, 7, 2, 3)

    self.all_wind_btn = QPushButton(qta.icon('fa5s.cannabis', color = 'olive'), 'View ALL wind')
    self.window_grid_layout.addWidget(self.all_wind_btn, 7, 1, 2, 3)

    self.appro_wind_btn = QPushButton(qta.icon('fa5s.chart-line', color = 'green'), 'View APPROXIMATE wind')
    self.window_grid_layout.addWidget(self.appro_wind_btn, 7, 7, 2, 3)
    pass

  def finish_layout(self):
    self.setLayout(self.window_grid_layout)
    pass

  def predict_info_function(self):
    self.alg.predict_wind()
    k, b = self.alg.predict_model()
    days = int((self.alg.all_consumption_data.mean() - b) / k)
    self.message_box.icon_label.setText('Prediction')
    self.message_box.message.setText(f'The Wind & Solar will replace coal in {self.alg.days2date(days)[0]}-{self.alg.days2date(days)[1]}-{self.alg.days2date(days)[2]}')
    self.message_box.show()
    pass

  def show_about(self):
    self.message_box.message.setText('Author: sakebow\nApplication: Energy Analysis')
    self.message_box.show()
    pass

  def events_of_window(self):
    self.about_btn.clicked.connect(lambda: self.show_about())
    self.exit_btn.clicked.connect(lambda: self.close())
    self.all_data_btn.clicked.connect(lambda: self.alg.show_all_data())
    self.year_data_btn.clicked.connect(lambda: self.alg.show_data_in_2006())
    self.season_data_btn.clicked.connect(lambda: self.alg.show_data_in_season('Consumption'))
    self.week_data_btn.clicked.connect(lambda: self.alg.show_data_in_week())
    self.all_solar_btn.clicked.connect(lambda: self.alg.show_all_data_for_field('Solar'))
    self.season_solar_btn.clicked.connect(lambda: self.alg.show_data_in_season('Solar'))
    self.all_wind_btn.clicked.connect(lambda: self.alg.show_all_data_for_field('Wind'))
    self.appro_wind_btn.clicked.connect(lambda: self.predict_info_function())
    pass

  pass
Example #19
0
class CodeEdit(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self._text_edit = CodeTextEdit(self)
        self._output_pane = QTextBrowser(self)
        self._output_pane.document().setDefaultFont(QFont('Courier', pointSize=7))
        self._output_pane.setWordWrapMode(QTextOption.NoWrap)

        self._output_pane_container = QWidget(self)
        self._output_pane_layout = QGridLayout(self._output_pane_container)
        self._output_pane_layout.setContentsMargins(0, 16, 0, 0)
        self._output_pane_layout.addWidget(QLabel(self.tr('Script Output')), 0, 0)
        self._output_pane_layout.addWidget(self._output_pane)

        self._splitter = QSplitter(Qt.Vertical, self)

        self._splitter.addWidget(self._text_edit)
        self._splitter.addWidget(self._output_pane_container)
        self._splitter.setStretchFactor(0, 3)
        self._splitter.setStretchFactor(1, 1)

        self._layout = QGridLayout(self)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.addWidget(self._splitter, 0, 0)

        self._text_edit.editComplete.connect(self.editComplete)
   
    editComplete = pyqtSignal(str)

    @property
    def textEdit(self):
        return self._text_edit
    
    @property
    def outputPane(self):
        return self._output_pane
    
    def setFontSize(self, font_size):
        self._text_edit.document().setDefaultFont(QFont('Courier', pointSize=font_size))
        self._output_pane.document().setDefaultFont(QFont('Courier', pointSize=font_size))
        self._text_edit.setTabStopWidth(font_size * 2)
        self._output_pane.setTabStopWidth(font_size * 2)

    def setModel(self, model):
        self._text_edit.setPlainText(model.text)
        model.textChanged.connect(self._set_text(self._text_edit))
        if hasattr(model, 'output'):
            self._output_pane.setPlainText(model.output)
            model.outputChanged.connect(self._set_text(self._output_pane, True))
            self._output_pane.setVisible(True)
        else:
            self._output_pane_container.setVisible(False)
        self.editComplete.connect(self._handle_text_changed(model))
        model.validationMessageChanged.connect(self._handle_validation_message)
    
    def _set_text(self, widget, scroll_to_end=False):
        def _(text):
            if widget.toPlainText() != text:
                widget.setPlainText(text)
                if scroll_to_end:
                    widget.verticalScrollBar().setSliderPosition(widget.verticalScrollBar().maximum())
        return _

    def _handle_text_changed(self, model):
        def _setter(value):
            model.text = value
        return _setter

    def _handle_validation_message(self, message):
        if message:
            palette = self.palette()
            invalid_color = QColor(Qt.red)
            invalid_color.setAlphaF(0.2)
            palette.setColor(QPalette.Base, invalid_color)
        else:
            palette = self.style().standardPalette()
        self._text_edit.setPalette(palette)
        self._text_edit.setToolTip(message or None)
Example #20
0
    def __init__(self, parent=None):
        super(WebTab, self).__init__(parent)

        self.current = {
            'title': "[EMPTY]",
            'address': ""
        }

        # address bar
        self.address_bar = AddressBar(parent=self)

        # webkit (the actual "web engine")
        self.webkit = WebView(parent=self)

        # set_prefix: app defined, carries str
        self.webkit.set_prefix.connect(self.address_bar.set_model)  # CFG02
        # javascript_state: app defined, carries bool
        self.webkit.javascript_state.connect(self.address_bar.set_bgcolor)

        # small label displaying instance ID and pending tab operations

        info_label = QLabel(parent=self)
        info_label.setText('?')  # CFG02

        # webkit_info: app defined, carries str
        self.webkit.attr.webkit_info.connect(info_label.setText)

        def update_address(qurl):
            """ The 'connect' gives a QUrl and setText receives a string;
            can't just connect setText

            Required because a 3XX HTTP redirection will change the address,
            and without updating, the address bar will be left stale

            AB02 AB03

            """
            self.current['address'] = qurl.toString()
            self.address_bar.setText(self.current['address'])

        # urlChanged carries QUrl; loadStarted carries nothing;
        # loadFinished carries bool; titleChanged carries str;
        # loadProgress carries int
        self.webkit.urlChanged.connect(update_address)
        self.webkit.loadStarted.connect(self.load_started)
        self.webkit.loadFinished.connect(self.load_finished)
        self.webkit.titleChanged.connect(self.save_title)
        self.webkit.loadProgress.connect(self.load_progress)

        def fill_notifier(message, request):
            """ sends a message to be displayed by the notifier

            """
            notify(message + " " + request.url().toString())

        # downloadRequested carries QNetworkRequest
        self.webkit.page().downloadRequested.connect(
            partial(fill_notifier, "download"))
        # unsupportedContent carries QNetworkReply
        self.webkit.page().unsupportedContent.connect(
            partial(fill_notifier, "unsupported"))

        # input area for access-key navigation

        self.nav_bar = NavigateInput(parent=self)
        # editingFinished carries nothing
        self.nav_bar.editingFinished.connect(self.webkit.clear_labels)

        # textEdited carries str
        self.nav_bar.textEdited.connect(self.webkit.akeynav)
        # nonvalid_tag (app defined) carries nothing
        self.webkit.nonvalid_tag.connect(self.nav_bar.clear)

        # 'corner' message and notification label, not on timer, smaller

        self.message_label = MessageLabel(self.webkit)

        def handle_hovered(link, title, content):
            """ When hovered, if ALT is pressed, show message label;
            hide otherwise

            """

            if ((QApplication.keyboardModifiers() & Qt.AltModifier) and
                    (link or title or content)):
                # ugly hack to ensure proper resizing; find a better way?
                self.message_label.hide()
                self.message_label.setText(
                    link + " " + title + " " + content)
                self.message_label.show()
            else:
                self.message_label.hide()

        # linkHovered carries str, str, str
        self.webkit.page().linkHovered.connect(handle_hovered)

        def handle_signaled(title):
            """ We received a string through a signal; display it on
            the message label

            """

            # if title:
            self.message_label.hide()
            self.message_label.setText(title)
            self.message_label.show()

        # show_message (app defined) carries str
        self.webkit.show_message.connect(handle_signaled)
        # loadStarted carries nothing
        self.webkit.loadStarted.connect(self.message_label.hide)

        # At the time navigation is requested load_requested is sent, and the
        # requested url is set as text in grey at the address bar. Once the
        # urlChanged signal is received, the actual url is set in black.

        # load_requested (app defined) carries str
        self.webkit.load_requested.connect(
            partial(self.address_bar.set_txt_color,
                    color=QColor(128, 128, 128)))

        def hide_message_label(*_):
            """ WARNING scrollRequested carries int, int, QRect;
            star swallows all

            """
            self.message_label.hide()

        self.webkit.page().scrollRequested.connect(hide_message_label)

        # focus_webkit (app defined) carries nothing
        self.webkit.hide_overlay.connect(self.message_label.hide)
        self.webkit.focus_webkit.connect(self.address_bar.restore)

        # progress bar
        self.pbar = QProgressBar(self)

        self.pbar.setRange(0, 100)
        self.pbar.setTextVisible(False)
        self.pbar.setVisible(False)
        self.pbar.setMaximumHeight(7)

        # search in page
        self.search_frame = SearchFrame(parent=self)  # NAV20
        # textChanged carries str
        self.search_frame.search_line.textChanged.connect(self.do_search)

        # layout
        grid = QGridLayout(self)
        grid.setSpacing(0)
        grid.setVerticalSpacing(0)
        grid.setContentsMargins(0, 0, 0, 0)
        grid.setRowStretch(1, 1)

        grid.addWidget(info_label, 0, 0, 1, 1)
        grid.addWidget(self.address_bar, 0, 1, 1, 1)
        grid.addWidget(self.nav_bar, 0, 2, 1, 1)

        grid.addWidget(self.webkit, 1, 0, 1, 3)

        grid.addWidget(self.search_frame, 2, 0, 1, 3)
        grid.addWidget(self.pbar, 3, 0, 1, 3)

        def show_search():
            """ One-time callback for QShortcut NAV20 """
            self.search_frame.setVisible(True)
            self.search_frame.search_line.setFocus()

        def hide_search():
            """ One-time callback for QShortcut NAV20 """
            self.search_frame.setVisible(False)
            self.webkit.findText("")
            self.webkit.setFocus()

        def navigate_completion(key=Qt.Key_Down):
            """ Sends an "arrow press" to the completion popup to navigate
            results.

            Not the best way to do this. It would be better to find out what
            function is being called by that arrow press.

            AB01

            """
            event = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier)

            self.address_bar.completer().popup().keyPressEvent(event)

        # the star swallows all arguments that aren't named 'store'
        def reset_addressbar(*, store=False):
            """ Restore the address bar to its original address and color (it
            could have changed because of a hover event).

            Optionally, store the original address in the clipboard.

            AB03

            """

            if self.current['address']:
                self.address_bar.set_txt_color(self.current['address'],
                                               color=QColor(0, 0, 0))

            if store:
                clipboard(self.current['address'])

        # urlChanged carries QUrl (ignored)
        self.webkit.urlChanged.connect(reset_addressbar)

        def enter_address_bar(clear=True):
            """ do not try entering the address bar if a load is in
            progress; do an 'stop' first

            AB00

            """

            if 'in_page_load' not in self.webkit.attr:
                if clear:
                    self.address_bar.clear_and_focus()
                else:
                    self.address_bar.setFocus()

        def cancel():
            """ if we're in the middle of loading the document, stop loading.
            Otherwise, hide the message label. The general concept is to reach
            a basic state.

            """

            if 'in_page_load' not in self.webkit.attr:
                self.message_label.hide()
                self.webkit.update()
            else:
                self.webkit.stop()

        set_shortcuts([
            # search NAV20
            ("G", self.webkit, show_search),
            ("Escape", self.search_frame, hide_search),
            ("Return", self.search_frame, self.do_search),
            ("Ctrl+J", self.search_frame, self.do_search),
            # go to page AB00
            ("Ctrl+J", self.address_bar, partial(
                self.webkit.navigate, self.address_bar)),
            ("Return", self.address_bar, partial(
                self.webkit.navigate, self.address_bar)),
            # address bar interaction
            ("A", self.webkit, cancel),
            ("Ctrl+L", self.webkit, enter_address_bar),  # AB00
            ("Ctrl+Shift+L", self.webkit, partial(
                enter_address_bar, clear=False)),
            ("Escape", self.address_bar, self.webkit.setFocus),  # AB00
            ("Ctrl+I", self.address_bar, navigate_completion),  # AB01
            ("Ctrl+P", self.address_bar, partial(
                navigate_completion, Qt.Key_Up)),
            # in-page element navigation
            ("Ñ", self, self.enter_nav),  # NAV11
            (";", self, self.enter_nav),
            # DOM01
            ("Ctrl+Ñ", self, partial(self.enter_nav, target="titles")),
            # toggle
            ("Q", self.webkit, self.toggle_script),  # TOG01
            # clipboard
            ("E", self, partial(reset_addressbar, store=True))  # CB05
            ])
Example #21
0
class Window(QWidget):
    def __init__(self, cc):
        super().__init__()

        self.camCtr = cc
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Camera Control')
        self.setMinimumWidth(260)
        self.grid = QGridLayout()
        self.grid.setContentsMargins(4, 4, 4, 4)
        self.grid.setSpacing(2)

        self.lbls = {}
        self.sls = {}
        self.buttons = {}
        self.button_status = {}
        row = 1
        for name, c in self.camCtr.ctrls.items():
            txt = name.replace("_", " ").capitalize() + ":"
            txt = txt.replace("White balance temperature", "WB temperature")
            lbl = QLabel(txt)
            self.grid.addWidget(lbl, row, 1, 1, 1, Qt.AlignRight)
            self.lbls[name] = lbl
            if c["type"] == "bool":
                button = QPushButton()
                if c["value"]:
                    button.setText('ON')
                    button.setStyleSheet("background-color: green")
                    self.button_status[name] = True
                else:
                    button.setText('OFF')
                    button.setStyleSheet("background-color: red")
                    self.button_status[name] = False
                button.clicked.connect(
                    lambda val, name=name: self.button_Change(val, name))
                self.grid.addWidget(button, row, 2, 1, 1, Qt.AlignCenter)
                self.buttons[name] = button
            else:
                sl = QSlider()
                sl.setOrientation(Qt.Horizontal)
                sl.setMaximum(c["max"])
                sl.setMinimum(c["min"])
                sl.valueChanged.connect(
                    lambda val, name=name: self.sl_Change(val, name))
                sl.setMinimumWidth(250)
                sl.setTickInterval(c.get("step", 1))
                sl.setValue(c["value"])
                if c.get("flags", "") == "inactive":
                    lbl.setDisabled(True)
                    sl.setDisabled(True)
                self.grid.addWidget(sl, row, 2, 1, 1, Qt.AlignRight)
                self.sls[name] = sl
            row += 1

        self.actions_grid = QGridLayout()
        self.actions = {}
        for i, action in enumerate(
            ("default", "sync", "update", "load", "save")):
            b = QPushButton()
            b.setText(action.capitalize())
            b.clicked.connect(
                lambda _, action=action: self.action_Slot(action))
            self.actions_grid.addWidget(b, 1, i, 1, 1, Qt.AlignCenter)
        self.grid.addLayout(self.actions_grid, row, 1, 1, 2, Qt.AlignCenter)

        self.mainLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.grid)
        self.setLayout(self.mainLayout)
        self.show()

    def sl_Change(self, val, name):
        if not self.camCtr.setValue(name, val):
            # Give user feedback if parameter was not
            # accepted. Unfortunately, not all invalid parameters are
            # actually flagged.
            self.sync()
            return

    def sync(self):
        self.camCtr.get_ctls()
        for name, c in self.camCtr.ctrls.items():
            if c["type"] == "bool":
                if c["value"]:
                    self.buttons[name].setText('ON')
                    self.buttons[name].setStyleSheet("background-color: green")
                    self.button_status[name] = True
                else:
                    self.buttons[name].setText('OFF')
                    self.buttons[name].setStyleSheet("background-color: red")
                    self.button_status[name] = False
            else:
                self.sls[name].setValue(c["value"])
                if c.get("flags", "") == "inactive":
                    self.sls[name].setDisabled(True)
                    self.lbls[name].setDisabled(True)
                else:
                    self.sls[name].setDisabled(False)
                    self.lbls[name].setDisabled(False)

    def button_Change(self, _, name):
        if self.button_status[name]:
            self.buttons[name].setText('OFF')
            self.buttons[name].setStyleSheet("background-color: red")
            self.button_status[name] = False
            self.camCtr.setValue(name, "0")
        else:
            self.buttons[name].setText('ON')
            self.buttons[name].setStyleSheet("background-color: green")
            self.button_status[name] = True
            self.camCtr.setValue(name, "1")
        # Check if any controls have become enabled.
        self.sync()

    def action_Slot(self, name):
        if name == "default":
            self.camCtr.update(reset=True)
        elif name == "update":
            self.camCtr.update()
        elif name == "save" or name == "load":
            conf_dir = os.path.join(Path.home(), ".config", "cam_control")
            Path(conf_dir).mkdir(parents=True, exist_ok=True)
            if name == "save":
                file_name, _ = QFileDialog.getSaveFileName(
                    self, "Save Cam Control configuration", conf_dir,
                    "Cam Control Conf (*.ccconf)")
                if file_name:
                    if not file_name.endswith(".ccconf"):
                        file_name += ".ccconf"
                    with open(file_name, "w") as fd:
                        json.dump(self.camCtr.ctrls, fd)
            else:
                file_name, _ = QFileDialog.getOpenFileName(
                    self, "Load Cam Control configuration", conf_dir,
                    "Cam Control Conf (*.ccconf)")
                if file_name:
                    with open(file_name, "r") as fd:
                        self.camCtr.ctrls = json.load(fd)
                    self.camCtr.update()
        self.sync()
Example #22
0
    def __init__(self, parent=None):
        super(WebTab, self).__init__(parent)

        self.current = {'title': "[EMPTY]", 'address': ""}

        # address bar
        self.address_bar = AddressBar(parent=self)

        # webkit (the actual "web engine")
        self.webkit = WebView(parent=self)

        # set_prefix: app defined, carries str
        self.webkit.set_prefix.connect(self.address_bar.set_model)  # CFG02
        # javascript_state: app defined, carries bool
        self.webkit.javascript_state.connect(self.address_bar.set_bgcolor)

        # small label displaying instance ID and pending tab operations

        info_label = QLabel(parent=self)
        info_label.setText('?')  # CFG02

        # webkit_info: app defined, carries str
        self.webkit.attr.webkit_info.connect(info_label.setText)

        def update_address(qurl):
            """ The 'connect' gives a QUrl and setText receives a string;
            can't just connect setText

            Required because a 3XX HTTP redirection will change the address,
            and without updating, the address bar will be left stale

            AB02 AB03

            """
            self.current['address'] = qurl.toString()
            self.address_bar.setText(self.current['address'])

        # urlChanged carries QUrl; loadStarted carries nothing;
        # loadFinished carries bool; titleChanged carries str;
        # loadProgress carries int
        self.webkit.urlChanged.connect(update_address)
        self.webkit.loadStarted.connect(self.load_started)
        self.webkit.loadFinished.connect(self.load_finished)
        self.webkit.titleChanged.connect(self.save_title)
        self.webkit.loadProgress.connect(self.load_progress)

        def fill_notifier(message, request):
            """ sends a message to be displayed by the notifier

            """
            notify(message + " " + request.url().toString())

        # downloadRequested carries QNetworkRequest
        self.webkit.page().downloadRequested.connect(
            partial(fill_notifier, "download"))
        # unsupportedContent carries QNetworkReply
        self.webkit.page().unsupportedContent.connect(
            partial(fill_notifier, "unsupported"))

        # input area for access-key navigation

        self.nav_bar = NavigateInput(parent=self)
        # editingFinished carries nothing
        self.nav_bar.editingFinished.connect(self.webkit.clear_labels)

        # textEdited carries str
        self.nav_bar.textEdited.connect(self.webkit.akeynav)
        # nonvalid_tag (app defined) carries nothing
        self.webkit.nonvalid_tag.connect(self.nav_bar.clear)

        # 'corner' message and notification label, not on timer, smaller

        self.message_label = MessageLabel(self.webkit)

        def handle_hovered(link, title, content):
            """ When hovered, if ALT is pressed, show message label;
            hide otherwise

            """

            if ((QApplication.keyboardModifiers() & Qt.AltModifier)
                    and (link or title or content)):
                # ugly hack to ensure proper resizing; find a better way?
                self.message_label.hide()
                self.message_label.setText(link + " " + title + " " + content)
                self.message_label.show()
            else:
                self.message_label.hide()

        # linkHovered carries str, str, str
        self.webkit.page().linkHovered.connect(handle_hovered)

        def handle_signaled(title):
            """ We received a string through a signal; display it on
            the message label

            """

            # if title:
            self.message_label.hide()
            self.message_label.setText(title)
            self.message_label.show()

        # show_message (app defined) carries str
        self.webkit.show_message.connect(handle_signaled)
        # loadStarted carries nothing
        self.webkit.loadStarted.connect(self.message_label.hide)

        # At the time navigation is requested load_requested is sent, and the
        # requested url is set as text in grey at the address bar. Once the
        # urlChanged signal is received, the actual url is set in black.

        # load_requested (app defined) carries str
        self.webkit.load_requested.connect(
            partial(self.address_bar.set_txt_color,
                    color=QColor(128, 128, 128)))

        def hide_message_label(*_):
            """ WARNING scrollRequested carries int, int, QRect;
            star swallows all

            """
            self.message_label.hide()

        self.webkit.page().scrollRequested.connect(hide_message_label)

        # focus_webkit (app defined) carries nothing
        self.webkit.hide_overlay.connect(self.message_label.hide)
        self.webkit.focus_webkit.connect(self.address_bar.restore)

        # progress bar
        self.pbar = QProgressBar(self)

        self.pbar.setRange(0, 100)
        self.pbar.setTextVisible(False)
        self.pbar.setVisible(False)
        self.pbar.setMaximumHeight(7)

        # search in page
        self.search_frame = SearchFrame(parent=self)  # NAV20
        # textChanged carries str
        self.search_frame.search_line.textChanged.connect(self.do_search)

        # layout
        grid = QGridLayout(self)
        grid.setSpacing(0)
        grid.setVerticalSpacing(0)
        grid.setContentsMargins(0, 0, 0, 0)
        grid.setRowStretch(1, 1)

        grid.addWidget(info_label, 0, 0, 1, 1)
        grid.addWidget(self.address_bar, 0, 1, 1, 1)
        grid.addWidget(self.nav_bar, 0, 2, 1, 1)

        grid.addWidget(self.webkit, 1, 0, 1, 3)

        grid.addWidget(self.search_frame, 2, 0, 1, 3)
        grid.addWidget(self.pbar, 3, 0, 1, 3)

        def show_search():
            """ One-time callback for QShortcut NAV20 """
            self.search_frame.setVisible(True)
            self.search_frame.search_line.setFocus()

        def hide_search():
            """ One-time callback for QShortcut NAV20 """
            self.search_frame.setVisible(False)
            self.webkit.findText("")
            self.webkit.setFocus()

        def navigate_completion(key=Qt.Key_Down):
            """ Sends an "arrow press" to the completion popup to navigate
            results.

            Not the best way to do this. It would be better to find out what
            function is being called by that arrow press.

            AB01

            """
            event = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier)

            self.address_bar.completer().popup().keyPressEvent(event)

        # the star swallows all arguments that aren't named 'store'
        def reset_addressbar(*, store=False):
            """ Restore the address bar to its original address and color (it
            could have changed because of a hover event).

            Optionally, store the original address in the clipboard.

            AB03

            """

            if self.current['address']:
                self.address_bar.set_txt_color(self.current['address'],
                                               color=QColor(0, 0, 0))

            if store:
                clipboard(self.current['address'])

        # urlChanged carries QUrl (ignored)
        self.webkit.urlChanged.connect(reset_addressbar)

        def enter_address_bar(clear=True):
            """ do not try entering the address bar if a load is in
            progress; do an 'stop' first

            AB00

            """

            if 'in_page_load' not in self.webkit.attr:
                if clear:
                    self.address_bar.clear_and_focus()
                else:
                    self.address_bar.setFocus()

        def cancel():
            """ if we're in the middle of loading the document, stop loading.
            Otherwise, hide the message label. The general concept is to reach
            a basic state.

            """

            if 'in_page_load' not in self.webkit.attr:
                self.message_label.hide()
                self.webkit.update()
            else:
                self.webkit.stop()

        set_shortcuts([
            # search NAV20
            ("G", self.webkit, show_search),
            ("Escape", self.search_frame, hide_search),
            ("Return", self.search_frame, self.do_search),
            ("Ctrl+J", self.search_frame, self.do_search),
            # go to page AB00
            ("Ctrl+J", self.address_bar,
             partial(self.webkit.navigate, self.address_bar)),
            ("Return", self.address_bar,
             partial(self.webkit.navigate, self.address_bar)),
            # address bar interaction
            ("A", self.webkit, cancel),
            ("Ctrl+L", self.webkit, enter_address_bar),  # AB00
            ("Ctrl+Shift+L", self.webkit,
             partial(enter_address_bar, clear=False)),
            ("Escape", self.address_bar, self.webkit.setFocus),  # AB00
            ("Ctrl+I", self.address_bar, navigate_completion),  # AB01
            ("Ctrl+P", self.address_bar, partial(navigate_completion,
                                                 Qt.Key_Up)),
            # in-page element navigation
            ("Ñ", self, self.enter_nav),  # NAV11
            (";", self, self.enter_nav),
            # DOM01
            ("Ctrl+Ñ", self, partial(self.enter_nav, target="titles")),
            # toggle
            ("Q", self.webkit, self.toggle_script),  # TOG01
            # clipboard
            ("E", self, partial(reset_addressbar, store=True))  # CB05
        ])
class BulkValueSelectorWidget(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self._value_selector = ListView(self)
        self._value_selector.setSelectionMode(ListView.ExtendedSelection)
        self._value_selector.selectedItemsChanged.connect(lambda: self.selectedValuesChanged.emit(self.selectedValues))

        self._layout = QGridLayout(self)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.addWidget(self._value_selector)
        self.setLayout(self._layout)

    valuesChanged = pyqtSignal(QAbstractItemModel)
    selectedValuesChanged = pyqtSignal(list)
    dataCommitted = pyqtSignal(list)

    @auto_property(QAbstractItemModel)
    def values(self):
        return self._value_selector.model()
    
    @values.setter
    def values(self, value):
        self._value_selector.setModel(value)
        self._value_selector.selectAll()
        self.valuesChanged.emit(value)
        self.selectedValuesChanged.emit(self.selectedValues)

    def setValues(self, values):
        self.values = values
        values.dataChanged.connect(self._handle_values_changed)
        if hasattr(values, 'selectionModel'):
            self._value_selector.setSelectionModel(values.selectionModel)
    
    def selectAll(self):
        self._value_selector.selectAll()
    
    @auto_property(list)
    def selectedValues(self):
        if isinstance(self._value_selector.model(), QStringListModel):
            return [
                self._value_selector.model().stringList()[i.row()]\
                    for i in self._value_selector.selectedIndexes() if i.row() < self._value_selector.model().rowCount()
            ]
        return [self._value_selector.model().data(i, DataRole) for i in self._value_selector.selectedIndexes() if i.row() < self._value_selector.model().rowCount()]
    
    @selectedValues.setter
    def selectedValues(self, values):
        select_values = (
            self._select_values_stringlist if isinstance(self._value_selector.model(), QStringListModel) 
            else self._select_values if self._value_selector.model()
            else None
        )
        if select_values:
            signals_blocked = self.blockSignals(True)
            self._value_selector.clearSelection()
            select_values(values)
            self.blockSignals(signals_blocked)
            self.selectedValuesChanged.emit(self.selectedValues)
    
    def _select_values_stringlist(self, values):
        for value in values:
            index = self._value_selector.model().stringList().index(value)
            model_index = self._value_selector.model().createIndex(index, 0)
            self._value_selector.selectionModel().setCurrentIndex(model_index, QItemSelectionModel.Rows | QItemSelectionModel.Select)
    
    def _select_values(self, values):
        model = self._value_selector.model()
        for i in range(model.rowCount()):
            model_index = model.createIndex(i, 0)
            data = model.data(model_index, DataRole)
            if data in values:
                self._value_selector.selectionModel().setCurrentIndex(model_index, QItemSelectionModel.Rows | QItemSelectionModel.Select)

    def _handle_values_changed(self):
        self.selectedValuesChanged.emit(self.selectedValues)

    def keyPressEvent(self, event):
        if event.key() in [Qt.Key_Enter, Qt.Key_Return]:
            self.dataCommitted.emit(self.selectedValues)
Example #24
0
class ConfigWidget(QWidget):
    def __init__(self, plugin):
        QWidget.__init__(self)
        self.plugin = plugin

        self.overl = l = QVBoxLayout(self)
        self.gb = QGroupBox(_('Metadata fields to download'), self)
        if plugin.config_help_message:
            self.pchm = QLabel(plugin.config_help_message)
            self.pchm.setWordWrap(True)
            self.pchm.setOpenExternalLinks(True)
            l.addWidget(self.pchm, 10)
        l.addWidget(self.gb)
        self.gb.l = g = QVBoxLayout(self.gb)
        g.setContentsMargins(0, 0, 0, 0)
        self.fields_view = v = FieldsList(self)
        g.addWidget(v)
        v.setFlow(QListView.Flow.LeftToRight)
        v.setWrapping(True)
        v.setResizeMode(QListView.ResizeMode.Adjust)
        self.fields_model = FieldsModel(self.plugin)
        self.fields_model.initialize()
        v.setModel(self.fields_model)
        self.memory = []
        self.widgets = []
        self.l = QGridLayout()
        self.l.setContentsMargins(0, 0, 0, 0)
        l.addLayout(self.l, 100)
        for opt in plugin.options:
            self.create_widgets(opt)

    def create_widgets(self, opt):
        val = self.plugin.prefs[opt.name]
        if opt.type == 'number':
            c = QSpinBox if isinstance(opt.default,
                                       numbers.Integral) else QDoubleSpinBox
            widget = c(self)
            widget.setValue(val)
        elif opt.type == 'string':
            widget = QLineEdit(self)
            widget.setText(val if val else '')
        elif opt.type == 'bool':
            widget = QCheckBox(opt.label, self)
            widget.setChecked(bool(val))
        elif opt.type == 'choices':
            widget = QComboBox(self)
            items = list(iteritems(opt.choices))
            items.sort(key=lambda k_v: sort_key(k_v[1]))
            for key, label in items:
                widget.addItem(label, (key))
            idx = widget.findData((val))
            widget.setCurrentIndex(idx)
        widget.opt = opt
        widget.setToolTip(textwrap.fill(opt.desc))
        self.widgets.append(widget)
        r = self.l.rowCount()
        if opt.type == 'bool':
            self.l.addWidget(widget, r, 0, 1, self.l.columnCount())
        else:
            l = QLabel(opt.label)
            l.setToolTip(widget.toolTip())
            self.memory.append(l)
            l.setBuddy(widget)
            self.l.addWidget(l, r, 0, 1, 1)
            self.l.addWidget(widget, r, 1, 1, 1)

    def commit(self):
        self.fields_model.commit()
        for w in self.widgets:
            if isinstance(w, (QSpinBox, QDoubleSpinBox)):
                val = w.value()
            elif isinstance(w, QLineEdit):
                val = unicode_type(w.text())
            elif isinstance(w, QCheckBox):
                val = w.isChecked()
            elif isinstance(w, QComboBox):
                idx = w.currentIndex()
                val = unicode_type(w.itemData(idx) or '')
            self.plugin.prefs[w.opt.name] = val
Example #25
0
    def __init__(self, text, colors, color_caption):
        TestableWidget.__init__(self)
        self.setWindowFlags(Qt.Popup)

        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(0, 0, 0, 0)
        border = "border: 1px solid #9b9b9b;"
        self.setStyleSheet('QFrame[frameShape="4"]{  color: #9b9b9b;}')

        # -- CAPTION ----------------------------------
        caption = QFrame(self, flags=Qt.WindowFlags())
        caption_layout = QHBoxLayout()
        self._lbl_caption = QLabel(text)
        self._lbl_caption.setStyleSheet("border: 0px solid blue;")
        caption_layout.addWidget(self._lbl_caption, alignment=Qt.Alignment())
        caption.setLayout(caption_layout)
        caption_layout.setContentsMargins(9, 5, 9, 5)
        caption.setStyleSheet(f"background-color: {color_caption}; {border}")

        # -- COLORS GRID ------------------------------
        colorbox = QFrame(self, flags=Qt.WindowFlags())
        color_layout = QGridLayout()
        colorbox.setLayout(color_layout)
        color_layout.setContentsMargins(9, 0, 9, 0)
        nn = 7
        self.clrbtn = []
        for i, color in enumerate(colors):
            self.clrbtn.append(QToolButton())
            css = (f"QToolButton {{{border}background-color:{color};}}"
                   f"QToolButton:hover {{border: 1px solid red; }}")
            self.clrbtn[-1].setStyleSheet(css)
            self.clrbtn[-1].clicked.connect(
                lambda x, c=color: self.select_color_(c))
            # noinspection PyArgumentList
            color_layout.addWidget(self.clrbtn[-1], i // nn, i % nn)

        # -- SPLITTER ---------------------------------
        h_frame = QFrame(None, flags=Qt.WindowFlags())
        h_frame.setFrameShape(QFrame.HLine)
        h_frame.setContentsMargins(0, 0, 0, 0)

        # -- BOTTOM (other color) ---------------------
        btns = QFrame(self, flags=Qt.WindowFlags())
        btn_layout = QHBoxLayout()
        other = QToolButton()
        other.clicked.connect(self.other_color_)
        other.setAutoRaise(True)
        other.setIcon(QIcon(img("editor/colorwheel")))
        btn_layout.addWidget(other, alignment=Qt.Alignment())
        self._lbl_other = QLabel(self.tr("other colors"))
        btn_layout.addWidget(self._lbl_other, alignment=Qt.Alignment())
        btns.setLayout(btn_layout)
        btn_layout.setContentsMargins(9, 0, 9, 9)
        self.clrbtn.append(other)

        # ---------------------------------------------
        main_layout.addWidget(caption, alignment=Qt.Alignment())
        main_layout.addWidget(colorbox, alignment=Qt.Alignment())
        main_layout.addWidget(h_frame, alignment=Qt.Alignment())
        main_layout.addWidget(btns, alignment=Qt.Alignment())

        self.setLayout(main_layout)
Example #26
0
    def __init__(self, color_caption):
        TestableWidget.__init__(self)
        self.setWindowFlags(Qt.Popup)
        self._text = self.tr("Table")

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

        b = "border: 1px solid #9b9b9b;"
        self._styles = {
            "border": b,
            "border_blue": "border: 0px solid blue;",
            "selection": f"QToolButton {{{b}background-color:#fee5e2;}}",
            "white": f"QToolButton {{{b}background-color:white;}}",
            "frame": 'QFrame[frameShape="4"]{color: #9b9b9b;}'}

        self.setStyleSheet(self._styles["frame"])

        # -- CAPTION ----------------------------------
        caption = QFrame(self, flags=Qt.WindowFlags())
        caption_layout = QHBoxLayout()
        self._lbl_caption = QLabel(self._text)
        self._lbl_caption.setStyleSheet(self._styles["border_blue"])
        caption_layout.addWidget(self._lbl_caption, alignment=Qt.Alignment())
        caption.setLayout(caption_layout)
        caption_layout.setContentsMargins(9, 5, 9, 5)
        caption.setStyleSheet(
            f"background-color: {color_caption}; {self._styles['border']}")

        # -- CELLS GRID -------------------------------
        cellsbox = QFrame(self, flags=Qt.WindowFlags())
        cells = QGridLayout()
        cells.setSpacing(1)
        cellsbox.setLayout(cells)
        cells.setContentsMargins(9, 0, 9, 0)
        self._nn = 10
        self._clrbtn = []
        colors = ["white" for _ in range(self._nn ** 2)]
        cellsbox.leaveEvent = lambda x: self._leave_cell()
        for i, color in enumerate(colors):
            self._clrbtn.append(QToolButton())
            # noinspection PyPep8Naming
            self._clrbtn[-1].enterEvent = lambda x, n=i: self._enter_cell(n)
            self._clrbtn[-1].setStyleSheet(self._styles["white"])
            self._clrbtn[-1].clicked.connect(
                lambda x, n=i: self.select_size_(n))
            # noinspection PyArgumentList
            cells.addWidget(self._clrbtn[-1], i // self._nn, i % self._nn)

        # -- SPLITTER ---------------------------------
        h_frame = QFrame(None, flags=Qt.WindowFlags())
        h_frame.setFrameShape(QFrame.HLine)
        h_frame.setContentsMargins(0, 0, 0, 0)

        # -- BOTTOM (other color) ---------------------
        btns = QFrame(self, flags=Qt.WindowFlags())
        btn_layout = QHBoxLayout()
        other = QToolButton()
        other.clicked.connect(self.other_size_)
        other.setAutoRaise(True)
        other.setIcon(QIcon(img("editor/table_gray")))
        btn_layout.addWidget(other, alignment=Qt.Alignment())
        self._lbl_other = QLabel(self.tr("insert table"))
        btn_layout.addWidget(self._lbl_other, alignment=Qt.Alignment())
        btns.setLayout(btn_layout)
        btn_layout.setContentsMargins(9, 0, 9, 9)
        self._clrbtn.append(other)

        # ---------------------------------------------
        main_layout.addWidget(caption, alignment=Qt.Alignment())
        main_layout.addWidget(cellsbox, alignment=Qt.Alignment())
        main_layout.addWidget(h_frame, alignment=Qt.Alignment())
        main_layout.addWidget(btns, alignment=Qt.Alignment())

        self.setLayout(main_layout)
Example #27
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)
class DashboardQWidget(QWidget):
    """
        Class who manage Host and Services resume QWidgets with number of:

        * Hosts: ``UP``, ``UNREACHABLE``, ``DOWN``
        * Services: ``OK``, ``WARNING``, ``CRITICAL``, ``UNKNWON``, ``UNREACHABLE``
        * Hosts and services: ``NOT_MONITORED``, ``ACKNOWLEDGED``, ``DOWNTIMED``

    """

    def __init__(self, parent=None):
        super(DashboardQWidget, self).__init__(parent)
        # Fields
        self.layout = QGridLayout()
        self.items_nb = {
            'hosts_nb': QLabel(),
            'services_nb': QLabel()
        }
        self.hosts_labels = {
            'hosts_up': QLabel(),
            'hosts_unreachable': QLabel(),
            'hosts_down': QLabel(),
            'hosts_not_monitored': QLabel(),
            'acknowledge': QLabel(),
            'downtime': QLabel()
        }
        self.services_labels = {
            'services_ok': QLabel(),
            'services_warning': QLabel(),
            'services_critical': QLabel(),
            'services_unknown': QLabel(),
            'services_unreachable': QLabel(),
            'services_not_monitored': QLabel(),
            'acknowledge': QLabel(),
            'downtime': QLabel()
        }
        self.hosts_buttons = {
            'hosts_up': QPushButton(),
            'hosts_unreachable': QPushButton(),
            'hosts_down': QPushButton(),
            'hosts_not_monitored': QPushButton(),
            'acknowledge': QPushButton(),
            'downtime': QPushButton()
        }
        self.services_buttons = {
            'services_ok': QPushButton(),
            'services_warning': QPushButton(),
            'services_critical': QPushButton(),
            'services_unknown': QPushButton(),
            'services_unreachable': QPushButton(),
            'services_not_monitored': QPushButton(),
            'acknowledge': QPushButton(),
            'downtime': QPushButton()
        }
        self.refresh_timer = QTimer()
        self.setFixedHeight(85)

    def initialize(self):
        """
        Initialize QWidget

        """

        self.setLayout(self.layout)
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.get_host_resume_widget()
        self.get_services_resume_widget()

        self.update_dashboard()

        update_dashboard = int(settings.get_config('Alignak-app', 'update_dashboard')) * 1000
        self.refresh_timer.setInterval(update_dashboard)
        self.refresh_timer.start()
        self.refresh_timer.timeout.connect(self.update_dashboard)

    def get_host_resume_widget(self):
        """
        Return Host resume QWidget

        """

        self.layout.addWidget(QLabel(_('<b>Hosts:</b>')), 0, 0, 1, 1)
        self.items_nb['hosts_nb'].setObjectName('subtitle')
        self.layout.addWidget(self.items_nb['hosts_nb'], 1, 0, 1, 1)
        row = 1
        for icon in Host.get_available_icons():
            self.hosts_buttons[icon].setIcon(QIcon(settings.get_image(icon)))
            self.hosts_buttons[icon].setFixedSize(48, 24)
            self.hosts_buttons[icon].setObjectName(icon)
            self.hosts_buttons[icon].setToolTip(
                _('Hosts %s. See in WebUI ?') % icon.replace('hosts_', '').upper()
            )
            self.hosts_buttons[icon].clicked.connect(
                lambda: self.open_item_type_url('hosts')
            )
            self.layout.addWidget(self.hosts_buttons[icon], 0, row, 1, 1)
            self.layout.setAlignment(self.hosts_buttons[icon], Qt.AlignCenter)
            self.hosts_labels[icon].setObjectName(icon)
            self.layout.addWidget(self.hosts_labels[icon], 1, row, 1, 1)
            self.layout.setAlignment(self.hosts_labels[icon], Qt.AlignCenter)
            row += 1

    def get_services_resume_widget(self):
        """
        Return Services resume QWidget

        """

        self.layout.addWidget(QLabel('<b>Services:</b>'), 2, 0, 1, 1)
        self.items_nb['services_nb'].setObjectName('subtitle')
        self.layout.addWidget(self.items_nb['services_nb'], 3, 0, 1, 1)
        row = 1
        for icon in Service.get_available_icons():
            self.services_buttons[icon].setIcon(QIcon(settings.get_image(icon)))
            self.services_buttons[icon].setFixedSize(48, 24)
            self.services_buttons[icon].setObjectName(icon)
            self.services_buttons[icon].setToolTip(
                _('Services %s. See in WebUI ?') % icon.replace('services_', '').upper()
            )
            self.services_buttons[icon].clicked.connect(
                lambda: self.open_item_type_url('services')
            )
            self.layout.addWidget(self.services_buttons[icon], 2, row, 1, 1)
            self.layout.setAlignment(self.services_buttons[icon], Qt.AlignCenter)
            self.services_labels[icon].setObjectName(icon)
            self.layout.addWidget(self.services_labels[icon], 3, row, 1, 1)
            self.layout.setAlignment(self.services_labels[icon], Qt.AlignCenter)
            row += 1

    def open_item_type_url(self, item_type):
        """
        Retrieve sender to send right endpoint to open_url() function for item type

        :param item_type: type of item: hosts | services
        :type item_type: str
        """

        endpoint = self.sender().objectName()

        open_url('%s%s' % (item_type, get_url_endpoint_from_icon_name(endpoint)))

    def update_dashboard(self):
        """
        Update number of items in dashboard

        """

        synthesis = data_manager.get_synthesis_count()

        hosts_sum = 0
        for item in synthesis['hosts']:
            hosts_sum += synthesis['hosts'][item]
        services_sum = 0
        for item in synthesis['services']:
            services_sum += synthesis['services'][item]

        # Hosts percentages
        self.items_nb['hosts_nb'].setText("%d hosts" % hosts_sum)
        for icon in Host.get_available_icons():
            host_nb = synthesis['hosts'][icon.replace('hosts_', '')]
            percent = 0.0
            try:
                percent = float(host_nb) * 100.0 / float(hosts_sum)
            except ZeroDivisionError:
                pass
            item_text = '%d (%.02f%%)' % (host_nb, percent)
            self.hosts_labels[icon].setText(item_text)

        # Services percentage
        self.items_nb['services_nb'].setText("%d services" % services_sum)
        for icon in Service.get_available_icons():
            service_nb = synthesis['services'][icon.replace('services_', '')]
            percent = 0.0
            try:
                percent = float(service_nb) * 100.0 / float(services_sum)
            except ZeroDivisionError:
                pass
            item_text = '%d (%.01f%%)' % (service_nb, percent)
            self.services_labels[icon].setText(item_text)

        for button in self.hosts_buttons:
            if settings.get_config('Alignak', 'webui'):
                self.hosts_buttons[button].setEnabled(True)
                self.hosts_buttons[button].setToolTip(
                    _('Hosts %s. See in WebUI ?') % button.replace('hosts_', '').upper()
                )
            else:
                self.hosts_buttons[button].setToolTip(
                    _("Hosts %s. WebUI is not set in configuration file.") % button.replace(
                        'hosts_', '').upper()
                )

        for button in self.services_buttons:
            if settings.get_config('Alignak', 'webui'):
                self.services_buttons[button].setEnabled(True)
                self.services_buttons[button].setToolTip(
                    _('Services %s. See in WebUI ?') % button.replace('services_', '').upper()
                )
            else:
                self.services_buttons[button].setToolTip(
                    _("Services %s. WebUI is not set in configuration file.") % button.replace(
                        'services_', '').upper()
                )
Example #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 createGuiCalibration():
    gb = QGroupBox("Gui Calibration")

    layout = QGridLayout()

    label1 = QLabel("Time speed (delay):")
    label2 = QLabel("Sine amplitude:")
    label3 = QLabel("Pen width:")
    label4 = QLabel("Vertical position:")
    label5 = QLabel("X axis offset from right:")

    timeDelay_sb = QSpinBox()
    timeDelay_sb.setRange(2, 20)  # actual ms is times 10
    timeDelay_sb.setValue(tracker.timer_interval /
                          10)  # value is in multiples of 10 ms
    timeDelay_sb.setMaximumWidth(60)
    timeDelay_sb.setMinimumHeight(25)
    timeDelay_sb.valueChanged.connect(tracker.set_timer_interval)

    amplitude_sb = QSpinBox()
    amplitude_sb.setRange(20, 300)
    amplitude_sb.setValue(tracker.amplitude)
    amplitude_sb.setMaximumWidth(60)
    amplitude_sb.setMinimumHeight(25)
    amplitude_sb.valueChanged.connect(tracker.set_amplitude)

    penWidth_sb = QSpinBox()
    penWidth_sb.setRange(1, 20)
    penWidth_sb.setValue(tracker.pen_width)
    penWidth_sb.setMaximumWidth(60)
    penWidth_sb.setMinimumHeight(25)
    penWidth_sb.valueChanged.connect(tracker.set_pen_width)

    vertPos_sb = QSpinBox()
    vertPos_sb.setRange(200, 800)
    vertPos_sb.setValue(tracker.x_axis_y_coordinate)
    vertPos_sb.setMaximumWidth(60)
    vertPos_sb.setMinimumHeight(25)
    vertPos_sb.valueChanged.connect(tracker.set_x_axis_y_coordinate)

    xAxisLength_sb = QSpinBox()
    xAxisLength_sb.setRange(50, 1000)
    xAxisLength_sb.setValue(tracker.x_axis_offset_from_right)
    xAxisLength_sb.setMaximumWidth(60)
    xAxisLength_sb.setMinimumHeight(25)
    xAxisLength_sb.valueChanged.connect(tracker.set_x_axis_offset_from_right)

    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)

    layout.addWidget(label1, 0, 0, 1, 1)
    layout.addWidget(timeDelay_sb, 0, 1, 1, 1)
    layout.addWidget(label2, 1, 0, 1, 1)
    layout.addWidget(amplitude_sb, 1, 1, 1, 1)
    layout.addWidget(label3, 2, 0, 1, 1)
    layout.addWidget(penWidth_sb, 2, 1, 1, 1)
    layout.addWidget(label4, 3, 0, 1, 1)
    layout.addWidget(vertPos_sb, 3, 1, 1, 1)
    layout.addWidget(label5, 4, 0, 1, 1)
    layout.addWidget(xAxisLength_sb, 4, 1, 1, 1)

    upper = QWidget()
    upper.setLayout(layout)

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

    vbox = QVBoxLayout()

    vbox.setContentsMargins(0, 0, 0, 0)
    vbox.setSpacing(0)

    vbox.addWidget(upper)
    vbox.addStretch(1)

    gb.setLayout(vbox)
    return gb
Example #31
0
class Box(QWindow):
    def __init__(self,
                 title,
                 icon,
                 width,
                 height,
                 x,
                 y,
                 type,
                 text,
                 parent=None,
                 flags=Qt.WindowFlags()):
        super().__init__(title,
                         icon,
                         width,
                         height,
                         x,
                         y,
                         parent=parent,
                         flags=flags)
        self.grid_layout = QGridLayout()
        self.grid_layout.setContentsMargins(0, 0, 0, 0)
        self.init_layout(title, icon)
        self.init_widget(type, text)
        self.finish_layout()
        pass

    def init_layout(self, title, icon):
        super().init_layout(title, icon)
        self.resize(CONFIG.BOX_WIDTH, CONFIG.BOX_HEIGHT)
        self.move(CONFIG.BOX_X, CONFIG.BOX_Y)
        self.setWindowTitle(title)
        self.setWindowIcon(icon)
        pass

    def init_widget(self, type, text):
        super().init_widget()
        self.icon_label = QLabel()
        if type == 1:
            self.icon_label.setText('Prediction')
        elif type == 2:
            self.icon_label.setText('ERROR')
        else:
            self.icon_label.setText('About')
            pass
        self.icon_label.setFont(QFont('Ubuntu', 30, QFont.Bold))
        self.icon_label.setAlignment(Qt.AlignCenter)

        self.message = QLabel()
        self.message.setText(text)
        self.message.setFont(QFont('Ubuntu', 14))
        self.message.setAlignment(Qt.AlignCenter)
        self.message.setWordWrap(True)
        self.grid_layout.addWidget(self.icon_label, 0, 0, 1, 3)
        self.grid_layout.addWidget(self.message, 1, 0, 1, 3)
        pass

    def finish_layout(self):
        super().finish_layout()
        self.setLayout(self.grid_layout)
        pass

    pass
Example #32
0
class QAnalyzeUI(QWindow):
    def __init__(self,
                 title,
                 icon,
                 width=CONFIG.WINDOW_WIDTH,
                 height=CONFIG.WINDOW_HEIGHT,
                 x=CONFIG.WINDOW_X,
                 y=CONFIG.WINDOW_Y,
                 parent=None,
                 flags=Qt.WindowFlags()):
        super().__init__(title,
                         icon,
                         width,
                         height,
                         x,
                         y,
                         parent=parent,
                         flags=flags)
        self.grid_layout = QGridLayout()
        self.grid_layout.setContentsMargins(0, 0, 0, 0)
        self.init_layout(title, icon)
        self.init_widget()
        self.finish_layout()
        self.set_events()
        self.about_box = Box(
            title='About',
            icon=qta.icon('fa5s.broadcast-tower', color='red'),
            width=CONFIG.BOX_WIDTH,
            height=CONFIG.BOX_HEIGHT,
            x=CONFIG.BOX_X,
            y=CONFIG.BOX_Y,
            type=0,
            text='Here goes something you must attention before it\'s too late'
        )
        self.predict_box = Box(title='Prediction',
                               icon=qta.icon('fa5s.broadcast-tower',
                                             color='red'),
                               width=CONFIG.BOX_WIDTH,
                               height=CONFIG.BOX_HEIGHT,
                               x=CONFIG.BOX_X,
                               y=CONFIG.BOX_Y,
                               type=1,
                               text='')
        self.alg = AnalyzeAlg()
        pass

    def init_layout(self, title, icon):
        super().init_layout(title, icon)
        self.resize(CONFIG.WINDOW_WIDTH, CONFIG.WINDOW_HEIGHT)
        self.move(CONFIG.WINDOW_X, CONFIG.WINDOW_Y)
        self.setWindowTitle(title)
        self.setWindowIcon(icon)
        pass

    def init_widget(self):
        super().init_widget()
        self.about_btn = QPushButton(qta.icon('fa5s.lightbulb', color='black'),
                                     'About')
        self.grid_layout.addWidget(self.about_btn, 0, 0, 1, 5)

        self.exit_btn = QPushButton(qta.icon('fa5s.skull', color='red'),
                                    'Exit')
        self.grid_layout.addWidget(self.exit_btn, 0, 6, 1, 5)

        self.all_data_btn = QPushButton(
            qta.icon('fa5s.database', color='skyblue'), 'View ALL consumption')
        self.grid_layout.addWidget(self.all_data_btn, 1, 1, 2, 3)

        self.year_data_btn = QPushButton(
            qta.icon('fa5s.calendar', color='navy'),
            'View consumption in 2006')
        self.grid_layout.addWidget(self.year_data_btn, 1, 7, 2, 3)

        self.season_data_btn = QPushButton(
            qta.icon('fa5s.crow', color='black'), 'View consumption in SEASON')
        self.grid_layout.addWidget(self.season_data_btn, 3, 1, 2, 3)

        self.week_data_btn = QPushButton(
            qta.icon('fa5s.calendar-alt', color='crimson'),
            'View consumption in WEEK')
        self.grid_layout.addWidget(self.week_data_btn, 3, 7, 2, 3)

        self.all_solar_btn = QPushButton(
            qta.icon('fa5s.cloud-sun', color='orange'), 'View ALL solar')
        self.grid_layout.addWidget(self.all_solar_btn, 5, 1, 2, 3)

        self.season_solar_btn = QPushButton(
            qta.icon('fa5s.cloud', color='grey'), 'View solar in SEASON')
        self.grid_layout.addWidget(self.season_solar_btn, 5, 7, 2, 3)

        self.all_wind_btn = QPushButton(
            qta.icon('fa5s.cannabis', color='olive'), 'View ALL wind')
        self.grid_layout.addWidget(self.all_wind_btn, 7, 1, 2, 3)

        self.appro_wind_btn = QPushButton(
            qta.icon('fa5s.chart-line', color='green'),
            'View APPROXIMATE wind')
        self.grid_layout.addWidget(self.appro_wind_btn, 7, 7, 2, 3)
        pass

    def finish_layout(self):
        super().finish_layout()
        self.setLayout(self.grid_layout)
        pass

    def set_events(self):
        super().set_events()
        self.about_btn.clicked.connect(lambda: self.about())
        self.exit_btn.clicked.connect(lambda: self.close())
        self.all_data_btn.clicked.connect(lambda: self.alg.show_all_data())
        self.year_data_btn.clicked.connect(
            lambda: self.alg.show_data_in_2006())
        self.season_data_btn.clicked.connect(
            lambda: self.alg.show_data_in_season('Consumption'))
        self.week_data_btn.clicked.connect(
            lambda: self.alg.show_data_in_week())
        self.all_solar_btn.clicked.connect(
            lambda: self.alg.show_all_data_for_field('Solar'))
        self.season_solar_btn.clicked.connect(
            lambda: self.alg.show_data_in_season('Solar'))
        self.all_wind_btn.clicked.connect(
            lambda: self.alg.show_all_data_for_field('Wind'))
        self.appro_wind_btn.clicked.connect(
            lambda: self.predict_info_function())
        pass

    def about(self):
        self.about_box.message.setText(
            'Author: sakebow\nApplication: Energy Analysis')
        self.about_box.show()
        pass

    def predict_info_function(self):
        self.alg.predict_wind()
        k, b = self.alg.predict_model()
        days = int((self.alg.all_consumption_data.mean() - b) / k)
        self.predict_box.icon_label.setText('Prediction')
        self.predict_box.message.setText(
            f'The Wind & Solar will replace coal in {self.alg.days2date(days)[0]}-{self.alg.days2date(days)[1]}-{self.alg.days2date(days)[2]}'
        )
        self.predict_box.show()
        pass

    pass
Example #33
0
class Window(QWidget):
    def __init__(self, cc):
        super().__init__()

        self.camCtr = cc
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Camera Control')
        self.setMinimumWidth(260)
        self.grid = QGridLayout()
        self.grid.setContentsMargins(4, 4, 4, 4)
        self.grid.setSpacing(2)

        ### add control elements ###
        self.backlight_lbl = QLabel("Backlight Compensation")
        self.grid.addWidget(self.backlight_lbl, 10, 1, 1, 1, Qt.AlignLeft)
        self.backlight_comp_sl = QSlider()
        self.backlight_comp_sl.setOrientation(Qt.Horizontal)
        self.backlight_comp_sl.setValue(
            self.camCtr.getValue('backlight_compensation'))
        self.backlight_comp_sl.setTickInterval(1)
        self.backlight_comp_sl.setMaximum(
            self.camCtr.ctrls['backlight_compensation'][2])
        self.backlight_comp_sl.setMinimum(
            self.camCtr.ctrls['backlight_compensation'][1])
        self.backlight_comp_sl.valueChanged.connect(
            self.backlight_com_sl_Change)
        self.backlight_comp_sl.setMinimumWidth(200)
        self.grid.addWidget(self.backlight_comp_sl, 10, 2, 1, 1, Qt.AlignRight)

        self.brightness_lbl = QLabel("Brightness")
        self.grid.addWidget(self.brightness_lbl, 12, 1, 1, 1, Qt.AlignLeft)
        self.brightness_sl = QSlider()
        self.brightness_sl.setOrientation(Qt.Horizontal)
        self.brightness_sl.setValue(self.camCtr.getValue('brightness'))
        self.brightness_sl.setTickInterval(1)
        self.brightness_sl.setMaximum(self.camCtr.ctrls['brightness'][2])
        self.brightness_sl.setMinimum(self.camCtr.ctrls['brightness'][1])
        self.brightness_sl.valueChanged.connect(self.brighness_sl_Change)
        self.brightness_sl.setMinimumWidth(200)
        self.grid.addWidget(self.brightness_sl, 12, 2, 1, 1, Qt.AlignRight)

        self.sharpness_lbl = QLabel("Sharpness")
        self.grid.addWidget(self.sharpness_lbl, 13, 1, 1, 1, Qt.AlignLeft)
        self.sharpness_sl = QSlider()
        self.sharpness_sl.setOrientation(Qt.Horizontal)
        self.sharpness_sl.setValue(self.camCtr.getValue('sharpness'))
        self.sharpness_sl.setTickInterval(1)
        self.sharpness_sl.setMaximum(self.camCtr.ctrls['sharpness'][2])
        self.sharpness_sl.setMinimum(self.camCtr.ctrls['sharpness'][1])
        self.sharpness_sl.valueChanged.connect(self.sharpness_sl_Change)
        self.sharpness_sl.setMinimumWidth(200)
        self.grid.addWidget(self.sharpness_sl, 13, 2, 1, 1, Qt.AlignRight)

        self.contrast_lbl = QLabel("Contrast")
        self.grid.addWidget(self.contrast_lbl, 14, 1, 1, 1, Qt.AlignLeft)
        self.contrast_sl = QSlider()
        self.contrast_sl.setOrientation(Qt.Horizontal)
        self.contrast_sl.setValue(self.camCtr.getValue('contrast'))
        self.contrast_sl.setTickInterval(1)
        self.contrast_sl.setMaximum(self.camCtr.ctrls['contrast'][2])
        self.contrast_sl.setMinimum(self.camCtr.ctrls['contrast'][1])
        self.contrast_sl.valueChanged.connect(self.contrast_sl_Change)
        self.contrast_sl.setMinimumWidth(200)
        self.grid.addWidget(self.contrast_sl, 14, 2, 1, 1, Qt.AlignRight)

        self.reset = QPushButton()
        self.reset.setText('Reset')
        self.reset.clicked.connect(self.reset_Slot)
        self.grid.addWidget(self.reset, 17, 1, 1, 1, Qt.AlignCenter)

        ### end adding control elements

        self.mainLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.grid)
        self.setLayout(self.mainLayout)
        self.show()

    def backlight_com_sl_Change(self):
        self.camCtr.setValue('backlight_compensation',
                             self.backlight_comp_sl.value())

    def brighness_sl_Change(self):
        self.camCtr.setValue('brightness', self.brightness_sl.value())

    def sharpness_sl_Change(self):
        self.camCtr.setValue('sharpness', self.sharpness_sl.value())

    def contrast_sl_Change(self):
        self.camCtr.setValue('contrast', self.contrast_sl.value())

    def reset_Slot(self):
        self.camCtr.resetControls()
        self.backlight_comp_sl.setValue(
            self.camCtr.ctrls['backlight_compensation'][4])
        self.brightness_sl.setValue(self.camCtr.ctrls['brightness'][4])
        self.sharpness_sl.setValue(self.camCtr.ctrls['sharpness'][4])
        self.contrast_sl.setValue(self.camCtr.ctrls['contrast'][4])
Example #34
0
class Window(QWidget):
    def __init__(self, cc):
        super().__init__()

        self.autofocus_bool = False
        self.camCtr = cc
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Camera Control')
        self.setMinimumWidth(260)
        self.grid = QGridLayout()
        self.grid.setContentsMargins(4, 4, 4, 4)
        self.grid.setSpacing(2)

        ### add control elements ###
        self.backlight_lbl = QLabel("Backlight Compensation")
        self.grid.addWidget(self.backlight_lbl, 10, 1, 1, 1, Qt.AlignLeft)
        self.backlight_comp_sl = QSlider()
        self.backlight_comp_sl.setOrientation(Qt.Horizontal)
        self.backlight_comp_sl.setValue(
            self.camCtr.getValue('backlight_compensation'))
        self.backlight_comp_sl.setTickInterval(1)
        self.backlight_comp_sl.setMaximum(
            self.camCtr.ctrls['backlight_compensation'][2])
        self.backlight_comp_sl.setMinimum(
            self.camCtr.ctrls['backlight_compensation'][1])
        self.backlight_comp_sl.valueChanged.connect(
            self.backlight_com_sl_Change)
        self.backlight_comp_sl.setMinimumWidth(200)
        self.grid.addWidget(self.backlight_comp_sl, 10, 2, 1, 1, Qt.AlignRight)

        self.brightness_lbl = QLabel("Brightness")
        self.grid.addWidget(self.brightness_lbl, 12, 1, 1, 1, Qt.AlignLeft)
        self.brightness_sl = QSlider()
        self.brightness_sl.setOrientation(Qt.Horizontal)
        self.brightness_sl.setValue(self.camCtr.getValue('brightness'))
        self.brightness_sl.setTickInterval(1)
        self.brightness_sl.setMaximum(self.camCtr.ctrls['brightness'][2])
        self.brightness_sl.setMinimum(self.camCtr.ctrls['brightness'][1])
        self.brightness_sl.valueChanged.connect(self.brighness_sl_Change)
        self.brightness_sl.setMinimumWidth(200)
        self.grid.addWidget(self.brightness_sl, 12, 2, 1, 1, Qt.AlignRight)

        self.sharpness_lbl = QLabel("Sharpness")
        self.grid.addWidget(self.sharpness_lbl, 13, 1, 1, 1, Qt.AlignLeft)
        self.sharpness_sl = QSlider()
        self.sharpness_sl.setOrientation(Qt.Horizontal)
        self.sharpness_sl.setValue(self.camCtr.getValue('sharpness'))
        self.sharpness_sl.setTickInterval(1)
        self.sharpness_sl.setMaximum(self.camCtr.ctrls['sharpness'][2])
        self.sharpness_sl.setMinimum(self.camCtr.ctrls['sharpness'][1])
        self.sharpness_sl.valueChanged.connect(self.sharpness_sl_Change)
        self.sharpness_sl.setMinimumWidth(200)
        self.grid.addWidget(self.sharpness_sl, 13, 2, 1, 1, Qt.AlignRight)

        self.contrast_lbl = QLabel("Contrast")
        self.grid.addWidget(self.contrast_lbl, 14, 1, 1, 1, Qt.AlignLeft)
        self.contrast_sl = QSlider()
        self.contrast_sl.setOrientation(Qt.Horizontal)
        self.contrast_sl.setValue(self.camCtr.getValue('contrast'))
        self.contrast_sl.setTickInterval(1)
        self.contrast_sl.setMaximum(self.camCtr.ctrls['contrast'][2])
        self.contrast_sl.setMinimum(self.camCtr.ctrls['contrast'][1])
        self.contrast_sl.valueChanged.connect(self.contrast_sl_Change)
        self.contrast_sl.setMinimumWidth(200)
        self.grid.addWidget(self.contrast_sl, 14, 2, 1, 1, Qt.AlignRight)

        self.focabs_lbl = QLabel("Absolute Focus")
        self.grid.addWidget(self.focabs_lbl, 15, 1, 1, 1, Qt.AlignLeft)
        self.focabs_sl = QSlider()
        self.focabs_sl.setOrientation(Qt.Horizontal)
        self.focabs_sl.setValue(self.camCtr.getValue('focus_absolute'))
        self.focabs_sl.setTickInterval(1)
        self.focabs_sl.setMaximum(self.camCtr.ctrls['focus_absolute'][2])
        self.focabs_sl.setMinimum(self.camCtr.ctrls['focus_absolute'][1])
        self.focabs_sl.valueChanged.connect(self.focabs_sl_Change)
        self.focabs_sl.setMinimumWidth(200)
        self.grid.addWidget(self.focabs_sl, 15, 2, 1, 1, Qt.AlignRight)
        self.grid.addWidget(QLabel(""), 16, 1, 1, 1, Qt.AlignCenter)

        self.reset = QPushButton()
        self.reset.setText('Reset')
        self.reset.clicked.connect(self.reset_Slot)
        self.grid.addWidget(self.reset, 17, 1, 1, 1, Qt.AlignCenter)

        self.autofocus = QPushButton()
        self.autofocus.setText('Autofocus: OFF')
        self.autofocus.setStyleSheet("background-color: red")
        self.autofocus.clicked.connect(self.autofocus_Slot)
        self.grid.addWidget(self.autofocus, 17, 2, 1, 1, Qt.AlignCenter)
        ### end adding control elements

        self.mainLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.grid)
        self.setLayout(self.mainLayout)
        self.show()

    def backlight_com_sl_Change(self):
        self.camCtr.setValue('backlight_compensation',
                             self.backlight_comp_sl.value())

    def brighness_sl_Change(self):
        self.camCtr.setValue('brightness', self.brightness_sl.value())

    def sharpness_sl_Change(self):
        self.camCtr.setValue('sharpness', self.sharpness_sl.value())

    def contrast_sl_Change(self):
        self.camCtr.setValue('contrast', self.contrast_sl.value())

    def focabs_sl_Change(self):
        self.camCtr.setValue('focus_absolute', self.focabs_sl.value())

    def reset_Slot(self):
        self.camCtr.resetControls()
        self.backlight_comp_sl.setValue(
            self.camCtr.ctrls['backlight_compensation'][4])
        self.brightness_sl.setValue(self.camCtr.ctrls['brightness'][4])
        self.sharpness_sl.setValue(self.camCtr.ctrls['sharpness'][4])
        self.contrast_sl.setValue(self.camCtr.ctrls['contrast'][4])
        if not camCtr.autofocus:
            self.focabs_sl.setValue(self.camCtr.ctrls['focus_absolute'][4])

    def autofocus_Slot(self):
        if not self.camCtr.autofocus:
            self.camCtr.setAutofocus(True)
            self.focabs_sl.setDisabled(True)
            self.autofocus.setText('Autofocus: ON')
            self.autofocus.setStyleSheet("background-color: green")
        else:
            self.camCtr.setAutofocus(False)
            self.focabs_sl.setDisabled(False)
            self.autofocus.setText('Autofocus: OFF')
            self.autofocus.setStyleSheet("background-color: red")
            self.focabs_sl.setValue(self.camCtr.getValue('focus_absolute'))