Beispiel #1
0
    def __init__(self, settings_obj, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.source_obj = settings_obj
        if isinstance(settings_obj, list):
            self.type_ = type(
                settings_obj[0]) if len(settings_obj) > 0 else str
            [self.listWidget.addItem(str(t)) for t in settings_obj]
            self.listWidget.itemDoubleClicked.connect(
                self.on_item_double_clicked)
            self.dictGroupBox.hide()
        elif isinstance(settings_obj, dict):
            self.listGroupBox.hide()
            self.controls = {}
            layout = QBoxLayout(QBoxLayout.TopToBottom)
            for key, value in settings_obj.items():
                control = QCheckBox(key, self)
                layout.addWidget(control)
                control.setChecked(value)
                self.controls[key] = control
            layout.addItem(
                QSpacerItem(0, 0, QSizePolicy.Expanding,
                            QSizePolicy.Expanding))
            self.dictGroupBox.setLayout(layout)

        self.addButton.clicked.connect(self.on_add_button_clicked)
        self.okButton.clicked.connect(self.on_ok_button_clicked)
Beispiel #2
0
    def __init__(self):
        super(Window, self).__init__()
        box = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.resize(1200, 800)

        def canvas_on_close_handler(_1, _2):
            self.close()
        _context.canvas.set_on_close_handler(canvas_on_close_handler)
        box.addWidget(_context.canvas.native)
        
        rightBoxWidget = QWidget()
        rightBox = QBoxLayout(QBoxLayout.TopToBottom, rightBoxWidget)
        rightBox.setAlignment(Qt.AlignTop)
        box.addWidget(rightBoxWidget)

        tensor_view_selector = TensorRankViewSelector()
        rightBox.addWidget(tensor_view_selector)

        #button = QPushButton('Change View', self)
        #button.setToolTip('Change View Port')
        #rightBox.addWidget(button)

        xyzRangeSelector = XYZRangeSelector()
        rightBox.addWidget(xyzRangeSelector)

        tw_container = TensorRankShower()
        rightBox.addWidget(tw_container)

        self.show()
Beispiel #3
0
 def init_ui(self):
     self.setMinimumWidth(500)
     self.setMinimumHeight(400)
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     self.setLayout(layout)
     self.lb_1.setPixmap(self.pixmap)
     layout.addWidget(self.lb_1)
    def __init__(self):
        super().__init__()

        # information widget
        self.plotWidget = VariantPlotWidget()
        self.infoWidget = VariantInfoWidget()

        # splitter settings
        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(self.plotWidget)
        splitter.addWidget(self.infoWidget)
        splitter.setStretchFactor(0, 3)
        splitter.setStretchFactor(1, 1)

        # layout
        layout = QBoxLayout(QBoxLayout.TopToBottom)
        layout.addWidget(splitter)
        self.setLayout(layout)

        # connect signals
        self.plotWidget.curvePlotted.connect(self.infoWidget.updateResults)
        self.plotWidget.plotReady.connect(self.infoWidget.showResults)
        self.plotWidget.cleared.connect(self.infoWidget.clear)
        self.infoWidget.legendChanged.connect(self.plotWidget.paintCalculation)

        # translate the graphical user interface
        self.retranslateUi()
Beispiel #5
0
    def __init__(self, session, ui_area):
        from PyQt5.QtWidgets import QBoxLayout
        self.session = session
        from chimerax.core.commands import run
        from .options import CategorizedSettingsPanel
        self.options_widget = CategorizedSettingsPanel(help_cb=lambda *, category=None, ses=session, run=run:
            run(ses, "help help:user/preferences.html"
            + ("" if category is None else "#" + category.replace(' ', '').lower())))
        self.options = {}

        for setting, setting_info in self.settings_info.items():
            opt_name, category, opt_class, updater, converter, balloon, set_setting = setting_info
            if isinstance(opt_class, tuple):
                opt_class, kw = opt_class
                if 'session' in kw:
                    kw['session'] = self.session
            else:
                kw = {}
            opt = opt_class(opt_name, getattr(core_settings, setting), self._opt_cb,
                attr_name=setting, settings=core_settings, balloon=balloon, auto_set_attr=set_setting, **kw)
            self.options_widget.add_option(category, opt)
            self.options[setting] = opt

        core_settings.triggers.add_handler('setting changed', self._core_setting_changed)
        layout = QBoxLayout(QBoxLayout.TopToBottom)
        layout.setSpacing(5)
        layout.addWidget(self.options_widget, 1)
        layout.setContentsMargins(0, 0, 0, 0)

        ui_area.setLayout(layout)
 def __init__(self, parent):
     super(ScoresWindow, self).__init__(parent)
     self.parent = parent
     mainLayout = QBoxLayout(QBoxLayout.TopToBottom)
     columnLayout = QBoxLayout(QBoxLayout.LeftToRight)
     column = [QBoxLayout(QBoxLayout.TopToBottom) for i in range(3)]
     for i in column: columnLayout.addLayout(i)
     self.cell = [QLabel() for i in range(9)]
     for i in range(9): column[i//3].addWidget(self.cell[i])
     chartView = QChartView()
     axisY = QValueAxis()
     axisY.setRange(-700,700)
     axisY.setLabelFormat("%d")
     self.chart = LineChart(((10,20,30,40,50,60,70,80),(0,-10,-20,-30,-40,50,-20,0)))
     self.chart.addAxis(axisY, Qt.AlignLeft)
     for i in self.chart.series:
         i.attachAxis(axisY)
     chartView.setChart(self.chart)
     self.level = QLabel()
     mainLayout.addLayout(columnLayout)
     mainLayout.addWidget(chartView)
     self.setLayout(mainLayout)
     self.setFixedSize(300,400)
     self.setModal(True)
     self.setStrings()
Beispiel #7
0
class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)
        # 배치될 위젯 변수 선언
        self.lb_1 = QLabel()
        self.lb_2 = QLabel()
        self.pb_1 = QPushButton()
        self.pb_2 = QPushButton()
        # 레이아웃 선언 및 Form Widget에 설정
        self.layout_1 = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.setLayout(self.layout_1)
        self.init_widget()

    def init_widget(self):
        self.setWindowTitle("Layout Basic")
        self.setFixedWidth(640)

        # 라벨1의 설정 및 레이아웃 추가
        self.lb_1.setText("Label 1")
        self.lb_1.setStyleSheet("background-color: yellow")
        self.pb_1.setText("Button 1")
        self.layout_1.addWidget(self.lb_1)
        self.layout_1.addWidget(self.pb_1)

        # 라벨2의 설정 및 레이아웃 추가
        self.lb_2.setText("Label 2")
        self.lb_2.setStyleSheet("background-color: red")
        self.pb_2.setText("Button 2")
        self.layout_1.addWidget(self.lb_2)
        self.layout_1.addWidget(self.pb_2)
Beispiel #8
0
    def put_into_layout(self, programs, qbtn, sbtn):
        layout = QBoxLayout(2)  # TopToBottom
        upper = QBoxLayout(2)
        lower = QBoxLayout(0)  # LeftToRight
        upperboxes = {}

        #     calculation of boxlayout
        for i in range(self.funcs['HOWMANYPROGRAMS']):
            columns = self.funcs['COLUMNS']
            if i % columns == 0:
                upperboxes[f'box{i}'] = QBoxLayout(0)
                for j in range(columns):
                    try:
                        upperboxes[f'box{i}'].addWidget(
                            programs[f'program{j+i}'])
                    except:
                        continue
                upper.addLayout(upperboxes[f'box{i}'])

        lower.addWidget(qbtn)
        lower.addWidget(sbtn)
        layout.addLayout(upper)
        layout.addLayout(lower)

        return layout
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        self.setGeometry(300, 300, 400, 400)
        self.setWindowFlag(Qt.WindowStaysOnTopHint)
        
        layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.target_rect = QWidget(parent=self, flags=Qt.Widget)
        self.target_rect.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.target_rect.setStyleSheet("background-color: black")
        layout.addWidget(self.target_rect)

        buttons = QWidget()
        buttons.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        layout.addWidget(buttons)
        layout2 = QBoxLayout(QBoxLayout.LeftToRight)
        buttons.setLayout(layout2)

        self.btn_capture = QPushButton(parent=self, text='분석')
        self.btn_exit = QPushButton(parent=self, text='종료')
        self.btn_capture.clicked.connect(self.on_btn_capture_clicked)
        self.btn_exit.clicked.connect(sys.exit)
        layout2.addWidget(self.btn_capture)
        layout2.addWidget(self.btn_exit)

        self.result_text = QPlainTextEdit()
        self.result_text.setMaximumHeight(100)
        self.result_text.setEnabled(False)
        self.result_text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        layout.addWidget(self.result_text)

        self.setLayout(layout)

        self.image_process_thread = ImageProcessClass(self)
        self.image_process_thread.resstr.connect(self.thread_end)
    def __init__(self, algorithms):
        super(Window, self).__init__()

        self.stackedWidget = QStackedWidget()
        self.orientationCombo = QComboBox()

        for category in categories:
            pass



        for algorithm in algorithms:
            self.orientationCombo.addItem(algorithm.get_name())
            self.stackedWidget.addWidget(GroupOfSliders(algorithm))

            layout = QBoxLayout(QBoxLayout.TopToBottom)

            settings_layout = QBoxLayout(QBoxLayout.TopToBottom)
            settings_layout.addWidget(self.stackedWidget)

            select_layout = QBoxLayout(QBoxLayout.TopToBottom)
            select_layout.addWidget(self.orientationCombo)

            layout.addItem(settings_layout)
            layout.addItem(select_layout)

            self.setLayout(layout)
            self.setWindowTitle(algorithm.get_name() + " Settings")
class myForm(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        self.lb_1 = QLabel()
        self.lb_2 = QLabel()
        self.pb_1 = QPushButton()
        self.pb_2 = QPushButton()

        self.layout_1 = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.setLayout(self.layout_1)
        self.init_widget()

    def init_widget(self):
        self.setWindowTitle("Layout exercise application")
        self.setFixedWidth(640)

        self.lb_1.setText("Label 1")
        self.lb_1.setStyleSheet("background-color: blue")
        self.pb_1.setText("Button 1")
        self.layout_1.addWidget(self.lb_1)
        self.layout_1.addWidget(self.pb_1)

        self.layout_1.addWidget(self.lb_2)
        self.layout_1.addWidget(self.pb_2)
        self.lb_2.setText("Label 99")
        self.lb_2.setStyleSheet("background-color: red")
        self.pb_2.setText("Button 99")
Beispiel #12
0
    def init_ui(self):
        self.setMinimumWidth(320)
        self.setMinimumHeight(240)
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        self.setLayout(layout)

        lb_1 = QLabel()
        self.origin_pixmap = self.origin_pixmap.scaledToHeight(240)  # 사이즈가 조정
        lb_1.setPixmap(self.origin_pixmap)
        layout.addWidget(lb_1)

        # 자를 영역 선택, 복사
        rect = QRect(50, 50, 50, 50)
        cropped = self.origin_pixmap.copy(rect)

        self.lb_2 = QLabel()
        self.lb_2.setPixmap(cropped)
        self.lb_2.setFixedSize(100, 100)
        layout.addWidget(self.lb_2)

        w = Rectangle(parent=lb_1)
        w.setGeometry(0, 0, 100, 100)
        w.setStyleSheet("background-color: red")
        opacity_effect = QGraphicsOpacityEffect(self)
        opacity_effect.setOpacity(0.3)
        w.setGraphicsEffect(opacity_effect)

        w.change_position.connect(self.crop_image)
Beispiel #13
0
class QPushButtonWidgetForm(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)
        self.setWindowTitle(__appname__)
        self.btn_push = QPushButton()
        self.edt_number = QLineEdit()
        self.layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.setLayout(self.layout)
        self.init_widget()

    def init_widget(self):
        self.setWindowTitle("QPushButton Shortcut")
        self.click_cnt = 0
        self.edt_number.setText(str(self.click_cnt))

        self.btn_push.setText("더하기 단축키(Alt + F7)")
        self.btn_push.pressed.connect(self.buttonClicked)
        self.btn_push.setShortcut("Alt+F7")

        self.layout.addWidget(self.edt_number)
        self.layout.addWidget(self.btn_push)

    def buttonClicked(self):
        self.click_cnt += 1
        self.edt_number.setText(str(self.click_cnt))
 def __init__(self):
     QWidget.__init__(self, flags=Qt.Widget)
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     pb = QPushButton("Hello")
     layout.addWidget(pb)
     layout.setSizeConstraint(QBoxLayout.SetFixedSize)
     self.setLayout(layout)
 def init_widget(self):
     self.setWindowTitle("Hello World")
     self.setGeometry(10, 10, 100, 50)
     self.label = QLabel()
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     layout.addWidget(self.label)
     self.setLayout(layout)
    def init_widget(self):
        self.setWindowTitle("Serial Controller")
        layout = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        grid_box = QGridLayout()

        grid_box.addWidget(QLabel(self.tr("Port")), 0, 0)
        grid_box.addWidget(self.cb_port, 0, 1)

        grid_box.addWidget(QLabel(self.tr("Baud Rate")), 1, 0)
        grid_box.addWidget(self.cb_baud_rate, 1, 1)

        grid_box.addWidget(QLabel(self.tr("Data Bits")), 2, 0)
        grid_box.addWidget(self.cb_data_bits, 2, 1)

        grid_box.addWidget(QLabel(self.tr("Flow Control")), 3, 0)
        grid_box.addWidget(self.cb_flow_control, 3, 1)

        grid_box.addWidget(QLabel(self.tr("Parity")), 4, 0)
        grid_box.addWidget(self.cb_parity, 4, 1)

        grid_box.addWidget(QLabel(self.tr("Stop Bits")), 5, 0)
        grid_box.addWidget(self.cb_stop_bits, 5, 1)

        self._fill_serial_info()
        self.gb.setLayout(grid_box)
        layout.addWidget(self.gb)
        self.setLayout(layout)
	def __init__(self, message, title):
		super(ErrorMessage, self).__init__()
		self.message = message

		# self.setWindowTitle(title)
		self.setStyleSheet(style.style_loader.stylesheet)

		self.label = QLabel(str(self.message), self)

		self.label_widget = QWidget(self)
		label_layout = QBoxLayout(QBoxLayout.LeftToRight)
		label_layout.addWidget(self.label)
		self.label_widget.setLayout(label_layout)

		self.submit_btn = QPushButton('OK', self)
		self.submit_btn.clicked.connect(self.submit)

		self.submit_btn_widget = QWidget(self)
		submit_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		submit_btn_layout.addWidget(self.submit_btn)
		self.submit_btn_widget.setLayout(submit_btn_layout)

		layout = QFormLayout()
		layout.addRow(self.label_widget)
		layout.addRow(self.submit_btn_widget)
		self.setLayout(layout)

		self.show()
		self.setFixedHeight(self.height())
		self.setFixedWidth(self.width())
		self.close()
Beispiel #18
0
    def __init__(self):
        super(FlowBoardEditorToolBar, self).__init__()
        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))

        boardbox = QBoxLayout(QBoxLayout.TopToBottom)
        boardbox.setSpacing(2)

        self._sizelist = QComboBox()
        for s in range(5, 16):
            self._sizelist.addItem("{0}x{0}".format(s), s)
        self._sizelist.setCurrentIndex(2)
        boardbox.addWidget(self._sizelist)
        self._sizelist.currentIndexChanged.connect(self._sizelistChanged)

        self._clearbutton = QPushButton("clear")
        boardbox.addWidget(self._clearbutton)
        self._clearbutton.clicked.connect(self._clearClicked)

        boardboxwidget = QWidget()
        boardboxwidget.setLayout(boardbox)
        self.addWidget(boardboxwidget)

        self._toolchooser = FlowToolChooser()
        self.addWidget(self._toolchooser)
        self._toolchooser.changed.connect(self._toolChanged)
Beispiel #19
0
    def __init__(self, viewport):
        super().__init__()
        self.viewport = viewport
        self.moduleName = "QViewportHeader"

        self.setContentsMargins(0, 0, 0, 0)
        boxLayout = QBoxLayout(QBoxLayout.LeftToRight)
        boxLayout.setContentsMargins(0, 0, 0, 0)
        boxLayout.setSpacing(0)
        self.setLayout(boxLayout)

        titleBtn = QToolButton()
        titleBtn.setAutoRaise(True)
        titleBtn.setToolButtonStyle(Qt.ToolButtonTextOnly)
        titleBtn.setPopupMode(QToolButton.InstantPopup)
        self.titleBtn = titleBtn

        pivotSnapping = QToolButton()
        pivotSnapping.setToolTip("Pivot Snapping")
        pivotSnapping.setAutoRaise(True)
        pivotSnapping.setCheckable(True)
        self.pivotSnapping = pivotSnapping

        boxLayout.addWidget(titleBtn, 1)

        boxLayout.addStretch(1)
Beispiel #20
0
    def __init__(self):
        super(Window, self).__init__()
        box = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.resize(1200, 800)

        tensor_display_context = TensorDisplayContext(_tensor_data)

        def canvas_on_close_handler(_1, _2):
            self.close()
        tensor_display_context.canvas.set_on_close_handler(canvas_on_close_handler)
        box.addWidget(tensor_display_context.canvas.native)
        
        rightBoxWidget = QWidget()
        rightBox = QBoxLayout(QBoxLayout.TopToBottom, rightBoxWidget)
        rightBox.setAlignment(Qt.AlignTop)
        box.addWidget(rightBoxWidget)

        tensor_view_selector = TensorRankViewSelector()
        rightBox.addWidget(tensor_view_selector)

        xyzRangeSelector = XYZRangeSelector(_tensor_data)
        rightBox.addWidget(xyzRangeSelector)

        tw_container = TensorRankShower(_tensor_data)
        rightBox.addWidget(tw_container)

#        esc_shortcut = QShortcut(self)
#        esc_shortcut.activated.connect(self.close)
        
        self.show()
    def init_widget(self):
        """
        현재 위젯의 모양등을 초기화
        """
        self.setWindowTitle(
            "Movon - Nordic Mesh Serial Comm Test Program v0.1")
        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        self.setLayout(form_lbx)

        self.pb.clicked.connect(self.slot_clicked_connect_button)
        self.pb_clear.clicked.connect(self.slot_clicked_clear_button)
        self.serial.received_data.connect(self.read_data)
        #test_data = bytes([0x02]) + bytes("TEST DATA", "utf-8") + bytes([0x03])
        test_data = bytes([0x06]) + bytes([0x02]) + bytes([0x48]) + bytes([
            0x65
        ]) + bytes([0x6C]) + bytes([0x6C]) + bytes([0x6F])  # test text 'Hello'
        self.pb_send.clicked.connect(lambda: self.serial.writeData(test_data))
        form_lbx.addWidget(self.serial)
        form_lbx.addWidget(self.te)
        form_lbx.addWidget(self.pb_clear)
        form_lbx.addWidget(self.pb_send)
        form_lbx.addWidget(self.pb)

        # 많이 사용하는 옵션을 미리 지정해 둔다.
        # 115200 8N1
        self.serial.cb_baud_rate.setCurrentIndex(7)
        self.serial.cb_data_bits.setCurrentIndex(3)
Beispiel #22
0
    def __init__(self, parent: QtWidgets.QBoxLayout, stretch, *args, **kwargs):
        super(VideoLabel, self).__init__(*args, **kwargs)
        self.setSizePolicy(QtWidgets.QSizePolicy.Ignored,
                           QtWidgets.QSizePolicy.Ignored)
        self.setScaledContents(True)

        parent.addWidget(self, stretch=stretch)
Beispiel #23
0
    def __init__(self, parent=None):
        super(FlowSolvingPopup, self).__init__(parent)

        layout = QBoxLayout(QBoxLayout.TopToBottom)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)

        self._solverWidget = FlowSolverWidget()
        self._solverWidget.finished.connect(self._solverFinished)
        layout.addWidget(self._solverWidget)

        status = QStatusBar()
        status.setSizeGripEnabled(False)

        self._againButton = QPushButton("next")
        self._againButton.setVisible(False)
        self._againButton.clicked.connect(self._againClicked)
        status.addPermanentWidget(self._againButton)

        self._abortButton = QPushButton("close")
        self._abortButton.clicked.connect(self._abortClicked)
        status.addPermanentWidget(self._abortButton)

        self._messageLabel = QLabel("ready")
        status.addWidget(self._messageLabel)
        layout.addWidget(status)

        layout.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(layout)

        self._timer = QTimer()
        self._timer.timeout.connect(self._timerTick)
Beispiel #24
0
    def init_widget(self):
        self.setWindowTitle("Timer")
        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        self.setLayout(form_lbx)

        self.th.change_value.connect(self.pgsb.setValue)
        form_lbx.addWidget(self.pgsb)
Beispiel #25
0
class AspectRatioWidget(QWidget):
    '''Widget that keeps the aspect ratio of child widget on resize'''
    def __init__(self, widget, aspectRatio):
        super(AspectRatioWidget, self).__init__()
        self.layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.layout.addItem(QSpacerItem(0, 0))
        self.layout.addWidget(widget)
        self.layout.addItem(QSpacerItem(0, 0))
        self.setAspectRatio(aspectRatio)

    def setAspectRatio(self, aspectRatio):
        self.aspectRatio = aspectRatio
        self.updateAspectRatio()

    def updateAspectRatio(self):
        newAspectRatio = self.size().width() / self.size().height()
        if newAspectRatio > self.aspectRatio:
            # Too wide
            self.layout.setDirection(QBoxLayout.LeftToRight)
            widgetStretch = self.height() * self.aspectRatio
            outerStretch = (self.width() - widgetStretch) / 2 + 0.5
        else:
            # Too tall
            self.layout.setDirection(QBoxLayout.TopToBottom)
            widgetStretch = self.width() * (1 / self.aspectRatio)
            outerStretch = (self.height() - widgetStretch) / 2 + 0.5

        self.layout.setStretch(0, outerStretch)
        self.layout.setStretch(1, widgetStretch)
        self.layout.setStretch(2, outerStretch)

    def resizeEvent(self, event):
        self.updateAspectRatio()
Beispiel #26
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)
Beispiel #27
0
class GUI(QDialog):

    def __init__(self, settings):
        super(QDialog, self).__init__()
        self.setWindowTitle("Settings")
        self.setWindowIcon(QIcon('ui/icon.png'))
        self.setModal(True)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

        self._button_box = QDialogButtonBox(
            QDialogButtonBox.Ok
        )
        self._button_box.button(QDialogButtonBox.Ok).clicked.connect(self.accept)

        self._tabs = QTabWidget()

        self._layout = QBoxLayout(QBoxLayout.TopToBottom)
        self._layout.addWidget(self._tabs)
        self._layout.addWidget(self._button_box)

        self.setLayout(self._layout)

        # setup tabs
        self.tab_list = {}
        self.widgets = {}

        # general tab
        general_tab = GeneralTab(settings)
        self._tabs.addTab(general_tab, general_tab.get_title())
        characters_tab = CharactersTab(settings)
        self._tabs.addTab(characters_tab, characters_tab.get_title())

    def set_show_tab(self, tab):
        if tab == "characters":
            self._tabs.setCurrentIndex(1)
class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)
        self.setWindowTitle("ItemView QTreeView")
        self.setFixedWidth(310)
        self.setFixedHeight(200)

        data = [{
            "name":
            "Mouse Action",
            "icon":
            "assets/mouse.png",
            "objects": [
                {
                    "name": "Click",
                    "icon": "assets/network.png",
                    "objects": None
                },
                {
                    "name": "Double Click",
                    "icon": "assets/mail.png",
                    "objects": None
                },
            ]
        }, {
            "name":
            "Keyboard",
            "icon":
            "assets/keyboard.png",
            "objects": [
                {
                    "name": "Send Hotkey",
                    "icon": "assets/earth.png",
                    "objects": None
                },
                {
                    "name": "Type",
                    "icon": "assets/folder.png",
                    "objects": None
                },
            ]
        }]

        self.layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.setLayout(self.layout)

        # QTreeView 생성 및 설정
        view = QTreeView(self)
        # QTreeView 스타일시트 설정
        view.setStyleSheet(open("./ItemViews_QTreeView_03_style.css").read())
        view.setAlternatingRowColors(True)  # 라인별 교차색
        self.model = Model(data)
        view.setModel(self.model)
        self.layout.addWidget(view)

        # 그림을 띄울 QLabel 생성
        self.lb = QLabel()
        self.lb.setFixedSize(50, 50)
        self.layout.addWidget(self.lb)
Beispiel #29
0
class MainWidget(QWidget):
    def __init__(self, urls, toggle_sequence):
        super(MainWidget, self).__init__()

        self._connection = connection.Connection(self.set_captive_portal_url)
        self._captive_portal_url = ''
        self._urls = cycle(urls)
        self._current_url = next(self._urls)
        self._browser_widget = browser_widget.BrowserWidget(self._current_url)
        self._is_captive_portal_visible = False
        self._captive_portal_message = captive_portal_message.CaptivePortalMessage(
            self._toggle_captive_portal)

        self._layout = QBoxLayout(QBoxLayout.BottomToTop)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
        self._layout.addWidget(self._browser_widget)

        QShortcut(toggle_sequence, self).activated.connect(self._load_next_url)

        self.setLayout(self._layout)
        self.show()
        self._connection.start_daemon()

    def set_captive_portal_url(self, url):
        self._captive_portal_url = url
        if url == '' and not self._is_captive_portal_visible:
            self._captive_portal_message.setParent(None)
        else:
            self._update_captive_portal_message()
            self._layout.addWidget(self._captive_portal_message)

    # Private

    def _load_next_url(self):
        if self._is_captive_portal_visible:
            self._browser_widget.load(self._current_url)
            self._is_captive_portal_visible = False
            self._update_captive_portal_message()
        else:
            self._current_url = next(self._urls)
            self._browser_widget.load(self._current_url)

    def _toggle_captive_portal(self):
        if self._is_captive_portal_visible:
            if not self._connection.is_captive():
                self._captive_portal_message.setParent(None)
            self._browser_widget.load(self._current_url)
        else:
            self._browser_widget.load(QUrl(self._captive_portal_url))
        self._is_captive_portal_visible = not self._is_captive_portal_visible
        self._update_captive_portal_message()

    def _update_captive_portal_message(self):
        if self._is_captive_portal_visible:
            self._captive_portal_message.setCloseMessage(
                self._connection.is_captive())
        else:
            self._captive_portal_message.setOpenMessage()
Beispiel #30
0
    def init_widget(self):
        self.setWindowTitle("Signal Slot")
        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        self.setLayout(form_lbx)

        self.sd.valueChanged.connect(lambda v: self.lb.setText(str(v)))
        form_lbx.addWidget(self.sd)
        form_lbx.addWidget(self.lb)
Beispiel #31
0
    def init_widget(self):
        self.setWindowTitle("Hello World")
        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        self.setLayout(form_lbx)

        te = QTextEdit()

        form_lbx.addWidget(te)
Beispiel #32
0
    def init_widget(self):
        self.setWindowTitle("Custom Signal")
        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        self.setLayout(form_lbx)

        self.tic_gen.Tic.connect(lambda: self.te.insertPlainText(
            time.strftime("[%H:%M:%S] Tic!\n")))

        form_lbx.addWidget(self.te)
Beispiel #33
0
 def __init__(self, parent):
     super(FormWidget, self).__init__(parent)
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     self.setLayout(layout)
     self.progressbar = CustomProgressBar(0, 3)
     btn_start = QPushButton("START")
     layout.addWidget(self.progressbar, 0)
     layout.addWidget(btn_start, 0)
     btn_start.clicked.connect(self.on_start)
    def init_widget(self):

        self.setWindowTitle("Custom Signal")
        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent = self)
        self.setLayout(form_lbx)

        self.pb.clicked.connect(self.count)
        form_lbx.addWidget(self.lb)
        form_lbx.addWidget(self.pb)
class ComboBoxWidget(QGroupBox):
    """
    This is the combobox widget as it is shown in the settings
    panel of the GUI. It gets initialized with a name
    With self.valueChanged on can connect a pyqt slot with the
    combobox pyqtSignal.
    """

    def __init__(self, name, options, slot=None, default=None):
        super(ComboBoxWidget, self).__init__()
        self.activated = pyqtSignal()

        # ComboBox itself
        self.combobox = QtWidgets.QComboBox()
        self.combobox.orientationCombo = PyQt5.QtWidgets.QComboBox()
        self.combobox.setFixedWidth(220)

        # Label
        self.label = QtWidgets.QLabel()
        self.label.setText(name + ": ")

        self.SingleCheckBoxLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.SingleCheckBoxLayout.addWidget(self.label)
        self.SingleCheckBoxLayout.addWidget(self.combobox, Qt.AlignRight)
        self.setLayout(self.SingleCheckBoxLayout)
        self.setFixedHeight(70)
        self.setFlat(True)

        # options
        for i in options:
            self.add_item(i)

        if default is not None:
            index = self.combobox.findText(default)
            if index != -1:
                self.combobox.setCurrentIndex(index)

        if slot is not None:
            self.combobox.activated.connect(slot)


    def add_item(self, option, image=None):
        """

        Args:
            | *option*: A string option refers to an entry which can be selected in the combobox later.
            | *image*: An optional icon that can be shown combobox.
        """
        if image is None:
            self.combobox.addItem(option)
        else:
            self.combobox.addItem(QIcon(image), option)
    def __init__(self, algorithm):
        super(GroupOfSliders, self).__init__()

        GroupOfSliderssLayout = QBoxLayout(QBoxLayout.TopToBottom)
        GroupOfSliders.setFixedHeight(self, 300)

        for slider in algorithm.integer_sliders:
            GroupOfSliderssLayout.addWidget(
                    SliderWidget(slider.name, slider.lower, slider.upper, slider.step_size, slider.default,
                                 False))

        for slider in algorithm.float_sliders:
            GroupOfSliderssLayout.addWidget(
                    SliderWidget(slider.name, slider.lower, slider.upper, slider.step_size, slider.default,
                                 True))

        for checkbox in algorithm.checkboxes:
            GroupOfSliderssLayout.addWidget(
                    CheckBoxWidget(checkbox.name, checkbox.default))

        for dropdown in algorithm.drop_downs:
            GroupOfSliderssLayout.addWidget(
                    ComboBoxWidget(dropdown.name, dropdown.options))

        self.setLayout(GroupOfSliderssLayout)
class GroupOfImages(QGroupBox):
    def __init__(self):
        super(GroupOfImages, self).__init__()

        self.GroupOfImagesLayout = QBoxLayout(QBoxLayout.TopToBottom)
        GroupOfImages.setFixedHeight(self, 300)
        GroupOfImages.setFixedWidth(self, 300)
        self.height = 300

    def addImage(self, image):
        self.GroupOfImagesLayout.addWidget(image)
        self.height += 300
        GroupOfImages.setFixedHeight(self, self.height + 300)
        self.setLayout(self.GroupOfImagesLayout)

    def removeImage(self, image):
        self.GroupOfImagesLayout.removeWidget(image)
        self.setLayout(self.GroupOfImagesLayout)

    def refreshView(self):
        self.setLayout(self.GroupOfImagesLayout)
    def __init__(self):
        super(Window, self).__init__()
        global current_state
        current_state = dict(screen_data)

        self.createControls()
        self.createCommandBox()

        self.brightnessSliders = SlidersGroup(self.commandBox)

        self.stackedWidget = QStackedWidget()
        self.stackedWidget.addWidget(self.brightnessSliders)

        layout = QBoxLayout(QBoxLayout.TopToBottom)
        layout.addWidget(self.stackedWidget)
        layout.addWidget(self.commandBoxGroup)
        layout.addWidget(self.controlsGroup)
        self.setLayout(layout)

        self.setWindowTitle("Brightness editor")
        self.resize(850, 500)

        command = "# get display names and brightness values\n" + \
                  get_brightness_command                 + "\n" + \
                  "# results (formatted): " + str(screen_data)
        if primary != None:
            command += " primary: " + screen_data[primary][0]
        self.commandBox.document().setPlainText(command)
Beispiel #39
0
    def __init__(self, orientation, title, parent=None):
        super(SlidersGroup, self).__init__(title, parent)

        self.slider = QSlider(orientation)
        self.slider.setFocusPolicy(Qt.StrongFocus)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setTickInterval(10)
        self.slider.setSingleStep(1)

        self.scrollBar = QScrollBar(orientation)
        self.scrollBar.setFocusPolicy(Qt.StrongFocus)

        self.dial = QDial()
        self.dial.setFocusPolicy(Qt.StrongFocus)

        self.slider.valueChanged.connect(self.scrollBar.setValue)
        self.scrollBar.valueChanged.connect(self.dial.setValue)
        self.dial.valueChanged.connect(self.slider.setValue)
        self.dial.valueChanged.connect(self.valueChanged)

        if orientation == Qt.Horizontal:
            direction = QBoxLayout.TopToBottom
        else:
            direction = QBoxLayout.LeftToRight

        slidersLayout = QBoxLayout(direction)
        slidersLayout.addWidget(self.slider)
        slidersLayout.addWidget(self.scrollBar)
        slidersLayout.addWidget(self.dial)
        self.setLayout(slidersLayout)    
    def __init__(self, parent=None):
        super(AddConfigurationDialog, self).__init__(parent)
        self._layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.setLayout(self._layout)
        self.setWindowTitle('Add configuration')

        self._nameField = QLineEdit()
        name_form_layout = QFormLayout()
        name_form_layout.addRow('Name:', self._nameField)
        self._layout.addLayout(name_form_layout)
        self._layout.addWidget(QLabel("You won't be able to change this name later."))
        self._cancelButton = QPushButton("Cancel")
        self._saveButton = QPushButton("Create")
        button_layout = QBoxLayout(QBoxLayout.LeftToRight)
        button_layout.addWidget(self._cancelButton)
        button_layout.addWidget(self._saveButton)
        self._layout.addLayout(button_layout)
        
        self._configuration = None
        
        self._cancelButton.clicked.connect(self.reject)
        self._saveButton.clicked.connect(self._saved)
class AddConfigurationDialog(QDialog):
    def __init__(self, parent=None):
        super(AddConfigurationDialog, self).__init__(parent)
        self._layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.setLayout(self._layout)
        self.setWindowTitle('Add configuration')

        self._nameField = QLineEdit()
        name_form_layout = QFormLayout()
        name_form_layout.addRow('Name:', self._nameField)
        self._layout.addLayout(name_form_layout)
        self._layout.addWidget(QLabel("You won't be able to change this name later."))
        self._cancelButton = QPushButton("Cancel")
        self._saveButton = QPushButton("Create")
        button_layout = QBoxLayout(QBoxLayout.LeftToRight)
        button_layout.addWidget(self._cancelButton)
        button_layout.addWidget(self._saveButton)
        self._layout.addLayout(button_layout)
        
        self._configuration = None
        
        self._cancelButton.clicked.connect(self.reject)
        self._saveButton.clicked.connect(self._saved)
        
    def _saved(self):
        name = self._nameField.text()
        self._configuration = Configuration(name)
        data = DataStorage()
        data.add_configuration(self._configuration)
        data.persist()
        self.accept()
        
    def get_configuration(self):
        """
        Returns the created configuration if called after executing the dialog or None otherwise.
        :rtype: Configuration
        """
        return self._configuration
	def __init__(self, parent):
		super(RoundManagerWidget, self).__init__(parent)
		self.parent = parent

		self.sort_order = 'by_name'

		view.notifier.observers.append(self)
		timer = QTimer(self)
		timer.timeout.connect(self.update)
		timer.start()

		self.header_label = QLabel('Round')

		self.header_widget = QWidget(self)
		header_layout = QBoxLayout(QBoxLayout.LeftToRight)
		header_layout.addWidget(self.header_label)
		self.header_widget.setLayout(header_layout)

		self.submit_btn = QPushButton(self)
		self.submit_btn.clicked.connect(self.submit)

		self.submit_btn_widget = QWidget(self)
		submit_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		submit_btn_layout.addWidget(self.submit_btn)
		self.submit_btn_widget.setLayout(submit_btn_layout)

		self.round_info = QLabel()
		self.round_info.setAlignment(Qt.AlignCenter)
		self.timer_display = QLabel()
		self.timer_display.setAlignment(Qt.AlignCenter)

		self.info_widget = QWidget(self)
		info_layout = QBoxLayout(QBoxLayout.LeftToRight)
		info_layout.addWidget(self.round_info)
		info_layout.addWidget(self.timer_display)
		self.info_widget.setLayout(info_layout)

		self.error = None

		layout = QFormLayout()
		layout.addRow(self.header_widget)
		layout.addRow(self.submit_btn_widget)
		layout.addRow(self.info_widget)
		self.setLayout(layout)

		self.update()
Beispiel #43
0
  def __init__(self, *args, **kwargs):
    # set parent
    super().__init__(kwargs['main_window'])

    self.setModal(True)
    self.show()
    
    self.setWindowTitle("New Course")

    self.setFixedSize(400, 150)

    # main widget
    #main_widget = QWidget()
    main_layout = QBoxLayout(QBoxLayout.TopToBottom)

    # form widget
    form_widget = QWidget()
    form_layout = QFormLayout()
    form_layout.setFormAlignment(QtCore.Qt.AlignLeft)
    new_course_label = QLabel("Course Name:")
    new_course_entry = CustomLineEdit(default_entry="<Enter course name>")
    new_course_entry.setFixedWidth(230)
    form_layout.addRow(new_course_label, new_course_entry)
    form_widget.setLayout(form_layout)

    # action buttons
    action_widget = QWidget()
    add_course_button = QPushButton("Add Course")
    cancel_button = QPushButton("Cancel")
    action_layout = QBoxLayout(QBoxLayout.LeftToRight)
    action_layout.addWidget(cancel_button)
    action_layout.addWidget(add_course_button)
    action_widget.setLayout(action_layout)
    action_widget.setTabOrder(add_course_button, cancel_button)

    # add widgets
    main_layout.addWidget(form_widget)
    main_layout.addWidget(action_widget)
    self.setLayout(main_layout)

    new_course_entry.setFocus()
    new_course_entry.selectAll()
class SliderWidget(QGroupBox):
    valueChanged = pyqtSignal()

    def __init__(self, name, lower, upper, step_size, default, float_flag):
        super(SliderWidget, self).__init__()

        self.internal_steps = abs(upper - lower) / step_size

        def to_internal_coordinate(self, value):
            return (self.internal_steps / (upper - lower)) * (value - lower)

        def to_external_coordinate(self, value):
            return lower + (value * (upper - lower)) / self.internal_steps

        # Slider itself
        self.slider = \
            Slider(0, self.internal_steps, 1, to_internal_coordinate(self, default)) \
            .slider

        # Textfield
        if float_flag:
            self.textfield = \
                DoubleTextfield(lower, upper, step_size, default) \
                .textfield
        else:
            self.textfield = \
                IntegerTextfield(lower, upper, step_size, default)\
                .textfield

        # Label
        self.label = QLabel()
        self.label.setText(name + ": ")

        # Connect Textfield with Slider
        def textfield_value_changed(value):
            self.slider.setValue(to_internal_coordinate(self, value))

        def slider_value_changed(value):
            self.textfield.setValue(to_external_coordinate(self, value))

        self.textfield.valueChanged.connect(textfield_value_changed)
        self.slider.valueChanged.connect(slider_value_changed)

        self.SingleSlidersLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.SingleSlidersLayout.addWidget(self.label)
        self.SingleSlidersLayout.addWidget(self.slider)
        self.SingleSlidersLayout.addWidget(self.textfield)
        self.setLayout(self.SingleSlidersLayout)
        self.setFixedHeight(50)
        self.setFlat(True)
	def __init__(self):
		super(AddPlayerWidget, self).__init__()

		self.users = {}

		# self.setWindowTitle('Add Player')
		self.setStyleSheet(style.style_loader.stylesheet)

		self.label = QLabel('Enter Name:', self)

		self.label_widget = QWidget(self)
		label_layout = QBoxLayout(QBoxLayout.LeftToRight)
		label_layout.addWidget(self.label)
		self.label_widget.setLayout(label_layout)

		self.user_box = QComboBox(self)
		self.user_box.setFixedWidth(210)
		self.user_box.setFixedHeight(50)

		self.user_box_widget = QWidget(self)
		user_box_layout = QBoxLayout(QBoxLayout.LeftToRight)
		user_box_layout.addWidget(self.user_box)
		self.user_box_widget.setLayout(user_box_layout)

		self.submit_btn = QPushButton('Add Player', self)
		self.submit_btn.clicked.connect(self.submit)

		self.submit_btn_widget = QWidget(self)
		submit_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		submit_btn_layout.addWidget(self.submit_btn)
		self.submit_btn_widget.setLayout(submit_btn_layout)

		layout = QFormLayout()
		layout.addRow(self.label_widget)
		layout.addRow(self.user_box_widget)
		layout.addRow(self.submit_btn_widget)
		self.setLayout(layout)

		self.show()
		self.setFixedHeight(self.height())
		self.setFixedWidth(self.width())
		self.close()
	def __init__(self, parent):
		super(PairingsWidget, self).__init__(parent)
		self.parent = parent

		view.notifier.observers.append(self)

		self.header_label = QLabel('Pairings')

		self.header_widget = QWidget(self)
		header_layout = QBoxLayout(QBoxLayout.TopToBottom)
		header_layout.addWidget(self.header_label)
		self.header_widget.setLayout(header_layout)

		self.pairings_list = QTableWidget(style.style_loader.TABLE_INITIAL_LENGTH, 2, self)
		self.pairings_list.setFixedHeight(300)
		self.pairings_list.setFixedWidth(400)
		self.pairings_list.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
		self.pairings_list.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)

		self.pairings_list_widget = QWidget(self)
		pairings_list_layout = QBoxLayout(QBoxLayout.LeftToRight)
		pairings_list_layout.addWidget(self.pairings_list)
		self.pairings_list_widget.setLayout(pairings_list_layout)

		self.report_btn = QPushButton('Report Results', self)
		self.report_btn.clicked.connect(parent.show_report_result_widget)

		self.report_btn_widget = QWidget(self)
		report_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		report_btn_layout.addWidget(self.report_btn)
		self.report_btn_widget.setLayout(report_btn_layout)

		layout = QFormLayout()
		layout.addRow(self.header_widget)
		layout.addRow(self.pairings_list_widget)
		layout.addRow(self.report_btn_widget)
		self.setLayout(layout)

		self.update()
    def createBrightnessCtrl(self, name, value, i):
        sl = QSlider(Qt.Vertical)
        sl.setFocusPolicy(Qt.StrongFocus)
        sl.setTickPosition(QSlider.TicksBothSides)
        sl.setTickInterval(10)
        sl.setSingleStep(1)
        sl.setMinimum(5)
        sl.setMaximum(100)
        sl.setValue(value)

        sb = QSpinBox()
        sb.setRange(5, 100)
        sb.setSingleStep(10)
        sb.setValue(value)

        sl.valueChanged.connect(sb.setValue)
        sb.valueChanged.connect(sl.setValue)
        if i != None:
            sl.valueChanged.connect(self.setValuePartial(i))
            sb.valueChanged.connect(self.setValuePartial(i))

        boxLayout = QBoxLayout(QBoxLayout.LeftToRight)
        lbl = QLabel(name)
        boxLayout.addWidget(lbl)
        boxLayout.addWidget(sb)

        boxLayout.addWidget(sl)

        self.slidersLayout.addLayout(boxLayout)
        # stretch is between (label, spinner, slider) groups
        if i != None:
            self.slidersLayout.addStretch()

        self.sliders.append(sl)
#        self.spinBoxes.append(sl)
        self.labels.append(lbl)
class SliderWidget(QGroupBox):
    """
    This is a combined widget for a slider in the GUI. It
    contains several input fields and a slider itself. By setting
    the constructor value, the complete widget is connected in itself.
    The name will be displayed in front of the widget. lower and upper
    refer to the sliders range, step_size tells the distance of each step
    and default is the preset value in the GUI.
    The float_flag determines whether the slider should represent float values or not.
    Set float_flag to true if you want to store float values.
    With self.valueChanged on can connect a pyqt slot with the
    float slider pyqtSignal.
    A SliderWidget is built by a Slider, a QLabel and either a DoubleTextfield or an IntegerTextfield.
    """

    def __init__(self, name, lower, upper, step_size, default, slot, float_flag):
        super(SliderWidget, self).__init__()
        self.valueChanged = pyqtSignal()
        self.internal_steps = abs(upper - lower) / step_size

        print("Default " + str(default))

        def to_internal_coordinate(value):
            return (self.internal_steps / (upper - lower)) * (value - lower)

        def to_external_coordinate(value):
            return lower + (value * (upper - lower)) / self.internal_steps

        # Slider itself
        self.slider = \
            Slider(0, self.internal_steps, 1, to_internal_coordinate(default)).slider

        # Textfield
        if float_flag:
            self.textfield = \
                DoubleTextfield(lower, upper, step_size, default).textfield
        else:
            self.textfield = \
                IntegerTextfield(lower, upper, step_size, default).textfield

        # Label
        self.label = QLabel()
        self.label.setText(name + ": ")

        # Connect Textfield with Slider
        def textfield_value_changed(value):
            self.slider.setValue(to_internal_coordinate(value))

        def slider_value_changed(value):
            self.textfield.setValue(to_external_coordinate(value))

        self.textfield.valueChanged.connect(textfield_value_changed)
        self.slider.valueChanged.connect(slider_value_changed)

        self.SingleSlidersLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.SingleSlidersLayout.addWidget(self.label)
        self.SingleSlidersLayout.addWidget(self.slider)
        self.SingleSlidersLayout.addWidget(self.textfield)
        self.setLayout(self.SingleSlidersLayout)
        self.setFixedHeight(70)
        self.setFlat(True)

        self.textfield.valueChanged.connect(lambda : slot(self.textfield.value()))
app = QApplication(sys.argv)

# Make widgets

window = QWidget()

btn1 = QPushButton("One")
btn2 = QPushButton("Two")
btn3 = QPushButton("Three")

# Set the layout

box = QBoxLayout(QBoxLayout.Direction(0))  # TODO

box.addWidget(btn1)
box.addWidget(btn2)
box.addWidget(btn3)

box.setContentsMargins(0, 0, 0, 0)  # set the spacing around the layout (in pixels)
box.setSpacing(0)                   # set the spacing between elements (in pixels)

window.setLayout(box)

# Show
window.show()

# The mainloop of the application. The event handling starts from this point.
# The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
exit_code = app.exec_()
Beispiel #50
0
    def __init__(self, settings):
        super(QWidget, self).__init__()
        self._layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.setLayout(self._layout)
        self.settings = settings

        # eq directory
        widget = QWidget()
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        widget.setLayout(layout)
        label = QLabel("Everquest Directory: ")
        layout.addWidget(label)
        text = QLineEdit()
        text.setText(self.settings.get_value("general", "eq_directory"))
        text.setToolTip(self.settings.get_value("general", "eq_directory"))
        text.setDisabled(True)
        self._text_eq_directory = text
        layout.addWidget(text, 1)
        button = QPushButton("Browse...")
        button.clicked.connect(self._get_eq_directory)
        layout.addWidget(button)
        self._layout.addWidget(widget, 0, Qt.AlignTop)

        # eq directory info
        frame = QFrame()
        frame.setFrameShadow(QFrame.Sunken)
        frame.setFrameShape(QFrame.Box)
        frame_layout = QBoxLayout(QBoxLayout.LeftToRight)
        frame.setLayout(frame_layout)
        widget = QWidget()
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        widget.setLayout(layout)
        self._label_eq_directory = QLabel()
        layout.addWidget(self._label_eq_directory, 1)
        frame_layout.addWidget(widget, 1, Qt.AlignCenter)
        self._layout.addWidget(frame, 1)

        # parse interval
        widget = QWidget()
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        widget.setLayout(layout)
        label = QLabel("Seconds between parse checks: ")
        layout.addWidget(label, 0, Qt.AlignLeft)
        text = QLineEdit()
        text.setText(str(self.settings.get_value("general", "parse_interval")))
        text.editingFinished.connect(self._parse_interval_editing_finished)
        text.setMaxLength(3)
        self._text_parse_interval = text
        metrics = QFontMetrics(QApplication.font())
        text.setFixedWidth(metrics.width("888888"))
        layout.addWidget(text, 0, Qt.AlignLeft)
        self._layout.addWidget(widget, 0, Qt.AlignTop | Qt.AlignLeft)

        # spacing at bottom of window
        widget = QWidget()
        self._layout.addWidget(widget, 1)

        # setup
        if settings.get_value("general", "eq_directory") is not None:
            self._check_directory_stats()
Beispiel #51
0
class ConfigurationView(QWidget):
    """
    Displays the configuration view.
    """

    def __init__(self, parent=None):
        super(ConfigurationView, self).__init__(parent)
        self._layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.setLayout(self._layout)
        self._editView = EditView(parent)
        # initialize list view
        self._listView = QListView()
        self._configuration_model = self._get_config_model()
        self._listView.setModel(self._configuration_model)
        # initialize detail view
        self._detailView = QWidget()
        self._detailLayout = QBoxLayout(QBoxLayout.TopToBottom)
        self._detailView.setLayout(self._detailLayout)

        self._detailPanels = {}
        self._currentDetailPanel = None
        self._currentConfiguration = None # type: Configuration
        self._config_wide_print_amounts = {}
        self._recalculateEffectivePrintAmounts = False

        # add widgets to layout
        self._layout.addWidget(QLabel("List of Configurations"))
        self._layout.addWidget(self._listView)
        self._layout.addWidget(self._detailView)

        self._create_detail_view()
        # hide detail view on start
        self._detailView.hide()

        # selected configs map
        self._selected_configs = {}
        self._selected_counter = 0

        # add event listener for selection change
        self._listView.clicked.connect(self._on_selection_change)
        self._listView.selectionModel().currentChanged.connect(self._on_selection_change)

    def add_configuration(self, configuration):
        """
        Adds the given configuration to the list view and opens the edit view.
        :param configuration:
        :type configuration: Configuration
        """
        item = create_new_list_item(configuration.get_name())
        self._configuration_model.appendRow(item)
        self._editView.show_for_configuration(configuration)

    def select_first_item(self):
        rect = QRect(0,0,1,1)
        self._listView.setSelection(rect, QItemSelectionModel.Select)

    def update_model(self):
        self._configuration_model = self._get_config_model()
        self._listView.setModel(self._configuration_model)

    @staticmethod
    def _get_config_model():
        data = DataStorage()
        configurations_order = data.get_configurations_order()
        model = QStandardItemModel()

        for name in configurations_order:
            item = create_new_list_item(name)
            model.appendRow(item)

        return model

    def _on_selection_change(self, model_index):
        """
        Called on selecting a new item in the listView.
        :param model_index: index of selected item
        :type model_index: QModelIndex
        """
        data = DataStorage()
        configurations = data.get_configurations()
        selected_item = self._configuration_model.itemFromIndex(model_index) # type: QStandardItem
        current_config_name = selected_item.text()
        current_config = configurations[current_config_name] # type: Configuration
        self._show_detail_view(current_config)
        config_wide_print_amount = self._config_wide_print_amounts[current_config_name]
        material_print_amounts = current_config.get_effective_material_print_amounts(
            config_wide_print_amount,
            self._recalculateEffectivePrintAmounts
        )
        self._recalculateEffectivePrintAmounts = False

        if self._selected_counter == 0:
            MaterialView.reset_check_state_and_print_amount()

        for material in current_config.get_materials():
            item = get_item(MaterialView.get_model().invisibleRootItem(), material.get_name())
            if item is not None:
                print_amount = material_print_amounts[material.get_name()]
                if is_checked(selected_item):
                    check_item(item)
                    if current_config_name not in self._selected_configs:
                        print_amount += int(item.text(1))
                    else:
                        print_amount = int(item.text(1))

                item.setText(1, str(print_amount))

        if is_checked(selected_item) and current_config_name not in self._selected_configs:
            self._selected_configs[current_config_name] = True
            self._selected_counter += 1
        if not is_checked(selected_item) and current_config_name in self._selected_configs:
            self._selected_configs.pop(current_config_name)
            self._selected_counter -= 1

        self._currentConfiguration = current_config

    def _create_detail_view(self):
        """
        Adds the permanent elements to the detail view.
        """
        edit_button = QPushButton("Edit")
        edit_button.clicked.connect(self._show_edit_view)
        self._detailLayout.addWidget(QLabel("Detail view for selected configuration"))
        self._detailLayout.addWidget(edit_button)

    def _change_config_wide_print_amount(self, new_value):
        self._config_wide_print_amounts[self._currentConfiguration.get_name()] = new_value
        self._recalculateEffectivePrintAmounts = True

    def _create_update_function_for_sub_configs(self, sub_config, configuration):
        def update_func(new_value):
            if self._currentConfiguration.get_name() == configuration.get_name():
                self._currentConfiguration.set_config_print_amount(sub_config, new_value)
            self._recalculateEffectivePrintAmounts = True
        return update_func
    
    def _show_edit_view(self):
        """
        Shows the edit view for the selected configuration.
        """
        self._editView.show_for_configuration(self._currentConfiguration)
        selected_indexes = self._listView.selectedIndexes()
        self._on_selection_change(selected_indexes[0])

    def _show_detail_view(self, configuration: Configuration):
        """
        Shows the detail view for the selected configuration.
        :param configuration:
        :type configuration: Configuration
        """
        if self._currentDetailPanel is not None:
            self._currentDetailPanel.hide()
        if configuration.get_name() in self._detailPanels:
            self._currentDetailPanel = self._detailPanels[configuration.get_name()]
            self._currentDetailPanel.show()
        else:
            panel = QWidget()
            layout = QFormLayout()
            panel.setLayout(layout)

            config_wide_counter = QSpinBox()
            config_wide_counter.setMinimum(1)
            config_wide_counter.setValue(1)
            config_wide_counter.valueChanged.connect(self._change_config_wide_print_amount)

            # add panel to parent layout
            self._detailLayout.addWidget(panel)
            # save panel for future use
            self._detailPanels[configuration.get_name()] = panel
            self._currentDetailPanel = panel
            self._config_wide_print_amounts[configuration.get_name()] = 1

            # panel
            layout.addRow("Print this config x times", config_wide_counter)
            layout.addRow("Child configurations", QLabel())
            configurations = configuration.get_configurations()
            config_print_amounts = configuration.get_config_print_amounts()
            for config in configurations: # type: Configuration
                config_counter = QSpinBox()
                config_counter.setMinimum(1)
                config_counter.setValue(config_print_amounts[config.get_name()])
                update_func = self._create_update_function_for_sub_configs(config, configuration)
                config_counter.valueChanged.connect(update_func)
                layout.addRow("Print config " + config.get_name() + " x times", config_counter)

        self._detailView.show()
Beispiel #52
0
    def _create_layout(self):
        top_layout_top = QBoxLayout(0)
        label_width = QLabel('Width:')
        width_value = str(self._get_argument('width', 500))
        self._width_input = QLineEdit(text=width_value)
        top_layout_top.addWidget(label_width)
        top_layout_top.addWidget(self._width_input)

        top_layout_bottom = QBoxLayout(0)
        label_height = QLabel('Height:')
        height_value = str(self._get_argument('height', 500))
        self._height_input = QLineEdit(text=height_value)
        top_layout_bottom.addWidget(label_height)
        top_layout_bottom.addWidget(self._height_input)

        center_layout_top = QBoxLayout(0)
        label_range_real = QLabel('Real axis range:')
        real_axis_range = self._get_argument('real_axis_range', [-2.0, 1.0])
        self._range_real1_input = QLineEdit(
            text=str(real_axis_range[0]), placeholderText='real.a')
        self._range_real2_input = QLineEdit(
            text=str(real_axis_range[1]), placeholderText='real.b')
        center_layout_top.addWidget(label_range_real)
        center_layout_top.addWidget(self._range_real1_input)
        center_layout_top.addWidget(self._range_real2_input)

        center_layout_bottom = QBoxLayout(0)
        label_range_imag = QLabel('Imaginary axis range:')
        imag_axis_range = self._get_argument('imag_axis_range', [-1.5, 1.5])
        self._range_imag1_input = QLineEdit(
            text=str(imag_axis_range[0]), placeholderText='imag.a')
        self._range_imag2_input = QLineEdit(
            text=str(imag_axis_range[1]), placeholderText='imag.b')
        center_layout_bottom.addWidget(label_range_imag)
        center_layout_bottom.addWidget(self._range_imag1_input)
        center_layout_bottom.addWidget(self._range_imag2_input)

        bottom_layout_top = QBoxLayout(0)
        label_tasks = QLabel('Number of tasks:')
        tasks_value = str(self._get_argument('tasks', 1))
        self._tasks_input = QLineEdit(text=tasks_value)
        bottom_layout_top.addWidget(label_tasks)
        bottom_layout_top.addWidget(self._tasks_input)

        self._gpu_checkbox = None
        gpu_value = self._get_argument('gpu', 0)
        if gpu_value:
            self._gpu_checkbox = QCheckBox('GPU acceleration')
            self._gpu_checkbox.setChecked(gpu_value)
            bottom_layout_top.addWidget(self._gpu_checkbox)

        bottom_layout_bottom = QVBoxLayout()
        self._process_btn = QPushButton('Process')
        self._process_btn.setDefault(True)
        bottom_layout_bottom.addWidget(self._process_btn)
        self._process_btn.clicked.connect(self._process_mandelbrot)

        image_layout = QVBoxLayout()
        self._image_label = QLabel()
        self._image_label.setVisible(False)

        self._save_btn = QPushButton('Save')
        self._save_btn.clicked.connect(self._save_visualisation)
        self._save_btn.setVisible(False)
        image_layout.addWidget(self._image_label)
        image_layout.addWidget(self._save_btn)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(top_layout_top)
        mainLayout.addLayout(top_layout_bottom)
        mainLayout.addLayout(center_layout_top)
        mainLayout.addLayout(center_layout_bottom)
        mainLayout.addLayout(bottom_layout_top)
        mainLayout.addLayout(bottom_layout_bottom)
        mainLayout.addLayout(image_layout)

        self.setLayout(mainLayout)
        self.setWindowTitle('Mandelbrot Visualisation')
Beispiel #53
0
class PrintView(QWidget):
    """
    Displays the print view.
    """
    def __init__(self, parent=None):
        super(PrintView, self).__init__(parent)
        self._layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.setLayout(self._layout)
        # initialize
        config = Config()
        self._printerSelection = QComboBox()
        self._printerSelection.addItems(config.get("Data", "printers").split(","))
        self._printerSelection.setEditable(True)
        self._printButton = QPushButton("Print")

        form_layout = QFormLayout()
        form_layout.addRow("Printer:", self._printerSelection)
        self._layout.addLayout(form_layout)
        self._layout.addWidget(self._printButton)
        self._model = None # type: QTreeWidget

        # initialize event listener
        self._printButton.clicked.connect(self._print)

    def set_parent_model(self, model):
        self._model = model

    def _print(self):
        """
        Prints the selected materials.
        """
        print_amounts = self._calculate_print_amounts(self._model.invisibleRootItem())
        printer = self._printerSelection.currentText()
        ssh_input = SSHInput(self.parent())
        connection = Connection(ssh_input)
        self._printButton.setText("Printing...")
        self._printButton.setDown(True)
        result = connection.send_print_data(print_amounts, printer)
        if not result:
            error = connection.get_error_object()
            if error.output is not None:
                show_error_alert(error.output)
            else:
                show_error_alert("Something went wrong")
        self._printButton.setText("Print")
        self._printButton.setDown(False)

    def _calculate_print_amounts(self, root_item):
        """
        :param root_item:
        :type root_item: QTreeWidgetItem
        :rtype: dict
        """
        print_amounts = {}
        if root_item.childCount() > 0:
            for child_index in range(root_item.childCount()):
                child = root_item.child(child_index)
                if is_checked_tree(child):
                    print_amounts[child.text(0)] = int(child.text(1))
                else:
                    child_print_amounts = self._calculate_print_amounts(child)
                    print_amounts.update(child_print_amounts)

        elif is_checked_tree(root_item):
            print_amounts[root_item.text(0)] = int(root_item.text(1))

        return print_amounts
	def __init__(self, parent):
		super(TournamentOrganizerWidget, self).__init__(parent)
		self.parent = parent

		# Default Players (for quick testing)
		player_names = [
			'Frodo',
			'Sam',
			'Merry',
			'Pippin',
			'Gandalf',
			'Aragorn',
			'Legolas',
			'Gimli',
			'Boromir'
		]
		# for name in player_names:
		# 	to.add_player(name, None)

		self.sort_order = 'by_name'

		view.notifier.observers.append(self)

		self.header_label = QLabel('Players')

		self.header_widget = QWidget(self)
		header_layout = QBoxLayout(QBoxLayout.LeftToRight)
		header_layout.addWidget(self.header_label)
		self.header_widget.setLayout(header_layout)

		self.sort_by_name_btn = QPushButton('Sort by Name', self)
		self.sort_by_name_btn.clicked.connect(self.sort_by_name)
		self.sort_by_rank_btn = QPushButton('Sort by Rank', self)
		self.sort_by_rank_btn.clicked.connect(self.sort_by_rank)

		self.sort_btns_widget = QWidget(self)
		sort_btns_layout = QBoxLayout(QBoxLayout.LeftToRight)
		sort_btns_layout.addWidget(self.sort_by_name_btn)
		sort_btns_layout.addSpacing(10)
		sort_btns_layout.addWidget(self.sort_by_rank_btn)
		self.sort_btns_widget.setLayout(sort_btns_layout)

		self.player_list = QTableWidget(style.style_loader.TABLE_INITIAL_LENGTH, 2, self)
		self.player_list.setHorizontalHeaderLabels(['Name', 'Record'])
		self.player_list.setFixedHeight(300)
		self.player_list.setFixedWidth(400)
		self.player_list.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
		self.player_list.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)
		self.player_list.horizontalHeader().setVisible(True)

		self.player_list_widget = QWidget(self)
		player_list_layout = QBoxLayout(QBoxLayout.LeftToRight)
		player_list_layout.addWidget(self.player_list)
		self.player_list_widget.setLayout(player_list_layout)

		self.add_player_btn = QPushButton('Add Player', self)
		self.add_player_btn.clicked.connect(self.parent.show_add_player_widget)
		self.remove_player_btn = QPushButton('Remove Player', self)
		self.remove_player_btn.clicked.connect(self.parent.show_remove_player_widget)

		self.player_btns_widget = QWidget(self)
		player_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		player_btn_layout.addWidget(self.add_player_btn)
		player_btn_layout.addSpacing(10)
		player_btn_layout.addWidget(self.remove_player_btn)
		self.player_btns_widget.setLayout(player_btn_layout)

		self.error = None

		layout = QFormLayout()
		layout.addRow(self.header_widget)
		layout.addRow(self.sort_btns_widget)
		layout.addRow(self.player_list_widget)
		layout.addRow(self.player_btns_widget)
		self.setLayout(layout)

		self.update()
Beispiel #55
0
class E5SideBar(QWidget):
    """
    Class implementing a sidebar with a widget area, that is hidden or shown,
    if the current tab is clicked again.
    """
    Version = 1
    
    North = 0
    East = 1
    South = 2
    West = 3
    
    def __init__(self, orientation=None, delay=200, parent=None):
        """
        Constructor
        
        @param orientation orientation of the sidebar widget (North, East,
            South, West)
        @param delay value for the expand/shrink delay in milliseconds
            (integer)
        @param parent parent widget (QWidget)
        """
        super(E5SideBar, self).__init__(parent)
        
        self.__tabBar = QTabBar()
        self.__tabBar.setDrawBase(True)
        self.__tabBar.setShape(QTabBar.RoundedNorth)
        self.__tabBar.setUsesScrollButtons(True)
        self.__tabBar.setDrawBase(False)
        self.__stackedWidget = QStackedWidget(self)
        self.__stackedWidget.setContentsMargins(0, 0, 0, 0)
        self.__autoHideButton = QToolButton()
        self.__autoHideButton.setCheckable(True)
        self.__autoHideButton.setIcon(
            UI.PixmapCache.getIcon("autoHideOff.png"))
        self.__autoHideButton.setChecked(True)
        self.__autoHideButton.setToolTip(
            self.tr("Deselect to activate automatic collapsing"))
        self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.barLayout.setContentsMargins(0, 0, 0, 0)
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.barLayout.addWidget(self.__autoHideButton)
        self.barLayout.addWidget(self.__tabBar)
        self.layout.addLayout(self.barLayout)
        self.layout.addWidget(self.__stackedWidget)
        self.setLayout(self.layout)
        
        # initialize the delay timer
        self.__actionMethod = None
        self.__delayTimer = QTimer(self)
        self.__delayTimer.setSingleShot(True)
        self.__delayTimer.setInterval(delay)
        self.__delayTimer.timeout.connect(self.__delayedAction)
        
        self.__minimized = False
        self.__minSize = 0
        self.__maxSize = 0
        self.__bigSize = QSize()
        
        self.splitter = None
        self.splitterSizes = []
        
        self.__hasFocus = False
        # flag storing if this widget or any child has the focus
        self.__autoHide = False
        
        self.__tabBar.installEventFilter(self)
        
        self.__orientation = E5SideBar.North
        if orientation is None:
            orientation = E5SideBar.North
        self.setOrientation(orientation)
        
        self.__tabBar.currentChanged[int].connect(
            self.__stackedWidget.setCurrentIndex)
        e5App().focusChanged[QWidget, QWidget].connect(self.__appFocusChanged)
        self.__autoHideButton.toggled[bool].connect(self.__autoHideToggled)
    
    def setSplitter(self, splitter):
        """
        Public method to set the splitter managing the sidebar.
        
        @param splitter reference to the splitter (QSplitter)
        """
        self.splitter = splitter
        self.splitter.splitterMoved.connect(self.__splitterMoved)
        self.splitter.setChildrenCollapsible(False)
        index = self.splitter.indexOf(self)
        self.splitter.setCollapsible(index, False)
    
    def __splitterMoved(self, pos, index):
        """
        Private slot to react on splitter moves.
        
        @param pos new position of the splitter handle (integer)
        @param index index of the splitter handle (integer)
        """
        if self.splitter:
            self.splitterSizes = self.splitter.sizes()
    
    def __delayedAction(self):
        """
        Private slot to handle the firing of the delay timer.
        """
        if self.__actionMethod is not None:
            self.__actionMethod()
    
    def setDelay(self, delay):
        """
        Public method to set the delay value for the expand/shrink delay in
        milliseconds.
        
        @param delay value for the expand/shrink delay in milliseconds
            (integer)
        """
        self.__delayTimer.setInterval(delay)
    
    def delay(self):
        """
        Public method to get the delay value for the expand/shrink delay in
        milliseconds.
        
        @return value for the expand/shrink delay in milliseconds (integer)
        """
        return self.__delayTimer.interval()
    
    def __cancelDelayTimer(self):
        """
        Private method to cancel the current delay timer.
        """
        self.__delayTimer.stop()
        self.__actionMethod = None
    
    def shrink(self):
        """
        Public method to record a shrink request.
        """
        self.__delayTimer.stop()
        self.__actionMethod = self.__shrinkIt
        self.__delayTimer.start()
   
    def __shrinkIt(self):
        """
        Private method to shrink the sidebar.
        """
        self.__minimized = True
        self.__bigSize = self.size()
        if self.__orientation in [E5SideBar.North, E5SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
            self.__maxSize = self.maximumHeight()
        else:
            self.__minSize = self.minimumSizeHint().width()
            self.__maxSize = self.maximumWidth()
        if self.splitter:
            self.splitterSizes = self.splitter.sizes()
        
        self.__stackedWidget.hide()
        
        if self.__orientation in [E5SideBar.North, E5SideBar.South]:
            self.setFixedHeight(self.__tabBar.minimumSizeHint().height())
        else:
            self.setFixedWidth(self.__tabBar.minimumSizeHint().width())
        
        self.__actionMethod = None
    
    def expand(self):
        """
        Public method to record a expand request.
        """
        self.__delayTimer.stop()
        self.__actionMethod = self.__expandIt
        self.__delayTimer.start()
    
    def __expandIt(self):
        """
        Private method to expand the sidebar.
        """
        self.__minimized = False
        self.__stackedWidget.show()
        self.resize(self.__bigSize)
        if self.__orientation in [E5SideBar.North, E5SideBar.South]:
            minSize = max(self.__minSize, self.minimumSizeHint().height())
            self.setMinimumHeight(minSize)
            self.setMaximumHeight(self.__maxSize)
        else:
            minSize = max(self.__minSize, self.minimumSizeHint().width())
            self.setMinimumWidth(minSize)
            self.setMaximumWidth(self.__maxSize)
        if self.splitter:
            self.splitter.setSizes(self.splitterSizes)
        
        self.__actionMethod = None
    
    def isMinimized(self):
        """
        Public method to check the minimized state.
        
        @return flag indicating the minimized state (boolean)
        """
        return self.__minimized
    
    def isAutoHiding(self):
        """
        Public method to check, if the auto hide function is active.
        
        @return flag indicating the state of auto hiding (boolean)
        """
        return self.__autoHide
    
    def eventFilter(self, obj, evt):
        """
        Public method to handle some events for the tabbar.
        
        @param obj reference to the object (QObject)
        @param evt reference to the event object (QEvent)
        @return flag indicating, if the event was handled (boolean)
        """
        if obj == self.__tabBar:
            if evt.type() == QEvent.MouseButtonPress:
                pos = evt.pos()
                for i in range(self.__tabBar.count()):
                    if self.__tabBar.tabRect(i).contains(pos):
                        break
                
                if i == self.__tabBar.currentIndex():
                    if self.isMinimized():
                        self.expand()
                    else:
                        self.shrink()
                    return True
                elif self.isMinimized():
                    self.expand()
            elif evt.type() == QEvent.Wheel:
                if qVersion() >= "5.0.0":
                    delta = evt.angleDelta().y()
                else:
                    delta = evt.delta()
                if delta > 0:
                    self.prevTab()
                else:
                    self.nextTab()
                return True
        
        return QWidget.eventFilter(self, obj, evt)
    
    def addTab(self, widget, iconOrLabel, label=None):
        """
        Public method to add a tab to the sidebar.
        
        @param widget reference to the widget to add (QWidget)
        @param iconOrLabel reference to the icon or the label text of the tab
            (QIcon, string)
        @param label the labeltext of the tab (string) (only to be
            used, if the second parameter is a QIcon)
        """
        if label:
            index = self.__tabBar.addTab(iconOrLabel, label)
            self.__tabBar.setTabToolTip(index, label)
        else:
            index = self.__tabBar.addTab(iconOrLabel)
            self.__tabBar.setTabToolTip(index, iconOrLabel)
        self.__stackedWidget.addWidget(widget)
        if self.__orientation in [E5SideBar.North, E5SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def insertTab(self, index, widget, iconOrLabel, label=None):
        """
        Public method to insert a tab into the sidebar.
        
        @param index the index to insert the tab at (integer)
        @param widget reference to the widget to insert (QWidget)
        @param iconOrLabel reference to the icon or the labeltext of the tab
            (QIcon, string)
        @param label the labeltext of the tab (string) (only to be
            used, if the second parameter is a QIcon)
        """
        if label:
            index = self.__tabBar.insertTab(index, iconOrLabel, label)
            self.__tabBar.setTabToolTip(index, label)
        else:
            index = self.__tabBar.insertTab(index, iconOrLabel)
            self.__tabBar.setTabToolTip(index, iconOrLabel)
        self.__stackedWidget.insertWidget(index, widget)
        if self.__orientation in [E5SideBar.North, E5SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def removeTab(self, index):
        """
        Public method to remove a tab.
        
        @param index the index of the tab to remove (integer)
        """
        self.__stackedWidget.removeWidget(self.__stackedWidget.widget(index))
        self.__tabBar.removeTab(index)
        if self.__orientation in [E5SideBar.North, E5SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def clear(self):
        """
        Public method to remove all tabs.
        """
        while self.count() > 0:
            self.removeTab(0)
    
    def prevTab(self):
        """
        Public slot used to show the previous tab.
        """
        ind = self.currentIndex() - 1
        if ind == -1:
            ind = self.count() - 1
            
        self.setCurrentIndex(ind)
        self.currentWidget().setFocus()
    
    def nextTab(self):
        """
        Public slot used to show the next tab.
        """
        ind = self.currentIndex() + 1
        if ind == self.count():
            ind = 0
            
        self.setCurrentIndex(ind)
        self.currentWidget().setFocus()
    
    def count(self):
        """
        Public method to get the number of tabs.
        
        @return number of tabs in the sidebar (integer)
        """
        return self.__tabBar.count()
    
    def currentIndex(self):
        """
        Public method to get the index of the current tab.
        
        @return index of the current tab (integer)
        """
        return self.__stackedWidget.currentIndex()
    
    def setCurrentIndex(self, index):
        """
        Public slot to set the current index.
        
        @param index the index to set as the current index (integer)
        """
        self.__tabBar.setCurrentIndex(index)
        self.__stackedWidget.setCurrentIndex(index)
        if self.isMinimized():
            self.expand()
    
    def currentWidget(self):
        """
        Public method to get a reference to the current widget.
        
        @return reference to the current widget (QWidget)
        """
        return self.__stackedWidget.currentWidget()
    
    def setCurrentWidget(self, widget):
        """
        Public slot to set the current widget.
        
        @param widget reference to the widget to become the current widget
            (QWidget)
        """
        self.__stackedWidget.setCurrentWidget(widget)
        self.__tabBar.setCurrentIndex(self.__stackedWidget.currentIndex())
        if self.isMinimized():
            self.expand()
    
    def indexOf(self, widget):
        """
        Public method to get the index of the given widget.
        
        @param widget reference to the widget to get the index of (QWidget)
        @return index of the given widget (integer)
        """
        return self.__stackedWidget.indexOf(widget)
    
    def isTabEnabled(self, index):
        """
        Public method to check, if a tab is enabled.
        
        @param index index of the tab to check (integer)
        @return flag indicating the enabled state (boolean)
        """
        return self.__tabBar.isTabEnabled(index)
    
    def setTabEnabled(self, index, enabled):
        """
        Public method to set the enabled state of a tab.
        
        @param index index of the tab to set (integer)
        @param enabled enabled state to set (boolean)
        """
        self.__tabBar.setTabEnabled(index, enabled)
    
    def orientation(self):
        """
        Public method to get the orientation of the sidebar.
        
        @return orientation of the sidebar (North, East, South, West)
        """
        return self.__orientation
    
    def setOrientation(self, orient):
        """
        Public method to set the orientation of the sidebar.

        @param orient orientation of the sidebar (North, East, South, West)
        """
        if orient == E5SideBar.North:
            self.__tabBar.setShape(QTabBar.RoundedNorth)
            self.__tabBar.setSizePolicy(
                QSizePolicy.Expanding, QSizePolicy.Preferred)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        elif orient == E5SideBar.East:
            self.__tabBar.setShape(QTabBar.RoundedEast)
            self.__tabBar.setSizePolicy(
                QSizePolicy.Preferred, QSizePolicy.Expanding)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.RightToLeft)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        elif orient == E5SideBar.South:
            self.__tabBar.setShape(QTabBar.RoundedSouth)
            self.__tabBar.setSizePolicy(
                QSizePolicy.Expanding, QSizePolicy.Preferred)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.BottomToTop)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        elif orient == E5SideBar.West:
            self.__tabBar.setShape(QTabBar.RoundedWest)
            self.__tabBar.setSizePolicy(
                QSizePolicy.Preferred, QSizePolicy.Expanding)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        self.__orientation = orient
    
    def tabIcon(self, index):
        """
        Public method to get the icon of a tab.
        
        @param index index of the tab (integer)
        @return icon of the tab (QIcon)
        """
        return self.__tabBar.tabIcon(index)
    
    def setTabIcon(self, index, icon):
        """
        Public method to set the icon of a tab.
        
        @param index index of the tab (integer)
        @param icon icon to be set (QIcon)
        """
        self.__tabBar.setTabIcon(index, icon)
    
    def tabText(self, index):
        """
        Public method to get the text of a tab.
        
        @param index index of the tab (integer)
        @return text of the tab (string)
        """
        return self.__tabBar.tabText(index)
    
    def setTabText(self, index, text):
        """
        Public method to set the text of a tab.
        
        @param index index of the tab (integer)
        @param text text to set (string)
        """
        self.__tabBar.setTabText(index, text)
    
    def tabToolTip(self, index):
        """
        Public method to get the tooltip text of a tab.
        
        @param index index of the tab (integer)
        @return tooltip text of the tab (string)
        """
        return self.__tabBar.tabToolTip(index)
    
    def setTabToolTip(self, index, tip):
        """
        Public method to set the tooltip text of a tab.
        
        @param index index of the tab (integer)
        @param tip tooltip text to set (string)
        """
        self.__tabBar.setTabToolTip(index, tip)
    
    def tabWhatsThis(self, index):
        """
        Public method to get the WhatsThis text of a tab.
        
        @param index index of the tab (integer)
        @return WhatsThis text of the tab (string)
        """
        return self.__tabBar.tabWhatsThis(index)
    
    def setTabWhatsThis(self, index, text):
        """
        Public method to set the WhatsThis text of a tab.
        
        @param index index of the tab (integer)
        @param text WhatsThis text to set (string)
        """
        self.__tabBar.setTabWhatsThis(index, text)
    
    def widget(self, index):
        """
        Public method to get a reference to the widget associated with a tab.
        
        @param index index of the tab (integer)
        @return reference to the widget (QWidget)
        """
        return self.__stackedWidget.widget(index)
    
    def saveState(self):
        """
        Public method to save the state of the sidebar.
        
        @return saved state as a byte array (QByteArray)
        """
        if len(self.splitterSizes) == 0:
            if self.splitter:
                self.splitterSizes = self.splitter.sizes()
            self.__bigSize = self.size()
            if self.__orientation in [E5SideBar.North, E5SideBar.South]:
                self.__minSize = self.minimumSizeHint().height()
                self.__maxSize = self.maximumHeight()
            else:
                self.__minSize = self.minimumSizeHint().width()
                self.__maxSize = self.maximumWidth()
        
        data = QByteArray()
        stream = QDataStream(data, QIODevice.WriteOnly)
        stream.setVersion(QDataStream.Qt_4_6)
        
        stream.writeUInt16(self.Version)
        stream.writeBool(self.__minimized)
        stream << self.__bigSize
        stream.writeUInt16(self.__minSize)
        stream.writeUInt16(self.__maxSize)
        stream.writeUInt16(len(self.splitterSizes))
        for size in self.splitterSizes:
            stream.writeUInt16(size)
        stream.writeBool(self.__autoHide)
        
        return data
    
    def restoreState(self, state):
        """
        Public method to restore the state of the sidebar.
        
        @param state byte array containing the saved state (QByteArray)
        @return flag indicating success (boolean)
        """
        if state.isEmpty():
            return False
        
        if self.__orientation in [E5SideBar.North, E5SideBar.South]:
            minSize = self.layout.minimumSize().height()
            maxSize = self.maximumHeight()
        else:
            minSize = self.layout.minimumSize().width()
            maxSize = self.maximumWidth()
        
        data = QByteArray(state)
        stream = QDataStream(data, QIODevice.ReadOnly)
        stream.setVersion(QDataStream.Qt_4_6)
        stream.readUInt16()  # version
        minimized = stream.readBool()
        
        if minimized and not self.__minimized:
            self.shrink()
        
        stream >> self.__bigSize
        self.__minSize = max(stream.readUInt16(), minSize)
        self.__maxSize = max(stream.readUInt16(), maxSize)
        count = stream.readUInt16()
        self.splitterSizes = []
        for i in range(count):
            self.splitterSizes.append(stream.readUInt16())
        
        self.__autoHide = stream.readBool()
        self.__autoHideButton.setChecked(not self.__autoHide)
        
        if not minimized:
            self.expand()
        
        return True
    
    #######################################################################
    ## methods below implement the autohide functionality
    #######################################################################
    
    def __autoHideToggled(self, checked):
        """
        Private slot to handle the toggling of the autohide button.
        
        @param checked flag indicating the checked state of the button
            (boolean)
        """
        self.__autoHide = not checked
        if self.__autoHide:
            self.__autoHideButton.setIcon(
                UI.PixmapCache.getIcon("autoHideOn.png"))
        else:
            self.__autoHideButton.setIcon(
                UI.PixmapCache.getIcon("autoHideOff.png"))
    
    def __appFocusChanged(self, old, now):
        """
        Private slot to handle a change of the focus.
        
        @param old reference to the widget, that lost focus (QWidget or None)
        @param now reference to the widget having the focus (QWidget or None)
        """
        self.__hasFocus = self.isAncestorOf(now)
        if self.__autoHide and not self.__hasFocus and not self.isMinimized():
            self.shrink()
        elif self.__autoHide and self.__hasFocus and self.isMinimized():
            self.expand()
    
    def enterEvent(self, event):
        """
        Protected method to handle the mouse entering this widget.
        
        @param event reference to the event (QEvent)
        """
        if self.__autoHide and self.isMinimized():
            self.expand()
        else:
            self.__cancelDelayTimer()
    
    def leaveEvent(self, event):
        """
        Protected method to handle the mouse leaving this widget.
        
        @param event reference to the event (QEvent)
        """
        if self.__autoHide and not self.__hasFocus and not self.isMinimized():
            self.shrink()
        else:
            self.__cancelDelayTimer()
    
    def shutdown(self):
        """
        Public method to shut down the object.
        
        This method does some preparations so the object can be deleted
        properly. It disconnects from the focusChanged signal in order to
        avoid trouble later on.
        """
        e5App().focusChanged[QWidget, QWidget].disconnect(
            self.__appFocusChanged)
Beispiel #56
0
class IconEditorPalette(QWidget):
    """
    Class implementing a palette widget for the icon editor.
    
    @signal colorSelected(QColor) emitted after a new color has been selected
    @signal compositingChanged(QPainter.CompositionMode) emitted to signal a
        change of the compositing mode
    """
    colorSelected = pyqtSignal(QColor)
    compositingChanged = pyqtSignal(QPainter.CompositionMode)
    
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        super(IconEditorPalette, self).__init__(parent)
        
        if self.layoutDirection == Qt.Horizontal:
            direction = QBoxLayout.LeftToRight
        else:
            direction = QBoxLayout.TopToBottom
        self.__layout = QBoxLayout(direction, self)
        self.setLayout(self.__layout)
        
        self.__preview = QLabel(self)
        self.__preview.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.__preview.setFixedHeight(64)
        self.__preview.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.__preview.setWhatsThis(self.tr(
            """<b>Preview</b>"""
            """<p>This is a 1:1 preview of the current icon.</p>"""
        ))
        self.__layout.addWidget(self.__preview)
        
        self.__color = QLabel(self)
        self.__color.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.__color.setFixedHeight(24)
        self.__color.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.__color.setWhatsThis(self.tr(
            """<b>Current Color</b>"""
            """<p>This is the currently selected color used for drawing.</p>"""
        ))
        self.__layout.addWidget(self.__color)
        
        self.__colorTxt = QLabel(self)
        self.__colorTxt.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.__colorTxt.setWhatsThis(self.tr(
            """<b>Current Color Value</b>"""
            """<p>This is the currently selected color value used for"""
            """ drawing.</p>"""
        ))
        self.__layout.addWidget(self.__colorTxt)
        
        self.__colorButton = QPushButton(self.tr("Select Color"), self)
        self.__colorButton.setWhatsThis(self.tr(
            """<b>Select Color</b>"""
            """<p>Select the current drawing color via a color selection"""
            """ dialog.</p>"""
        ))
        self.__colorButton.clicked.connect(self.__selectColor)
        self.__layout.addWidget(self.__colorButton)
        
        self.__colorAlpha = QSpinBox(self)
        self.__colorAlpha.setRange(0, 255)
        self.__colorAlpha.setWhatsThis(self.tr(
            """<b>Select alpha channel value</b>"""
            """<p>Select the value for the alpha channel of the current"""
            """ color.</p>"""
        ))
        self.__layout.addWidget(self.__colorAlpha)
        self.__colorAlpha.valueChanged[int].connect(self.__alphaChanged)
        
        self.__compositingGroup = QGroupBox(self.tr("Compositing"), self)
        self.__compositingGroupLayout = QVBoxLayout(self.__compositingGroup)
        self.__compositingGroup.setLayout(self.__compositingGroupLayout)
        self.__sourceButton = QRadioButton(self.tr("Replace"),
                                           self.__compositingGroup)
        self.__sourceButton.setWhatsThis(self.tr(
            """<b>Replace</b>"""
            """<p>Replace the existing pixel with a new color.</p>"""
        ))
        self.__sourceButton.clicked[bool].connect(self.__compositingChanged)
        self.__compositingGroupLayout.addWidget(self.__sourceButton)
        self.__sourceOverButton = QRadioButton(self.tr("Blend"),
                                               self.__compositingGroup)
        self.__sourceOverButton.setWhatsThis(self.tr(
            """<b>Blend</b>"""
            """<p>Blend the new color over the existing pixel.</p>"""
        ))
        self.__sourceOverButton.setChecked(True)
        self.__sourceOverButton.clicked[bool].connect(
            self.__compositingChanged)
        self.__compositingGroupLayout.addWidget(self.__sourceOverButton)
        self.__layout.addWidget(self.__compositingGroup)
        
        spacer = QSpacerItem(
            10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.__layout.addItem(spacer)
    
    def previewChanged(self, pixmap):
        """
        Public slot to update the preview.
        
        @param pixmap new preview pixmap (QPixmap)
        """
        self.__preview.setPixmap(pixmap)
    
    def colorChanged(self, color):
        """
        Public slot to update the color preview.
        
        @param color new color (QColor)
        """
        self.__currentColor = color
        self.__currentAlpha = color.alpha()
        
        pm = QPixmap(90, 18)
        pm.fill(color)
        self.__color.setPixmap(pm)
        
        self.__colorTxt.setText(
            "{0:d}, {1:d}, {2:d}, {3:d}".format(
                color.red(), color.green(), color.blue(), color.alpha()))
        
        self.__colorAlpha.setValue(self.__currentAlpha)
    
    def __selectColor(self):
        """
        Private slot to select a new drawing color.
        """
        col = QColorDialog.getColor(self.__currentColor)
        col.setAlpha(self.__currentAlpha)
        
        if col.isValid():
            self.colorSelected.emit(col)
    
    def __alphaChanged(self, val):
        """
        Private slot to track changes of the alpha channel.
        
        @param val value of the alpha channel
        """
        if val != self.__currentAlpha:
            col = QColor(self.__currentColor)
            col.setAlpha(val)
            self.colorSelected.emit(col)
    
    def setCompositingMode(self, mode):
        """
        Public method to set the compositing mode.
        
        @param mode compositing mode to set (QPainter.CompositionMode)
        """
        if mode == QPainter.CompositionMode_Source:
            self.__sourceButton.setChecked(True)
        elif mode == QPainter.CompositionMode_SourceOver:
            self.__sourceOverButton.setChecked(True)
    
    def __compositingChanged(self, on):
        """
        Private slot to handle a change of the compositing mode.
        
        @param on flag indicating the checked state of the compositing button
            (boolean)
        """
        if on:
            if self.__sourceButton.isChecked():
                self.compositingChanged.emit(
                    QPainter.CompositionMode_Source)
            elif self.__sourceOverButton.isChecked():
                self.compositingChanged.emit(
                    QPainter.CompositionMode_SourceOver)
    def load_settings_widgets_from_pipeline_groupbox(self, position):
        """
        Extracts all widgets from a single algorithm and returns a QBoxLayout
        Args:
            alg: the alg instance we extract from

        Returns: a QBoxLayout containing all widgets for this particular alg.

        """

        alg = self.pipeline.executed_cats[position].active_algorithm

        print("alg " + str(alg))
        print("cat " + str(self.pipeline.executed_cats[position]))

        empty_flag = True

        groupOfSliders = QGroupBox()
        sp = QSizePolicy()
        sp.setVerticalPolicy(QSizePolicy.Preferred)
        # groupOfSliders.setSizePolicy(sp)
        groupOfSliderssLayout = QBoxLayout(QBoxLayout.TopToBottom)
        groupOfSliderssLayout.setContentsMargins(0, -0, -0, 0)
        groupOfSliderssLayout.setAlignment(Qt.AlignTop)
        groupOfSliderssLayout.setSpacing(0)

        print("Build Slider @ "+ str(position))

        # create integer sliders
        for slider in alg.integer_sliders:
            empty_flag = False
            print("slider.value " + str(slider.value))
            print("slider " + str(slider))
            #print(alg.get_name() + ": add slider (int).")
            groupOfSliderssLayout.addWidget(
                SliderWidget(slider.name, slider.lower, slider.upper, slider.step_size, slider.value,
                             slider.set_value, False))

        # create float sliders
        for slider in alg.float_sliders:
            empty_flag = False
            #print(alg.get_name() + ": add slider (float).")
            groupOfSliderssLayout.addWidget(
                SliderWidget(slider.name, slider.lower, slider.upper, slider.step_size, slider.value,
                             slider.set_value, True), 0, Qt.AlignTop)

        # create checkboxes
        for checkbox in alg.checkboxes:
            empty_flag = False
            #print(alg.get_name() + ": add checkbox.")
            groupOfSliderssLayout.addWidget(CheckBoxWidget(checkbox.name, checkbox.value, checkbox.set_value), 0,
                                            Qt.AlignTop)

        # create dropdowns
        for combobox in alg.drop_downs:
            empty_flag = False
            #print(alg.get_name() + ": add combobox.")
            groupOfSliderssLayout.addWidget(
                ComboBoxWidget(combobox.name, combobox.options, combobox.set_value, combobox.value), 0, Qt.AlignTop)

        if empty_flag:
            label = QLabel()
            label.setText("This algorithm has no Settings.")
            groupOfSliderssLayout.addWidget(label, 0, Qt.AlignHCenter)

        groupOfSliders.setLayout(groupOfSliderssLayout)

        return groupOfSliders
Beispiel #58
0
class QPageWidget(QScrollArea):
    """ The QPageWidget provides a stack widget with animated page transitions. """

    #Emits
    currentChanged = pyqtSignal()
    
    def __init__(self, parent = None, direction = "ltr", rtf = False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
                
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        
        #qboxlayout setmargin özelliği yok
        #self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()

    def _animateFinished(self):
        """ Its called by TimeLine when animation finished.

        It first runs the outMethod of last Page and then the inMethod of current Page
        Finally tt gives the focus to the current page and fixes the scrollBar
        """

        # Disable other widgets
        for page in self.__pages:
            if not page == self.__pages[self.__current]:
                page.widget.setEnabled(False)

        # Run last page's outMethod if exists
        if self.__pages[self.__last].outMethod:
            self.__pages[self.__last].outMethod()

        # Run new page's inMethod if exists
        if self.__pages[self.__current].inMethod:
            self.__pages[self.__current].inMethod()

        # Give focus to the current Page
        self.__pages[self.__current].widget.setFocus()

        # Update scrollbar position for current page
        self.__scrollBar.setValue(self.__current * self.__base_value())

        # Emit currentChanged SIGNAL
        self.currentChanged.emit()

    def event(self, event):
        """ Overrides the main event handler to catch resize events """
        # Catch Resize event
        if event.type() == QEvent.Resize:
            # Update each page size limits to mainwidget's new size
            for page in self.__pages:
                page.widget.setMinimumSize(self.size())
                page.widget.setMaximumSize(self.size())

            # Update viewport size limits to mainwidget's new size
            # It's a workaround for QScrollArea updateGeometry bug
            self.viewport().setMinimumSize(self.size())
            self.viewport().setMaximumSize(self.size())

            # Update scrollbar position for current page
            self.__scrollBar.setValue(self.__current * self.__base_value())

        # Return the Event
        return QScrollArea.event(self, event)

    def keyPressEvent(self, event):
        """ Overrides the keyPressEvent to ignore them """
        pass

    def wheelEvent(self, event):
        """ Overrides the wheelEvent to ignore them """
        pass

    def createPage(self, widget, inMethod = None, outMethod = None):
        """ Creates and adds new Page for given widget with given in/out methods.

        widget: A QWidget which is the mainwidget for this Page
        inMethod: (optional) QPageWidget triggers this method when the Page appear
        outMethod: (optional) QPageWidget triggers this method when the Page disappear
        """
        self.addPage(Page(widget, inMethod, outMethod))

    def addPage(self, page):
        """ Adds the given Page to the stack.

        page: A Page object
        """
        # First remove the last page; its __tmp_page
        self.__pages.pop()

        # Add new page
        self.__pages.append(page)
        self.layout.addWidget(page.widget)

        # Add __tmp_page to end
        self.__pages.append(self.__tmp_page)
        self.layout.addWidget(self.__tmp_page.widget)

        # Create connections for page navigation signals from new page
        try:
            page.widget.pageNext.connect(self.next)
            page.widget.pagePrevious.connect(self.prev)
            page.widget.setCurrent[int].connect(self.setCurrent)
        except:
            pass

    def __setCurrent(self, pageNumber):
        """ Internal method to set current page index. """
        self.__last = self.__current
        self.__current = min(max(0, pageNumber), len(self.__pages) - 2)
        if pageNumber == len(self.__pages) - 1 and self.__return_to_first:
            self.__current = 0

    def setCurrent(self, pageNumber = 0):
        """ Set and flip the page with given pageNumber.

        pageNumber: index number of Page (default is 0)
        """
        self.__setCurrent(pageNumber)
        self.flipPage()

    def getCurrent(self):
        """ Returns current page index. """
        return self.__current

    def getCurrentWidget(self):
        """ Returns current page widget. """
        return self.getWidget(self.getCurrent())

    def getWidget(self, pageNumber):
        """ Returns widget for given page index 

        pageNumber: index number of Page
        """
        try:
            return self.__pages[pageNumber].widget
        except:
            return None

    def count(self):
        """ Returns number of pages. """
        return len(self.__pages) - 1

    def setAnimation(self, animation = 35):
        """ Set the transition animation with the given animation.

        animation: the number represents predefined QEasingCurves
                   List of predefined QEasingCurves can be found from:
                   http://doc.qt.nokia.com/4/qeasingcurve.html#Type-enum

                   Default is QEasingCurve::InOutBack (35)
        """
        self.__animation = animation
        self.__timeline.setEasingCurve(QEasingCurve(self.__animation))

    def setDuration(self, duration = 400):
        """ Set the transition duration.

        duration: duration time in ms
        """
        self.__duration = duration
        self.__timeline.setDuration(self.__duration)

    def flipPage(self, direction=0):
        """ Flip the page with given direction.

        direction: can be -1, 0 or +1
                   -1: previous page (if exists)
                    0: just flip to current page
                   +1: next page (if exists)
        """
        # Enable all widgets
        for page in self.__pages:
            page.widget.setEnabled(True)

        # Check given direction
        direction = direction if direction == 0 else max(min(1, direction), -1)

        # If direction is equal to zero no need to re-set current
        if not direction == 0:
            self.__setCurrent(self.__current + direction)

        # If last page is different from new page, flip it !
        if not self.__last == self.__current:
            self.__timeline.setFrameRange(self.__scrollBar.value(), self.__current * self.__base_value())
            self.__timeline.start()

    def next(self):
        """ Helper method to flip next page. """
        self.flipPage(1)

    def prev(self):
        """ Helper method to flip previous page. """
        self.flipPage(-1)
	def __init__(self, parent):
		super(UserManagerWidget, self).__init__(parent)
		self.parent = parent

		self.sort_order = 'by_name'

		view.notifier.observers.append(self)

		self.header_label = QLabel('Users')

		self.header_widget = QWidget(self)
		header_layout = QBoxLayout(QBoxLayout.LeftToRight)
		header_layout.addWidget(self.header_label)
		self.header_widget.setLayout(header_layout)

		self.sort_by_name_btn = QPushButton('Sort by Name', self)
		self.sort_by_name_btn.clicked.connect(self.sort_by_name)
		self.sort_by_rank_btn = QPushButton('Sort by Rank', self)
		self.sort_by_rank_btn.clicked.connect(self.sort_by_rank)

		self.sort_btns_widget = QWidget(self)
		sort_btns_layout = QBoxLayout(QBoxLayout.LeftToRight)
		sort_btns_layout.addWidget(self.sort_by_name_btn)
		sort_btns_layout.addSpacing(10)
		sort_btns_layout.addWidget(self.sort_by_rank_btn)
		self.sort_btns_widget.setLayout(sort_btns_layout)

		self.user_list = QTableWidget(style.style_loader.TABLE_INITIAL_LENGTH, 3, self)
		self.user_list.setFixedHeight(300)
		self.user_list.setFixedWidth(400)
		self.user_list.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
		self.user_list.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)

		self.user_list_widget = QWidget(self)
		user_list_layout = QBoxLayout(QBoxLayout.LeftToRight)
		user_list_layout.addWidget(self.user_list)
		self.user_list_widget.setLayout(user_list_layout)

		self.add_player_btn = QPushButton('Add User', self)
		self.add_player_btn.clicked.connect(self.parent.show_add_user_widget)
		self.remove_player_btn = QPushButton('Remove User', self)
		self.remove_player_btn.clicked.connect(self.parent.show_remove_user_widget)

		self.player_btns_widget = QWidget(self)
		player_btn_layout = QBoxLayout(QBoxLayout.LeftToRight)
		player_btn_layout.addWidget(self.add_player_btn)
		player_btn_layout.addSpacing(10)
		player_btn_layout.addWidget(self.remove_player_btn)
		self.player_btns_widget.setLayout(player_btn_layout)

		self.error = None

		layout = QFormLayout()
		layout.addRow(self.header_widget)
		layout.addRow(self.sort_btns_widget)
		layout.addRow(self.user_list_widget)
		layout.addRow(self.player_btns_widget)
		self.setLayout(layout)

		self.update()
Beispiel #60
0
class EditView(QDialog):
    """
    Displays the edit view
    """
    _material_model = None  # type: QTreeWidget
    _configuration_model = None  # type: QTreeWidget
    
    def __init__(self, parent=None):
        super(EditView, self).__init__(parent)
        self._layout = QBoxLayout(QBoxLayout.LeftToRight)
        self.setLayout(self._layout)
        self.setWindowTitle('Edit configuration')
        
        self._configurationTreeWidget = TreeWidget()
        self._configurationTreeWidget.setColumnCount(2)
        self._configurationTreeWidget.setHeaderLabels(["Configuration name", "Print amount"])
        self._materialTreeWidget = TreeWidget()
        self._materialTreeWidget.setColumnCount(2)
        self._materialTreeWidget.setHeaderLabels(["Material name", "Print amount"])
        self._initialize_material_model()
        
        self._currentConfiguration = None # type: Configuration
        
        config_widget = QWidget()
        self._configLayout = QBoxLayout(QBoxLayout.TopToBottom)
        self._nameField = QLineEdit()
        self._nameField.setEnabled(False)
        name_form_layout = QFormLayout()
        name_form_layout.addRow('Name:', self._nameField)
        self._configLayout.addLayout(name_form_layout)
        self._configLayout.addWidget(QLabel('List of configurations'))
        self._configLayout.addWidget(self._configurationTreeWidget)
        config_widget.setLayout(self._configLayout)
        
        self._saveButton = QPushButton("Save")
        material_widget = QWidget()
        self._materialLayout = QBoxLayout(QBoxLayout.TopToBottom)
        self._materialLayout.addWidget(self._saveButton)
        self._materialLayout.addWidget(QLabel('List of materials'))
        self._materialLayout.addWidget(self._materialTreeWidget)
        material_widget.setLayout(self._materialLayout)
        
        self._layout.addWidget(config_widget)
        self._layout.addWidget(material_widget)

        # add event listener for selection change
        self._configurationTreeWidget.setEditTriggers(self._configurationTreeWidget.NoEditTriggers)
        self._materialTreeWidget.setEditTriggers(self._materialTreeWidget.NoEditTriggers)
        self._configurationTreeWidget.itemDoubleClicked.connect(self._check_edit_configuration)
        self._materialTreeWidget.itemDoubleClicked.connect(self._check_edit_material)
        self._materialTreeWidget.expanded.connect(self._resize_columns)
        self._materialTreeWidget.collapsed.connect(self._resize_columns)
        self._materialTreeWidget.itemChecked.connect(self._on_toggle)
        self._saveButton.clicked.connect(self._save)

    @staticmethod
    def get_material_model():
        return EditView._material_model

    @staticmethod
    def get_configuration_model():
        return EditView._configuration_model
        
    def _resize_columns(self):
        self._materialTreeWidget.resizeColumnToContents(0)
        self._materialTreeWidget.resizeColumnToContents(1)
        self._configurationTreeWidget.resizeColumnToContents(0)
        self._configurationTreeWidget.resizeColumnToContents(1)
        
    def _check_edit_material(self, item, column):
        """
        Checks if the column of the item can be edited and set edit state if that is the case.
        :param item:
        :type item: QTreeWidgetItem
        :param column:
        :type column: number
        """
        if column == 1:
            self._materialTreeWidget.editItem(item, column)
            
    def _check_edit_configuration(self, item, column):
        """
        Checks if the column of the item can be edited and set edit state if that is the case.
        :param item:
        :type item: QTreeWidgetItem
        :param column:
        :type column: number
        """
        if column == 1:
            self._configurationTreeWidget.editItem(item, column)
            
    def _on_toggle(self, model_index):
        """
        Called on selecting a new item in the treeView.
        :param model_index: index of selected item
        :type model_index: QModelIndex
        """
        self._materialTreeWidget.blockSignals(True)
        selected_item = self._materialTreeWidget.itemFromIndex(model_index)  # type: QTreeWidgetItem
        parent_item = selected_item.parent()
        if parent_item is not None:
            check_parents_tree(parent_item)
        else:
            check_all_children_tree(selected_item)
        self._materialTreeWidget.blockSignals(False)
        
    def _initialize_material_model(self):
        data = DataStorage()
        materials = data.get_materials()
        materials_order = data.get_materials_order()

        for name in materials_order:
            EditView._add_material(materials[name], self._materialTreeWidget)

        if EditView._material_model is None:
            EditView._material_model = self._materialTreeWidget

    @staticmethod
    def _add_material(material, item):
        sub_item = create_new_tree_item(material.get_name(), item)
        for sub_material in material.get_materials():
            EditView._add_material(sub_material, sub_item)
            
    def _initialize_configuration_model(self, configuration):
        data = DataStorage()
        configurations = data.get_configurations()
        configurations_order = data.get_configurations_order()

        for name in configurations_order:
            if name == configuration.get_name():
                continue
            EditView._add_configuration(configurations[name], self._configurationTreeWidget)

        EditView._configuration_model = self._configurationTreeWidget
        
        material_print_amounts = configuration.get_material_print_amounts()
        for material in configuration.get_materials():
            item = get_item(self._materialTreeWidget.invisibleRootItem(), material.get_name())
            check_item(item)
            if item is not None:
                print_amount = material_print_amounts[material.get_name()]
                item.setText(1, str(print_amount))

        configuration_print_amounts = configuration.get_config_print_amounts()
        for configuration in configuration.get_configurations():
            item = get_item(self._configurationTreeWidget.invisibleRootItem(), configuration.get_name())
            check_item(item)
            if item is not None:
                print_amount = configuration_print_amounts[configuration.get_name()]
                item.setText(1, str(print_amount))

    @staticmethod
    def _add_configuration(configuration, item):
        create_new_tree_item(configuration.get_name(), item)
        
    def _calculate_print_amounts(self, root_item):
        """
        :param root_item:
        :type root_item: QTreeWidgetItem
        :rtype: dict
        """
        print_amounts = {}
        if root_item.childCount() > 0:
            for child_index in range(root_item.childCount()):
                child = root_item.child(child_index)
                if is_checked_tree(child):
                    print_amounts[child.text(0)] = int(child.text(1))
                else:
                    child_print_amounts = self._calculate_print_amounts(child)
                    print_amounts.update(child_print_amounts)

        elif is_checked_tree(root_item):
            print_amounts[root_item.text(0)] = int(root_item.text(1))

        return print_amounts
    
    def _save(self):
        # update sub configurations
        config_print_amounts = self._calculate_print_amounts(self._configurationTreeWidget.invisibleRootItem())
        for config in self._currentConfiguration.get_configurations():  # type: Configuration
            if config.get_name() not in config_print_amounts:
                self._currentConfiguration.remove_configuration(config)
            else:
                self._currentConfiguration.set_config_print_amount(config, config_print_amounts[config.get_name()])
                del config_print_amounts[config.get_name()]

        data = DataStorage()
        for config_name in config_print_amounts:
            config = data.get_configuration(config_name)
            self._currentConfiguration.add_configuration(config, config_print_amounts[config_name])
        
        # update material configurations
        material_print_amounts = self._calculate_print_amounts(self._materialTreeWidget.invisibleRootItem())
        for material in self._currentConfiguration.get_materials():  # type: Material
            if material.get_name() not in material_print_amounts:
                self._currentConfiguration.remove_material(material)
            else:
                self._currentConfiguration.set_material_print_amount(
                    material, material_print_amounts[material.get_name()]
                )
                del material_print_amounts[material.get_name()]
        
        for material_name in material_print_amounts:
            material = data.get_material(material_name)
            self._currentConfiguration.add_material(material, material_print_amounts[material_name])
        
        data.update_configuration(self._currentConfiguration.get_name(), self._currentConfiguration)
        data.persist()
        self.done(QDialog.Accepted)

    def show_for_configuration(self, configuration):
        """
        Shows the window for the given configuration.
        :param configuration:
        :type configuration: Configuration
        """
        self._currentConfiguration = configuration
        self._initialize_configuration_model(configuration)
        self._resize_columns()
        self._nameField.setText(configuration.get_name())
        self.setWindowFlags(Qt.Window)
        self.setModal(True)
        self.showMaximized()
        self.exec()