Example #1
0
    def __init__(self, *args, **kwargs):
        super(PreviewWidget, self).__init__(*args, **kwargs)
        self.setAttribute(Qt.WA_StyledBackground, True)  # 支持样式
        layout = QGridLayout(self)
        layout.setVerticalSpacing(20)
        layout.setContentsMargins(10, 10, 10, 30)
        self.previewImage = PreviewImage(self)
        layout.addWidget(self.previewImage, 1, 0, 1, 3)  # 主题预览图片

        layout.addItem(
            QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum), 2,
            0)
        self.titleLabel = QLabel(self, objectName="titleLabel")
        self.titleLabel.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.titleLabel, 2, 1)  # 主题名字
        layout.addItem(
            QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum), 2,
            2)

        layout.addWidget(
            QPushButton("立即设置",
                        self,
                        clicked=self.onChoosed,
                        objectName="applyButton",
                        cursor=Qt.PointingHandCursor), 3, 1)
        layout.addWidget(
            QPushButton(self,
                        clicked=self.closed.emit,
                        objectName="closeButton",
                        cursor=Qt.PointingHandCursor), 5, 1)  # 关闭按钮
Example #2
0
    def wm_init_info(self):
        self.wu_app_nm = 'MyApp'
        self.wu_app_vr = '1.2.3'
        self.wu_app_au = 'Harawata'
        mu_lo = QGridLayout()
        mu_lo.addWidget(QLabel('Application name'), 0, 0,
                        Qt.AlignRight | Qt.AlignCenter)
        mu_lo.addWidget(QLabel('Application version'), 1, 0,
                        Qt.AlignRight | Qt.AlignCenter)
        mu_lo.addWidget(QLabel('Application author'), 2, 0,
                        Qt.AlignRight | Qt.AlignCenter)

        def mf2_le(x_str):
            fu2_it = QLineEdit()
            fu2_it.setText(x_str)
            fu2_it.setReadOnly(True)
            return fu2_it

        mu_lo.addWidget(mf2_le(self.wu_app_nm), 0, 1,
                        Qt.AlignLeft | Qt.AlignCenter)
        mu_lo.addWidget(mf2_le(self.wu_app_vr), 1, 1,
                        Qt.AlignLeft | Qt.AlignCenter)
        mu_lo.addWidget(mf2_le(self.wu_app_au), 2, 1,
                        Qt.AlignLeft | Qt.AlignCenter)
        for bu2_row in range(3):
            mu_lo.addItem(
                QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum),
                bu2_row, 2)
        return mu_lo
Example #3
0
    def __init__(self):
        # Be sure to call the super class method
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(480, 240))  # Set sizes
        self.setWindowTitle("Settings Application")  # Set a title
        central_widget = QWidget(self)  # Create a central widget
        self.setCentralWidget(central_widget)  # Set the central widget

        grid_layout = QGridLayout()  # Create a QGridLayout
        central_widget.setLayout(
            grid_layout)  # Set the layout into the central widget
        grid_layout.addWidget(
            QLabel("Application, which can minimize to Tray", self), 0, 0)

        # Add a checkbox, which will depend on the behavior of the program when the window is closed
        self.check_box = QCheckBox('Settings CheckBox for minimizing to tray')
        grid_layout.addWidget(self.check_box, 1, 0)
        grid_layout.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding), 2,
            0)

        # Get settings
        settings = QSettings()
        # Get checkbox state with speciying type of checkbox:
        # type=bool is a replacement of toBool() in PyQt5
        check_state = settings.value(SETTINGS_TRAY, False, type=bool)
        # Set state
        self.check_box.setChecked(check_state)
        # connect the slot to the signal by clicking the checkbox to save the state settings
        self.check_box.clicked.connect(self.save_check_box_settings)
Example #4
0
    def __init__(self,winParent, pose3d):
        super(PercentajeWidget, self).__init__()
        self.winParent=winParent
        self.map = cv2.imread("resources/images/mapgrannyannie.png", cv2.IMREAD_GRAYSCALE)
        self.map = cv2.resize(self.map, (500, 500))
        self.pose3d = pose3d
        self.percentajeHouse = 0
        self.numPixels = self.calculatePixelsWhite()
        self.numPixelsWalked = 0
        self.numPixelInit = 656

        layout = QGridLayout()

        self.seconds = 0
        self.MAXseconds = 900
        self.contSeconds = 0
        self.secondsArray = [0]

        self.devPercentajes = [0]
        self.percentajePrev = 0
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)

        layout.addWidget(self.canvas)

        vSpacer = QSpacerItem(30, 50, QSizePolicy.Ignored, QSizePolicy.Ignored)
        layout.addItem(vSpacer,1,0)

        self.setFixedSize(1200,500);

        self.setLayout(layout)

        timer = QTimer(self)
        timer.start(1000)
        timer.timeout.connect(self.accountantTime)
Example #5
0
    def __init__(self):
        super(EncodingParameters, self).__init__()

        self.total_label = QLabel("shares.total (N)")
        self.total_spinbox = QSpinBox()
        self.total_spinbox.setRange(1, 255)

        self.needed_label = QLabel("shares.needed (K)")
        self.needed_spinbox = QSpinBox()
        self.needed_spinbox.setRange(1, 255)

        self.happy_label = QLabel("shares.happy (H)")
        self.happy_spinbox = QSpinBox()
        self.happy_spinbox.setRange(1, 255)

        layout = QGridLayout(self)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, 0), 1, 1, 1, 4)
        layout.addWidget(self.total_label, 1, 2)
        layout.addWidget(self.total_spinbox, 1, 3)
        layout.addWidget(self.needed_label, 2, 2)
        layout.addWidget(self.needed_spinbox, 2, 3)
        layout.addWidget(self.happy_label, 3, 2)
        layout.addWidget(self.happy_spinbox, 3, 3)

        self.needed_spinbox.valueChanged.connect(self.on_value_changed)
        self.happy_spinbox.valueChanged.connect(self.on_value_changed)
        self.total_spinbox.valueChanged.connect(self.on_total_changed)
    def __init__(self, pose3d, parent=None):
        super(MainWindow, self).__init__(parent)

        layout = QGridLayout()

        self.seconds = 0
        self.MAXseconds = 900
        self.contSeconds = 0
        self.secondsArray = [0]

        self.devPercentajes = [0]
        self.percentaje = porcentajeWidget(self, pose3d)
        self.percentajePrev = 0
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)

        layout.addWidget(self.canvas)

        vSpacer = QSpacerItem(30, 50, QSizePolicy.Ignored, QSizePolicy.Ignored)
        layout.addItem(vSpacer, 1, 0)

        self.setFixedSize(1200, 500)

        self.setLayout(layout)

        timer = QTimer(self)
        timer.start(1000)
        timer.timeout.connect(self.contadorTime)
Example #7
0
    def __init__(self, parent: QMainWindow, object_name="tab_home"):
        super().__init__(parent)
        self.setObjectName(object_name)

        self.setAutoFillBackground(True)

        layout = QGridLayout()
        layout.setSizeConstraint(QLayout.SetMaximumSize)
        layout.setContentsMargins(0, 0, 0, 0)

        layout.addItem(QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Expanding), 0, 0)
        layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Expanding), 1, 0)

        display_widget = QWidget(self)

        inner_layout = QVBoxLayout(self)
        inner_layout.addWidget(DeskClock(self))
        inner_layout.addWidget(WeatherWidget(self))
        display_widget.setLayout(inner_layout)

        layout.addWidget(display_widget, 1, 1)

        layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Expanding), 1, 2)
        layout.addItem(QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Expanding), 2, 1)

        self.setLayout(layout)
Example #8
0
    def loginParents(self):
        gb1 = QGroupBox("Login")
        self.main_box.addWidget(gb1)
        # base layout
        base_box = QBoxLayout(QBoxLayout.TopToBottom, self)
        button_box = QBoxLayout(QBoxLayout.LeftToRight, self)

        line_edit_id       = self.loginID()
        line_edit_password = self.loginPassword()
        line_edit_id.textChanged.connect(self.senderTextID)
        line_edit_password.textChanged.connect(self.senderTextPassword)
        #self.password_text = line_edit_password.setEchoMode(QLineEdit.Password)

        save_button        = self.saveButton()
        cancel_button      = self.cancelButton()
        save_button.pressed.connect(self.saveFile)

        layout = QGridLayout()
        layout.addItem(QSpacerItem(30, 0))
        layout.addWidget(QLabel("ID             : "), 1, 0)
        layout.addWidget(line_edit_id, 1, 1)
        layout.addWidget(QLabel("Password  : "),2 ,0)
        layout.addWidget(line_edit_password, 2, 1)
        button_box.addWidget(save_button)
        button_box.addWidget(cancel_button)
        base_box.addLayout(layout)
        base_box.addLayout(button_box)

        gb1.setLayout(base_box)
Example #9
0
    def __topPanelBuilder(self):
        layout = QGridLayout()

        self.pluginDropdown = QtWidgets.QComboBox()
        self.poiTypeDropdown = QtWidgets.QComboBox()

        pluginLabel = QtWidgets.QLabel("Plugin")
        staticLabel = QtWidgets.QLabel("static")
        poiTypeLabel = QtWidgets.QLabel("Point of Interest Type")
        self.staticRunBtn = QtWidgets.QPushButton("Run")
        DynamicAn = QtWidgets.QLabel("Dynamic Analysis")
        self.dynamicRunbtn = QtWidgets.QPushButton("Run")
        self.dynamicStopbtn = QtWidgets.QPushButton("Stop")
        self.argsCheck = QCheckBox("Use Arguments")
        self.argsBox = QLineEdit()
        self.argsBox.setPlaceholderText("Arguments for Binary")
        self.argsBox.setEnabled(False)
        spacerItem = QtWidgets.QSpacerItem(1, 1, QSizePolicy.Expanding)

        layout.addWidget(pluginLabel, 0, 0, 1, 1)
        layout.addWidget(self.pluginDropdown, 0, 1, 1, 2)
        layout.addWidget(poiTypeLabel, 0, 3, 1, 2)
        layout.addWidget(self.poiTypeDropdown, 0, 5, 1, 2)
        layout.addItem(spacerItem, 0, 6, 1, 10)

        layout.addWidget(staticLabel, 1, 0, 1, 1)
        layout.addWidget(self.staticRunBtn, 1, 1, 1, 1)
        layout.addWidget(DynamicAn, 1, 2, 1, 1)
        layout.addWidget(self.dynamicRunbtn, 1, 3, 1, 1)
        layout.addWidget(self.dynamicStopbtn, 1, 4, 1, 1)
        layout.addWidget(self.argsCheck, 1, 5, 1, 1)
        layout.addWidget(self.argsBox, 1, 6, 1, 2)
        layout.addItem(spacerItem, 1, 5, 1, 13)

        return layout
Example #10
0
    def _setup_plotctrl(self, parent):
        frame = QWidget(parent)
        grid = QGridLayout(frame)
        grid.setContentsMargins(1, 1, 1, 1)

        self.lst_plots = QListWidget(frame)
        self.lst_plots.setSelectionMode(QAbstractItemView.ExtendedSelection)
        size_policy = QSizePolicy(QSizePolicy.Minimum,
                                  QSizePolicy.MinimumExpanding)
        size_policy.setVerticalStretch(1)
        self.lst_plots.setSizePolicy(size_policy)
        self.lst_plots.setMinimumSize(QSize(0, 30))
        self.lst_plots.setMaximumHeight(350)
        self.lst_plots.itemSelectionChanged.connect(self._toggle_buttons)
        self.lst_plots.itemDoubleClicked.connect(self._toggle_plot)
        grid.addWidget(self.lst_plots, 0, 0, 1, 2)

        btn_show = QPushButton(frame)
        btn_show.setText('Show')
        grid.addWidget(btn_show, 1, 0, 1, 1)
        btn_show.clicked.connect(self._show_plot)
        btn_show.setEnabled(False)
        btn_hide = QPushButton(frame)
        btn_hide.setText('Hide')
        btn_hide.setEnabled(False)
        grid.addWidget(btn_hide, 1, 1, 1, 1)
        btn_hide.clicked.connect(self._hide_plot)

        spacer = QSpacerItem(20, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
        grid.addItem(spacer, 2, 0, 1, 2)

        self.buttons = {'show': btn_show, 'hide': btn_hide}
        return frame
Example #11
0
    def __init__(self, pose3d, laser1, laser2, laser3, parent=None):
        super(MainWindow, self).__init__(parent)

        layout = QGridLayout()
        self.cheese = cheeseWidget(self, pose3d)
        self.time = timeWidget(self)
        self.quality = qualityWidget(self, laser1, laser2, laser3)
        self.distance = distanceWidget(self, pose3d)
        self.mark = markWidget(self, pose3d, self.time, self.quality,
                               self.distance)
        self.logo = logoWidget(self)
        layout.addWidget(self.cheese, 1, 0)
        layout.addWidget(self.time, 0, 0)
        layout.addWidget(self.distance, 0, 2)
        layout.addWidget(self.quality, 1, 2)
        layout.addWidget(self.mark, 0, 1)
        layout.addWidget(self.logo, 2, 2)

        vSpacer = QSpacerItem(30, 50, QSizePolicy.Ignored, QSizePolicy.Ignored)
        layout.addItem(vSpacer, 1, 0)

        self.setFixedSize(940, 640)

        self.setLayout(layout)
        self.updGUI.connect(self.update)
Example #12
0
    def _init_ui(self):
        self._video_frame = QLabel()
        layout = QVBoxLayout()
        self._video_frame.setMinimumHeight(self._image_height)
        self._video_frame.setMinimumWidth(self._image_width)
        layout.addWidget(self._video_frame)

        self._frame_value_widget = QWidget()
        frame_value_layout = QGridLayout(self._frame_value_widget)
        frame_value_layout.setVerticalSpacing(5)

        current_frame_lbl = QLabel('Current frame:')
        self._current_frame_value_lbl = QLabel('0')
        frame_value_layout.addWidget(current_frame_lbl, 0, 0)
        frame_value_layout.addWidget(self._current_frame_value_lbl, 0, 1)

        frame_acq_lbl = QLabel('Current frame acquisition time:')
        self._current_frame_acq_value_lbl = QLabel('')
        frame_value_layout.addWidget(frame_acq_lbl, 1, 0)
        frame_value_layout.addWidget(self._current_frame_acq_value_lbl, 1, 1)

        self._frame_sld = QSlider(Qt.Horizontal, self)
        frame_value_layout.addWidget(self._frame_sld, 2, 0, 1, 2)
        vertical_spacer = QSpacerItem(10, 1, QSizePolicy.Minimum,
                                      QSizePolicy.Expanding)
        frame_value_layout.addItem(vertical_spacer, 3, 0, 1, 2)

        self._frame_value_widget.setVisible(False)
        layout.addWidget(self._frame_value_widget)

        self.setLayout(layout)
Example #13
0
    def __init__(self, parent=None):
        super(InviteCodeWidget, self).__init__()
        self.parent = parent

        self.label = QLabel("Enter invite code:")
        font = QFont()
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setStyleSheet("color: grey")
        self.label.setAlignment(Qt.AlignCenter)

        self.lineedit = InviteCodeLineEdit(self)

        self.checkbox = QCheckBox("Connect over the Tor network")
        self.checkbox.setEnabled(True)
        self.checkbox.setCheckable(False)
        self.checkbox.setStyleSheet("color: grey")
        self.checkbox.setFocusPolicy(Qt.NoFocus)

        layout = QGridLayout(self)
        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 1, 1)
        layout.addWidget(self.label, 2, 1)
        layout.addWidget(self.lineedit, 3, 1)
        #layout.addWidget(self.checkbox, 4, 1, Qt.AlignCenter)
        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 5, 1)
Example #14
0
    def __init__(self, parent=None):
        super(CodeEntryWidget, self).__init__()
        self.parent = parent

        self.icon = QLabel()
        pixmap = QPixmap(resource('gridsync.png')).scaled(220, 220)
        self.icon.setPixmap(pixmap)
        self.icon.setAlignment(Qt.AlignCenter)

        self.slogan = QLabel("<i>Secure, distributed storage</i>")
        font = QFont()
        font.setPointSize(12)
        self.slogan.setFont(font)
        self.slogan.setStyleSheet("color: grey")
        self.slogan.setAlignment(Qt.AlignCenter)

        self.label = QLabel("Enter invite code:")
        font = QFont()
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setStyleSheet("color: grey")
        self.label.setAlignment(Qt.AlignCenter)

        self.lineedit = InviteCodeLineEdit(self)

        self.checkbox = QCheckBox("Connect over the Tor network")
        self.checkbox.setEnabled(True)
        self.checkbox.setCheckable(False)
        self.checkbox.setStyleSheet("color: grey")
        self.checkbox.setFocusPolicy(Qt.NoFocus)

        self.message = QLabel()
        self.message.setStyleSheet("color: red")
        self.message.setAlignment(Qt.AlignCenter)
        self.message.hide()

        self.help = QLabel()
        self.help.setText("<a href>I don't have an invite code</a>")
        font = QFont()
        font.setPointSize(9)
        self.help.setFont(font)
        self.help.setAlignment(Qt.AlignCenter)
        #self.help.linkActivated.connect(self.on_click)

        layout = QGridLayout(self)
        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 0, 0)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, 0), 1, 1)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, 0), 1, 2)
        layout.addWidget(self.icon, 1, 3)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, 0), 1, 4)
        layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, 0), 1, 5)
        layout.addWidget(self.slogan, 2, 3)
        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 3, 1)
        layout.addWidget(self.label, 4, 3, 1, 1)
        layout.addWidget(self.lineedit, 5, 2, 1, 3)
        #layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 6, 1)
        #layout.addWidget(self.checkbox, 6, 3, 1, 1, Qt.AlignCenter)
        layout.addWidget(self.message, 7, 3)
        layout.addWidget(self.help, 8, 3)
        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 9, 1)
Example #15
0
    def __init__(self):
        super().__init__()
        notifications_groupbox = QGroupBox("Notifications:", self)
        notifications_label = QLabel("Show a desktop notification when...")
        self.checkbox_connection = QCheckBox("Connection status changes")
        self.checkbox_folder = QCheckBox("A folder is updated")
        self.checkbox_invite = QCheckBox("An invite code is used")

        notifications_layout = QGridLayout()
        notifications_layout.addWidget(notifications_label)
        notifications_layout.addWidget(self.checkbox_folder)
        notifications_layout.addWidget(self.checkbox_invite)
        notifications_layout.addWidget(self.checkbox_connection)
        notifications_groupbox.setLayout(notifications_layout)

        layout = QGridLayout(self)
        layout.addWidget(notifications_groupbox)
        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding))

        self.checkbox_connection.stateChanged.connect(
            self.on_checkbox_connection_changed)
        self.checkbox_folder.stateChanged.connect(
            self.on_checkbox_folder_changed)
        self.checkbox_invite.stateChanged.connect(
            self.on_checkbox_invite_changed)

        self.load_preferences()
Example #16
0
class ResetSettings(QFrame):
    def __init__(self):
        super(ResetSettings, self).__init__()
        self.label = QLabel(self)
        self.label.setText("Reset settings:")

        self.button = QPushButton(self)
        self.button.setText("Reset")
        self.button.clicked.connect(self.reset_settings)
        self.button.setFixedWidth(120)

        self.layout = QGridLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(self.label, 0, 0, 1, 1)
        self.layout.addItem(SPACER, 0, 1, 1, 1)
        self.layout.addWidget(self.button, 0, 2, 1, 1)
        self.setLayout(self.layout)

    def reset_settings(self):
        prompt = QMessageBox.question(
            self,
            "Reset settings", "Are you sure?\n"
            "This will reset all settings to their default value, "
            "and the application will quit.",
            buttons=QMessageBox.No | QMessageBox.Yes,
            defaultButton=QMessageBox.No)
        if prompt == QMessageBox.Yes:
            reset_defaults()
            QCoreApplication.quit()
Example #17
0
    def createEditBox(self):
        # create group box
        self.editBox = QGroupBox()
        self.editBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
        gridLayout = QGridLayout(self.editBox)

        # create input fields
        self.operationInput = QLineEdit(self.model.projectData("operation"))
        self.operationInput.setFixedWidth(self._INPUTS_FIXED_WIDTH)
        self.operationInput.setClearButtonEnabled(True)
        self.operationLabel = QLabel()
        self.operationLabel.setBuddy(self.operationInput)
        gridLayout.addWidget(self.operationLabel, 0, 0)
        gridLayout.addWidget(self.operationInput, 0, 1)

        self.districtInput = QLineEdit(self.model.projectData("district"))
        self.districtInput.setFixedWidth(self._INPUTS_FIXED_WIDTH)
        self.districtInput.setClearButtonEnabled(True)
        self.districtLabel = QLabel()
        self.districtLabel.setBuddy(self.districtInput)
        gridLayout.addWidget(self.districtLabel, 0, 2)
        gridLayout.addWidget(self.districtInput, 0, 3)

        self.managerInput = QLineEdit(self.model.projectData("manager"))
        self.managerInput.setFixedWidth(self._INPUTS_FIXED_WIDTH)
        self.managerInput.setClearButtonEnabled(True)
        self.managerLabel = QLabel()
        self.managerLabel.setBuddy(self.managerInput)
        gridLayout.addWidget(self.managerLabel, 1, 0)
        gridLayout.addWidget(self.managerInput, 1, 1)

        self.locationInput = QLineEdit(self.model.projectData("location"))
        self.locationInput.setFixedWidth(self._INPUTS_FIXED_WIDTH)
        self.locationInput.setClearButtonEnabled(True)
        self.locationLabel = QLabel()
        self.locationLabel.setBuddy(self.locationInput)
        gridLayout.addWidget(self.locationLabel, 1, 2)
        gridLayout.addWidget(self.locationInput, 1, 3)

        lineFrame = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.VLine)
        gridLayout.addWidget(lineFrame, 0, 4, 2, 1)

        self.taxInput = QCheckBox()
        self.taxInput.setChecked(self.model.projectData("tax"))
        self.taxLabel = QLabel()
        self.taxLabel.setBuddy(self.taxInput)
        self.taxHint = ToolTipLabel()
        gridLayout.addWidget(self.taxLabel, 0, 5)
        gridLayout.addWidget(self.taxInput, 0, 6)
        gridLayout.addWidget(self.taxHint, 0, 7, Qt.AlignRight)
        gridLayout.setColumnMinimumWidth(7, 40)

        rightSpacer = QSpacerItem(20, 0, QSizePolicy.Expanding,
                                  QSizePolicy.Fixed)
        gridLayout.addItem(rightSpacer, 0, 8, 2, 1)

        self.dataWidget = EnhancedTreeWidget()
        gridLayout.addWidget(self.dataWidget, 2, 0, 1, 9)

        return self.editBox
 def __init__(self, pose3d, parent=None):
     super(MainWindow, self).__init__(parent)
     
     layout = QGridLayout()
     
     self.seconds = 0
     self.MAXseconds = 900
     self.contSeconds = 0
     self.secondsArray = [0]
     
     self.devPercentajes = [0]
     self.percentaje = porcentajeWidget(self, pose3d)
     self.percentajePrev = 0
     self.figure = plt.figure()
     self.canvas = FigureCanvas(self.figure)
     
     layout.addWidget(self.canvas)
     
     vSpacer = QSpacerItem(30, 50, QSizePolicy.Ignored, QSizePolicy.Ignored)
     layout.addItem(vSpacer,1,0)
     
     self.setFixedSize(1200,500);
     
     self.setLayout(layout)
     
     timer = QTimer(self)
     timer.start(1000)
     timer.timeout.connect(self.contadorTime)
Example #19
0
    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        self.setFixedSize(150, 300)
        self.move(300, 300)

        lab_p1 = QPushButton()
        lab_p2 = QPushButton()
        lab_p3 = QPushButton()
        lab_p1.setIcon(QIcon('msg2.png'))
        lab_p1.setIconSize(QSize(64, 64))
        lab_p2.setIcon(QIcon('video1.png'))
        lab_p2.setIconSize(QSize(64, 64))
        lab_p3.setIcon(QIcon('audio2.png'))
        lab_p3.setIconSize(QSize(64, 64))
        grid.addItem(QSpacerItem(150, 10), 0, 0, 1, 15)
        grid.addWidget(lab_p1, 0, 1, 1, 13)
        grid.addWidget(lab_p2, 1, 1, 1, 13)
        grid.addWidget(lab_p3, 2, 1, 1, 13)

        lab_p1.clicked.connect(self.startmsg)
        lab_p2.clicked.connect(self.startvideo)
        lab_p3.clicked.connect(self.startmsg)

        self.setWindowTitle('Pychat')
        self.setWindowIcon(QIcon('chat.png'))
        self.show()
Example #20
0
    def createWindow(self, mainWindow, title, icon, markdown):
        """Create readme sub window."""
        super().__init__(None)
        self.setWindowIcon(QIcon(scctool.settings.getAbsPath(icon)))
        self.mainWindow = mainWindow

        self.createMarkdownViewer(markdown)

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.viewer, 0, 0, 1, 3)
        closeButton = QPushButton(_("&OK"))
        closeButton.clicked.connect(self.close)
        mainLayout.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum), 1,
            0)
        mainLayout.addWidget(closeButton, 1, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle(title)

        self.resize(
            QSize(mainWindow.size().width() * 0.9,
                  self.sizeHint().height()))
        relativeChange = QPoint(mainWindow.size().width() / 2,
                                mainWindow.size().height() / 3)\
            - QPoint(self.size().width() / 2,
                     self.size().height() / 3)
        self.move(mainWindow.pos() + relativeChange)
Example #21
0
    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        self.setFixedSize(240, 300)
        self.move(300, 300)
        self.setWindowTitle('Pychat')
        self.setWindowIcon(QIcon('chat.png'))

        btn_go = QPushButton('Go')
        lab_ip = QLineEdit('0.0.0.0')
        lab_port = QLineEdit('9000')
        lab1 = QLabel('IP addr:')
        lab2 = QLabel('port:')
        grid.addItem(QSpacerItem(200, 85), 0, 0, 1, 20)
        grid.addWidget(QLabel('Set  your  ip address and  port:'), 1, 1, 1, 18)
        grid.addItem(QSpacerItem(200, 15), 2, 0, 1, 20)
        grid.addWidget(lab1, 3, 1)
        grid.addWidget(lab_ip, 3, 2, 1, 18)
        grid.addItem(QSpacerItem(200, 10), 4, 0, 1, 20)
        grid.addWidget(lab2, 5, 1)
        grid.addWidget(lab_port, 5, 2, 1, 18)
        grid.addItem(QSpacerItem(200, 20), 6, 1, 1, 20)
        grid.addWidget(btn_go, 7, 1, 1, 19)
        grid.addItem(QSpacerItem(200, 10), 8, 0, 1, 20)
        grid.addWidget(QLabel('---------------------------------------------'),
                       9, 1, 1, 20)
        grid.addWidget(QLabel('Dev by cyz @ XJTU'), 10, 1, 1, 20)

        btn_go.clicked.connect(self.getlocal)

        self.lab_ip = lab_ip
        self.lab_port = lab_port

        self.show()
    def createEditBox(self):
        # create group box
        self.editBox = QGroupBox()
        self.editBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
        gridLayout = QGridLayout(self.editBox)

        # create input fields
        self.operationInput = QLineEdit(self.model.projectData("operation"))
        self.operationInput.setFixedWidth(self._INPUTS_FIXED_WIDTH)
        self.operationInput.setClearButtonEnabled(True)
        self.operationLabel = QLabel()
        self.operationLabel.setBuddy(self.operationInput)
        gridLayout.addWidget(self.operationLabel, 0, 0)
        gridLayout.addWidget(self.operationInput, 0, 1)

        self.districtInput = QLineEdit(self.model.projectData("district"))
        self.districtInput.setFixedWidth(self._INPUTS_FIXED_WIDTH)
        self.districtInput.setClearButtonEnabled(True)
        self.districtLabel = QLabel()
        self.districtLabel.setBuddy(self.districtInput)
        gridLayout.addWidget(self.districtLabel, 0, 2)
        gridLayout.addWidget(self.districtInput, 0, 3)

        self.managerInput = QLineEdit(self.model.projectData("manager"))
        self.managerInput.setFixedWidth(self._INPUTS_FIXED_WIDTH)
        self.managerInput.setClearButtonEnabled(True)
        self.managerLabel = QLabel()
        self.managerLabel.setBuddy(self.managerInput)
        gridLayout.addWidget(self.managerLabel, 1, 0)
        gridLayout.addWidget(self.managerInput, 1, 1)

        self.locationInput = QLineEdit(self.model.projectData("location"))
        self.locationInput.setFixedWidth(self._INPUTS_FIXED_WIDTH)
        self.locationInput.setClearButtonEnabled(True)
        self.locationLabel = QLabel()
        self.locationLabel.setBuddy(self.locationInput)
        gridLayout.addWidget(self.locationLabel, 1, 2)
        gridLayout.addWidget(self.locationInput, 1, 3)

        lineFrame = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.VLine)
        gridLayout.addWidget(lineFrame, 0, 4, 2, 1)

        self.taxInput = QCheckBox()
        self.taxInput.setChecked(self.model.projectData("tax"))
        self.taxLabel = QLabel()
        self.taxLabel.setBuddy(self.taxInput)
        self.taxHint = ToolTipLabel()
        gridLayout.addWidget(self.taxLabel, 0, 5)
        gridLayout.addWidget(self.taxInput, 0, 6)
        gridLayout.addWidget(self.taxHint, 0, 7, Qt.AlignRight)
        gridLayout.setColumnMinimumWidth(7, 40)

        rightSpacer = QSpacerItem(20, 0, QSizePolicy.Expanding, QSizePolicy.Fixed)
        gridLayout.addItem(rightSpacer, 0, 8, 2, 1)

        self.dataWidget = EnhancedTreeWidget()
        gridLayout.addWidget(self.dataWidget, 2, 0, 1, 9)

        return self.editBox
Example #23
0
    def __init__(self, parent=None, help_text='', show_stats=True):
        super(PasswordDialog, self).__init__(parent)
        self.setMinimumWidth(400)

        self.label = QLabel("Password:"******"Toggle visibility")
        self.action.triggered.connect(self.toggle_visibility)
        self.lineedit.addAction(self.action, QLineEdit.TrailingPosition)
        self.lineedit.returnPressed.connect(self.accept)

        layout = QGridLayout(self)
        layout.addWidget(self.label, 1, 1)
        layout.addWidget(self.lineedit, 2, 1)

        if show_stats:
            self.progressbar = QProgressBar()
            self.progressbar.setMaximum(4)
            self.progressbar.setTextVisible(False)
            self.progressbar.setFixedHeight(5)
            self.progressbar.setStyleSheet(
                'QProgressBar { background-color: transparent }'
                'QProgressBar::chunk { background-color: gray }')

            self.rating_label = QLabel()
            self.rating_label.setAlignment(Qt.AlignRight)

            self.time_label = QLabel()
            self.time_label.setStyleSheet('color: gray')

            layout.addWidget(self.progressbar, 3, 1)
            layout.addWidget(self.time_label, 4, 1)
            layout.addWidget(self.rating_label, 4, 1)

            self.lineedit.textChanged.connect(self.update_stats)

            self.update_color('transparent')

        if help_text:
            gbox = QGroupBox()
            gbox_layout = QGridLayout()
            gbox_label = QLabel(help_text)
            gbox_label.setWordWrap(True)
            gbox_label.setAlignment(Qt.AlignCenter)
            gbox_label.setStyleSheet('color: gray')
            gbox_layout.addWidget(gbox_label)
            gbox.setLayout(gbox_layout)
            layout.addWidget(gbox, 5, 1)

        layout.addItem(QSpacerItem(0, 0, 0, QSizePolicy.Expanding), 6, 1)
Example #24
0
    def init_ui(self):
        font = QtGui.QFont()
        font.setPointSize(10)
        self.setFont(font)
        self.mySide = table_widget()
        self.mySide.setFixedHeight(300)
        self.otherSide = table_widget()
        self.otherSide.setFixedHeight(300)

        self.mySide.cellClicked.connect(self.mySide_item_clicked)

        self.otherSide.cellClicked.connect(self.otherSide_item_clicked)

        self.filter_line = QComboBox()
        self.filter_line.currentTextChanged.connect(self.filter)

        self.left_side = show_details()
        self.right_side = show_details()

        self.left_side.setFixedHeight(150)
        self.left_side.setFixedWidth(400)
        self.right_side.setFixedHeight(150)
        self.right_side.setFixedWidth(400)

        # match button
        self.match_btn = QPushButton('Match')
        self.match_btn_enable()
        self.match_btn.clicked.connect(self.match_work)

        # Save button
        self.save_work_btn = QPushButton("Save")
        self.save_work_btn.clicked.connect(self.save_work)

        gBox = QGridLayout()
        self.filter_prev_btn = QPushButton()
        self.filter_prev_btn.setIcon(QIcon('D:\Programs\Py\TallyProject\Scripts\\assets\icons\provious.png'))
        self.filter_prev_btn.clicked.connect(self.go_prev)
        self.filter_next_btn = QPushButton()
        self.filter_next_btn.setIcon(QIcon('D:\Programs\Py\TallyProject\media\icons\\next.png'))
        self.filter_next_btn.clicked.connect(self.go_next)
        gBox.addWidget(self.filter_prev_btn,1,0)
        gBox.addWidget(self.filter_next_btn,1,1)
        gBox.addWidget(self.filter_line,0,0,1,0)

        Main_gBox = QGridLayout()

        Main_gBox.addItem(gBox, 0, 1)
        Main_gBox.addWidget(self.save_work_btn, 3,1)
        Main_gBox.addWidget(self.mySide, 1, 0)
        Main_gBox.addWidget(self.otherSide, 1, 2)
        Main_gBox.addWidget(self.left_side, 2, 0)
        Main_gBox.addWidget(self.match_btn, 2,1)
        Main_gBox.addWidget(self.right_side, 2, 2)

        self.setLayout(Main_gBox)
        self.setDisabled(True)

        self.In = Input()
        self.In.send_filePath.connect(self.get_file_input)
Example #25
0
class SynchronizedEditors(QWidget):
    def __init__(self):

        super(SynchronizedEditors, self).__init__()

        self._layout = QGridLayout()

        @property
        def layout(self):
            return self._layout

        @layout.setter
        def layout(self, layout):
            self._layout = layout

        self.initUI()

    def initUI(self):

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setLayout(self._layout)
        self.show()

    def addEditorWidget(self, imageEditorWidget, position=(0, 0)):

        self.checkPosition(position)
        self._layout.addWidget(imageEditorWidget, position[0], position[1])

    def checkPosition(self, position):

        widget = self._layout.itemAtPosition(position[0], position[1])
        if widget:
            freePos = self.getFreePosition()
            self._layout.removeItem(widget)
            self._layout.addItem(widget, freePos[0], freePos[1])

    def getFreePosition(self):
        i = 0
        j = 0
        while self._layout.itemAtPosition(i, j):
            while i > j:
                if self._layout.itemAtPosition(i, j):
                    break
                j = j + 1
            i = i + 1
        return (i, j)

    def link(self, iEWidget1, iEWidget2):
        iEWidget2._imageEditor.posModel = iEWidget1._imageEditor.posModel
        self._saveShape = iEWidget1._imageEditor.posModel.shape

    def unlink(self, iEWidget1, iEWidget2):
        shape = iEWidget1._imageEditor.posModel.shape
        iEWidget1._imageEditor.posModel = PositionModelImage()
        iEWidget2._imageEditor.posModel = PositionModelImage()
        iEWidget1._imageEditor.posModel.shape = shape
        iEWidget2._imageEditor.posModel.shape = shape
Example #26
0
    def setupUi(self):
        self.setWindowTitle("Body Fat Calculator")
        self.setGeometry(self.left, self.top, self.width, self.height)

        neckLabel = QLabel("Neck")
        waistLabel = QLabel("Waist")
        heightLabel = QLabel("Height")
        ftLabel = QLabel(" ft ")
        inLabel = QLabel("in")

        self.neckInput = QLineEdit()
        self.waistInput = QLineEdit()
        self.ftInput = QLineEdit()
        self.inInput = QLineEdit()
        self.waistLabel = QLabel()

        self.butt = QPushButton("Submit")
        self.result = QLabel()

        heightLayout = QHBoxLayout()
        heightLayout.addWidget(self.ftInput)
        heightLayout.addWidget(ftLabel)
        heightLayout.addWidget(self.inInput)
        # heightLayout.addWidget(inLabel)

        inputLayout = QGridLayout()
        inputLayout.addWidget(waistLabel, 1, 0)
        inputLayout.addWidget(self.waistInput, 1, 1)
        inputLayout.addWidget(QLabel('in'), 1, 2)
        inputLayout.addWidget(neckLabel, 2, 0)
        inputLayout.addWidget(self.neckInput, 2, 1)
        inputLayout.addWidget(QLabel('in'), 2, 2)
        inputLayout.addWidget(heightLabel, 3, 0)
        inputLayout.addItem(heightLayout, 3, 1)
        inputLayout.addWidget(inLabel, 3, 2)
        # inputLayout.addWidget(self.ftInput,3, 1)
        # inputLayout.addWidget(ftLabel,3, 2)
        # inputLayout.addWidget(self.inInput, 4, 1)
        # inputLayout.addWidget(inLabel, 4, 2)

        # inputLayout.addWidget(self.butt, 5, 0)
        # inputLayout.addWidget(self.result, 6, 0, 5, 1)

        bottomLayout = QVBoxLayout()

        submitLayout = QHBoxLayout()
        submitLayout.addWidget(self.butt)
        submitLayout.addWidget(self.result)

        bottomLayout.addLayout(submitLayout)
        bottomLayout.addWidget(self.waistLabel)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(inputLayout)
        mainLayout.addLayout(bottomLayout)

        self.setLayout(mainLayout)
        self.show()
Example #27
0
	def buildUi(self):	
	
		main_layout = QVBoxLayout()
		main_layout.setSpacing(12)

		var_box = QGroupBox(self.tr("Variables"))
		var_box_layout = QGridLayout(var_box)
		main_layout.addWidget(var_box)

		var_box_layout.addWidget(QLabel(self.tr("%ROOT% (root topic) :")), 0, 0)
		var_box_layout.addWidget(self._varRootInput, 0, 1)

		var_box_layout.addWidget(QLabel(self.tr("%INBOX% (correspondent inbox) :")), 1, 0)
		var_box_layout.addWidget(self._varInboxInput, 1, 1)

		var_box_layout.addWidget(QLabel(self.tr("%OUTBOX% (correspondent outbox) :")), 2, 0)
		var_box_layout.addWidget(self._varOutboxInput, 2, 1)

		regex_box = QGroupBox(self.tr("Regex to extract correspondent from topic"))
		regex_box_layout = QGridLayout(regex_box)
		main_layout.addWidget(regex_box)

		regex_box_layout.addWidget(QLabel(self.tr("Inbox :")), 0, 0)
		regex_box_layout.addWidget(self._regexInboxInput, 0, 1)
		regex_box_layout.addWidget(self._regexInbox, 1, 1)

		regex_box_layout.addItem(QSpacerItem(12 , 12), 2, 0)

		regex_box_layout.addWidget(QLabel(self.tr("Outbox :")), 3, 0)
		regex_box_layout.addWidget(self._regexOutboxInput, 3, 1)
		regex_box_layout.addWidget(self._regexOutbox, 4, 1)

		regex_box_layout.addItem(QSpacerItem(12 , 12), 5, 0)

		regex_box_layout.addWidget(QLabel(self.tr("Default :")), 6, 0)
		regex_box_layout.addWidget(self._regexDefaultInput, 6, 1)
		regex_box_layout.addWidget(self._regexDefault, 7, 1)

		main_layout.addSpacing(8)

		apply_button = QPushButton(self.tr("Apply"))
		ignore_button = QPushButton(self.tr("Ignore"))
		reset_button = QPushButton(self.tr("Reset"))

		button_layout = QHBoxLayout()
		button_layout.addWidget(reset_button)
		button_layout.addStretch()
		button_layout.addWidget(apply_button)
		button_layout.addWidget(ignore_button)
		main_layout.addLayout(button_layout)

		self.setLayout(main_layout)

		apply_button.pressed.connect(self.apply)
		ignore_button.pressed.connect(self.accept)
		reset_button.pressed.connect(self.reset)

		ignore_button.setFocus()
Example #28
0
    def __init__(self):
        # Обязательно нужно вызвать метод супер класса
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(200, 100))  # Устанавливаем размеры
        self.setWindowTitle(
            "Aperture Screener")  # Устанавливаем заголовок окна
        self.setWindowIcon(QtGui.QIcon("aperture_icon.ico"))
        central_widget = QWidget(self)  # Создаём центральный виджет
        self.setCentralWidget(
            central_widget)  # Устанавливаем центральный виджет

        grid_layout = QGridLayout(self)  # Создаём QGridLayout
        central_widget.setLayout(
            grid_layout
        )  # Устанавливаем данное размещение в центральный виджет
        grid_layout.addWidget(
            QLabel("Для съемки скриншота нажмите клавишу 'Prt Sc'", self), 0,
            0)

        # Добавляем чекбокс, от которого будет зависеть поведение программы при закрытии окна
        self.check_box = QCheckBox('Сворачивать в трей')
        grid_layout.addWidget(self.check_box, 1, 0)
        grid_layout.addWidget(
            QLabel("Для выбора папки сохранения нажмите 'Browse'", self), 2, 0)
        self.button = QPushButton("Browse", self)
        self.button.setGeometry(210, 70, 50, 25)

        self.button.clicked.connect(self.chooseFolder)
        self.textedit = QTextEdit(self)
        self.textedit.setGeometry(10, 70, 190, 25)
        grid_layout.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding), 3,
            0)
        self.ScreeenShotThread_instance = ScreeenShotThread()
        self.ScreeenShotThread_instance.start()

        # Инициализируем QSystemTrayIcon
        self.tray_icon = QSystemTrayIcon(QtGui.QIcon("aperture_icon.ico"))
        '''
            Объявим и добавим действия для работы с иконкой системного трея
            show - показать окно
            hide - скрыть окно
            exit - выход из программы
        '''
        show_action = QAction("Show", self)
        quit_action = QAction("Exit", self)
        hide_action = QAction("Hide", self)
        show_action.triggered.connect(self.show)
        hide_action.triggered.connect(self.hide)
        quit_action.triggered.connect(qApp.quit)
        tray_menu = QMenu()
        tray_menu.addAction(show_action)
        tray_menu.addAction(hide_action)
        tray_menu.addAction(quit_action)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()
    def initUI(self):
        

        grid = QGridLayout()
        self.setLayout(grid)

        self.widgetlabels = {}
        for ii, (name, value) in enumerate(default_param.items()):
            row = ii // self.param_per_row * 2
            col = (ii % self.param_per_row)
            

            w = ParamWidget(name, value=value)
            self.widgetlabels[name] = w

            if isinstance(w.widget, QCheckBox):
                grid.addWidget(w.widget, row, col, 2, 1)
                w.widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
            else:
                label = QLabel(name)
                grid.addWidget(label, row, col, 1, 1)
                label.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
                if isinstance(w.widget, QGridLayout):
                    grid.addLayout(w.widget, row+1, col, 1, 1)
                else:
                    grid.addWidget(w.widget, row+1, col, 1, 1)
                    w.widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        #assert all(x for x in self.widgetlabels)
        
        spacer = QSpacerItem(
            40,
            20,
            QSizePolicy.Preferred,
            QSizePolicy.Preferred)

        self.pushbutton_save = QPushButton('Save')
        self.pushbutton_file = QPushButton('Select File')
        self.lineEdit_file = QLineEdit(self.param_file)

        last_row = len(default_param) // self.param_per_row * 2 + 3
        last_col = max(self.param_per_row - 1, 3)
        grid.addWidget(self.pushbutton_save, last_row, 0, 1, 1)
        grid.addWidget(self.pushbutton_file, last_row, last_col, 1, 1)
        grid.addWidget(self.lineEdit_file, last_row, 1, 1, last_col - 1)
        grid.addItem(spacer, last_row - 1, 0, 1, 1)

        LineEditDragDrop(
            self.lineEdit_file,
            self.updateParamFile,
            os.path.isfile)

        # used to find if anything was modified.
        self.lastreadparams = self._readParams()

        self.show()
        self.setAttribute(Qt.WA_DeleteOnClose)
Example #30
0
    def show():
        """
        Bring up the panel to interactively show sales data.
        """
        app = QApplication([])
        app.setApplicationName("Car Sales")
        app.setStyleSheet(STYLE)

        window = QWidget()
        page = QGridLayout(window)
        # Row 0 has 2 labels
        for index, lable in enumerate(["Agents", "Customers"]):
            page.addWidget(QLabel(lable), 0, index * 2, 1, 2)
        # Row 1 has 2 LineEdit and 1 Run button
        agentInput = QLineEdit()
        page.addWidget(agentInput, 2, 0, 1, 2)
        customerInput = QLineEdit()
        page.addWidget(customerInput, 2, 2, 1, 2)

        runButton = QPushButton("Run")
        page.addWidget(runButton, 2, 4)

        # Row 2 has spacing accordingly
        page.addItem(QSpacerItem(200, 20), 3, 0, 1, 7)

        # Row 3 has 3 Labels
        for index, lable in enumerate(["Mean", "Median", "SD"]):
            page.addWidget(QLabel(lable), 4, index)

        # Row 4 has 3 labels contain result values
        Sales.mean = QLabel("0.0")
        Sales.median = QLabel("0.0")
        Sales.sd = QLabel("0.0")
        for index, value in enumerate([Sales.mean, Sales.median, Sales.sd]):
            page.addWidget(value, 5, index)

        # Row 5 is a table display results
        table = QTableWidget(5, 5)
        Sales.table = table
        table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        table.setHorizontalHeaderLabels(
            ["ID", "Deals", "Revenue", "Commission", "Bonus"])
        page.addWidget(table, 6, 0, 1, 7)

        # Set IntValidator to only accept integers
        agentInput.setValidator(QIntValidator(0, 500))
        customerInput.setValidator(QIntValidator(0, 10000))
        # Get input from users
        agentInput.textChanged.connect(Sales.initAgent)
        customerInput.textChanged.connect(Sales.initCustomer)
        # Run result if run clicked
        runButton.clicked.connect(Sales.showTable)

        window.show()

        app.exec()
Example #31
0
    def __init__(self):
        self.inhibitor = create_inibitor()
        self.settings = QtCore.QSettings(APP_NAME, APP_NAME)
        self.scheduler_event = None
        self.scheduler = sched.scheduler(time.time, time.sleep)
        self.scheduler.run(blocking=False)

        LOGGER.info("Using inhibitor %s", type(self.inhibitor))

        # Be sure to call the super class method
        QMainWindow.__init__(self)

        self.setMinimumSize(QtCore.QSize(480, 80))  # Set sizes
        self.setWindowTitle("System Tray Application")  # Set a title
        central_widget = QWidget(self)  # Create a central widget
        self.setCentralWidget(central_widget)  # Set the central widget

        grid_layout = QGridLayout(central_widget)  # Create a QGridLayout
        # central_widget.setLayout(grid_layout)  # Set the layout into the central widget
        grid_layout.addWidget(
            QLabel("Application, which can minimize to Tray", self), 0, 0)

        # Add a checkbox, which will depend on the behavior of the program when the window is closed
        self.check_box = QCheckBox('Minimize to Tray')
        grid_layout.addWidget(self.check_box, 1, 0)
        grid_layout.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding), 2,
            0)

        settings_action = QAction("Settings", self)
        settings_action.setIcon(self.style().standardIcon(
            QStyle.SP_DialogCloseButton))
        settings_action.triggered.connect(self.show)

        quit_action = QAction("Exit", self)
        quit_action.setIcon(self.style().standardIcon(
            QStyle.SP_DialogCloseButton))
        quit_action.triggered.connect(qApp.quit)

        tray_menu = QMenu()
        for minutes in [1, 30, 60, 120]:
            insomnia_action = QAction('{}m'.format(minutes), self)
            insomnia_action.triggered.connect(
                lambda x: self.schedule_insomnia(minutes))
            tray_menu.addAction(insomnia_action)

        tray_menu.addAction(settings_action)
        tray_menu.addAction(quit_action)

        # Init QSystemTrayIcon
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.activated.connect(self.toggle_insomnia)
        self.tray_icon.setContextMenu(tray_menu)

        self.set_insomnia(False)
        self.tray_icon.show()
Example #32
0
    def __init__(self, tooltip):
        LinkableSetting.__init__(self, ["log_level", "log_output"])
        QFrame.__init__(self)

        level_label = QLabel(self)
        level_label.setText("Debug mode:")
        level_label.setToolTip(tooltip)

        output_label = QLabel(self)
        output_label.setText("Debug Output:")
        output_label.setToolTip(tooltip)

        level_combobox = QComboBox(self)
        level_combobox.setFixedWidth(120)
        level_combobox.addItem("CRITICAL", 50)
        level_combobox.addItem("ERROR", 40)
        level_combobox.addItem("WARNING", 30)
        level_combobox.addItem("INFO", 20)
        level_combobox.addItem("DEBUG", 10)
        level_combobox.addItem("TRACE", 5)
        level_combobox.setInsertPolicy(QComboBox.NoInsert)
        LOG_MAPPING = {50: 0, 40: 1, 30: 2, 20: 3, 10: 4, 5: 5}
        level_combobox.setCurrentIndex(
            LOG_MAPPING[self.setting_values["log_level"]])
        level_combobox.currentIndexChanged.connect(
            lambda: self.on_setting_changed_from_gui(
                "log_level", level_combobox.currentData()))
        self.level_combobox = level_combobox

        output_combobox = QComboBox(self)
        output_combobox.setFixedWidth(120)
        output_combobox.addItem("NONE")
        output_combobox.addItem("TERMINAL")
        output_combobox.addItem("NEW WINDOW")
        output_combobox.addItem("BOTH")
        output_combobox.setInsertPolicy(QComboBox.NoInsert)
        output_combobox.setCurrentIndex(0)  # NONE by default
        output_combobox.setCurrentIndex(self.setting_values["log_output"])
        output_combobox.currentIndexChanged.connect(
            lambda val: self.on_setting_changed_from_gui("log_output", val))
        self.output_combobox = output_combobox

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(level_label, 0, 0, 1, 1)
        layout.addItem(SPACER, 0, 1, 1, 1)
        layout.addWidget(self.level_combobox, 0, 2, 1, 3, Qt.AlignRight)
        layout.addWidget(output_label, 1, 0, 1, 1)
        layout.addItem(SPACER, 1, 1, 1, 1)
        layout.addWidget(self.output_combobox, 1, 2, 1, 3, Qt.AlignRight)

        self.setLayout(layout)
Example #33
0
    def init_ui(self):
        """Init the UI"""
        klog.debug('init_ui')
        self.setWindowTitle('Cinfkiosk')
        #self.setWindowIcon(QIcon('web.png'))

        layout = QGridLayout(self)
        
        # Add graphs
        # FIXME Maybe flowlayout, gridlayout or anchorlayout
        max_column = 0
        max_row = 0
        for figure_def in self.xml.findall('figure'):
            # Make the figure
            figure_id = figure_def.attrib['id']
            if figure_id in self.figures:
                raise ValueError('The graph id must be unique. "{} already known"'.format(figure_id))
            klog.debug("Add figure: %s", figure_id)
            fig = CinfFigure(figure_def)

            # Add it to the grid layout
            # grid is [row, column, rowspan, columnspan] or [row, column]
            grid = typed(figure_def.find('grid'))
            # Pad 1's for the row and column span if necessary
            grid = grid + [1] * (4 - len(grid))
            klog.debug("Add to grid %s", grid)
            max_column = max(max_column, grid[1] + grid[3] - 1)
            max_row = max(max_row, grid[0] + grid[2] - 1)
            layout.addWidget(fig.native, *grid)

            self.figures[figure_id] = fig

        klog.debug("Add spacer to %s, %s", max_row + 1, max_column + 1)
        layout.addItem(QSpacerItem(1, 1), max_row + 1, max_column + 1)
        layout.setColumnStretch(max_column + 1, 1)
        layout.setRowStretch(max_row + 1, 1)
        self.setLayout(layout)

        klog.debug('show')
        self.showMaximized()
Example #34
0
    def __init__(self, pose3d, parent=None):
        super(MainWindow, self).__init__(parent)

        layout = QGridLayout()
        self.percentaje = percentajeWidget(self, pose3d)
        self.timeDigital = timeDigitalWidget(self, self.percentaje)
        self.timeAnalog = timeAnalogWidget(self)
        self.map = mapWidget(self, pose3d)
        self.logo = logoWidget(self)
        layout.addWidget(self.timeDigital,0,2)
        layout.addWidget(self.percentaje,0,0)
        layout.addWidget(self.map,1,0)
        layout.addWidget(self.timeAnalog,1,2)
        layout.addWidget(self.logo,2,2)

        vSpacer = QSpacerItem(50, 50, QSizePolicy.Ignored, QSizePolicy.Ignored)
        layout.addItem(vSpacer,1,0)

        self.setFixedSize(840,640);

        self.setLayout(layout)
        self.updGUI.connect(self.update)
Example #35
0
def add_to_grid(*items):
    """Add items to a QGrid layout easily.

    Keyword arguments:
    *items -- list with lists of items to be added.
              items in the same list will be added to the same line of grid.
    """
    layout = QGridLayout()
    # for now it adds only 1 item per cell.
    for x, _list in enumerate(items):
        for y, item in enumerate(_list):
            if isinstance(item, QWidget):
                layout.addWidget(item, x, y)
            elif isinstance(item, QLayout):
                layout.addLayout(item, x, y)
            elif isinstance(item, QSpacerItem):
                layout.addItem(item, x, y)
            elif item is None:
                pass
            else:
                raise TypeError("Argument of wrong type!")
    return layout
    def __init__(self, pose3d, laser1, laser2, laser3, parent=None):
        super(MainWindow, self).__init__(parent)
        
        layout = QGridLayout()
        self.cheese = cheeseWidget(self, pose3d)
        self.time = timeWidget(self)
        self.quality = qualityWidget(self, laser1, laser2, laser3)
        self.distance = distanceWidget(self, pose3d)
        self.mark = markWidget(self,pose3d, self.time, self.quality, self.distance)
        self.logo = logoWidget(self)
        layout.addWidget(self.cheese,1,0)
        layout.addWidget(self.time,0,0)
        layout.addWidget(self.distance,0,2)
        layout.addWidget(self.quality,1,2)
        layout.addWidget(self.mark,0,1)
        layout.addWidget(self.logo,2,2)
    
        vSpacer = QSpacerItem(30, 50, QSizePolicy.Ignored, QSizePolicy.Ignored)
        layout.addItem(vSpacer,1,0)
        
        self.setFixedSize(940,640);

        self.setLayout(layout)
        self.updGUI.connect(self.update)
Example #37
0
class Ui_MetroProgressCircleBar(object):

    def setupUi(self, MetroProgressCircle):
        MetroProgressCircle.setObjectName("MetroProgressCircle")
        MetroProgressCircle.resize(100, 100)
        self.gridLayout = QGridLayout(MetroProgressCircle)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setSpacing(0)
        self.gridLayout.setObjectName("gridLayout")
        spacerItem = QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 0, 1, 1, 1)
        spacerItem1 = QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem1, 2, 1, 1, 1)
        spacerItem2 = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem2, 1, 0, 1, 1)
        self.MetroProgressCircleBar = QWidget(MetroProgressCircle)
        self.MetroProgressCircleBar.setMinimumSize(QSize(100, 100))
        self.MetroProgressCircleBar.setMaximumSize(QSize(100, 100))
        self.MetroProgressCircleBar.setObjectName("MetroProgressCircleBar")
        self.MetroProgressBarCircle1 = QWidget(self.MetroProgressCircleBar)
        self.MetroProgressBarCircle1.setGeometry(QRect(92, 46, 8, 8))
        self.MetroProgressBarCircle1.setObjectName("MetroProgressBarCircle1")
        self.MetroProgressBarCircle2 = QWidget(self.MetroProgressCircleBar)
        self.MetroProgressBarCircle2.setGeometry(QRect(92, 46, 8, 8))
        self.MetroProgressBarCircle2.setObjectName("MetroProgressBarCircle2")
        self.MetroProgressBarCircle3 = QWidget(self.MetroProgressCircleBar)
        self.MetroProgressBarCircle3.setGeometry(QRect(92, 46, 8, 8))
        self.MetroProgressBarCircle3.setObjectName("MetroProgressBarCircle3")
        self.MetroProgressBarCircle4 = QWidget(self.MetroProgressCircleBar)
        self.MetroProgressBarCircle4.setGeometry(QRect(92, 46, 8, 8))
        self.MetroProgressBarCircle4.setObjectName("MetroProgressBarCircle4")
        self.MetroProgressBarCircle5 = QWidget(self.MetroProgressCircleBar)
        self.MetroProgressBarCircle5.setGeometry(QRect(92, 46, 8, 8))
        self.MetroProgressBarCircle5.setObjectName("MetroProgressBarCircle5")
        self.gridLayout.addWidget(self.MetroProgressCircleBar, 1, 1, 1, 1)
        spacerItem3 = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem3, 1, 2, 1, 1)
Example #38
0
class SettingDialog(QDialog):

    def __init__(self):
        super(SettingDialog, self).__init__()
        self.setupUi(self)

    def setupUi(self, setDialog):
        setDialog.setObjectName("setDialog")
        setDialog.setWindowTitle(self.tr("Settings"))
        setDialog.resize(540, 330)

        ##### main dialog #####
        self.mainGridLayout = QGridLayout(setDialog)

        self.tabWidget = QTabWidget(setDialog)
        self.tabWidget.setLayoutDirection(Qt.LeftToRight)  # 内容布局方向
        self.tabWidget.setTabPosition(QTabWidget.North)  # 标签位置
        self.tabWidget.setTabShape(QTabWidget.Rounded)  # 标签形状 Rounded, Triangular
        self.mainGridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)  # 行, 列, 占行数, 占列数

        self.buttonBox = QDialogButtonBox(setDialog)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel |
            QDialogButtonBox.Ok | QDialogButtonBox.Save)
        self.mainGridLayout.addWidget(self.buttonBox, 1, 0, 1, 1)

        ##### Basic tab #####
        self.basicTab = QWidget()
        self.tabWidget.addTab(self.basicTab, self.tr("Basic"))

        self.basicGridLayout = QGridLayout(self.basicTab)
        self.basicGridLayout.setContentsMargins(15, 10, 15, 20)

        self.workerNumLabel = QLabel(self.basicTab)
        self.workerNumLabel.setText(self.tr("worker number"))
        self.workerNumLabel.setToolTip(self.tr("number of worker for crawler"))
        self.basicGridLayout.addWidget(self.workerNumLabel, 0, 0, 1, 1)

        self.workerNumBox = QSpinBox(self.basicTab)
        self.workerNumBox.setMinimum(1)
        self.workerNumBox.setMaximum(30)
        self.workerNumBox.setValue(config['worker_num'])
        self.basicGridLayout.addWidget(self.workerNumBox, 0, 1, 1, 1)

        self.retryTimeLabel = QLabel(self.basicTab)
        self.retryTimeLabel.setText(self.tr("retry times"))
        self.retryTimeLabel.setToolTip(self.tr("retry times if network fails"))
        self.basicGridLayout.addWidget(self.retryTimeLabel, 1, 0, 1, 1)

        self.retryTimeBox = QSpinBox(self.basicTab)
        self.retryTimeBox.setValue(config['retry'])
        self.basicGridLayout.addWidget(self.retryTimeBox, 1, 1, 1, 1)

        self.retryWaitLabel = QLabel(self.basicTab)
        self.retryWaitLabel.setText(self.tr("retry wait time"))
        self.retryWaitLabel.setToolTip(self.tr("wait time before retry network access"))
        self.basicGridLayout.addWidget(self.retryWaitLabel, 2, 0, 1, 1)

        self.retryWaitBox = QSpinBox(self.basicTab)
        self.retryWaitBox.setValue(config['retry_time'])
        self.basicGridLayout.addWidget(self.retryWaitBox, 2, 1, 1, 1)

        ##### Network tab #####
        self.networkTab = QWidget()
        self.tabWidget.addTab(self.networkTab, self.tr("Network"))

        self.networkGridLayout = QGridLayout(self.networkTab)
        self.networkGridLayout.setContentsMargins(15, 20, 15, 20)

        self.addrLabel = QLabel(self.networkTab)
        self.addrLabel.setText(self.tr("proxy address"))
        self.addrLabel.setToolTip(self.tr("proxy address"))
        self.networkGridLayout.addWidget(self.addrLabel, 0, 0, 1, 1)

        self.addr = config['proxy']['http'].split('://') + ['']
        self.addrEdit = QLineEdit(self.networkTab)
        self.addrEdit.setText(self.addr[1])
        self.addrEdit.setToolTip(self.tr("[user:pass@]hostname[:port]"))
        self.networkGridLayout.addWidget(self.addrEdit, 0, 1, 1, 4)

        horSpacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.networkGridLayout.addItem(horSpacerItem, 1, 0, 1, 1)

        self.httpBtn = QRadioButton(self.networkTab)
        self.httpBtn.setText(self.tr("http"))
        self.networkGridLayout.addWidget(self.httpBtn, 1, 1, 1, 1)

        self.httpsBtn = QRadioButton(self.networkTab)
        self.httpsBtn.setText(self.tr("https"))
        self.networkGridLayout.addWidget(self.httpsBtn, 1, 2, 1, 1)

        self.socks4Btn = QRadioButton(self.networkTab)
        self.socks4Btn.setText(self.tr("socks4"))
        self.networkGridLayout.addWidget(self.socks4Btn, 1, 3, 1, 1)

        self.socks5Btn = QRadioButton(self.networkTab)
        self.socks5Btn.setText(self.tr("socks5"))
        self.networkGridLayout.addWidget(self.socks5Btn, 1, 4, 1, 1)

        verSpacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.networkGridLayout.addItem(verSpacerItem, 2, 0, 1, 1)

        self.radios = self.httpBtn, self.httpsBtn, self.socks4Btn, self.socks5Btn
        self.setRadioBtn(self.addr[0])  # 根据协议按下按钮

        # Signal & Slot
        self.buttonBox.accepted.connect(self.saveOptionSlot)
        self.buttonBox.accepted.connect(setDialog.accept)
        self.buttonBox.rejected.connect(setDialog.reject)
        self.buttonBox.clicked.connect(self.saveOptionToFileSlot)

    def setRadioBtn(self, scheme):
        """click btn"""
        for btn in self.radios:
            if btn.text() == scheme:
                btn.click()

    def getRadioBtn(self):
        """get clicked btn"""
        for btn in self.radios:
            if btn.isChecked():
                return btn.text()

        return None

    def saveOptionSlot(self):
        """save options"""
        config.load_config(**{
            'worker_num': self.workerNumBox.value(),
            'retry': self.retryTimeBox.value(),
            'retry_time': self.retryWaitBox.value(),
            'proxy': "%s://%s" % (self.getRadioBtn(), self.addrEdit.text()) \
                         if self.getRadioBtn() else ""
        })

    def saveOptionToFileSlot(self, btn):
        """save options to file via save_config func"""
        if btn.text() == 'Save':
            config.save_config()
class TemplateMultipleVariablesDialog(QDialog):
    """
    Class implementing a dialog for entering multiple template variables.
    """

    def __init__(self, variables, parent=None):
        """
        Constructor
        
        @param variables list of template variable names (list of strings)
        @param parent parent widget of this dialog (QWidget)
        """
        super(TemplateMultipleVariablesDialog, self).__init__(parent)

        self.TemplateMultipleVariablesDialogLayout = QVBoxLayout(self)
        self.TemplateMultipleVariablesDialogLayout.setContentsMargins(6, 6, 6, 6)
        self.TemplateMultipleVariablesDialogLayout.setSpacing(6)
        self.TemplateMultipleVariablesDialogLayout.setObjectName("TemplateMultipleVariablesDialogLayout")
        self.setLayout(self.TemplateMultipleVariablesDialogLayout)

        # generate the scrollarea
        self.variablesView = QScrollArea(self)
        self.variablesView.setObjectName("variablesView")
        self.TemplateMultipleVariablesDialogLayout.addWidget(self.variablesView)

        self.variablesView.setWidgetResizable(True)
        self.variablesView.setFrameStyle(QFrame.NoFrame)

        self.top = QWidget(self)
        self.variablesView.setWidget(self.top)
        self.grid = QGridLayout(self.top)
        self.grid.setContentsMargins(0, 0, 0, 0)
        self.grid.setSpacing(6)
        self.top.setLayout(self.grid)

        # populate the scrollarea with labels and text edits
        self.variablesEntries = {}
        row = 0
        for var in variables:
            label = QLabel("{0}:".format(var), self.top)
            self.grid.addWidget(label, row, 0, Qt.Alignment(Qt.AlignTop))
            if var.find(":") >= 0:
                formatStr = var[1:-1].split(":")[1]
                if formatStr in ["ml", "rl"]:
                    t = QTextEdit(self.top)
                    t.setTabChangesFocus(True)
                else:
                    t = QLineEdit(self.top)
            else:
                t = QLineEdit(self.top)
            self.grid.addWidget(t, row, 1)
            self.variablesEntries[var] = t
            row += 1
        # add a spacer to make the entries aligned at the top
        spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.grid.addItem(spacer, row, 1)
        self.variablesEntries[variables[0]].setFocus()
        self.top.adjustSize()

        # generate the buttons
        layout1 = QHBoxLayout()
        layout1.setContentsMargins(0, 0, 0, 0)
        layout1.setSpacing(6)
        layout1.setObjectName("layout1")

        spacer1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        layout1.addItem(spacer1)

        self.okButton = QPushButton(self)
        self.okButton.setObjectName("okButton")
        self.okButton.setDefault(True)
        layout1.addWidget(self.okButton)

        self.cancelButton = QPushButton(self)
        self.cancelButton.setObjectName("cancelButton")
        layout1.addWidget(self.cancelButton)

        spacer2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        layout1.addItem(spacer2)

        self.TemplateMultipleVariablesDialogLayout.addLayout(layout1)

        # set the texts of the standard widgets
        self.setWindowTitle(self.tr("Enter Template Variables"))
        self.okButton.setText(self.tr("&OK"))
        self.cancelButton.setText(self.tr("&Cancel"))

        # polish up the dialog
        self.resize(QSize(400, 480).expandedTo(self.minimumSizeHint()))

        self.okButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)

    def getVariables(self):
        """
        Public method to get the values for all variables.
        
        @return dictionary with the variable as a key and its value (string)
        """
        values = {}
        for var, textEdit in list(self.variablesEntries.items()):
            try:
                values[var] = textEdit.text()
            except AttributeError:
                values[var] = textEdit.toPlainText()
        return values
Example #40
0
class SensorsWidget(QWidget):
    sensorsUpdate = pyqtSignal()

    def __init__(self, winParent):
        super(SensorsWidget, self).__init__()
        self.winParent = winParent
        self.sensorsUpdate.connect(self.updateSensors)
        self.initUI()

    def initUI(self):

        self.mainLayout = QHBoxLayout()
        self.indLayout = QGridLayout()
        self.horizonLayout = QVBoxLayout()
        self.horizonData = QGridLayout()
        self.compassLayout = QVBoxLayout()
        self.compassData = QGridLayout()
        self.altLayout = QVBoxLayout()
        self.altData = QGridLayout()
        self.batteryLayout = QVBoxLayout()
        self.batteryData = QGridLayout()

        self.setMinimumSize(750, 450)
        self.setMaximumSize(750, 450)

        self.setWindowTitle("Sensors")

        self.pitchLabel = QLabel('Pitch:', self)
        self.pitchValueLabel = QLabel('0', self)
        self.pitchValueLabel.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)

        self.rollLabel = QLabel('Roll:', self)
        self.rollValueLabel = QLabel('0', self)
        self.rollValueLabel.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)

        self.yawLabel = QLabel('Yaw:', self)
        self.yawValueLabel = QLabel('0', self)
        self.yawValueLabel.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)

        self.altLabel = QLabel('Alt:', self)
        self.altValueLabel = QLabel('0', self)
        self.altValueLabel.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)

        self.pitchgLabel = QLabel("\272", self)
        self.rollgLabel = QLabel("\272", self)
        self.yawgLabel = QLabel("\272", self)
        self.altmLabel = QLabel('m', self)

        hSpacer = QSpacerItem(100, 30, QSizePolicy.Ignored, QSizePolicy.Ignored)

        self.horizonData.addItem(hSpacer, 0, 0, 1, 1, Qt.AlignLeft)
        self.horizonData.addWidget(self.pitchLabel, 0, 1, Qt.AlignCenter)
        self.horizonData.addWidget(self.pitchValueLabel, 0, 2, Qt.AlignCenter)
        self.horizonData.addWidget(self.pitchgLabel, 0, 3, Qt.AlignCenter)
        self.horizonData.addWidget(self.rollLabel, 0, 4, Qt.AlignCenter)
        self.horizonData.addWidget(self.rollValueLabel, 0, 5, Qt.AlignCenter)
        self.horizonData.addWidget(self.rollgLabel, 0, 6, Qt.AlignCenter)
        self.horizonData.addItem(hSpacer, 0, 7, 1, 1, Qt.AlignRight)

        self.compassData.addItem(hSpacer, 0, 0, 1, 1, Qt.AlignLeft)
        self.compassData.addWidget(self.yawLabel, 0, 1, Qt.AlignCenter)
        self.compassData.addWidget(self.yawValueLabel, 0, 2, Qt.AlignCenter)
        self.compassData.addWidget(self.yawgLabel, 0, 3, Qt.AlignCenter)
        self.compassData.addItem(hSpacer, 0, 4, 1, 1, Qt.AlignRight)

        self.altData.addItem(hSpacer, 0, 0, 1, 1, Qt.AlignLeft)
        self.altData.addWidget(self.altLabel, 0, 1, Qt.AlignCenter)
        self.altData.addWidget(self.altValueLabel, 0, 2, Qt.AlignCenter)
        self.altData.addWidget(self.altmLabel, 0, 3, Qt.AlignCenter)
        self.altData.addItem(hSpacer, 0, 4, 1, 1, Qt.AlignLeft)

        self.altd = qfi_ALT.qfi_ALT(self)

        self.altd.setFixedSize(QtCore.QSize(200,200))
        self.altLayout.addWidget(self.altd)
        self.altLayout.addLayout(self.altData)
        # self.altd.move(420,50)

        self.compass = qfi_HSI.qfi_HSI(self)
        self.compass.setFixedSize(QtCore.QSize(200, 200))
        self.compassLayout.addWidget(self.compass)
        self.compassLayout.addLayout(self.compassData)

        self.horizon = qfi_ADI.qfi_ADI(self)
        self.horizon.setFixedSize(QtCore.QSize(200, 200))
        self.horizonLayout.addWidget(self.horizon)
        self.horizonLayout.addLayout(self.horizonData)


        self.velLinX = qfi_SI.qfi_SI(self)
        self.velLinX.setFixedSize(QtCore.QSize(150, 150))
        # self.velLinX.move(60,270)
        self.velXLabel = QLabel('Linear X (m/s)', self)
        # self.velXLabel.move(95,420)


        self.velLinY = qfi_SI.qfi_SI(self)
        self.velLinY.setFixedSize(QtCore.QSize(150, 150))
        # self.velLinY.move(240,270)
        self.velYLabel = QLabel('Linear Y (m/s)', self)
        # self.velYLabel.move(275,420)

        self.velLinZ = qfi_SI.qfi_SI(self)
        self.velLinZ.setFixedSize(QtCore.QSize(150, 150))
        # self.velLinZ.setLabel("8 m/s")
        # self.velLinZ.move(420,270)
        self.velZLabel = QLabel('Linear Z (m/s)', self)
        # self.velZLabel.move(455,420)

        self.indLayout.addLayout(self.horizonLayout, 0, 0, Qt.AlignCenter)
        self.indLayout.addLayout(self.compassLayout, 0, 1, Qt.AlignCenter)
        self.indLayout.addLayout(self.altLayout, 0, 2, Qt.AlignCenter)
        self.indLayout.addWidget(self.velLinX, 1, 0, Qt.AlignCenter)
        self.indLayout.addWidget(self.velLinY, 1, 1, Qt.AlignCenter)
        self.indLayout.addWidget(self.velLinZ, 1, 2, Qt.AlignCenter)
        self.indLayout.addWidget(self.velXLabel, 2, 0, Qt.AlignCenter)
        self.indLayout.addWidget(self.velYLabel, 2, 1, Qt.AlignCenter)
        self.indLayout.addWidget(self.velZLabel, 2, 2, Qt.AlignCenter)

        self.battery=QProgressBar(self)
        self.battery.setValue(0)
        self.battery.resize(56,241)
        self.battery.setOrientation(Qt.Vertical)
        self.battery.setTextVisible(False)

        self.batteryLabel=QLabel('Battery (%)',self)
        self.batteryValueLabel = QLabel('0', self)
        self.batteryValueLabel.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)

        self.batteryData.addItem(hSpacer, 0, 0, 1, 1, Qt.AlignLeft)
        self.batteryData.addWidget(self.batteryLabel, 0, 1, Qt.AlignCenter)
        self.batteryData.addWidget(self.batteryValueLabel, 0, 2, Qt.AlignCenter)
        self.batteryData.addItem(hSpacer, 0, 4, 1, 1, Qt.AlignLeft)

        self.batteryLayout.addWidget(self.battery, 0,  Qt.AlignHCenter)
        self.batteryLayout.addLayout(self.batteryData)

        self.mainLayout.addLayout(self.indLayout)
        self.mainLayout.addLayout(self.batteryLayout)
        self.setLayout(self.mainLayout);

    def updateSensors(self):
        pose = self.winParent.getPose3D().getPose3d()

        if pose != None:
            qw = pose.q[0]
            qx = pose.q[1]
            qy = pose.q[2]
            qz = pose.q[3]
            self.drawAltd(pose.z)
            self.drawYawValues(self.quatToYaw(qw, qx, qy, qz) * 180 / math.pi)
            self.drawPitchRollValues(self.quatToPitch(qw, qx, qy, qz) * 180 / math.pi,
                                     self.quatToRoll(qw, qx, qy, qz) * 180 / math.pi)

        navdata = self.winParent.getNavData().getNavData()

        if navdata != None:
            self.battery.setValue(navdata.batteryPercent)
            self.batteryValueLabel.setText(str(navdata.batteryPercent))
            self.drawVelocities(navdata.vx, navdata.vy, navdata.vz)

    def drawYawValues(self, degress):
        value = "{0:.2f}".format(degress)
        self.yawValueLabel.setText(value)
        self.compass.setHeading(degress)
        self.compass.viewUpdate.emit()

    def drawAltd(self, meters):

        self.altd.setAltitude(meters * 10)
        self.altd.viewUpdate.emit()

        value = "{0:.0f}".format(meters)
        self.altValueLabel.setText(value)

    def drawPitchRollValues(self, pitch, roll):
        if (pitch > 0 and pitch <= 90):
            result = pitch / 90
            result = -result
        elif (pitch < 0 and pitch >= -90):
            result = pitch / -90
        else:
            result = 0.0

        self.horizon.setPitch(pitch)
        self.horizon.setRoll(-roll)
        self.horizon.viewUpdate.emit()
        pitchValue = "{0:.2f}".format(pitch)
        rollValue = "{0:.2f}".format(roll)
        self.pitchValueLabel.setText(pitchValue)
        self.rollValueLabel.setText(rollValue)

    def drawVelocities(self, vx, vy, vz):

        vx = math.fabs(vx)
        vx /= 1000.0
        self.velLinX.setSpeed(vx)
        self.velLinX.viewUpdate.emit()
        vx = math.fabs(vx)

        vy = math.fabs(vy)
        vy /= 1000.0
        self.velLinY.setSpeed(vy)
        self.velLinY.viewUpdate.emit()

        vz = math.fabs(vz)
        vz /= 1000.0
        self.velLinZ.setSpeed(vz)
        self.velLinZ.viewUpdate.emit()

    def quatToRoll(self, qw, qx, qy, qz):
        rotateXa0 = 2.0 * (qy * qz + qw * qx)
        rotateXa1 = qw * qw - qx * qx - qy * qy + qz * qz
        rotateX = 0.0

        if (rotateXa0 != 0.0 and rotateXa1 != 0.0):
            rotateX = math.atan2(rotateXa0, rotateXa1)

        return rotateX

    def quatToPitch(self, qw, qx, qy, qz):
        rotateYa0 = -2.0 * (qx * qz - qw * qy)
        rotateY = 0.0
        if (rotateYa0 >= 1.0):
            rotateY = math.pi / 2.0
        elif (rotateYa0 <= -1.0):
            rotateY = -math.pi / 2.0
        else:
            rotateY = math.asin(rotateYa0)

        return rotateY

    def quatToYaw(self, qw, qx, qy, qz):
        rotateZa0 = 2.0 * (qx * qy + qw * qz)
        rotateZa1 = qw * qw + qx * qx - qy * qy - qz * qz
        rotateZ = 0.0
        if (rotateZa0 != 0.0 and rotateZa1 != 0.0):
            rotateZ = math.atan2(rotateZa0, rotateZa1)

        return rotateZ

    def closeEvent(self, event):
        self.winParent.closeSensorsWidget()
Example #41
0
class CombinedValueRangeWidget(QWidget):
    def __init__(self, parent=None):
        super(CombinedValueRangeWidget, self).__init__(parent)
        self.roiWidgets = []
        self.roiLayout = QGridLayout(self)
        self.setLayout(self.roiLayout)
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("min"), 0, Qt.Alignment(Qt.AlignLeft))
        hbox.addWidget(QLabel("max"), 0, Qt.Alignment(Qt.AlignLeft))
        self.roiLayout.addLayout(hbox, 0, 1)
        self.roiLayout.addWidget(QLabel("Export Full Range"), 0, 2)

        self.roiLayout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum), 0, 3)
        self.roiCheckBoxes = []

        self.setFocusPolicy(Qt.TabFocus)

        self.lastInChain = super(CombinedValueRangeWidget, self).nextInFocusChain()

    def addRanges(self, keys, extents):
        for key, extent in zip(keys, extents):
            w = ValueRangeWidget(self)
            w.setFocusPolicy(Qt.TabFocus)
            w.setDType(numpy.uint32)
            w.setValues(0, extent)
            w.setLimits(0, extent)
            # w.setLabels("min:","max:")
            self.roiWidgets.append(w)
            row = self.roiLayout.rowCount()
            align = Qt.Alignment(Qt.AlignLeft)
            check = QCheckBox()
            self.roiCheckBoxes.append(check)
            check.setChecked(True)
            check.setFocusPolicy(Qt.ClickFocus)
            if extent == 1:
                w.setEnabled(False)

            self.roiLayout.addWidget(QLabel(key + ": "), row, 0, align)
            self.roiLayout.addWidget(self.roiWidgets[-1], row, 1, align)
            self.roiLayout.addWidget(check, row, 2, align)

        def onChanged(i):
            val1, val2 = self.roiWidgets[i].getValues()
            lim1, lim2 = self.roiWidgets[i].getLimits()
            # limits are stored as ranges
            if val1 == lim1 and val2 == lim2:
                self.roiCheckBoxes[i].setChecked(True)
            else:
                self.roiCheckBoxes[i].setChecked(False)

        def onCheck(i, state):
            if state == 0:
                return
            self.roiWidgets[i].setValues(0, extents[i])
            self.roiCheckBoxes[i].setChecked(True)

        for i, check in enumerate(self.roiCheckBoxes):
            check.stateChanged.connect(partial(onCheck, i))
            self.roiWidgets[i].changedSignal.connect(partial(onChanged, i))

    def focusInEvent(self, QFocusEvent):
        if len(self.roiWidgets) > 0:
            self.roiWidgets[0].setFocus()
Example #42
0
class WorkerDockWidget(QDockWidget):
    def __init__(self):
        super().__init__("Workers")

        # Create main widget for content and layout of Dockwidget
        self.mainWidget = QWidget()
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.mainWidgetLayout = QGridLayout(self.mainWidget)
        self.mainWidgetLayout.setSizeConstraint(QGridLayout.SetDefaultConstraint)

        # - Create frame for button and entry
        self.newConnWidget = QWidget(self.mainWidget)
        self.newConnWidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.newConnWidgetLayout = QFormLayout(self.newConnWidget)
        self.newConnWidgetLayout.setContentsMargins(0, 0, 0, 0)

        self.newConnButton = QPushButton(self.newConnWidget)
        self.newConnButton.setText("Connect")
        self.newConnButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.newConnWidgetLayout.setWidget(0, QFormLayout.LabelRole, self.newConnButton)

        self.newConnCombobox = QComboBox(self.newConnWidget)
        self.newConnCombobox.setEditable(True)
        self.newConnCombobox.setToolTip("Enter ip to connect to.\nEntry format:  ip:port\n(if port is omitted, default is used)")
        self.newConnCombobox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.newConnWidgetLayout.setWidget(0, QFormLayout.FieldRole, self.newConnCombobox)

        self.mainWidgetLayout.addWidget(self.newConnWidget, 0, 0, 1, 1)

        # - Add monitor controls
        self.controlsWidget = QWidget(self.mainWidget)
        self.controlsWidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.controlsWidgetLayout = QGridLayout(self.controlsWidget)
        self.controlsWidgetLayout.setContentsMargins(0, 0, 0, 0)

        self.startRepeatButton = QPushButton(self.controlsWidget)
        self.startRepeatButton.setIcon(QIcon("resources/icons/control_play.png"))
        self.startRepeatButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.startRepeatButton.setEnabled(False)
        self.controlsWidgetLayout.addWidget(self.startRepeatButton, 0, 0, 1, 1)

        self.stopButton = QPushButton(self.controlsWidget)
        self.stopButton.setIcon(QIcon("resources/icons/control_stop.png"))
        self.stopButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.stopButton.setEnabled(False)
        self.controlsWidgetLayout.addWidget(self.stopButton, 0, 1, 1, 1)

        self.controlsSpacer = QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.controlsWidgetLayout.addItem(self.controlsSpacer, 0, 2, 1, 1)

        self.mainWidgetLayout.addWidget(self.controlsWidget, 1, 0, 1, 1)


        # - Add worker treeview to content
        self.workerTree = QTreeWidget(self.mainWidget)
        self.workerTree.setColumnCount(1)

        self.workerTree.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.mainWidgetLayout.addWidget(self.workerTree, 2, 0, 1, 1)

        # Set dockwidget content to main widget
        self.setWidget(self.mainWidget)
    def __init__(self, tax=True):
        """The constructor initializes the class NewVariantDialog."""
        super().__init__()

        self.count = 0

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)

        self._LABEL_MIN_WIDTH = 240
        self._piece_unit = " St."
        self._currency_unit = " " + self.locale().currencySymbol(QLocale.CurrencyIsoCode)
        self._currency_unit_piece = self._currency_unit + "/" + self._piece_unit.strip()
        self._spinbox_step = 0.05

        # determine the sales tax
        self.tax = 1.0 + library.SALES_TAX if tax else 1.0

        # input fields
        self.tubeInput = QComboBox()
        self.tubeInput.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        self.tubeInput.addItems(library.TREESHELTERS_DESCRIPTION)
        self.tubeLabel = QLabel()
        self.tubeLabel.setMinimumWidth(self._LABEL_MIN_WIDTH)
        self.tubeLabel.setBuddy(self.tubeInput)
        self.tubeHint = ToolTipLabel()
        self.tubeHint.hide()

        self.costInput = QDoubleSpinBox()
        self.costInput.setSuffix(self._currency_unit_piece)
        self.costInput.setSingleStep(self._spinbox_step)
        self.costLabel = QLabel()
        self.costLabel.setBuddy(self.costInput)
        self.costHint = ToolTipLabel()
        self.costHint.hide()
        self.costCalculator = QPushButton()

        self.accessoriesInput = QDoubleSpinBox()
        self.accessoriesInput.setSuffix(self._currency_unit_piece)
        self.accessoriesInput.setSingleStep(self._spinbox_step)
        self.accessoriesLabel = QLabel()
        self.accessoriesLabel.setBuddy(self.accessoriesInput)
        self.accessoriesHint = ToolTipLabel()
        self.accessoriesHint.hide()
        self.accessoriesCalculator = QPushButton()

        self.installationInput = QDoubleSpinBox()
        self.installationInput.setSuffix(self._currency_unit_piece)
        self.installationInput.setSingleStep(self._spinbox_step)
        self.installationLabel = QLabel()
        self.installationLabel.setBuddy(self.installationInput)
        self.installationHint = ToolTipLabel()
        self.installationHint.hide()
        self.installationCalculator = QPushButton()

        self.maintenanceInput = QDoubleSpinBox()
        self.maintenanceInput.setSuffix(self._currency_unit_piece)
        self.maintenanceInput.setSingleStep(self._spinbox_step)
        self.maintenanceLabel = QLabel()
        self.maintenanceLabel.setBuddy(self.maintenanceInput)
        self.maintenanceHint = ToolTipLabel()
        self.maintenanceHint.hide()

        self.removalInput = QDoubleSpinBox()
        self.removalInput.setSuffix(self._currency_unit_piece)
        self.removalInput.setSingleStep(self._spinbox_step)
        self.removalLabel = QLabel()
        self.removalLabel.setBuddy(self.removalInput)
        self.removalHint = ToolTipLabel()
        self.removalHint.hide()

        spacerBottom = QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)

        # create the layout of the plant group box
        layout = QGridLayout(self)
        layout.addWidget(self.tubeLabel, 0, 0)
        layout.addWidget(self.tubeInput, 0, 1)
        layout.addWidget(self.tubeHint, 0, 2)
        layout.addWidget(self.costLabel, 1, 0)
        layout.addWidget(self.costInput, 1, 1)
        layout.addWidget(self.costHint, 1, 2)
        layout.addWidget(self.costCalculator, 1, 3)
        layout.addWidget(self.accessoriesLabel, 2, 0)
        layout.addWidget(self.accessoriesInput, 2, 1)
        layout.addWidget(self.accessoriesHint, 2, 2)
        layout.addWidget(self.accessoriesCalculator, 2, 3)
        layout.addWidget(self.installationLabel, 3, 0)
        layout.addWidget(self.installationInput, 3, 1)
        layout.addWidget(self.installationHint, 3, 2)
        layout.addWidget(self.installationCalculator, 3, 3)
        layout.addWidget(self.maintenanceLabel, 4, 0)
        layout.addWidget(self.maintenanceInput, 4, 1)
        layout.addWidget(self.maintenanceHint, 4, 2)
        layout.addWidget(self.removalLabel, 5, 0)
        layout.addWidget(self.removalInput, 5, 1)
        layout.addWidget(self.removalHint, 5, 2)
        layout.addItem(spacerBottom, 7, 0, 1, 3)

        # connect actions
        self.tubeInput.currentIndexChanged.connect(self.updateCost)
        self.costCalculator.clicked.connect(self.costCalculation)
        self.accessoriesCalculator.clicked.connect(self.accessoriesCalculation)
        self.installationCalculator.clicked.connect(self.installationCalculation)

        #self.installationInput.valueChanged.connect(self.updateMaintenanceAndRemoval)

        # translate the graphical user interface
        self.retranslateUi()
Example #44
0
class EditWindow(QWidget):
    """ Window for adding reminders.

    Useful attributes
    -----------------
    parentWindow : MainWindow object
        Parent of the window.
    taskArea : QScrollArea object
        Scroll area of window.
    rows : list of dictionaries
        Element of rows is a dictionary:
            {'date', 'text', 'edit', 'del'}.
        'date' and 'text' are QLabels,
        'edit' and 'del' are QPushButtons.
        Such dictionary represents one element from tasks list.
    grid : QGridLayout object
        Layout of objects in QScrollArea.
    activeTasks : list
        List of visible tasks in grid.
    filter : QHBoxLayout object
        Layout of filter widgets.
    (date|text)Field : QLineEdit object
        Filter widgets.

    """
    def __init__(self, parent=None):
        super().__init__()
        self.parentWindow = parent
        self.parentWindow.editActive = True
        self.activeTasks = tasks
        self.dateFieldText = ''
        self.textFieldText = ''
        self.initUI()

    def initUI(self):
        """ Init user interface. """
        # use QVBoxLayout to store two layouts vertically
        self.vl = QVBoxLayout()

        # widget for scrollArea
        self.topWidget = QWidget()
        self.grid = QGridLayout()
        self.topWidget.setLayout(self.grid)
        self.vl.addWidget(self.topWidget)

        # layout for filter
        self.filter = QHBoxLayout()
        # draw filter widgets
        self.drawFilter()
        spacer = QSpacerItem(10, 0, vPolicy=QSizePolicy.MinimumExpanding)
        self.vl.addItem(spacer)
        self.vl.addLayout(self.filter)

        self.setLayout(self.vl)
        self.rows = []

        self.taskArea = QScrollArea(self)
        self.taskArea.setWidget(self.topWidget)
        self.taskArea.setWidgetResizable(True)
        self.taskArea.resize(500, 350)
        self.resize(500, 395)
        self.setMinimumSize(460, 90)
        self.filterApply()
        self.show()
        self.move(QApplication.desktop().screen().rect().center() -
                  self.rect().center())
        self.setWindowTitle(conf.lang.EDIT_TITLE)
        iconEdit = Icon(byte=icons.edit).convertToIcon().getIcon()
        self.setWindowIcon(iconEdit)

    def drawFilter(self):
        """ Draws filter widgets. """
        clearLayout(self.filter)

        self.hideBtn = QPushButton()
        if conf.filter:
            self.hideBtn.setText(conf.lang.VISIBLE_F)
            self.hideBtn.setFixedSize(23, 23)
            self.vl.setContentsMargins(11, 11, 11, 11)
        else:
            self.hideBtn.setText(conf.lang.HIDDEN_F)
            self.hideBtn.setFixedSize(23, 15)
            self.vl.setContentsMargins(0, 0, 0, 0)
        self.hideBtn.clicked.connect(self.inverseFilter)
        self.filter.addWidget(self.hideBtn)
        if conf.filter:
            filterLbl = QLabel(conf.lang.FILTER)
            filterLbl.setStyleSheet('QLabel {' \
                                            'border-width: 0 1px 0 0;' \
                                            'border-style: solid;' \
                                            'border-color: black;' \
                                            'margin: 0 5px 0 0;' \
                                           '}')
            self.filter.addWidget(filterLbl)

            dateLbl = QLabel(conf.lang.DATE_F)
            self.filter.addWidget(dateLbl)
            self.dateField = QLineEdit()
            self.dateField.setText(self.dateFieldText)
            self.filter.addWidget(self.dateField)

            textLbl = QLabel(conf.lang.TEXT_F)
            self.filter.addWidget(textLbl)
            self.textField = QLineEdit()
            self.textField.setText(self.textFieldText)
            self.filter.addWidget(self.textField)

            self.dateField.textChanged.connect(self.filterApply)
            self.textField.textChanged.connect(self.filterApply)

    def inverseFilter(self):
        """ Change state of filter. """
        conf.filter = not conf.filter
        rewriteConfig()
        if not conf.filter:
            self.dateFieldText = self.dateField.text()
            self.textFieldText = self.textField.text()
        self.drawFilter()
        self.resizeEvent(QResizeEvent(QSize(self.width(), self.height()),
                                      QSize(self.width(), self.height())))

    def fill(self):
        """ Fill self.taskArea by items that represens tasks. """
        # delete items from self.grid
        clearLayout(self.grid)

        aTasks = self.activeTasks
        self.rows = [{} for i in range(len(aTasks))]
        if len(aTasks) == 0:
            noLbl = QLabel(conf.lang.NO_TASKS)
            noLbl.setAlignment(Qt.AlignCenter)
            self.grid.addWidget(noLbl, 0, 0, 1, 5)
        else:
            for i in range(len(aTasks)):
                datetime = ' '.join((dateToStr(aTasks[i].getDateTime())['date'],
                                     dateToStr(aTasks[i].getDateTime())['time']))
                # replace newlines and tabs in text
                text = aTasks[i].text.replace('\n', ' ').replace('\t', '   ')
                row = {}
                row['date'] = QLabel(datetime)
                row['text'] = QLabel()
                # change label's resizeEvent
                # with passing QLabel and text
                row['text'].resizeEvent = \
                            lambda evt, lbl=row['text'], txt=text: \
                                   self.labelResize(lbl, evt, txt)
                row['edit'] = QPushButton(conf.lang.EDIT)
                row['del'] = QPushButton(conf.lang.DELETE)
                row['edit'].setToolTip(conf.lang.EDIT_TOOLTIP_TEXT)
                row['del'].setToolTip(conf.lang.DELETE_TOOLTIP_TEXT)
                # pass k=i to lambda function to save value of i
                row['edit'].clicked.connect(lambda checked, k=i: self.edit(k))
                row['del'].clicked.connect(lambda checked, k=i: self.delete(k))

                self.rows[i] = row

                self.grid.addWidget(self.rows[i]['date'], i, 0)
                self.grid.addWidget(self.rows[i]['text'], i, 1, 1, 2)
                self.grid.addWidget(self.rows[i]['edit'], i, 3)
                self.grid.addWidget(self.rows[i]['del'], i, 4)
        # add spacer to pin rows to window's top side
        spacer = QSpacerItem(10, 0, vPolicy=QSizePolicy.MinimumExpanding)
        self.grid.addItem(spacer, len(aTasks), 0, 1, 5)
        self.grid.setColumnMinimumWidth(0, 100)
        self.grid.setColumnMinimumWidth(3, 80)
        self.grid.setColumnMinimumWidth(4, 80)
        for i in range(self.grid.columnCount()):
            self.grid.setColumnStretch(i, 0)
        self.grid.setColumnStretch(1, 1)

    def labelResize(self, label, event, text):
        """ Change label's text due to its size. """
        width = self.taskArea.width() - 320
        # if get width from event: width = event.size().width()
        # resizing will stop when full text is shown in label
        metrics = QFontMetrics(label.font())
        ellipsis = metrics.elidedText(text, Qt.ElideRight, width)
        label.setText(ellipsis)

    def filterApply(self):
        """ Selects tasks to be shown. """
        if conf.filter:
            date = self.dateField.text()
            text = self.textField.text().replace('\n', ' ').replace('\t', '   ')
            text = text.lower()
        else:
            date = ''
            text = ''

        aTasks = []
        for i in tasks:
            datetime = ' '.join((dateToStr(i.getDateTime())['date'],
                                 dateToStr(i.getDateTime())['time']))
            tasktext = i.text.replace('\n', ' ').replace('\t', '   ')
            tasktext = tasktext.lower()
            if datetime.find(date) > -1 and tasktext.find(text) > -1:
                aTasks.append(i)

        self.activeTasks = aTasks
        self.fill()

    def edit(self, index):
        """ Open addWindow with selected task. """
        self.parentWindow.addActive = True
        self.parentWindow.showWindow('addAction')
        addWindow = self.parentWindow.addWindow
        addWindow.dateEdit.setText(dateToStr(tasks[index].
                                   getDateTime())['date'])
        addWindow.timeEdit.setText(dateToStr(tasks[index].
                                   getDateTime())['time'])
        addWindow.textEdit.setText(tasks[index].text)
        addWindow.parentWindow = self
        # pass index parameter to notice it in addWindow
        addWindow.index = index
        self.hide()

    def delete(self, index):
        """ Delete selected reminder from tasks list. """
        entry = tasks[index]
        tasks.remove(entry)
        rewrite()
        self.filterApply()

    def resizeEvent(self, event):
        """ Resize taskArea due to size of window. """
        width = event.size().width()
        height = self.size().height()
        if conf.filter:
            self.taskArea.resize(width, height - 45)
        else:
            self.taskArea.resize(width, height - 15)

    def closeEvent(self, event):
        """ Closes window. """
        self.parentWindow.editActive = False
        event.ignore()
        self.hide()
    def __init__(self, parent):
        super(ProjectExecution, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)

        grid.addWidget(QLabel(_translate("ProjectExecution", "Main File:")), 0, 0)
        self.path = QLineEdit()
        ui_tools.LineEditButton(self.path, self.path.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.path.setText(self._parent._item.mainFile)
        self.path.setReadOnly(True)
        self.btnBrowse = QPushButton(QIcon(
            self.style().standardPixmap(self.style().SP_FileIcon)), '')
        grid.addWidget(self.path, 0, 1)
        grid.addWidget(self.btnBrowse, 0, 2)

        # this should be changed, and ALL pythonPath names to
        # python_custom_interpreter or something like that. this is NOT the
        # PYTHONPATH
        self.txtPythonPath = QLineEdit()
        self.txtPythonPath.setText(self._parent._item.pythonPath)
        self.btnPythonPath = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(_translate("ProjectExecution", "Python Custom Interpreter:")), 1, 0)
        grid.addWidget(self.txtPythonPath, 1, 1)
        grid.addWidget(self.btnPythonPath, 1, 2)

        # THIS IS THE MODAFUCKA REAL PYTHONPATH BRO, YEAH !!!
        grid.addWidget(QLabel(_translate("ProjectExecution", "Custom PYTHONPATH:")), 2, 0)
        self.PYTHONPATH = QPlainTextEdit()  # TODO : better widget
        self.PYTHONPATH.setPlainText(self._parent._item.PYTHONPATH)
        self.PYTHONPATH.setToolTip(_translate("ProjectExecution", "One path per line"))
        grid.addWidget(self.PYTHONPATH, 2, 1)

        # Additional builtins/globals for pyflakes
        grid.addWidget(QLabel(_translate("ProjectExecution", "Additional builtins/globals:")), 3, 0)
        self.additional_builtins = QLineEdit()
        self.additional_builtins.setText(
                ' '.join(self._parent._item.additional_builtins))
        self.additional_builtins.setToolTip(_translate("ProjectExecution", 
                "Space-separated list of symbols that will be considered as "
                "builtin in every file"))
        grid.addWidget(self.additional_builtins, 3, 1)

        self.txtPreExec = QLineEdit()
        ui_tools.LineEditButton(self.txtPreExec, self.txtPreExec.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtPreExec.setReadOnly(True)
        self.txtPreExec.setText(self._parent._item.preExecScript)
        self.btnPreExec = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(_translate("ProjectExecution", "Pre-exec Script:")), 4, 0)
        grid.addWidget(self.txtPreExec, 4, 1)
        grid.addWidget(self.btnPreExec, 4, 2)
        self.txtPostExec = QLineEdit()
        ui_tools.LineEditButton(self.txtPostExec, self.txtPostExec.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtPostExec.setReadOnly(True)
        self.txtPostExec.setText(self._parent._item.postExecScript)
        self.btnPostExec = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(_translate("ProjectExecution", "Post-exec Script:")), 5, 0)
        grid.addWidget(self.txtPostExec, 5, 1)
        grid.addWidget(self.btnPostExec, 5, 2)

        grid.addItem(QSpacerItem(5, 10, QSizePolicy.Expanding,
            QSizePolicy.Expanding), 6, 0)

        # Properties
        grid.addWidget(QLabel(_translate("ProjectExecution", "Properties:")), 7, 0)
        self.txtParams = QLineEdit()
        self.txtParams.setToolTip(
            _translate("ProjectExecution", "Separate the params with commas (ie: help, verbose)"))
        self.txtParams.setText(self._parent._item.programParams)
        grid.addWidget(QLabel(_translate("ProjectExecution", "Params (comma separated):")), 8, 0)
        grid.addWidget(self.txtParams, 8, 1)
        #Widgets for virtualenv properties
        self.txtVenvPath = QLineEdit()
        ui_tools.LineEditButton(self.txtVenvPath, self.txtVenvPath.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtVenvPath.setText(self._parent._item.venv)
        self._dir_completer = QCompleter()
        self._dir_completer.setModel(QDirModel(self._dir_completer))
        self.txtVenvPath.setCompleter(self._dir_completer)
        self.btnVenvPath = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(_translate("ProjectExecution", "Virtualenv Folder:")), 9, 0)
        grid.addWidget(self.txtVenvPath, 9, 1)
        grid.addWidget(self.btnVenvPath, 9, 2)

        self.btnBrowse.clicked['bool'].connect(self.select_file)
        self.btnPythonPath.clicked['bool'].connect(self._load_python_path)
        self.btnVenvPath.clicked['bool'].connect(self._load_python_venv)
        self.btnPreExec.clicked['bool'].connect(self.select_pre_exec_script)
        self.btnPostExec.clicked['bool'].connect(self.select_post_exec_script)
Example #46
0
class Cryptographie(Panel_simple):
    titre = "Cryptographie" # Donner un titre à chaque module

    def __init__(self, *args, **kw):
        Panel_simple.__init__(self, *args, **kw)

        self._freeze = False
        self.widget_modifie = None

        # La clé est la permutation de l'alphabet actuellement utilisée
        # pour le codage par substitution mono-alphabétique.
        self.generer_cle()

        # La clé de chiffrement pour le codage par substitution poly-alphabétique
        # (appelé aussi chiffre de Vigenère).
        self.cle_vigenere = 'EXEMPLE'

        # Signe indiquant un caractère non déchiffré
        self.symbole = '-' # '.'

        self.sizer = QVBoxLayout()

        self.textes = QGridLayout()
        self.textes.setSpacing(5)
        size = (400, 300)

        txt_clair = QLabel("<b>Texte en clair</b>")
        self.clair = QTextEdit()
        self.clair.setMinimumSize(*size)
        formater_clair = partial(self.formater, widget=self.clair)
        self.clair.textChanged.connect(formater_clair)
        self.clair.cursorPositionChanged.connect(formater_clair)
        self.copier_clair = QPushButton('Copier le texte en clair')
        self.copier_clair.clicked.connect(partial(self.copier, widget=self.clair))

        txt_code = QLabel("<b>Texte codé</b>")
        self.code = QTextEdit()
        self.code.setMinimumSize(*size)
        self.code.textChanged.connect(self.code_modifie)
        self.code.cursorPositionChanged.connect(partial(self.formater, widget=self.code))
        self.copier_code = QPushButton('Copier le texte codé')
        self.copier_code.clicked.connect(partial(self.copier, widget=self.code))

        self.textes.addWidget(txt_clair, 0, 0)
        self.textes.addItem(QSpacerItem(50, 1), 0, 1)
        self.textes.addWidget(txt_code, 0, 2)
        self.textes.addWidget(self.clair, 1, 0)
        self.textes.addWidget(self.code, 1, 2)
        self.textes.addWidget(self.copier_code, 2, 2)
        self.textes.addWidget(self.copier_clair, 2, 0)

        self.table = QGridLayout()
        self.table.setSpacing(3)
        self.cases = {}
        self.table.addWidget(QLabel("Codé : ", self), 0, 0)
        self.table.addWidget(QLabel("Clair : ", self), 1, 0)
        ##self.table.setColumnStretch(0, 100)
        for i, l in enumerate(majuscules):
            lettre = QLineEdit(l, self)
            lettre.setAlignment(Qt.AlignCenter)
            lettre.setReadOnly(True)
            lettre.setEnabled(False)
            self.table.addWidget(lettre, 0, i + 1)
            ##self.table.setColumnStretch(i + 1, 1)
        for i, l in enumerate(majuscules):
            c = self.cases[l] = CaseLettre(self)
            c.setMaxLength(1)
            self.table.addWidget(c, 1, i + 1)
            c.textChanged.connect(self.decoder)
        self.sizer.addLayout(self.textes)
        self.sizer.addLayout(self.table)
        self.setLayout(self.sizer)
        ##self.adjustSize()

        self.couleur1 = "5A28BE" # sky blue
        self.couleur2 = "C86400" # Lime Green
        self.couleur_position = "FFCDB3"
        self.reg = re.compile("([-A-Za-z]|<##>|</##>)+")
        ##couleur_position = wx.Color(255, 205, 179) # FFCDB3
        ##couleur1 = wx.Color(90, 40, 190) # 5A28BE
        ##couleur2 = wx.Color(200, 100, 0) # C86400
        ##black = wx.Color(0, 0, 0) # 000000
        ##white = wx.Color(255, 255, 255) # FFFFFF
        ##self.special = wx.TextAttr(wx.NullColour, couleur_position)
        ##self.fond = wx.TextAttr(couleur1, wx.NullColour) #"sky blue"
        ##self.fond2 = wx.TextAttr(couleur2, wx.NullColour) # "Lime Green"
        ##self.defaut = wx.TextAttr(black, white)
##
        ##self.Bind(wx.EVT_IDLE, self.OnIdle)
        timer = QTimer(self)
        timer.timeout.connect(self.OnIdle)
        timer.start(100)


        # DEBUG:
        ##self.code.setPlainText('WR IRAMXPZRHRDZ IK HRYYOVR AL IRYYBKY RYZ NOALWLZR POM WR NOLZ FKR W BD O VOMIR WRY YLVDRY IR PBDAZKOZLBD RZ WRY RYPOARY RDZMR WRY HBZY OWBMY FKR I QOELZKIR BD VMBKPR WRY WRZZMRY ALDF POM ALDF')

    def copier(self, evt=None, widget=None):
        self.vers_presse_papier(widget.toPlainText())


    def DlgModifierCle(self, evt=None):
        while True:
            text, ok = QInputDialog.getText(self, "Modifier la clé",
                    "La clé doit être une permutation de l'alphabet,\n"
                    "ou un chiffre qui indique de combien l'alphabet est décalé.",
                    text=str(self.cle))
            if ok:
                try:
                    self.modifier_cle(text)
                except:
                    print_error()
                    continue
            break


    def generer_cle(self):
        l = list(majuscules)
        shuffle(l)
        self.cle = ''.join(l)


    def modifier_cle(self, cle):
        cle = cle.strip().upper()
        if cle.isdigit():
            n = int(cle)
            cle = majuscules[n:] + majuscules[:n]
        # On teste qu'il s'agit bien d'une permutation de l'alphabet:
        assert ''.join(sorted(cle)) == majuscules
        self.cle = cle


    def coder(self, evt=None, cle=None, espaces=False):
        cle = (self.cle if cle is None else cle)
        clair = self.clair.toPlainText().upper()
        for key, val in dict_accents.items():
            clair = clair.replace(key, val)
        d = dict(zip(majuscules, cle))
        code = ''.join(d.get(s, ' ') for s in clair)
        code = re.sub(' +', ' ', code)
        if not espaces:
            code = code.replace(' ', '')
        self.code.setPlainText(code)
        return code


    @staticmethod
    def _vigenere(l1, l2):
        return chr((ord(l1) + ord(l2) - 130)%26 + 65)

    def coder_vigenere(self, evt=None, msg=None, cle=None, ask=False):
        def gen():
            length = len(cle)
            n = 0
            for car in clair:
                if car.isalpha():
                    yield self._vigenere(cle[n%length], car)
                    n += 1
                else:
                    yield car
        if ask:
            self.DlgModifierCleVigenere()
        if cle is None:
            cle = self.cle_vigenere
        if msg is None:
            msg = self.clair.toPlainText()
        msg = msg.upper()
        if cle is None:
            pass
        # Pour l'instant, les espaces ne sont pas supportés
        clair = msg.replace(' ', '')
        clair = self.clair.toPlainText().upper()
        for key, val in dict_accents.items():
            clair = clair.replace(key, val)
        code = ''.join(gen())
        self.code.setPlainText(code)
        return code

    def DlgModifierCleVigenere(self, evt=None):
        while True:
            text, ok = QInputDialog.getText(self, "Modifier la clé pour Vigenère",
                    "La clé doit contenir uniquement des lettres.",
                    text=self.cle_vigenere)
            if ok:
                text = text.strip()
                if not text.isalpha():
                    continue
                self.cle_vigenere = text.upper()
            break


    def decoder(self, txt=None):
        code = self.code.toPlainText().upper()
        def f(s):
            if s in majuscules:
                return self.cases[s].text() or self.symbole
            return s

        clair = ''.join(f(s) for s in code)
        self.clair.setPlainText(clair)


    def code_modifie(self, txt=None):
        self.decoder(txt)
        self.formater(txt, widget=self.code)

    def formater(self, evt=None, widget=None):
        ##evt.Skip()
        if self._freeze:
            return
        self.widget_modifie = widget



    def _formater(self, widget_modifie):
        # Impossible de formater les 2 textes de la même manière s'ils
        # ne sont pas de la même longueur.
        # Cela ne devrait se produire que temporairement (par ex.,
        # l'utilisateur copie un nouveau texte)
        if len(self.code.toPlainText()) != len(self.clair.toPlainText()):
            if self.code.toPlainText() and self.clair.toPlainText():
                print('Warning: le message codé et le message en clair ne sont '
                      'pas de même longueur.')
            return

        def colorier(m, col1=[self.couleur1], col2=[self.couleur2]):
            s = m.group(0)
            s = "<font color='#%s'>%s</font>" % (col1[0], s)
            col1[0], col2[0] = col2[0], col1[0]
            return s
        self._freeze = True
        pos = widget_modifie.textCursor().position()
        for w in (self.code, self.clair):
            txt = w.toPlainText()
            if pos != len(txt):
                txt = txt[:pos] + '<##>' + txt[pos] + '</##>' + txt[pos + 1:]
            new_txt = re.sub(self.reg, colorier, txt)
            new_txt = new_txt.replace("<##>",
                        "<font style='background-color: #%s;'>" % self.couleur_position)
            new_txt = new_txt.replace("</##>", "</font>")
            w.setHtml(new_txt)
        cursor = widget_modifie.textCursor()
        cursor.setPosition(pos)
        widget_modifie.setTextCursor(cursor)
        self._freeze = False
        self.widget_modifie = None


    def OnIdle(self, evt=None):
        if self.widget_modifie is not None and not self.parent.parent.closing:
            self._formater(self.widget_modifie)
Example #47
0
class BattleView(QObject):
    def __init__(self, battle_window, parent=None):
        super().__init__(parent)
        self.battleWindow = battle_window  # MainBattleWindow container_widget

        if len(self.battleWindow.config.errors) != 0:
            # noinspection PyArgumentList
            QMessageBox.critical(battle_window, 'Configuration Error', self.battleWindow.config.get_error_str())
            exit(-1)

        # main elements
        self.centralWidget = QWidget(self.battleWindow)
        self.gridLayout = QGridLayout(self.centralWidget)

        # misc side elements
        self.graphicsView_coatOfArm = CustomScene()
        self.graphicsView_currentUnit = CustomScene()
        self.graphicsView_targetedUnit = CustomScene()

        for button in self.graphicsView_coatOfArm, self.graphicsView_currentUnit, self.graphicsView_targetedUnit:
            button.enter_functions.append(self.set_label_hint)
            button.leave_functions.append(self.clear_label_hint)

        # buttons
        self.autoCombatButton = CustomButton(self.centralWidget)
        self.helpButton = CustomButton(self.centralWidget)
        self.retreatButton = CustomButton(self.centralWidget)
        self.endUnitTurnButton = CustomButton(self.centralWidget)
        self.nextTargetButton = CustomButton(self.centralWidget)

        for button in self.autoCombatButton, self.helpButton, self.retreatButton, self.nextTargetButton, self.endUnitTurnButton:
            button.enter_functions.append(self.set_label_hint)
            button.leave_functions.append(self.clear_label_hint)
            button.click_functions.append(self.click_button)

        # info containers
        self.dateLabel = QLabel(self.centralWidget)  # display current turn in battle
        self.hintLabel = QLabel(self.centralWidget)  # display hint when hovering over an elemend

        # the actual battle scene
        self.mainScene = MainQGraphicsScene()
        self.graphicsView_main = QGraphicsView(self.mainScene)
        self.gridLayout.addWidget(self.graphicsView_main, 1, 0, 12, 1)

    def setup_ui(self):
        self.battleWindow.setWindowTitle(self.battleWindow.config.get_text('battle.window.title') + ' v' + str(self.battleWindow.config.version))
        background = self.battleWindow.config.theme_selected.get_background_pixmap()
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(background))
        self.battleWindow.setMinimumSize(constants.get_min_resolution_qsize())
        self.battleWindow.setAutoFillBackground(True)
        self.gridLayout.setVerticalSpacing(0)

        self.setup_hint_label()  # Labels
        self.setup_turn_label()  # Labels
        self.setup_space()  # Space item

        self.setup_help_button()  # Help Push Button
        self.setup_next_target_button()  # Next Target Button
        self.setup_end_unit_button()  # End Unit Button
        self.setup_retreat_button()  # Retreat Button
        self.setup_auto_combat_button()  # Automatic battle button

        self.setup_targeted_unit_view()  # Targeted Unit view
        self.setup_current_unit_view()  # Current Unit View
        self.setup_coat_of_arms_view()  # Coat of Arm view

        self.setup_map()  # Main view
        self.battleWindow.setPalette(palette)
        self.battleWindow.setCentralWidget(self.centralWidget)

        # noinspection PyArgumentList
        QMetaObject.connectSlotsByName(self.battleWindow)

    def setup_map(self):
        self.mainScene = MainQGraphicsScene()
        self.graphicsView_main.setScene(self.mainScene)
        self.mainScene.set_battle_view(self.battleView)
        width = 2 * self.graphicsView_main.height() / math.sqrt(3)
        height = self.graphicsView_main.height()
        if width > self.graphicsView_main.width():
            width = self.graphicsView_main.width()
            height = self.graphicsView_main.width() * math.sqrt(3) / 2
        item = self.mainScene.addRect(0, 0, width - 15, height - 15)
        item.hide()
        self.battleView.draw_battle_map(self.mainScene)

    def resize_event(self):
        self.setup_map()

    # misc elements
    def setup_hint_label(self):
        size_policy = constants.default_size_policy(self.hintLabel, QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.hintLabel.setSizePolicy(size_policy)
        self.hintLabel.setFont(constants.default_font())
        self.hintLabel.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.gridLayout.addWidget(self.hintLabel, 0, 0, 1, 1)

    def setup_turn_label(self):
        size_policy = constants.default_size_policy(self.dateLabel, QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.dateLabel.setSizePolicy(size_policy)
        self.dateLabel.setFont(constants.default_font())
        self.dateLabel.setText('Turn ' + str(self.battleView.turn))
        self.dateLabel.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.gridLayout.addWidget(self.dateLabel, 0, 0, 1, 1)

    def setup_space(self):
        # Space between help Button and flag view
        spacer_item = QSpacerItem(20, 10, QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
        self.gridLayout.addItem(spacer_item, 2, 1, 1, 1)
        # Space between flag view and next target Button
        spacer_item1 = QSpacerItem(20, 10, QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
        self.gridLayout.addItem(spacer_item1, 4, 1, 1, 1)
        # Space between retreat Button and targetted unit view
        spacer_item2 = QSpacerItem(20, 10, QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.gridLayout.addItem(spacer_item2, 8, 1, 1, 1)
        # Space between current unit view and auto Button
        spacer_item3 = QSpacerItem(20, 10, QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
        self.gridLayout.addItem(spacer_item3, 11, 1, 1, 1)

    def setup_coat_of_arms_view(self):
        size = QSize(90, 120)
        self.battleView.draw_coat_of_arms(self.graphicsView_coatOfArm.scene(), size)
        self.graphicsView_coatOfArm.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        size_policy = constants.default_size_policy(self.graphicsView_coatOfArm, QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.graphicsView_coatOfArm.setSizePolicy(size_policy)
        self.graphicsView_coatOfArm.setMinimumSize(size)
        self.graphicsView_coatOfArm.setMaximumSize(size)
        self.graphicsView_coatOfArm.setStyleSheet("border-style: none;background: transparent")
        self.graphicsView_coatOfArm.setCacheMode(QGraphicsView.CacheBackground)
        self.gridLayout.addWidget(self.graphicsView_coatOfArm, 3, 1, 1, 1)

    # unit views
    def setup_targeted_unit_view(self):
        size = QSize(60, 60)
        army = self.get_computer_army()
        defending = (army == self.battleView.defender)
        self.battleView.draw_targetted_unit(defending, self.graphicsView_targetedUnit.scene(), size)
        size_policy = constants.default_size_policy(self.graphicsView_targetedUnit, QSizePolicy.Fixed,
                                                    QSizePolicy.Fixed)
        self.graphicsView_targetedUnit.setSizePolicy(size_policy)
        self.graphicsView_targetedUnit.setMinimumSize(size)
        self.graphicsView_targetedUnit.setMaximumSize(size)
        self.gridLayout.addWidget(self.graphicsView_targetedUnit, 9, 1, 1, 1, Qt.AlignCenter)

    def setup_current_unit_view(self):
        size = QSize(60, 60)
        army = self.get_human_army()
        defending = (army == self.battleView.defender)
        self.battleView.draw_current_unit(defending, self.graphicsView_currentUnit.scene(), size)
        size_policy = constants.default_size_policy(self.graphicsView_currentUnit, QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.graphicsView_currentUnit.setSizePolicy(size_policy)
        self.graphicsView_currentUnit.setMinimumSize(size)
        self.graphicsView_currentUnit.setMaximumSize(size)
        self.gridLayout.addWidget(self.graphicsView_currentUnit, 10, 1, 1, 1, Qt.AlignCenter)

    def get_human_army(self):
        if self.battleView.attacker.nation.computer:
            return self.battleView.defender
        return self.battleView.attacker

    def get_computer_army(self):
        if self.battleView.attacker.nation.computer:
            return self.battleView.attacker
        return self.battleView.defender

    # buttons
    def setup_next_target_button(self):
        size_policy = constants.default_size_policy(self.nextTargetButton, QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.nextTargetButton.setSizePolicy(size_policy)
        self.nextTargetButton.setMinimumSize(QSize(45, 45))
        self.nextTargetButton.setMaximumSize(QSize(45, 45))
        self.nextTargetButton.setText("")
        icon = QIcon()
        icon.addPixmap(QPixmap(self.battleWindow.config.theme_selected.get_target_button_pixmap()), QIcon.Normal, QIcon.Off)
        self.nextTargetButton.setIcon(icon)
        self.nextTargetButton.setIconSize(QSize(40, 40))
        self.gridLayout.addWidget(self.nextTargetButton, 5, 1, 1, 1, Qt.AlignCenter)

    def setup_end_unit_button(self):
        size_policy = constants.default_size_policy(self.endUnitTurnButton, QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.endUnitTurnButton.setSizePolicy(size_policy)
        self.endUnitTurnButton.setMinimumSize(QSize(45, 45))
        self.endUnitTurnButton.setMaximumSize(QSize(45, 45))
        self.endUnitTurnButton.setText("")
        icon1 = QIcon()
        icon1.addPixmap(self.battleWindow.config.theme_selected.get_end_button_pixmap(), QIcon.Normal, QIcon.Off)
        self.endUnitTurnButton.setIcon(icon1)
        self.endUnitTurnButton.setIconSize(QSize(40, 40))
        self.gridLayout.addWidget(self.endUnitTurnButton, 6, 1, 1, 1, Qt.AlignCenter)

    def setup_retreat_button(self):
        size_policy = constants.default_size_policy(self.retreatButton, QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.retreatButton.setSizePolicy(size_policy)
        self.retreatButton.setMinimumSize(QSize(45, 45))
        self.retreatButton.setMaximumSize(QSize(45, 45))
        self.retreatButton.setToolTip("")
        self.retreatButton.setWhatsThis("")
        self.retreatButton.setText("")
        icon2 = QIcon()
        icon2.addPixmap(QPixmap(self.battleWindow.config.theme_selected.get_retreat_button_pixmap()), QIcon.Normal, QIcon.Off)
        self.retreatButton.setIcon(icon2)
        self.retreatButton.setIconSize(QSize(42, 40))
        self.gridLayout.addWidget(self.retreatButton, 7, 1, 1, 1, Qt.AlignCenter)

    def setup_help_button(self):
        size_policy = constants.default_size_policy(self.helpButton, QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.helpButton.setSizePolicy(size_policy)
        self.helpButton.setMinimumSize(QSize(80, 80))
        self.helpButton.setMaximumSize(QSize(80, 80))
        self.helpButton.setText("")
        icon3 = QIcon()
        icon3.addPixmap(QPixmap(self.battleWindow.config.theme_selected.get_help_button_pixmap()), QIcon.Normal, QIcon.Off)
        self.helpButton.setIcon(icon3)
        self.helpButton.setIconSize(QSize(75, 75))
        self.gridLayout.addWidget(self.helpButton, 0, 1, 2, 1)

    def setup_auto_combat_button(self):
        size_policy = constants.default_size_policy(self.autoCombatButton, QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.autoCombatButton.setSizePolicy(size_policy)
        self.autoCombatButton.setMinimumSize(QSize(90, 90))
        self.autoCombatButton.setMaximumSize(QSize(90, 90))
        self.autoCombatButton.setText("")
        icon4 = QIcon()
        icon4.addPixmap(QPixmap(self.battleWindow.config.theme_selected.get_autocombat_button_pixmap()), QIcon.Normal, QIcon.Off)
        self.autoCombatButton.setIcon(icon4)
        self.autoCombatButton.setIconSize(QSize(80, 80))
        self.gridLayout.addWidget(self.autoCombatButton, 12, 1, 1, 1)

    # element interactions
    def clear_label_hint(self, generic_element):
        self.hintLabel.setText('')

    def set_label_hint(self, generic_element):
        text = ''
        if generic_element in self.battleView.map.fields:
            # TODO - not hooked up
            text = str(generic_element)
        elif generic_element == self.graphicsView_currentUnit:
            text = str(self.battleView.currentUnit)
        elif generic_element == self.graphicsView_targetedUnit:
            text = str(self.battleView.targettedUnit)
        elif generic_element == self.autoCombatButton:
            text = self.battleWindow.config.get_text('auto.play.label')
        elif generic_element == self.helpButton:
            text = self.battleWindow.config.get_text('help.tacticalbattle.label')
        elif generic_element == self.retreatButton:
            text = self.battleWindow.config.get_text('retreat.all.label')
        elif generic_element == self.endUnitTurnButton:
            text = self.battleWindow.config.get_text('end.unit.label')
        elif generic_element == self.nextTargetButton:
            text = self.battleWindow.config.get_text('next.target.label')
        if text != '':
            self.hintLabel.setText(text)

    def click_button(self, button_element):
        if button_element == self.autoCombatButton:
            self.battleView.autoCombat = True
        elif button_element == self.helpButton:
            print('click helpButton')
        elif button_element == self.retreatButton:
            self.get_human_army().retreat = True
        elif button_element == self.endUnitTurnButton:
            print('click endUnitTurnButton')
        elif button_element == self.nextTargetButton:
            print('click nextTargetButton')
    def __init__(self, count=0, piece=True):
        """The constructor initializes the class NewVariantDialog."""
        super().__init__()

        self.piece = piece

        self.count = count
        self.cost = 0
        self.total = 0
        self.value = 0

        # TODO
        self._LABEL_MIN_WIDTH = 75
        self._piece_unit = " St."
        self._length_unit = " Lfm."
        self._area_unit = " ha"
        self._currency_unit = " " + self.locale().currencySymbol(QLocale.CurrencyIsoCode)
        self._currency_unit_area = self._currency_unit + "/" + self._area_unit.strip()
        self._input_name = ""
        self._input_unit = ""
        if self.piece:
            self._currency_unit_container = self._currency_unit + "/" + self._piece_unit.strip()
            self._input_name = QApplication.translate("UnitCostDialog", "Number of plants")
            self._input_unit = self._piece_unit
        else:
            self._currency_unit_container = self._currency_unit + "/" + self._length_unit.strip()
            self._input_name = QApplication.translate("UnitCostDialog", "Fence length")
            self._input_unit = self._length_unit
        self._spinbox_step = 0.05

        # input group box
        inputGroup = QGroupBox(QApplication.translate("UnitCostDialog", "User input"))     # Benutzereingaben
        inputGroup.setFlat(True)

        self.areaInput = QDoubleSpinBox(decimals=1, maximum=99999, singleStep=0.1, suffix=self._area_unit, value=1.0)
        areaLabel = QLabel(QApplication.translate("UnitCostDialog", "Area") + ":")             # Fläche
        areaLabel.setMinimumWidth(self._LABEL_MIN_WIDTH)
        areaLabel.setBuddy(self.areaInput)

        self.countInput = self.countInput = QSpinBox(self, maximum=99999, suffix=self._input_unit)
        self.countInput.setValue(self.count)
        self.countLabel = QLabel(self._input_name + ":")
        self.countLabel.setBuddy(self.countInput)

        self.costInput = QDoubleSpinBox(maximum=99999)
        self.costInput.setSuffix(self._currency_unit_area)
        self.costInput.setSingleStep(self._spinbox_step)
        costLabel = QLabel(QApplication.translate("UnitCostDialog", "Cost/ha") + ":")       # Kosten/ha
        costLabel.setBuddy(self.costInput)

        spacerAlternative = QSpacerItem(0, 20, QSizePolicy.Minimum, QSizePolicy.Fixed)
        alternativeLabel = QLabel(QApplication.translate("UnitCostDialog", "Alternative user input") + ":")       # Alternative Benutzereingabe

        self.totalInput = QDoubleSpinBox(maximum=999999)
        self.totalInput.setSuffix(self._currency_unit)
        self.totalInput.setSingleStep(self._spinbox_step)
        totalLabel = QLabel(QApplication.translate("UnitCostDialog", "Total cost") + ":")       # Gesamtkosten
        totalLabel.setBuddy(self.totalInput)

        # create input group box layout
        inputLayout = QGridLayout(inputGroup)
        inputLayout.addWidget(areaLabel, 0, 0)
        inputLayout.addWidget(self.areaInput, 0, 1)
        inputLayout.addWidget(self.countLabel, 1, 0)
        inputLayout.addWidget(self.countInput, 1, 1)
        inputLayout.addWidget(costLabel, 2, 0)
        inputLayout.addWidget(self.costInput, 2, 1)
        inputLayout.addItem(spacerAlternative, 3, 0, 1, 2)
        inputLayout.addWidget(alternativeLabel, 4, 0, 1, 2)
        inputLayout.addWidget(totalLabel, 5, 0)
        inputLayout.addWidget(self.totalInput, 5, 1)

        # result group box
        resultGroup = QGroupBox(QApplication.translate("UnitCostDialog", "Calculation results"))     # Berechnungsergebnisse
        resultGroup.setFlat(True)

        self.unitResult = QLabel("0.00" + self._currency_unit_container)
        if self.piece:
            unitLabel = QLabel(QApplication.translate("UnitCostDialog", "Unit cost") + ":")       # Stückkosten
        else:
            unitLabel = QLabel(QApplication.translate("UnitCostDialog", "Fence cost") + ":")       # Zaunkosten
        unitLabel.setFixedWidth(self._LABEL_MIN_WIDTH)
        unitLabel.setBuddy(self.unitResult)

        # create input group box layout
        resultLayout = QGridLayout(resultGroup)
        resultLayout.addWidget(unitLabel, 0, 0)
        resultLayout.addWidget(self.unitResult, 0, 1)

        # create button box
        lineFrame = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.HLine)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)

        # create dialog main layout
        layout = QVBoxLayout(self)
        layout.addWidget(inputGroup)
        layout.addWidget(resultGroup)
        layout.addWidget(lineFrame)
        layout.addWidget(self.buttonBox)

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

        self.areaInput.valueChanged.connect(self.calculateTotal)
        self.countInput.valueChanged.connect(self.calculateTotal)
        self.costInput.valueChanged.connect(self.calculateTotal)
        self.totalInput.valueChanged.connect(self.calculateCost)
Example #49
0
class _BasePrompt(QWidget):

    """Base class for all prompts."""

    KEY_MODE = usertypes.KeyMode.prompt

    def __init__(self, question, parent=None):
        super().__init__(parent)
        self.question = question
        self._vbox = QVBoxLayout(self)
        self._vbox.setSpacing(15)
        self._key_grid = None

    def __repr__(self):
        return utils.get_repr(self, question=self.question, constructor=True)

    def _init_texts(self, question):
        assert question.title is not None, question
        title = '<font size="4"><b>{}</b></font>'.format(
            html.escape(question.title))
        title_label = QLabel(title, self)
        self._vbox.addWidget(title_label)
        if question.text is not None:
            # Not doing any HTML escaping here as the text can be formatted
            text_label = QLabel(question.text)
            text_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
            self._vbox.addWidget(text_label)

    def _init_key_label(self):
        assert self._key_grid is None, self._key_grid
        self._key_grid = QGridLayout()
        self._key_grid.setVerticalSpacing(0)

        all_bindings = config.key_instance.get_reverse_bindings_for(
            self.KEY_MODE.name)
        labels = []

        for cmd, text in self._allowed_commands():
            bindings = all_bindings.get(cmd, [])
            if bindings:
                binding = None
                preferred = ['<enter>', '<escape>']
                for pref in preferred:
                    if pref in bindings:
                        binding = pref
                if binding is None:
                    binding = bindings[0]
                key_label = QLabel('<b>{}</b>'.format(html.escape(binding)))
                text_label = QLabel(text)
                labels.append((key_label, text_label))

        for i, (key_label, text_label) in enumerate(labels):
            self._key_grid.addWidget(key_label, i, 0)
            self._key_grid.addWidget(text_label, i, 1)

        spacer = QSpacerItem(0, 0, QSizePolicy.Expanding)
        self._key_grid.addItem(spacer, 0, 2)

        self._vbox.addLayout(self._key_grid)

    def accept(self, value=None):
        raise NotImplementedError

    def download_open(self, _cmdline):
        """Open the download directly if this is a download prompt."""
        raise UnsupportedOperationError

    def item_focus(self, _which):
        """Switch to next file item if this is a filename prompt.."""
        raise UnsupportedOperationError

    def _allowed_commands(self):
        """Get the commands we could run as response to this message."""
        raise NotImplementedError
class QtGroupBoxPropertyBrowserPrivate():
    def __init__(self):
        self.q_ptr = None
        self.m_indexToItem = QMap()
        self.m_itemToIndex = QMap()
        self.m_widgetToItem = QMap()
        self.m_mainLayout = 0
        self.m_children = QList()
        self.m_recreateQueue = QList()

    def createEditor(self, property, parent):
        return self.q_ptr.createEditor(property, parent)

    def init(self, parent):
        self.m_mainLayout = QGridLayout()
        parent.setLayout(self.m_mainLayout)
        item = QSpacerItem(0, 0, QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.m_mainLayout.addItem(item, 0, 0)

    def slotEditorDestroyed(self):
        editor = self.q_ptr.sender()
        if (not editor):
            return
        if (not editor in self.m_widgetToItem.keys()):
            return
        self.m_widgetToItem[editor].widget = 0
        self.m_widgetToItem.remove(editor)

    def slotUpdate(self):
        for item in self.m_recreateQueue:
            par = item.parent
            w = 0
            l = 0
            oldRow = -1
            if (not par):
                w = self.q_ptr
                l = self.m_mainLayout
                oldRow = self.m_children.indexOf(item)
            else:
                w = par.groupBox
                l = par.layout
                oldRow = par.children.indexOf(item)
                if (self.hasHeader(par)):
                    oldRow += 2

            if (item.widget):
                item.widget.setParent(w)
            elif (item.widgetLabel):
                item.widgetLabel.setParent(w)
            else:
                item.widgetLabel = QLabel(w)
                item.widgetLabel.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed))
                item.widgetLabel.setTextFormat(Qt.PlainText)

            span = 1
            if (item.widget):
                l.addWidget(item.widget, oldRow, 1, 1, 1)
            elif (item.widgetLabel):
                l.addWidget(item.widgetLabel, oldRow, 1, 1, 1)
            else:
                span = 2
            item.label = QLabel(w)
            item.label.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
            l.addWidget(item.label, oldRow, 0, 1, span)

            self.updateItem(item)

        self.m_recreateQueue.clear()

    def updateLater(self):
        QTimer.singleShot(0, self.q_ptr, self.slotUpdate())

    def propertyInserted(self, index, afterIndex):
        afterItem = self.m_indexToItem[afterIndex]
        parentItem = self.m_indexToItem.value(index.parent())

        newItem = WidgetItem()
        newItem.parent = parentItem

        layout = 0
        parentWidget = 0
        row = -1
        if (not afterItem):
            row = 0
            if (parentItem):
                parentItem.children.insert(0, newItem)
            else:
                self.m_children.insert(0, newItem)
        else:
            if (parentItem):
                row = parentItem.children.indexOf(afterItem) + 1
                parentItem.children.insert(row, newItem)
            else:
                row = self.m_children.indexOf(afterItem) + 1
                self.m_children.insert(row, newItem)

        if (parentItem and self.hasHeader(parentItem)):
            row += 2

        if (not parentItem):
            layout = self.m_mainLayout
            parentWidget = self.q_ptr
        else:
            if not parentItem.groupBox:
                self.m_recreateQueue.removeAll(parentItem)
                par = parentItem.parent
                w = 0
                l = 0
                oldRow = -1
                if (not par):
                    w = self.q_ptr
                    l = self.m_mainLayout
                    oldRow = self.m_children.indexOf(parentItem)
                else:
                    w = par.groupBox
                    l = par.layout
                    oldRow = par.children.indexOf(parentItem)
                    if (self.hasHeader(par)):
                        oldRow += 2

                parentItem.groupBox = QGroupBox(w)
                parentItem.layout = QGridLayout()
                parentItem.groupBox.setLayout(parentItem.layout)
                if (parentItem.label):
                    l.removeWidget(parentItem.label)
                    parentItem.label.close()
                    parentItem.label = 0

                if (parentItem.widget):
                    l.removeWidget(parentItem.widget)
                    parentItem.widget.setParent(parentItem.groupBox)
                    parentItem.layout.addWidget(parentItem.widget, 0, 0, 1, 2)
                    parentItem.line = QFrame(parentItem.groupBox)
                elif (parentItem.widgetLabel):
                    l.removeWidget(parentItem.widgetLabel)
                    parentItem.widgetLabel.close()
                    parentItem.widgetLabel = 0

                if (parentItem.line):
                    parentItem.line.setFrameShape(QFrame.HLine)
                    parentItem.line.setFrameShadow(QFrame.Sunken)
                    parentItem.layout.addWidget(parentItem.line, 1, 0, 1, 2)

                l.addWidget(parentItem.groupBox, oldRow, 0, 1, 2)
                self.updateItem(parentItem)

            layout = parentItem.layout
            parentWidget = parentItem.groupBox

        newItem.label = QLabel(parentWidget)
        newItem.label.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        newItem.widget = self.createEditor(index.property(), parentWidget)
        if (not newItem.widget):
            newItem.widgetLabel = QLabel(parentWidget)
            newItem.widgetLabel.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed))
            newItem.widgetLabel.setTextFormat(Qt.PlainText)
        else:
            newItem.widget.destroyed.connect(self.slotEditorDestroyed)
            self.m_widgetToItem[newItem.widget] = newItem

        self.insertRow(layout, row)
        span = 1
        if (newItem.widget):
            layout.addWidget(newItem.widget, row, 1)
        elif (newItem.widgetLabel):
            layout.addWidget(newItem.widgetLabel, row, 1)
        else:
            span = 2
        layout.addWidget(newItem.label, row, 0, 1, span)

        self.m_itemToIndex[newItem] = index
        self.m_indexToItem[index] = newItem

        self.updateItem(newItem)

    def propertyRemoved(self, index):
        item = self.m_indexToItem[index]

        self.m_indexToItem.remove(index)
        self.m_itemToIndex.remove(item)

        parentItem = item.parent

        row = -1

        if (parentItem):
            row = parentItem.children.indexOf(item)
            parentItem.children.removeAt(row)
            if (self.hasHeader(parentItem)):
                row += 2
        else:
            row = self.m_children.indexOf(item)
            self.m_children.removeAt(row)

        if (item.widget):
            item.widget.close()
            del item.widget
        if (item.label):
            item.label.close()
            del item.label
        if (item.widgetLabel):
            item.widgetLabel.close()
            del item.widgetLabel
        if (item.groupBox):
            item.groupBox.close()
            del item.groupBox

        if (not parentItem):
            self.removeRow(self.m_mainLayout, row)
        elif len(parentItem.children) > 0:
            self.removeRow(parentItem.layout, row)
        else:
            par = parentItem.parent
            l = 0
            oldRow = -1
            if (not par):
                l = self.m_mainLayout
                oldRow = self.m_children.indexOf(parentItem)
            else:
                l = par.layout
                oldRow = par.children.indexOf(parentItem)
                if (self.hasHeader(par)):
                    oldRow += 2

            if (parentItem.widget):
                parentItem.widget.hide()
                parentItem.widget.setParent(0)
            elif (parentItem.widgetLabel):
                parentItem.widgetLabel.hide()
                parentItem.widgetLabel.setParent(0)
            else:
                #parentItem.widgetLabel = QLabel(w)
                pass

            l.removeWidget(parentItem.groupBox)
            parentItem.groupBox.close()
            parentItem.groupBox = 0
            parentItem.line = 0
            parentItem.layout = 0
            if (not parentItem in self.m_recreateQueue):
                 self.m_recreateQueue.append(parentItem)
            self.updateLater()

        self.m_recreateQueue.removeAll(item)

        del item

    def insertRow(self, layout, row):
        itemToPos = QMap()
        idx = 0
        while (idx < layout.count()):
            r, c, rs, cs = layout.getItemPosition(idx)
            if (r >= row):
                itemToPos[layout.takeAt(idx)] = QRect(r + 1, c, rs, cs)
            else:
                idx += 1

        for it in itemToPos.keys():
            r = itemToPos[it]
            layout.addItem(it, r.x(), r.y(), r.width(), r.height())

    def removeRow(self, layout, row):
        itemToPos = QMap()
        idx = 0
        while (idx < layout.count()):
            r, c, rs, cs = layout.getItemPosition(idx)
            if (r > row):
                itemToPos[layout.takeAt(idx)] = QRect(r - 1, c, rs, cs)
            else:
                idx += 1

        for it in itemToPos.keys():
            r = itemToPos[it]
            layout.addItem(it, r.x(), r.y(), r.width(), r.height())

    def hasHeader(self, item):
        if (item.widget):
            return True
        return False

    def propertyChanged(self, index):
        item = self.m_indexToItem[index]

        self.updateItem(item)

    def updateItem(self, item):
        property = self.m_itemToIndex[item].property()
        if (item.groupBox):
            font = item.groupBox.font()
            font.setUnderline(property.isModified())
            item.groupBox.setFont(font)
            item.groupBox.setTitle(property.propertyName())
            item.groupBox.setToolTip(property.toolTip())
            item.groupBox.setStatusTip(property.statusTip())
            item.groupBox.setWhatsThis(property.whatsThis())
            item.groupBox.setEnabled(property.isEnabled())

        if (item.label):
            font = item.label.font()
            font.setUnderline(property.isModified())
            item.label.setFont(font)
            item.label.setText(property.propertyName())
            item.label.setToolTip(property.toolTip())
            item.label.setStatusTip(property.statusTip())
            item.label.setWhatsThis(property.whatsThis())
            item.label.setEnabled(property.isEnabled())

        if (item.widgetLabel):
            font = item.widgetLabel.font()
            font.setUnderline(False)
            item.widgetLabel.setFont(font)
            item.widgetLabel.setText(property.valueText())
            item.widgetLabel.setToolTip(property.valueText())
            item.widgetLabel.setEnabled(property.isEnabled())

        if (item.widget):
            font = item.widget.font()
            font.setUnderline(False)
            item.widget.setFont(font)
            item.widget.setEnabled(property.isEnabled())
            item.widget.setToolTip(property.valueText())
Example #51
0
class CSVOptionsWindow(QWidget):
    def __init__(self, mainwindow):
        QWidget.__init__(self, mainwindow, Qt.Window)
        self._setupUi()
        self.doc = mainwindow.doc
        self.model = mainwindow.model.csv_options
        self.tableModel = CSVOptionsTableModel(self.model, self.tableView)
        self.model.view = self
        self.encodingComboBox.addItems(SUPPORTED_ENCODINGS)

        self.cancelButton.clicked.connect(self.hide)
        self.continueButton.clicked.connect(self.model.continue_import)
        self.targetComboBox.currentIndexChanged.connect(self.targetIndexChanged)
        self.layoutComboBox.currentIndexChanged.connect(self.layoutIndexChanged)
        self.rescanButton.clicked.connect(self.rescanClicked)

    def _setupUi(self):
        self.setWindowTitle(tr("CSV Options"))
        self.resize(526, 369)
        self.verticalLayout = QVBoxLayout(self)
        msg = tr(
            "Specify which CSV columns correspond to which transaction fields. You must also "
            "uncheck the \"Import\" column for lines that don\'t represent a transaction "
            "(header, footer, comments)."
        )
        self.label = QLabel(msg)
        self.label.setWordWrap(True)
        self.verticalLayout.addWidget(self.label)
        self.gridLayout = QGridLayout()
        self.label_2 = QLabel(tr("Layout:"))
        self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)
        self.layoutComboBox = QComboBox(self)
        self.layoutComboBox.setMinimumSize(QtCore.QSize(160, 0))
        self.gridLayout.addWidget(self.layoutComboBox, 0, 1, 1, 1)
        self.label_4 = QLabel(tr("Delimiter:"))
        self.gridLayout.addWidget(self.label_4, 0, 3, 1, 1)
        self.fieldSeparatorEdit = QLineEdit(self)
        self.fieldSeparatorEdit.setMaximumSize(QtCore.QSize(30, 16777215))
        self.gridLayout.addWidget(self.fieldSeparatorEdit, 0, 4, 1, 1)
        self.targetComboBox = QComboBox(self)
        self.gridLayout.addWidget(self.targetComboBox, 1, 1, 1, 1)
        self.label_3 = QLabel(tr("Target:"))
        self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1)
        self.encodingComboBox = QComboBox(self)
        self.gridLayout.addWidget(self.encodingComboBox, 1, 4, 1, 1)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem, 2, 2, 1, 1)
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setSpacing(0)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.rescanButton = QPushButton(tr("Rescan"))
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.rescanButton.sizePolicy().hasHeightForWidth())
        self.rescanButton.setSizePolicy(sizePolicy)
        self.horizontalLayout_2.addWidget(self.rescanButton)
        self.gridLayout.addLayout(self.horizontalLayout_2, 2, 3, 1, 2)
        self.label_5 = QLabel(tr("Encoding:"))
        self.gridLayout.addWidget(self.label_5, 1, 3, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout)
        self.tableView = QTableView(self)
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.setShowGrid(False)
        self.tableView.horizontalHeader().setHighlightSections(False)
        self.tableView.verticalHeader().setVisible(False)
        self.tableView.verticalHeader().setDefaultSectionSize(18)
        self.verticalLayout.addWidget(self.tableView)
        self.horizontalLayout = QHBoxLayout()
        spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.cancelButton = QPushButton(tr("Cancel"))
        self.cancelButton.setShortcut("Esc")
        self.horizontalLayout.addWidget(self.cancelButton)
        self.continueButton = QPushButton(tr("Continue Import"))
        self.continueButton.setDefault(True)
        self.horizontalLayout.addWidget(self.continueButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

    # --- Private
    def _newLayout(self):
        title = tr("New Layout")
        msg = tr("Choose a name for your new layout:")
        name, ok = QInputDialog.getText(self, title, msg)
        if ok and name:
            self.model.new_layout(name)

    def _renameLayout(self):
        title = tr("Rename Layout")
        msg = tr("Choose a name for your layout:")
        name, ok = QInputDialog.getText(self, title, msg)
        if ok and name:
            self.model.rename_selected_layout(name)

    # --- Event Handling
    def layoutIndexChanged(self, index):
        # This one is a little complicated. We want to only be able to select the layouts. If
        # anything else is clicked, we revert back to the old index. If the item has user data,
        # it means that an action has to be performed.
        if index < 0:
            return
        elif index < len(self.model.layout_names):
            layout_name = None if index == 0 else str(self.layoutComboBox.itemText(index))
            self.model.select_layout(layout_name)
        else:
            self.layoutComboBox.setCurrentIndex(self.layoutComboBox.findText(self.model.layout.name))
            data = str(self.layoutComboBox.itemData(index))
            if data == NEW_LAYOUT:
                self._newLayout()
            elif data == RENAME_LAYOUT:
                self._renameLayout()
            elif data == DELETE_LAYOUT:
                self.model.delete_selected_layout()

    def rescanClicked(self):
        self.model.encoding_index = self.encodingComboBox.currentIndex()
        self.model.field_separator = str(self.fieldSeparatorEdit.text())
        self.model.rescan()

    def targetIndexChanged(self, index):
        self.model.selected_target_index = index

    # --- model --> view
    # hide() is called from the model, but is already covered by QWidget
    def refresh_columns(self):
        self.tableModel.beginResetModel()
        self.tableModel.endResetModel()

    def refresh_columns_name(self):
        self.tableModel.refreshColumnsName()

    def refresh_layout_menu(self):
        self.layoutComboBox.currentIndexChanged.disconnect(self.layoutIndexChanged)
        self.layoutComboBox.clear()
        self.layoutComboBox.addItems(self.model.layout_names)
        self.layoutComboBox.insertSeparator(self.layoutComboBox.count())
        self.layoutComboBox.addItem(tr("New Layout..."), NEW_LAYOUT)
        self.layoutComboBox.addItem(tr("Rename Selected Layout..."), RENAME_LAYOUT)
        self.layoutComboBox.addItem(tr("Delete Selected Layout"), DELETE_LAYOUT)
        self.layoutComboBox.setCurrentIndex(self.layoutComboBox.findText(self.model.layout.name))
        self.layoutComboBox.currentIndexChanged.connect(self.layoutIndexChanged)

    def refresh_lines(self):
        self.tableModel.beginResetModel()
        self.tableModel.endResetModel()
        self.fieldSeparatorEdit.setText(self.model.field_separator)

    def refresh_targets(self):
        self.targetComboBox.currentIndexChanged.disconnect(self.targetIndexChanged)
        self.targetComboBox.clear()
        self.targetComboBox.addItems(self.model.target_account_names)
        self.targetComboBox.currentIndexChanged.connect(self.targetIndexChanged)

    def show(self):
        # For non-modal dialogs, show() is not enough to bring the window at the forefront, we have
        # to call raise() as well
        QWidget.show(self)
        self.raise_()

    def show_message(self, msg):
        title = "Warning"
        QMessageBox.warning(self, title, msg)
Example #52
0
class OptionsWindow(QWidget):
    """ Window for changing settings.

    Useful attributes
    -----------------
    parentWindow : MainWindow object
        Parent of the window.
    langCombo : QComboBox object
        Language selector.
    tdelta(Days|Hours|Mins|Secs)Edit : QLineEdit object
        Widgets for time delta change.
    mesoutSecsEdit : QLineEdit object
        Widget for message timeout change.
    backupMinsEdit : QLineEdit object
        Widget for backup timeout change.
    """
    def __init__(self, parent=None):
        super().__init__()
        self.parentWindow = parent
        self.parentWindow.optActive = True
        self.initUI()

    def initUI(self):
        """ Init user interface. """
        self.setWindowTitle(conf.lang.OPT_TITLE)
        iconOpt = Icon(byte=icons.options).convertToIcon().getIcon()
        self.setWindowIcon(iconOpt)

        self.resize(500, 175)
        self.move(QApplication.desktop().screen().rect().center() -
                  self.rect().center()) # center window on screen

        self.grid = QGridLayout()
        self.setLayout(self.grid)

        self.fill()

    def fill(self):
        """ Fills window with widgets. """
        clearLayout(self.grid)

        # language selector
        self.grid.addWidget(QLabel(conf.lang.CHANGE_LANGUAGE), 0, 0)
        self.langCombo = QComboBox()
        langList = []
        for i in langs.values():
            if i.NAME == conf.lang.NAME:
                langList.insert(0, i.FULL_NAME) # current language is first
            else:
                langList.append(i.FULL_NAME)

        self.langCombo.insertItems(0, langList)
        self.grid.addWidget(self.langCombo, 0, 1, 1, 4)

        # tdelta change
        tdeltaDict = parseSeconds(conf.tdelta, dic=True)
        self.grid.addWidget(QLabel(conf.lang.CHANGE_TDELTA), 1, 0)

        self.tdeltaDaysEdit = QLineEdit()
        self.tdeltaDaysEdit.setText(str(tdeltaDict['days']))
        self.tdeltaDaysEdit.setValidator(QIntValidator(0, 999))
        self.grid.addWidget(self.tdeltaDaysEdit, 1, 1)
        self.grid.addWidget(QLabel(conf.lang.DAYS), 1, 2)

        self.tdeltaHoursEdit = QLineEdit()
        self.tdeltaHoursEdit.setText(str(tdeltaDict['hours']))
        self.tdeltaHoursEdit.setValidator(QIntValidator(0, 23))
        self.grid.addWidget(self.tdeltaHoursEdit, 1, 3)
        self.grid.addWidget(QLabel(conf.lang.HOURS), 1, 4)

        self.tdeltaMinsEdit = QLineEdit()
        self.tdeltaMinsEdit.setText(str(tdeltaDict['minutes']))
        self.tdeltaMinsEdit.setValidator(QIntValidator(0, 59))
        self.grid.addWidget(self.tdeltaMinsEdit, 1, 5)
        self.grid.addWidget(QLabel(conf.lang.MINUTES), 1, 6)

        self.tdeltaSecsEdit = QLineEdit()
        self.tdeltaSecsEdit.setText(str(tdeltaDict['seconds']))
        self.tdeltaSecsEdit.setValidator(QIntValidator(0, 59))
        self.grid.addWidget(self.tdeltaSecsEdit, 1, 7)
        self.grid.addWidget(QLabel(conf.lang.SECONDS), 1, 8)

        # mesout change
        self.grid.addWidget(QLabel(conf.lang.MESSAGE_TIMER), 2, 0)
        self.mesoutSecsEdit = QLineEdit()
        self.mesoutSecsEdit.setText(str(conf.mesout))
        self.mesoutSecsEdit.setValidator(QIntValidator(0, 299))
        self.grid.addWidget(self.mesoutSecsEdit, 2, 1)
        self.grid.addWidget(QLabel(conf.lang.SECONDS), 2, 2)

        # backup timeout change
        self.grid.addWidget(QLabel(conf.lang.BACKUP_TIMER), 3, 0)
        self.backupMinsEdit = QLineEdit()
        self.backupMinsEdit.setText(str(int(conf.backup / 60)))
        self.backupMinsEdit.setValidator(QIntValidator(0, 999))
        self.grid.addWidget(self.backupMinsEdit, 3, 1)
        self.grid.addWidget(QLabel(conf.lang.MINUTES), 3, 2)

        spacer = QSpacerItem(10, 0, vPolicy=QSizePolicy.MinimumExpanding)
        self.grid.addItem(spacer, 4, 0)

        saveBtn = QPushButton(conf.lang.SAVE)
        saveBtn.clicked.connect(self.save)
        self.grid.addWidget(saveBtn, 5, 5, 1, 2)
        closeBtn = QPushButton(conf.lang.CLOSE)
        closeBtn.clicked.connect(lambda: self.closeEvent(QCloseEvent()))
        self.grid.addWidget(closeBtn, 5, 7, 1, 2)

    def save(self):
        """ Save changes to config. """
        tdelta = [self.tdeltaSecsEdit.text(), self.tdeltaMinsEdit.text(),
                  self.tdeltaHoursEdit.text(), self.tdeltaDaysEdit.text()]
        tdelta = list(map(lambda x: int(x) if x != '' else 0, tdelta))
        tdelta[1] *= 60
        tdelta[2] *= 3600
        tdelta[3] *= 86400
        tdelta = sum(tdelta)
        conf.tdelta = tdelta

        if self.mesoutSecsEdit.text() == '':
            self.mesoutSecsEdit.setText('0')
        mesout = int(self.mesoutSecsEdit.text())
        if mesout == 0:
            mesout = 60
        conf.mesout = mesout

        if self.backupMinsEdit.text() == '':
            self.backupMinsEdit.setText('0')
        backup = int(self.backupMinsEdit.text())
        if backup == 0:
            backup = 5
        conf.backup = backup * 60

        if self.langCombo.currentText() != conf.lang.FULL_NAME:
            for i in langs.values():
                if i.FULL_NAME == self.langCombo.currentText():
                    conf.lang = i

        self.closeEvent(QCloseEvent(), changed=True)

    def closeEvent(self, event, changed=False):
        """ Closes window. """
        self.parentWindow.optActive = False
        if self.parentWindow.addActive:
            self.parentWindow.addWindow.show()
            if self.parentWindow.addWindow.index == None:
                if self.parentWindow.editActive:
                    self.parentWindow.editWindow.show()
        else:
            if self.parentWindow.editActive:
                self.parentWindow.editWindow.show()

        event.ignore()

        if changed:
            reload()

        self.hide()
class QtButtonPropertyBrowserPrivate():
    def __init__(self):
        self.q_ptr = None
        self.WidgetItem = WidgetItem()
        self.m_indexToItem = QMap()
        self.m_itemToIndex = QMap()
        self.m_widgetToItem = QMap()
        self.m_buttonToItem = QMap()
        self.m_mainLayout = None
        self.m_children = QList()
        self.m_recreateQueue = QList()

    def createEditor(self, property, parent):
        return self.q_ptr.createEditor(property, parent)

    def createButton(self, parent=None):
        button = QToolButton(parent)
        button.setCheckable(True)
        button.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed))
        button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        button.setArrowType(Qt.DownArrow)
        button.setIconSize(QSize(3, 16))
        ###
        #QIcon icon
        #icon.addPixmap(self.style().standardPixmap(QStyle.SP_ArrowDown), QIcon.Normal, QIcon.Off)
        #icon.addPixmap(self.style().standardPixmap(QStyle.SP_ArrowUp), QIcon.Normal, QIcon.On)
        #button.setIcon(icon)
        ###
        return button

    def gridRow(self, item):
        siblings = QList()
        if (item.parent):
            siblings = item.parent.children
        else:
            siblings = self.m_children

        row = 0
        for sibling in siblings:
            if (sibling == item):
                return row
            row += self.gridSpan(sibling)

        return -1

    def gridSpan(self, item):
        if (item.container and item.expanded):
            return 2
        return 1

    def init(self, parent):
        self.m_mainLayout = QGridLayout()
        parent.setLayout(self.m_mainLayout)
        item = QSpacerItem(0, 0, QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.m_mainLayout.addItem(item, 0, 0)

    def slotEditorDestroyed(self):
        editor = self.q_ptr.sender()
        if (not editor):
            return
        if not self.m_widgetToItem.get(editor):
            return
        self.m_widgetToItem[editor].widget = 0
        self.m_widgetToItem.remove(editor)

    def slotUpdate(self):
        for item in self.m_recreateQueue:
            parent = item.parent
            w = 0
            l = 0
            oldRow = self.gridRow(item)
            if (parent):
                w = parent.container
                l = parent.layout
            else:
                w = self.q_ptr
                l = self.m_mainLayout

            span = 1
            if (not item.widget and not item.widgetLabel):
                span = 2
            item.label = QLabel(w)
            item.label.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
            l.addWidget(item.label, oldRow, 0, 1, span)

            self.updateItem(item)

        self.m_recreateQueue.clear()

    def setExpanded(self, item, expanded):
        if (item.expanded == expanded):
            return

        if (not item.container):
            return

        item.expanded = expanded
        row = self.gridRow(item)
        parent = item.parent
        l = 0
        if (parent):
            l = parent.layout
        else:
            l = self.m_mainLayout

        if (expanded):
            self.insertRow(l, row + 1)
            l.addWidget(item.container, row + 1, 0, 1, 2)
            item.container.show()
        else:
            l.removeWidget(item.container)
            item.container.hide()
            self.removeRow(l, row + 1)

        item.button.setChecked(expanded)
        if expanded:
            item.button.setArrowType(Qt.UpArrow)
        else:
            item.button.setArrowType(Qt.DownArrow)

    def slotToggled(self, checked):
        item = self.m_buttonToItem[self.q_ptr.sender()]
        if (not item):
            return

        self.setExpanded(item, checked)

        if (checked):
            self.q_ptr.expandedSignal.emit(self.m_itemToIndex[item])
        else:
            self.q_ptr.collapsedSignal.emit(self.m_itemToIndex[item])

    def updateLater(self):
        QTimer.singleShot(0, self.slotUpdate)

    def propertyInserted(self, index, afterIndex):
        afterItem = self.m_indexToItem[afterIndex]
        parentItem = self.m_indexToItem.value(index.parent())

        newItem = WidgetItem()
        newItem.parent = parentItem

        layout = 0
        parentWidget = 0
        row = -1
        if (not afterItem):
            row = 0
            if (parentItem):
                parentItem.children.insert(0, newItem)
            else:
                self.m_children.insert(0, newItem)
        else:
            row = self.gridRow(afterItem) + self.gridSpan(afterItem)
            if (parentItem):
                parentItem.children.insert(parentItem.children.indexOf(afterItem) + 1, newItem)
            else:
                self.m_children.insert(self.m_children.indexOf(afterItem) + 1, newItem)

        if (not parentItem):
            layout = self.m_mainLayout
            parentWidget = self.q_ptr
        else:
            if (not parentItem.container):
                self.m_recreateQueue.removeAll(parentItem)
                grandParent = parentItem.parent
                l = 0
                oldRow = self.gridRow(parentItem)
                if (grandParent):
                    l = grandParent.layout
                else:
                    l = self.m_mainLayout

                container = QFrame()
                container.setFrameShape(QFrame.Panel)
                container.setFrameShadow(QFrame.Raised)
                parentItem.container = container
                parentItem.button = self.createButton()
                self.m_buttonToItem[parentItem.button] = parentItem
                parentItem.button.toggled.connect(self.slotToggled)
                parentItem.layout = QGridLayout()
                container.setLayout(parentItem.layout)
                if (parentItem.label):
                    l.removeWidget(parentItem.label)
                    parentItem.label.close()
                    parentItem.label = 0

                span = 1
                if (not parentItem.widget and not parentItem.widgetLabel):
                    span = 2
                l.addWidget(parentItem.button, oldRow, 0, 1, span)
                self.updateItem(parentItem)

            layout = parentItem.layout
            parentWidget = parentItem.container

        newItem.label = QLabel(parentWidget)
        newItem.label.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        newItem.widget = self.createEditor(index.property(), parentWidget)
        if (newItem.widget):
            newItem.widget.destroyed.connect(self.slotEditorDestroyed)
            self.m_widgetToItem[newItem.widget] = newItem
        elif (index.property().hasValue()):
            newItem.widgetLabel = QLabel(parentWidget)
            newItem.widgetLabel.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed))

        self.insertRow(layout, row)
        span = 1
        if (newItem.widget):
            layout.addWidget(newItem.widget, row, 1)
        elif (newItem.widgetLabel):
            layout.addWidget(newItem.widgetLabel, row, 1)
        else:
            span = 2
        layout.addWidget(newItem.label, row, 0, span, 1)

        self.m_itemToIndex[newItem] = index
        self.m_indexToItem[index] = newItem

        self.updateItem(newItem)

    def propertyRemoved(self, index):
        item = self.m_indexToItem[index]

        self.m_indexToItem.remove(index)
        self.m_itemToIndex.remove(item)

        parentItem = item.parent

        row = self.gridRow(item)

        if (parentItem):
            parentItem.children.removeAt(parentItem.children.indexOf(item))
        else:
            self.m_children.removeAt(self.m_children.indexOf(item))

        colSpan = self.gridSpan(item)

        self.m_buttonToItem.remove(item.button)

        if (item.widget):
            item.widget.close()
            del item.widget
        if (item.label):
            item.label.close()
            del item.label
        if (item.widgetLabel):
            item.widgetLabel.close()
            del item.widgetLabel
        if (item.button):
            item.button.close()
            del item.button
        if (item.container):
            item.container.close()
            del item.container

        if (not parentItem):
            self.removeRow(self.m_mainLayout, row)
            if (colSpan > 1):
                self.removeRow(self.m_mainLayout, row)
        elif (len(parentItem.children) != 0):
            self.removeRow(parentItem.layout, row)
            if (colSpan > 1):
                self.removeRow(parentItem.layout, row)
        else:
            grandParent = parentItem.parent
            l = 0
            if (grandParent):
                l = grandParent.layout
            else:
                l = self.m_mainLayout

            parentRow = self.gridRow(parentItem)
            parentSpan = self.gridSpan(parentItem)

            l.removeWidget(parentItem.button)
            l.removeWidget(parentItem.container)
            parentItem.button.close()
            del parentItem.button
            parentItem.container.close()
            del parentItem.container
            parentItem.button = 0
            parentItem.container = 0
            parentItem.layout = 0
            if (not parentItem in self.m_recreateQueue):
                 self.m_recreateQueue.append(parentItem)
            if (parentSpan > 1):
                self.removeRow(l, parentRow + 1)

            self.updateLater()

        self.m_recreateQueue.removeAll(item)

        del item

    def insertRow(self, layout, row):
        itemToPos = QMap()
        idx = 0
        while (idx < len(layout)):
            r, c, rs, cs = layout.getItemPosition(idx)
            if (r >= row):
                itemToPos[layout.takeAt(idx)] = QRect(r + 1, c, rs, cs)
            else:
                idx += 1

        for k in itemToPos.keys():
            r = itemToPos[k]
            layout.addItem(k, r.x(), r.y(), r.width(), r.height())

    def removeRow(self, layout, row):
        itemToPos = QMap()
        idx = 0
        while (idx < len(layout)):
            r, c, rs, cs = layout.getItemPosition(idx)
            if (r > row):
                itemToPos[layout.takeAt(idx)] = QRect(r - 1, c, rs, cs)
            else:
                idx += 1

        for k in itemToPos.keys():
            r = itemToPos[k]
            layout.addItem(k, r.x(), r.y(), r.width(), r.height())

    def propertyChanged(self, index):
        item = self.m_indexToItem[index]

        self.updateItem(item)

    def updateItem(self, item):
        property = self.m_itemToIndex[item].property()
        if (item.button):
            font = item.button.font()
            font.setUnderline(property.isModified())
            item.button.setFont(font)
            item.button.setText(property.propertyName())
            item.button.setToolTip(property.toolTip())
            item.button.setStatusTip(property.statusTip())
            item.button.setWhatsThis(property.whatsThis())
            item.button.setEnabled(property.isEnabled())

        if (item.label):
            font = item.label.font()
            font.setUnderline(property.isModified())
            item.label.setFont(font)
            item.label.setText(property.propertyName())
            item.label.setToolTip(property.toolTip())
            item.label.setStatusTip(property.statusTip())
            item.label.setWhatsThis(property.whatsThis())
            item.label.setEnabled(property.isEnabled())

        if (item.widgetLabel):
            font = item.widgetLabel.font()
            font.setUnderline(False)
            item.widgetLabel.setFont(font)
            item.widgetLabel.setText(property.valueText())
            item.widgetLabel.setToolTip(property.valueText())
            item.widgetLabel.setEnabled(property.isEnabled())

        if (item.widget):
            font = item.widget.font()
            font.setUnderline(False)
            item.widget.setFont(font)
            item.widget.setEnabled(property.isEnabled())
            item.widget.setToolTip(property.valueText())
Example #54
0
class NewView(BaseView):
    def _setup(self):
        self._setupUi()

        self.networthButton.clicked.connect(self.networthButtonClicked)
        self.profitButton.clicked.connect(self.profitButtonClicked)
        self.transactionButton.clicked.connect(self.transactionButtonClicked)
        self.gledgerButton.clicked.connect(self.gledgerButtonClicked)
        self.scheduleButton.clicked.connect(self.scheduleButtonClicked)
        self.budgetButton.clicked.connect(self.budgetButtonClicked)
        self.docpropsButton.clicked.connect(self.docpropsButtonClicked)
        self.shortcut1.activated.connect(self.networthButtonClicked)
        self.shortcut2.activated.connect(self.profitButtonClicked)
        self.shortcut3.activated.connect(self.transactionButtonClicked)
        self.shortcut4.activated.connect(self.gledgerButtonClicked)
        self.shortcut5.activated.connect(self.scheduleButtonClicked)
        self.shortcut6.activated.connect(self.budgetButtonClicked)
        self.shortcut7.activated.connect(self.docpropsButtonClicked)

    def _setupUi(self):
        self.resize(400, 300)
        self.gridLayout = QGridLayout(self)
        self.label = QLabel(tr("Choose a type for this tab:"))
        self.label.setAlignment(Qt.AlignCenter)
        self.gridLayout.addWidget(self.label, 0, 0, 1, 3)
        self.gridLayout.addItem(horizontalSpacer(), 1, 0, 1, 1)
        self.verticalLayout = QVBoxLayout()
        BUTTONS = [
            ('networthButton', tr("1. Net Worth"), 'balance_sheet_16'),
            ('profitButton', tr("2. Profit && Loss"), 'income_statement_16'),
            ('transactionButton', tr("3. Transactions"), 'transaction_table_16'),
            ('gledgerButton', tr("4. General Ledger"), 'gledger_16'),
            ('scheduleButton', tr("5. Schedules"), 'schedules_16'),
            ('budgetButton', tr("6. Budgets"), 'budget_16'),
            ('docpropsButton', tr("7. Document Properties"), 'gledger_16'),
        ]
        for i, (name, label, icon) in enumerate(BUTTONS, start=1):
            button = QPushButton(label)
            if icon:
                button.setIcon(QIcon(QPixmap(':/{}'.format(icon))))
            self.verticalLayout.addWidget(button)
            setattr(self, name, button)
            shortcut = QShortcut(self)
            shortcut.setKey(QKeySequence(str(i)))
            shortcut.setContext(Qt.WidgetShortcut)
            setattr(self, 'shortcut{}'.format(i), shortcut)
        self.gridLayout.addLayout(self.verticalLayout, 1, 1, 1, 1)
        self.gridLayout.addItem(horizontalSpacer(), 1, 2, 1, 1)
        self.gridLayout.addItem(verticalSpacer(), 2, 1, 1, 1)

    # --- Event Handlers
    def networthButtonClicked(self):
        self.model.select_pane_type(PaneType.NetWorth)

    def profitButtonClicked(self):
        self.model.select_pane_type(PaneType.Profit)

    def transactionButtonClicked(self):
        self.model.select_pane_type(PaneType.Transaction)

    def gledgerButtonClicked(self):
        self.model.select_pane_type(PaneType.GeneralLedger)

    def scheduleButtonClicked(self):
        self.model.select_pane_type(PaneType.Schedule)

    def budgetButtonClicked(self):
        self.model.select_pane_type(PaneType.Budget)

    def docpropsButtonClicked(self):
        self.model.select_pane_type(PaneType.DocProps)