Beispiel #1
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
Beispiel #2
0
    def __init__(self):
        "另一种初始化方法"
        super(Window, self).__init__()

        self.initGUI("BoxLayout")

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

        label = QLabel("C")
        layout.addWidget(label, 0)
        label = QLabel("C++")
        layout.addWidget(label, 0)

        layout2 = QBoxLayout(QBoxLayout.TopToBottom)
        layout.addLayout(layout2)

        label = QLabel("Java")
        layout2.addWidget(label, 0)
        label = QLabel("Python")
        layout2.addWidget(label, 0)

        # 新的布局,管理两个按钮
        layout3 = QBoxLayout(QBoxLayout.RightToLeft)
        layout.addLayout(layout3)

        # TODO: 给按钮添加响应方法
        btn_opacity_half = QPushButton("半透明")
        layout3.addWidget(btn_opacity_half)
        btn_opacity_all = QPushButton("完全不透明")
        layout3.addWidget(btn_opacity_all)
Beispiel #3
0
    def __init__(self, parent):
        super(PolicyWindow, self).__init__(parent)
        self.parent = parent
        mainLayout = QBoxLayout(QBoxLayout.TopToBottom)
        topLayout = QBoxLayout(QBoxLayout.TopToBottom)
        buttonLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.policy = QGroupBox()
        self.remain = QLabel()
        self.opt = [QRadioButton("Radio " + str(i)) for i in range(6)]
        for i in self.opt:
            topLayout.addWidget(i)
        self.policy.setLayout(topLayout)

        self.cancel = QPushButton("Cancel")
        self.accept = QPushButton("OK")
        buttonLayout.addWidget(self.cancel)
        buttonLayout.addWidget(self.accept)
        self.cancel.released.connect(self.close)
        self.accept.released.connect(self.doEnactPolicy)
        mainLayout.addWidget(self.policy)
        mainLayout.addWidget(self.remain)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)
        self.setFixedSize(300, 250)
        self.setModal(True)
Beispiel #4
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)
 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 #6
0
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)
        self.setWindowTitle("QTreeWidget Column")
        self.setFixedWidth(300)
        self.setFixedHeight(300)

        # TreeWidget 1
        self.tw_1 = QTreeWidget(self)
        self.tw_1.setColumnCount(1)
        self.tw_1.setHeaderLabels(self.HEADER)

        # TreeWidget 1
        self.tw_2 = QTreeWidget(self)
        self.tw_2.setColumnCount(1)
        self.tw_2.setHeaderLabels(self.HEADER)

        # Buttons
        self.pb_move_left = QPushButton("<-")
        self.pb_move_right = QPushButton("->")

        layout = QBoxLayout(QBoxLayout.LeftToRight)
        layout.addWidget(self.tw_1)
        layout.addWidget(self.tw_2)

        main_layout = QBoxLayout(QBoxLayout.TopToBottom)
        main_layout.addLayout(layout)
        main_layout.addWidget(self.pb_move_right)
        main_layout.addWidget(self.pb_move_left)

        self.setLayout(main_layout)
Beispiel #7
0
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        self.setWindowTitle("Soccer Highlight")
        self.setWindowIcon(QIcon('./images/soccer.png'))
        self.setFixedWidth(640)
        self.setFixedHeight(480)
        # self.setStyleSheet("background-color: white")
        # self.setWindowOpacity()
        layout_base = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.setLayout(layout_base)

        # 첫 번째 그룹 QBoxLayout
        grp_1 = QGroupBox("LEAUGE")
        layout_base.addWidget(grp_1)
        layout = QHBoxLayout()
        layout.addWidget(QPushButton("Laliga"))
        layout.addWidget(QPushButton("Serie A"))
        layout.addWidget(QPushButton("Ligue 1"))
        layout.addWidget(QPushButton("Bundesliga"))
        layout.addWidget(QPushButton("K-League"))
        grp_1.setLayout(layout)

        # 두 번째 그룹 QGridLayout
        grp_2 = QGroupBox("Select your file & League")
        layout_base.addWidget(grp_2)
        grp_2_layout = QBoxLayout(QBoxLayout.LeftToRight)
        grp_2.setLayout(grp_2_layout)
        layout = QGridLayout()
        # layout.addItem(QSpacerItem(10, 200))

        # 파일 선택 버튼
        self.file_b = QPushButton('File Open')
        self.file_b.clicked.connect(self.pushButtonClicked)
        layout.addWidget(self.file_b, 1, 0)

        # 파일 이름 출력
        self.f_label = QLabel()
        layout.addWidget(self.f_label)

        # 리그 선택
        L_cb = QComboBox(self)
        L_cb.addItem('Laliga')
        L_cb.addItem('Serie A')
        L_cb.addItem('Ligue 1')
        L_cb.addItem('Bundesliga')
        L_cb.addItem('K-League')

        grp_2_layout.addLayout(layout)
        grp_2_layout.addWidget(L_cb)

        # 세 번째 그룹 QFormLaytout
        grp_3 = QGroupBox("Make HighLight")
        layout_base.addWidget(grp_3)
        layout = QFormLayout()
        grp_3.setLayout(layout)
        self.submit_b = QPushButton('확인')
        self.submit_b.clicked.connect(self.makeHighlight)
        layout.addRow(self.submit_b)
Beispiel #8
0
    def __init__(self, parent: QtWidgets.QBoxLayout, stretch, vd, tp, *args,
                 **kwargs):
        super().__init__(*args, **kwargs)

        self._initLayout()
        self._initRequestModule(vd, tp)

        parent.addLayout(self, stretch)
Beispiel #9
0
 def createLayout(self):
     #build layout for the dialog box
     importButton = QPushButton("Import", self)
     importButton.clicked.connect(self.importSVG)
     
     saveButton = QPushButton("Save", self)
     saveButton.clicked.connect(self.saveEvent)
     
     self.symbolName = QLineEdit(self)
     self.symbolName.setPlaceholderText("Enter Symbol Name")
     symbolNameLabel = QLabel("Symbol Name")
     symbolNameLabel.setBuddy(self.symbolName)
     
     self.symbolClass = QLineEdit(self)
     self.symbolClass.setPlaceholderText("Enter Symbol Class Name")
     symbolClassLabel = QLabel("Symbol Class Name")
     symbolClassLabel.setBuddy(self.symbolClass)
     
     self.symbolCategory = QLineEdit(self)
     self.symbolCategory.setPlaceholderText("Enter Symbol Category")
     symbolCategoryLabel = QLabel("Symbol Category")
     symbolCategoryLabel.setBuddy(self.symbolCategory)
     
     addGripItem = QPushButton("Add Grip Item", self)
     addGripItem.clicked.connect(self.addGrip)
     addLineGripItem = QPushButton("Add Line Grip Item", self)
     addLineGripItem.clicked.connect(self.addLineGrip)
     
     self.painter = QGraphicsScene()
     view = QGraphicsView(self.painter)
     
     layout = QGridLayout(self)
     
     subLayout = QBoxLayout(QBoxLayout.LeftToRight)
     subLayout.addWidget(importButton)
     subLayout.addWidget(saveButton)
     subLayout.addStretch(1)
     
     layout.addLayout(subLayout, 0, 0, 1, -1)
     
     subLayout2 = QBoxLayout(QBoxLayout.LeftToRight)
     subLayout2.addWidget(view, stretch=1)
     
     subLayout3 = QBoxLayout(QBoxLayout.TopToBottom)
     subLayout3.addWidget(symbolNameLabel)
     subLayout3.addWidget(self.symbolName)
     subLayout3.addWidget(symbolClassLabel)
     subLayout3.addWidget(self.symbolClass)
     subLayout3.addWidget(symbolCategoryLabel)
     subLayout3.addWidget(self.symbolCategory)
     subLayout3.addStretch(1)
     subLayout3.addWidget(addGripItem)
     subLayout3.addWidget(addLineGripItem)
     subLayout2.addLayout(subLayout3)
     
     layout.addLayout(subLayout2, 1, 0, -1, -1)
     self.setLayout(layout)
Beispiel #10
0
    def create_add_layout(self, parent: wid.QBoxLayout):
        hbox = QHBoxLayout()
        hbox.addWidget(wid.QLabel("Process name"))
        hbox.addWidget(self.line_proc_name)
        parent.addLayout(hbox)

        hbox = QHBoxLayout()
        hbox.addWidget(wid.QLabel("Path"))
        hbox.addWidget(self.line_path)
        parent.addLayout(hbox)

        parent.addWidget(self.create_add_button())
Beispiel #11
0
    def __init__(self,
                 title,
                 contents,
                 is_contents_from_table=False,
                 does_detail_exists=True):
        QWidget.__init__(self)
        QObject.__init__(self)
        top_widget_height = 35
        pointer_cursor = QCursor(Qt.PointingHandCursor)

        self.setWindowTitle(title)
        self.setMinimumSize(self.width(), self.height())
        self.setWindowIcon(QIcon(CONSTANT.ICON_PATH[0]))

        layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        top_layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        layout.addLayout(top_layout)

        if is_contents_from_table:
            contents.setParent(self)
            self.table = contents
        else:
            self.table = ArtifactTable(self, contents)
            if not does_detail_exists:
                self.table.is_detail_allowed = does_detail_exists
            self.table.artifacts_list = contents
            self.table.ui()
            layout.addWidget(self.table)

        self.filtering_widget = filtering_widget("Filter ({})".format(title))
        self.filtering_widget.setCheckedStatus(self.table.checked_status)
        self.filtering_widget.itemChanged.connect(self.table.filter)

        filter_btn = QPushButton(self)
        filter_btn.setIcon(QIcon(CONSTANT.ICON_PATH[1]))
        filter_btn.setFixedSize(top_widget_height, top_widget_height)
        filter_btn.setStyleSheet("background-color: darkslategray")
        filter_btn.setShortcut("Ctrl+D")
        filter_btn.clicked.connect(self.filtering_widget.show)
        filter_btn.setCursor(pointer_cursor)

        self.search_box = QLineEdit(self)
        self.search_box.setFixedHeight(top_widget_height)
        self.search_box.showMaximized()
        self.search_box.setFont(QFont("Arial", 12))
        self.search_box.setPlaceholderText("Search")
        self.search_box.returnPressed.connect(self.search)

        top_layout.addWidget(filter_btn)
        top_layout.addWidget(self.search_box)
        layout.addWidget(self.table)
        if self.table.isHidden():
            self.table.show()
Beispiel #12
0
    def init_lectures(self):
        headers = ['과목','시간','캠퍼스','강의실','교수명']

        self.lecture_list.setColumnCount(len(headers))
        self.lecture_list.setHeaderLabels(headers)

        self.wishlist.setColumnCount(len(headers))
        self.wishlist.setHeaderLabels(headers)


        list_layout = QBoxLayout(QBoxLayout.LeftToRight)
        list_layout.addWidget(self.lecture_list)
        list_layout.addWidget(self.wishlist)

        lecture_root = QTreeWidget.invisibleRootItem(self.lecture_list)
        # append data for exam
        datas = ['하','이','루','방','가']
        item = QTreeWidgetItem()
        for idx, data in enumerate(datas):
            item.setText(idx, data)

        lecture_root.addChild(item)

        datas = ['바','이','루','방','가']
        item = QTreeWidgetItem()
        for idx, data in enumerate(datas):
            item.setText(idx, data)

        lecture_root.addChild(item)

        datas = ['D', '0', 'R', 'K', '_']
        item = QTreeWidgetItem()
        for idx, data in enumerate(datas):
            item.setText(idx, data)

        lecture_root.addChild(item)

        # add button by layout
        btn_layout = QBoxLayout(QBoxLayout.RightToLeft)
        btn_layout.addWidget(self.add_btn)
        btn_layout.addWidget(self.del_btn)

        main_layout = QBoxLayout(QBoxLayout.TopToBottom)
        main_layout.addLayout(list_layout)
        main_layout.addLayout(btn_layout)

        # connect event when button clicked
        self.add_btn.clicked.connect(self.move_item)
        self.del_btn.clicked.connect(self.move_item)

        self.setLayout(main_layout)
        return main_layout
Beispiel #13
0
class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        # 레이아웃 선언 및 Form Widget에 설정
        self.layout_1 = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.layout_2 = QBoxLayout(QBoxLayout.LeftToRight)
        self.layout_3 = QBoxLayout(QBoxLayout.TopToBottom)

        # 부모 레이아웃에 자식 레이아웃을 추가
        self.layout_1.addLayout(self.layout_2)
        self.layout_1.addLayout(self.layout_3)

        self.web = QWebEngineView()
        self.pb_1 = QPushButton("요청하기")
        self.pb_2 = QPushButton("밝기지도")
        self.pb_3 = QPushButton("길찾기")
        # self.te_1 = QTextEdit()

        # Web과 통신할 수 있게 채널링
        channel = QWebChannel(self.web.page())
        self.web.page().setWebChannel(channel)
        self.handler = CallHandler()  # 반드시 인스턴스 변수로 사용해야 한다.
        channel.registerObject('handler', self.handler)  # js에서 불리울 이름

        self.setLayout(self.layout_1)
        self.init_widget()

    def init_widget(self):
        self.setWindowTitle("QWebChannel")
        self.setFixedWidth(360)
        self.setFixedHeight(640)

        # 로컬파일 사용시 절대경로만 사용해야 함
        #url = QDir().current().filePath("html/QWebEngineView_02_WebChannel.html")
        url = os.path.join(settings.BASE_DIR, 'Lumos_UI', 't-map',
                           'index.html')
        url = QUrl.fromLocalFile(url)
        self.web.load(url)

        # 핸들러 시그널 버튼이 눌러지면 console로 Hi를 보낸다.
        self.pb_1.clicked.connect(
            lambda v: self.handler.getText.emit(txt))  ##경로얻어오기
        self.pb_2.clicked.connect(
            lambda v: self.web.setUrl(QUrl("http://google.com")))  ##밝기지도
        self.pb_3.clicked.connect(
            lambda v: self.web.setUrl(QUrl(url)))  ##길찾기 API

        self.layout_2.addWidget(self.web)
 def __init__(self, parent):
     super(BasicInfoTab, self).__init__()
     mainLayout = QBoxLayout(QBoxLayout.TopToBottom)
     mainTableLayout = QBoxLayout(QBoxLayout.LeftToRight)
     headerLayout = QBoxLayout(QBoxLayout.LeftToRight)
     mainLowerLayout = QBoxLayout(QBoxLayout.LeftToRight)
     column = [QBoxLayout(QBoxLayout.TopToBottom) for i in range(4)]
     lowerColumn = [QBoxLayout(QBoxLayout.TopToBottom) for i in range(2)]
     self.hint = QLabel()
     headerLayout.addSpacing(172)
     headerLayout.addWidget(self.hint)
     self.topHeader = [QLabel(str(i)) for i in range(3)]
     column[0].addSpacing(20)
     for i in range(1, 4):
         column[i].addWidget(self.topHeader[i - 1])
     self.paramName = [QLabel("param " + str(i)) for i in range(20)]
     for i in range(20):
         if i <= 11: column[0].addWidget(self.paramName[i])
         else: lowerColumn[0].addWidget(self.paramName[i])
     self.sprpwrVal = [QLabel("data " + str(i)) for i in range(24)]
     for i in range(24):
         column[1 if i < 12 else 2].addWidget(self.sprpwrVal[i])
     self.otherVal = [QLabel() for i in range(12)]
     for i in self.otherVal:
         column[3].addWidget(i)
     self.infoVal = [QLabel("info " + str(i)) for i in range(8)]
     for i in self.infoVal:
         lowerColumn[1].addWidget(i)
     # Local news section
     self.localNewsGroup = QGroupBox("Local insights")
     self.localNewsLabel = QTextEdit()
     tmp = QBoxLayout(QBoxLayout.LeftToRight)
     tmp.addWidget(self.localNewsLabel)
     self.localNewsGroup.setLayout(tmp)
     # putting it all together
     for i in column:
         mainTableLayout.addLayout(i)
     for i in lowerColumn:
         mainLowerLayout.addLayout(i)
     mainLowerLayout.addSpacing(50)
     mainLowerLayout.addWidget(self.localNewsGroup)
     #preview = QGraphicsView(parent.mapView.scene())
     #preview.setFixedSize(200,200)
     #mainLowerLayout.addWidget(preview)
     mainLayout.addLayout(mainTableLayout)
     mainLayout.addLayout(headerLayout)
     mainLayout.addSpacing(5)
     mainLayout.addLayout(mainLowerLayout)
     self.setLayout(mainLayout)
Beispiel #15
0
 def add_settings(self):
     main_layout = QBoxLayout(QBoxLayout.TopToBottom)
     for box_title, settings in self.gui_settings.items():
         box = QGroupBox(box_title, self)
         box_layout = QBoxLayout(QBoxLayout.TopToBottom)
         for name, text in settings.items():
             control, layout = self.get_setting_control(name, text)
             box_layout.addLayout(layout)
             self.controls[name] = control
         box.setLayout(box_layout)
         main_layout.addWidget(box)
         if main_layout.count() > 2:
             self.settingsLayout.addItem(main_layout)
             main_layout = QBoxLayout(QBoxLayout.TopToBottom)
     main_layout.addStretch()
     self.settingsLayout.addItem(main_layout)
Beispiel #16
0
    def create_sync_layout(self, parent: wid.QBoxLayout):
        parent.addWidget(self.cb)
        self.cb.currentTextChanged.connect(self.show_on_change)

        hbox = QHBoxLayout()

        for btn in [
                self.create_download_button(),
                self.create_upload_button(),
                self.create_show_path_button(),
                self.create_remove_button()
        ]:
            hbox.addWidget(btn)

        parent.addLayout(hbox)
        return
Beispiel #17
0
    def __init__(self, parent):
        super(NewGameWindow, self).__init__(parent)
        self.parent = parent
        self.buttonGroups = [QButtonGroup() for i in range(3)]
        mainLayout = QBoxLayout(QBoxLayout.TopToBottom)
        columnLayout = QBoxLayout(QBoxLayout.LeftToRight)
        buttonLayout = QBoxLayout(QBoxLayout.LeftToRight)
        column = [QBoxLayout(QBoxLayout.TopToBottom) for i in range(3)]
        level = QGroupBox("Level of play")
        self.levelOpt = [QRadioButton(str(i)) for i in range(4)]
        for i in self.levelOpt:
            column[0].addWidget(i)
        side = QGroupBox("Side to play")
        mode = QGroupBox("Number of players")
        self.sideOpt = [QRadioButton(str(i)) for i in range(2)]
        self.modeOpt = [QRadioButton(str(i)) for i in range(2)]
        for i, j in zip(self.sideOpt, self.modeOpt):
            column[1].addWidget(i)
            column[2].addWidget(j)
        for i, col in zip((level, side, mode), column):
            i.setLayout(col)
            columnLayout.addWidget(i)
        for i, j in zip(self.levelOpt, range(4)):
            self.buttonGroups[0].addButton(i, j)
        for i, k, j in zip(self.sideOpt, self.modeOpt, range(2)):
            self.buttonGroups[1].addButton(i, j)
            self.buttonGroups[2].addButton(k, j)

        self.topText = QLabel(
            "Your goal in this game is to increase the geopolitical prestige of your chosen superpower"
            +
            " while avoiding a nuclear war. The four levels provide increasingly complex and accurate representations"
            + " of the real world of geopolitics.")
        self.topText.setWordWrap(True)
        cancel = QPushButton("Cancel")
        cancel.released.connect(self.close)
        accept = QPushButton("OK")
        accept.released.connect(self.doSetNewGame)
        buttonLayout.addWidget(cancel)
        buttonLayout.addWidget(accept)
        mainLayout.addWidget(self.topText)
        mainLayout.addLayout(columnLayout)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)
        self.setFixedSize(400, 310)
        self.setModal(True)
        self.setStrings()
    def init_widget(self):
        self.setWindowTitle("Custom Slot")
        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        control_lbx = QBoxLayout(QBoxLayout.LeftToRight, parent=self)
        self.setLayout(form_lbx)

        self.le.setMaximumWidth(40)

        # 시그널 슬롯 연결
        self.sld.valueChanged.connect(self.valueChanged)
        self.le.textChanged.connect(self.sld.setValue)
        self.dial.valueChanged.connect(self.sld.setValue)

        form_lbx.addWidget(self.dial)
        form_lbx.addLayout(control_lbx)
        control_lbx.addWidget(self.sld)
        control_lbx.addWidget(self.le)
Beispiel #19
0
    def _layout_control(self):
        self._control_group = QGroupBox('Control')

        self._control_lineEdit = QLineEdit()
        self._control_lineEdit.setDisabled(True)

        self._control_btn_start = QPushButton('Start', self)
        self._control_btn_start.clicked.connect(self.click_start)

        self._control_btn_stop = QPushButton('Stop', self)
        self._control_btn_stop.clicked.connect(self.click_stop)
        self._control_btn_stop.setDisabled(True)

        topBox = QBoxLayout(QBoxLayout.LeftToRight)
        topBox.addWidget(self._control_lineEdit)

        self.set_progress_text('[+] Load printers connected currently')
        pList = get_printer_list()
        if not pList:
            self.set_progress_text('[+] Connected nothing')

        else:
            self._printer_btn = {}

            for p in pList:
                self.set_progress_text(p.__str__())
                if p['name'] in TARGET_PRINTER_NAMES:
                    self._printer_btn[p['name']] = QPushButton(p['name'], self)
                    self._printer_btn[p['name']].clicked.connect(
                        getattr(self, "click_pbtn_" + p['name']))
                    topBox.addWidget(self._printer_btn[p['name']])

            self.set_progress_text('[+] Create meaningful printer buttons')

        bottomBox = QBoxLayout(QBoxLayout.LeftToRight)
        bottomBox.addStretch(1)
        bottomBox.addWidget(self._control_btn_start)
        bottomBox.addWidget(self._control_btn_stop)
        bottomBox.addStretch(1)

        box = QBoxLayout(QBoxLayout.TopToBottom)
        box.addLayout(topBox)
        box.addLayout(bottomBox)

        self._control_group.setLayout(box)
Beispiel #20
0
class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        # 레이아웃 선언 및 Form Widget에 설정
        self.layout_1 = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.layout_2 = QBoxLayout(QBoxLayout.LeftToRight)
        self.layout_3 = QBoxLayout(QBoxLayout.TopToBottom)

        # 부모 레이아웃에 자식 레이아웃을 추가
        self.layout_1.addLayout(self.layout_2)
        self.layout_1.addLayout(self.layout_3)

        self.web = QWebEngineView()
        self.pb_1 = QPushButton("요청하기")

        # Web과 통신할 수 있게 채널링
        channel = QWebChannel(self.web.page())
        self.web.page().setWebChannel(channel)
        self.handler = CallHandler()  # 반드시 인스턴스 변수로 사용해야 한다.
        channel.registerObject('handler', self.handler)  # js에서 불리울 이름

        self.setLayout(self.layout_1)
        self.init_widget()

    def init_widget(self):
        self.setWindowTitle("QWebChannel")
        self.setFixedWidth(640)
        self.setFixedHeight(480)

        # 로컬파일 사용시 절대경로만 사용해야 함
        url = QDir().current().filePath(
            "html/QWebEngineView_09_WebChannelDataType.html")
        url = QUrl.fromLocalFile(url)
        self.web.load(url)

        # 핸들러 시그널 버튼이 눌러지면 console로 value를 보낸다.
        value = {"data": "ABC", "msg": ["DEF", 1, {"A": False, "B": True}]}
        document = QJsonDocument()
        document.setObject(value)
        self.pb_1.clicked.connect(
            lambda v: self.handler.app_to_web_send_data.emit(document))

        self.layout_2.addWidget(self.web)
        self.layout_3.addWidget(self.pb_1)
Beispiel #21
0
class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        # 배치될 위젯 변수 선언
        self.lb_1 = QLabel()
        self.lb_2 = QLabel()
        self.lb_3 = QLabel()
        self.lb_4 = QLabel()
        self.lb_5 = QLabel()

        # 레이아웃 선언 및 Form Widget에 설정
        self.layout_1 = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.layout_2 = QBoxLayout(QBoxLayout.LeftToRight)
        self.layout_3 = QBoxLayout(QBoxLayout.TopToBottom)

        # 부모 레이아웃에 자식 레이아웃을 추가
        self.layout_1.addLayout(self.layout_2)
        self.layout_1.addLayout(self.layout_3)

        self.setLayout(self.layout_1)
        self.init_widget()

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

        self.lb_1.setText("Label 1")
        self.lb_2.setText("Label 2")
        self.lb_3.setText("Label 3")
        self.lb_4.setText("Label 4")
        self.lb_5.setText("Label 5")

        self.lb_1.setStyleSheet("background-color: yellow")
        self.lb_2.setStyleSheet("background-color: red")
        self.lb_3.setStyleSheet("background-color: blue")
        self.lb_4.setStyleSheet("background-color: pink")
        self.lb_5.setStyleSheet("background-color: grey")

        self.layout_2.addWidget(self.lb_1)
        self.layout_2.addWidget(self.lb_2)
        self.layout_3.addWidget(self.lb_3)
        self.layout_3.addWidget(self.lb_4)
        self.layout_3.addWidget(self.lb_5)
class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        # 레이아웃 선언 및 Form Widget에 설정
        self.layout_1 = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.layout_2 = QBoxLayout(QBoxLayout.LeftToRight)
        self.layout_3 = QBoxLayout(QBoxLayout.TopToBottom)

        # 부모 레이아웃에 자식 레이아웃을 추가
        self.layout_1.addLayout(self.layout_2)
        self.layout_1.addLayout(self.layout_3)

        self.web = QWebEngineView()
        self.pb_1 = QPushButton("요청하기")
        self.te_1 = QTextEdit()

        # Web과 통신할 수 있게 채널링
        channel = QWebChannel(self.web.page())
        self.web.page().setWebChannel(channel)
        self.handler = CallHandler()  # 반드시 인스턴스 변수로 사용해야 한다.
        channel.registerObject('handler', self.handler)  # js에서 불리울 이름

        self.setLayout(self.layout_1)
        self.init_widget()

    def init_widget(self):
        self.setWindowTitle("QWebChannel")
        self.setFixedWidth(640)
        self.setFixedHeight(480)

        # 로컬파일 사용시 절대경로만 사용해야 함
        url = QDir().current().filePath(
            "html/QWebEngineView_02_WebChannel.html")
        url = QUrl.fromLocalFile(url)
        self.web.load(url)

        # 핸들러 시그널 버튼이 눌러지면 console로 Hi를 보낸다.
        self.pb_1.clicked.connect(
            lambda v: self.handler.getText.emit(self.te_1.toPlainText()))

        self.layout_2.addWidget(self.web)
        self.layout_3.addWidget(self.pb_1)
        self.layout_3.addWidget(self.te_1)
Beispiel #23
0
class PDFList(QWidget):
    """A list of PDFs for a document."""
    def __init__(self, parent):
        super(PDFList, self).__init__()
        self.doc = None
        self.doc_window = None
        self.parent = parent
        self.addButton = QPushButton("&Add PDF")
        self.grid = QGridLayout()
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)

    def set_doc_window(self, doc_window):
        """Set the doc_window of this list of PDFs."""
        self.doc_window = doc_window
        self.addButton.clicked.connect(self.doc_window.addPDF)

    def set_doc(self, doc):
        """Set document."""
        self.doc = doc
        self.refresh()

    def refresh(self):
        """Refresh list of PDF documents."""
        item = self.grid.takeAt(0)
        while item:
            del item
            item = self.grid.takeAt(0)
        item = self.layout.takeAt(0)
        while item:
            del item
            item = self.layout.takeAt(0)
        files = self.doc.get_files()
        paths = self.doc.get_fullpaths()
        for index, (path, name) in enumerate(zip(paths, files)):
            label = PDFLabel(name, path)
            delete = QPushButton()
            delete.setIcon(QIcon.fromTheme("edit-delete"))
            delete.setText("")
            delete.setEnabled(False)  # TODO Delete this PDF
            self.grid.addWidget(label, index, 0)
            self.grid.addWidget(delete, index, 1)
        self.layout.addLayout(self.grid)
        self.layout.addWidget(self.addButton)
        self.setLayout(self.layout)
Beispiel #24
0
    def ui(self):
        self.setWindowTitle(self.title)
        from modules.constant import ICON_PATH
        self.setWindowIcon(QIcon(ICON_PATH[0]))
        self.setMinimumSize(self.width(), self.height())
        layout = QBoxLayout(QBoxLayout.TopToBottom, self)
        top_layout = QBoxLayout(QBoxLayout.LeftToRight, self)

        self.search_box = QLineEdit(self)
        self.search_box.returnPressed.connect(self.search)
        self.search_box.setFixedHeight(30)
        self.search_box.setPlaceholderText("Search")

        export_btn = QPushButton("Export as CSV", self)
        export_btn.setFixedHeight(30)
        export_btn.clicked.connect(self.export)
        export_btn.setFixedWidth(150)

        self.table = QTableWidget(self)
        self.table.setColumnCount(len(self.column_header))
        self.table.setHorizontalHeaderLabels(self.column_header)
        self.table.verticalHeader().setVisible(False)

        for row in range(len(self.contents)):
            self.table.insertRow(row)
            for col in range(len(self.column_header)):
                self.table.setItem(row, col,
                                   QTableWidgetItem(self.contents[row][col]))
                self.table.item(row, col).setTextAlignment(Qt.AlignCenter)
            self.table.item(row,
                            1).setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        self.table.resizeColumnsToContents()
        self.table.resizeRowsToContents()
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        top_layout.addWidget(self.search_box)
        top_layout.addWidget(export_btn)
        layout.addLayout(top_layout)
        layout.addWidget(self.table)

        self.show()
Beispiel #25
0
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        self.setWindowTitle("Various Layout Widgets")
        self.setFixedWidth(640)
        self.setFixedHeight(480)

        layout_base = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.setLayout(layout_base)

        # 첫 번째 그룹 QBoxLayout
        grp_1 = QGroupBox("QBoxLayout")
        layout_base.addWidget(grp_1)
        layout = QHBoxLayout()
        layout.addWidget(QPushButton("Butoon 1"))
        layout.addWidget(QPushButton("Butoon 1"))
        layout.addWidget(QPushButton("Butoon 1"))
        grp_1.setLayout(layout)

        # 두 번째 그룹 QGridLayout
        grp_2 = QGroupBox("QGridLayout")
        layout_base.addWidget(grp_2)
        grp_2_layout = QBoxLayout(QBoxLayout.LeftToRight)
        grp_2.setLayout(grp_2_layout)
        layout = QGridLayout()
        layout.addItem(QSpacerItem(10, 100))
        layout.addWidget(QLabel("Line Edit 1:"), 1, 0)
        layout.addWidget(QLabel("Line Edit 2:"), 2, 0)
        layout.addWidget(QLabel("Line Edit 2:"), 3, 0)
        layout.addWidget(QLineEdit(), 1, 1)
        layout.addWidget(QLineEdit(), 2, 1)
        layout.addWidget(QLineEdit(), 3, 1)
        grp_2_layout.addLayout(layout)
        grp_2_layout.addWidget(QTextEdit())

        # 세 번째 그룹 QFormLaytout
        grp_3 = QGroupBox("QFormLaytout")
        layout_base.addWidget(grp_3)
        layout = QFormLayout()
        grp_3.setLayout(layout)
        layout.addRow(QLabel("Line Edit 1:"), QLineEdit())
        layout.addRow(QLabel("Line Edit 2:"), QLineEdit())
        layout.addRow(QLabel("Line Edit 3:"), QLineEdit())
class myForm(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        self.lb_1 = QLabel()
        self.lb_2 = QLabel()
        self.lb_3 = QLabel()
        self.lb_4 = QLabel()
        self.lb_5 = QLabel()

        self.layout_1 = QBoxLayout(QBoxLayout.LeftToRight, self)
        self.layout_2 = QBoxLayout(QBoxLayout.LeftToRight)
        self.layout_3 = QBoxLayout(QBoxLayout.TopToBottom)

        self.setLayout(self.layout_1)
        self.layout_1.addLayout(self.layout_2)
        self.layout_1.addLayout(self.layout_3)

        self.init_widget()

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

        self.lb_1.setText("Label 1")
        self.lb_2.setText("Label 2")
        self.lb_3.setText("Label 3")
        self.lb_4.setText("Label 4")
        self.lb_5.setText("Label 5")

        self.lb_1.setStyleSheet("background-color: blue")
        self.lb_2.setStyleSheet("background-color: yellow")
        self.lb_3.setStyleSheet("background-color: red")
        self.lb_4.setStyleSheet("background-color: green")
        self.lb_5.setStyleSheet("background-color: pink")

        self.layout_2.addWidget(self.lb_1)
        self.layout_2.addWidget(self.lb_2)
        self.layout_2.addWidget(self.lb_3)
        self.layout_3.addWidget(self.lb_4)
        self.layout_3.addWidget(self.lb_5)
Beispiel #27
0
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.LOGGEDIN = False
        self.setWindowIcon(QIcon("assets/logo.png"))
        self.setWindowTitle("BeaconGraph")
        #self.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog)

        self.logo = QPixmap('assets/logo300.png')
        self.picLabel = QLabel(self)
        self.picLabel.setPixmap(self.logo)
        self.picLabel.setAlignment(Qt.AlignCenter)

        self.uri = QLineEdit(self)
        self.uri.setText("bolt://localhost:7687")
        self.QUriLabel = QLabel("DB URI")

        self.username = QLineEdit(self)
        self.username.setPlaceholderText("Neo4j Username")
        self.QUserLabel = QLabel("USERNAME")

        self.password = QLineEdit(self)
        self.password.setPlaceholderText("Neo4j Password")
        self.password.setEchoMode(QLineEdit.Password)
        self.QPasswordLabel = QLabel("PASSWORD")

        self.btn_Submit = QPushButton("LOGIN")

        self.setStyleSheet(qss)
        self.resize(400, 500)

        logoLayout = QBoxLayout(QBoxLayout.TopToBottom)
        logoLayout.addWidget(self.picLabel)

        layout = QFormLayout()
        layout.addRow(self.QUriLabel, self.uri)
        layout.addRow(self.QUserLabel, self.username)
        layout.addRow(self.QPasswordLabel, self.password)
        layout.addRow(self.btn_Submit)

        logoLayout.addLayout(layout)
        self.setLayout(logoLayout)
        self.btn_Submit.clicked.connect(self.Submit_btn)
Beispiel #28
0
    def only_(self):
        self.lala = QLabel(self)
        self.lala.setText("Welcome")
        self.lala.setAlignment(Qt.AlignCenter)
        self.lala.setFont(QFont("Times", 25, QFont.Bold))

        self.redbull = QPushButton('Sign-In', self)
        self.bluebull = QPushButton('Sign-Up', self)

        asasasas = QBoxLayout(QBoxLayout.TopToBottom)
        asasasas.addWidget(self.lala)

        boxeraa = QBoxLayout(QBoxLayout.LeftToRight)
        boxeraa.stretch(1)
        boxeraa.setSpacing(1)
        asasasas.addWidget(self.bull)
        boxeraa.addWidget(self.redbull)
        boxeraa.addWidget(self.bluebull)
        asasasas.addLayout(boxeraa)
        self.dummy.setLayout(asasasas)
Beispiel #29
0
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)

        self.setWindowTitle("Various Layout Widgets application")
        self.setFixedWidth(640)
        self.setFixedHeight(400)

        layout_base = QBoxLayout(QBoxLayout.TopToBottom, self)
        self.setLayout(layout_base)

        grp_1 = QGroupBox("1st group")
        layout_base.addWidget(grp_1)
        layout = QHBoxLayout()
        layout.addWidget(QPushButton("Button 1"))
        layout.addWidget(QPushButton("Button 2"))
        layout.addWidget(QPushButton("Button 3"))
        grp_1.setLayout(layout)

        grp_2 = QGroupBox("2nd group")
        layout_base.addWidget(grp_2)
        grp_2_layout = QBoxLayout(QBoxLayout.LeftToRight)
        grp_2.setLayout(grp_2_layout)
        layout = QGridLayout()
        layout.addItem(QSpacerItem(100, 200))
        layout.addWidget(QLabel("Line Edit 1:"), 1, 0)
        layout.addWidget(QLabel("Line Edit 2:"), 2, 0)
        layout.addWidget(QLabel("Line Edit 3:"), 3, 0)
        layout.addWidget(QLineEdit(), 1, 1)
        layout.addWidget(QLineEdit(), 2, 1)
        layout.addWidget(QLineEdit(), 3, 1)
        grp_2_layout.addLayout(layout)
        grp_2_layout.addWidget(QTextEdit())

        grp_3 = QGroupBox("Last group")
        layout_base.addWidget(grp_3)
        layout = QFormLayout()
        grp_3.setLayout(layout)
        layout.addRow(QLabel("Line Edit 1:"), QLineEdit())
        layout.addRow(QLabel("Line Edit 2:"), QLineEdit())
        layout.addRow(QLabel("Line Edit 3:"), QLineEdit())
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
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
Beispiel #32
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 #33
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()
class SlidersGroup(QGroupBox):

    valueChanged = pyqtSignal(int)

    def __init__(self, commandBox, parent=None):
        super(SlidersGroup, self).__init__("", parent)
        self.slidersLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.commandBox = commandBox

        self.sliders = []
#        self.spinBoxes = []
        self.labels = []
        if len(screen_data) == 1:
            self.slidersLayout.addStretch()
        for i, (name, value) in enumerate(screen_data):
            self.createBrightnessCtrl(name, value, i)

        if len(screen_data) > 1:
            self.createBrightnessCtrl("All", 100, None)
            self.sliders[-1].valueChanged.connect(self.setAllValues)

        self.setLayout(self.slidersLayout)

        self.refreshCurrentValues()

    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)

    def setValue(self, i, value):
        global screen_data
        screen_data[i] = (screen_data[i][0], value)
        self.refreshCommandBox()

    def setValuePartial(self, i):
        s = self.setValue
        return lambda value: s(i, value)

    def setAllValues(self, value):
        for sl in self.sliders:
            sl.setValue(value)

    def refreshCurrentValues(self):
        for i in range(len(screen_data)):
            lbl = self.labels[i]
            name, value = screen_data[i]
            if i == primary and len(screen_data) > 1:
                name += " (primary) "
            lbl.setText(name + " (" + str(value) + ")")
        self.refreshCommandBox()

    def refreshCommandBox(self):
        self.commandBox.document().setPlainText("# apply changes")
        for command in get_apply_commands():
            self.commandBox.appendPlainText(command)
Beispiel #35
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